text:
Q: Can I set text box to readonly when using Html.TextBoxFor? I have the following  tag with a Html.TextBoxFor expression and I want the contents to be read only, is this possible?
<%= Html.TextBoxFor(m => Model.Events.Subscribed[i].Action)%>

A: The following snippet worked for me.
@Html.TextBoxFor(m => m.Crown, new { id = "", @style = "padding-left:5px", @readonly = "true" })

A: <%= Html.TextBoxFor(m => Model.Events.Subscribed[i].Action, new {readonly=true})%>

A: This work for me...
@Html.TextBoxFor(model => model.RIF, new { value = @Model.RIF, @readonly = "readonly" })

A: Use the following:
 @Html.TextBoxFor(m => m.Whatever, new {@readonly = "readonly"})

If you want to assign a class to it you could do it the same way , by adding the
     @class = ""
 property. Hope this helps :)

A: Updated for modern versions of .NET per @1c1cle's suggestion in a comment:
<%= Html.TextBoxFor(model => Model.SomeFieldName, new {{"readonly", "true"}}) %>

Do realize that this is not a "secure" way to do this as somebody can inject javascript to change this.
Something to be aware of is that if you set that readonly value to false, you actually won't see any change in behavior! So if you need to drive this based on a variable, you cannot simply plug that variable in there. Instead you need to use conditional logic to simply not pass that readonly attribute in.
Here is an untested suggestion for how to do this (if there's a problem with this, you can always do an if/else):
<%= Html.TextBoxFor(model => Model.SomeFieldName, shouldBeReadOnlyBoolean ? new {{"readonly", "true"}} : null) %>

A: <%: Html.TextBoxFor(m => Model.Events.Subscribed[i].Action, new { @autocomplete = "off", @readonly=true})%>

This is how you set multiple properties

A: An other possibility :
<%= Html.TextBoxFor(model => Model.SomeFieldName, new Dictionary<string, object>(){{"disabled", "true"}}) %>

A: To make it read only
@Html.TextBoxFor(m=> m.Total, new {@class ="form-control", @readonly="true"})

To diable
@Html.TextBoxFor(m=> m.Total, new {@class ="form-control", @disabled="true"})

A: <%= Html.TextBoxFor(m => Model.Events.Subscribed[i].Action, new { @readonly = true })%>

A: Using the example of @Hunter, in the new { .. } part, add readonly = true, I think that will work.

A: In fact the answer of Brain Mains is almost correct:
@Html.TextBoxFor(model => model.RIF, new { value = @Model.RIF, @readonly = true })

A: In case if you have to apply your custom class you can use
  @Html.TextBoxFor(m => m.Birthday,   new Dictionary<string, object>() { {"readonly", "true"}, {"class", "commonField"} } )

Where are
commonField is CSS class
and Birthday could be string field that you probably can use to keep jQuery Datapicker date :)
<script>
             $(function () {
                 $("#Birthday").datepicker({

                 });
             });
  </script>

That's a real life example.

A:    @Html.TextBoxFor(model => model.IdUsuario, new { @Value = "" + User.Identity.GetUserId() + "", @disabled = "true" })

@disabled = "true"

Work very well

A: You can also disabled TextBoxFor
@Html.TextBoxFor(x=>x.day, null, new { @class = "form-control success" ,@disabled="disabled" })

A: By setting readonly attribute to either true or false is not going to work in most browsers, I have done it as below, when the mode of the page is "reload", I've not included "readonly" attribute.
@if(Model.Mode.Equals("edit")){
@Html.TextAreaFor(model => Model.Content.Data, new { id = "modEditor", @readonly = moduleEditModel.Content.ReadOnly, @style = "width:99%; height:360px;" })
}
@if (Model.Mode.Equals("reload")){
@Html.TextAreaFor(model => Model.Content.Data, new { id = "modEditor", @style = "width:99%; height:360px;" })}


text:
Q: Fuzzy index on dataset I'm facing a problem where I need to provide a search functionality where
a user can supply "as much information as he/she knows". This dataset should then be
matched against different lookup tables to determine if I reliably can associate it
against one of our local id's. e.g If we have a record for this search query.
Most of the fields are fuzzy.
Example:
One field could be name (where the user only have the first name) and another street
where the user only have the street number.
The dataset is of medium size (~10M entries).
What is the best approche for this problem? SQL + soundex? lucene?
Thanks!

A: You can score documents in Lucene and compare similarity. Inverted index tool like Lucene should be faster and much more scalable than traditional key-value lookups in SQL.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Join multiple secondary tables I have following tables:
master_table(id, col1, col2, discriminator_col)

join_table1(m_id, v_id)
value_table1(id, val)

join_table2(m_id, v_id)
value_table2(id, val)

there is single master table and several value tables joined to master table via join tables. Value tables contain single scalar value for each master_table row. Values from separate values tables are placed into descendant entities, so there are one MasterEntity and several Child1Entity, Child2Entity etc.
I would like not to create a separate entity for each value_table, just for each ChildEntity and somehow join value table to that entity.
MasterEntity:
@Entity
@Inheritance(...) // not sure what type of inheritance to use
public class MasterEntity {
    @Id
    private int id;

    private String col1;

    private String col2;
}

Child1Entity:
@Entity
public class Child1Entity extends MasterEntity {

    // need to get value_table1.val column here

}

I could create entity for value_table and add many-to-one relation to Child1Entity, but if it is possible to avoid I would like to do that.
I tried to add two secondary tables (join_table1, value_table1) to Child1Entity, but I can not join join_table1 with value_table1, just with master_table.

A: If you want to use @Inheritance, you can't have those join_tables. With those join tables, your model says:

*

*one value can belong to multiple master rows

*one master row can belong to multiple value rows
If you just want: 1 master belongs to 1 value row, than use this:
master (id, ...)
value1 (masterId, ...)
value2 (masterId, ...)

With @Inheritance(strategy=InheritanceType.JOINED).
For more information have a look here: http://en.wikibooks.org/wiki/Java_Persistence/Inheritance
BUT: Whenever you use @Inheritance you will have to create a separate @Entity class for everything.

If you really need the 5 table layout from above, use @ManyToMany.

Basically JPA is made for Mapping Java Objects to SQL Tables, not the other way round ;) If you need to do thing's which aren't possible using JPA (or too complicated), you can always use JDBC and craft your queries and Entity mappings by hand.


text:
Q: Return true to jquery from php file I was looking at this question: Return true/false to javascript from php file
But is not what I'm looking for, as I don't need to return text/strings in JSON.
What I want is to return true or false statements from loaded php file to jQuery.
jQuery: (How I think it could work)
if($("#lvlupann").load("/templ/checknlvl.php") == true){
                        $("#lvlupann").addClass("nlvlann");
                    }

And the mighty php file : (checknlvl.php)
if(1 == 1){
        return true;
    }

But obviously it doesn't return true/false, and class is not added... I know I'm going probably wrong on it, but don't know what to overwrite...
Any help would be appreciated.

A: You are doing it wrong.
The .load() method is asynchronous and does not return the value from the server (it returns the element that it was called on: $("#lvlupann")), so using the returned value in an if statement does not make sense.
You have to wait for the request to finish before you can use the value, like so:
$("#lvlupann").load("/templ/checknlvl.php", function (value) {
    if (value == true) {
        $("#lvlupann").addClass("nlvlann");
    }
});

As for the PHP file, the return true; will just stop the script. It does not send anything to the client. In order to send two or more things from PHP to the client you need to package the output in some fashion.
The $.get method would be useful:
$.get('/templ/checknlvl.php').done(function (data) {
    $("#lvlupann").html(data.content);
    if (data.success) {
        $("#lvlupann").addClass("nlvlann");
    }
});

<?php
echo json_encode([
    'content' => 'Some content...',
    'success' => true,
]);
die;

If all you want to do is get a boolean value from the PHP script then something like this would do it:
$.get('/templ/checknlvl.php').done(function (value) {
    if (value === "true") {
        $("#lvlupann").addClass("nlvlann");
    }
});

<?php
if (1 == 1) {
    echo 'true';
} else {
    echo 'false';
}
die;


text:
Q: How to enable code completion for custom modules in PyCharm? When I import a module such as numpy by typing import numpy as np, and then start typing np.... Pycharm auto-completes the code and shows suggestions.
But when I import a custom module that I built (import my_module as md), typing md.... doesn't show up the inner attributes of the module (although completing the code manually works and runs successfully). How can this be achieved?

A: You need to mark(Mark Directory as) folder with your package as Sources Root.

Steps:
Right click on folder -> Mark Directory as -> Sources Root
UPD: Also if folder does presented in project scope, open Preferences -> Project -> Project Structure -> Add Content Root -> And mark folder containing your module as Sources


text:
Q: No response received within reply timeout. Timeout was 5000ms (~5s). Used filter: No filter used or filter was 'null' I am trying to implement chat messenger using ejabberd. I am following this tutorial
https://github.com/Shubhank101/iOSAndroidChaosOverFlow-Projects/tree/master/Chat%20Application%20Using%20Xmpp%20Smack%20Api%20Android%20Tutorial
and getting this error

org.jivesoftware.smack.SmackException$NoResponseException: No response
  received within reply timeout. Timeout was 5000ms (~5s). Used filter:
  No filter used or filter was 'null'.

I am not using localhost. I am using live server.


text:
Q: Does "auto" keyword always evaluates floating point value as double? Continuing the question, which was closed:
C++: "auto" keyword affects math calculations?
As people suggested I modified the code by adding "f" suffix to floating-point values.
#include <cmath>
unsigned int nump=12u;
auto inner=2.5f;
auto outer=6.0f;
auto single=2.f*3.14159265359f/nump;
auto avg=0.5f*inner+0.5f*outer;
for (auto i=0u;i<nump;++i){
    auto theta=i*single;
    auto px=avg*sin(theta);
    auto py=avg*cos(theta);
    auto tw=17.f;
    int v1=std::round(1.f+px-tw/2.0f);
    int v2=std::round(2.f+py-tw/2.0f);
    std::cout<<"#"<<i<<":"<<v1<<";"<<v2<<std::endl;
}

versus
#include <cmath>
unsigned int nump=12u;
float inner=2.5f;
float outer=6.0f;
float single=2.f*3.14159265359f/nump;
float avg=0.5f*inner+0.5f*outer;
for (unsigned int i=0u;i<nump;++i){
    float theta=i*single;
    float px=avg*sin(theta);
    float py=avg*cos(theta);
    float tw=17.f;
    int v1=std::round(1.f+px-tw/2.0f);
    int v2=std::round(2.f+py-tw/2.0f);
    std::cout<<"#"<<i<<":"<<v1<<";"<<v2<<std::endl;
}

The result is exactly the same - output differs between two versions.
So does it mean that "auto" always evaluates floating point value to "double" type?

A: The issue is that your code is using ::sin instead of std::sin (and the same for cos). That is, you're using the sin function found in the global namespace.
std::sin is overloaded for float. But ::sin isn't, and it always returns a double (because ::sin is the legacy C function, and C doesn't have function overloading).
Use std::sin and std::cos in your code to fix the issue.

A: When you use the literal 2.5f you are already suggesting that the value is a float.
You'll see that if you try using 2.5 as literal when assigning value to an auto variable, it deduces this as double.
auto var1 = 2.5   // deduced as type double
auto var2 = 2.5f  // deduced as type float as suggested in literal


text:
Q: Get previous month's data alongside current month I have a table that roughly looks like this
Transaction   Date        Gain/Loss
15464         7/31/2018    $500
15464         6/30/2018   -$200
59872         7/31/2018    $1000
59872         6/30/2018    $2500

How can i add another column that calculates the difference between the current month's gain/loss and the previous month's for each specific transaction number? i.e.
Transaction   Date        Gain/Loss    Change in Gain/Loss
15464         7/31/2018    $500         $700
15464         6/30/2018   -$200        -$200
59872         7/31/2018    $1000       -$1500
59872         6/30/2018    $2500        $2500

A: I think you can use a correlated subquery:
select t.*,
       (select top (1)
        from t as t2
        where t2.transaction = t.transaction and t2.date < t.date
        order by t2.date desc
       ) as prev_gain_loss
from t;

Calculating the difference is just arithmetic.

A: Using your table as a base - and going on the assumption that each month records a single transaction on the last day of the month:
SELECT  T1.Transaction
        , T1.[Date]
        , T1.[Gain/Loss]
        , T2.[Date]
        , T1.[Gain/Loss]-T2.[Gain/Loss] AS [Change in Gain/Loss]
FROM    MyTable T1 LEFT JOIN MyTable T2 ON T1.Transaction = T2.Transaction AND
                                           T1.[Date] = DATESERIAL(YEAR(T2.[Date]), MONTH(T2.[Date])+2,0)

Consider that you have two tables - one displaying the figures for this month, and one displaying the figures for last month.
To join the two tables together you'd look at the Transaction number as the common attribute between the two tables.
The fact that both tables are the same table is irrelevant to Access - as long as it knows which is which by aliasing the table names as T1 and T2.
FROM    MyTable T1 LEFT JOIN MyTable T2 ON T1.Transaction = T2.Transaction
This would give too many records though.  The transaction for July would join to itself in the second table, and to the previous month.
The previous month transaction would also join to itself and the current month transaction.  This results in four records per transaction.
| Transaction | T1.Date    | Gain/Loss | T2.Date    | Change in Gain/Loss |
|-------------|------------|-----------|------------|---------------------|
| 15464       | 31/07/2018 | £500.00   | 30/06/2018 | £700.00             |
| 15464       | 31/07/2018 | £500.00   | 31/07/2018 | £0.00               |
| 15464       | 30/06/2018 | -£200.00  | 30/06/2018 | £0.00               |
| 15464       | 30/06/2018 | -£200.00  | 31/07/2018 | -£700.00            |
| 59872       | 31/07/2018 | £1,000.00 | 30/06/2018 | -£1,500.00          |
| 59872       | 31/07/2018 | £1,000.00 | 31/07/2018 | £0.00               |
| 59872       | 30/06/2018 | £2,500.00 | 30/06/2018 | £0.00               |
| 59872       | 30/06/2018 | £2,500.00 | 31/07/2018 | £1,500.00           |

To only perform the calculation on the previous month figure we need to join the current month to the previous month.
T1.[Date] = DATESERIAL(YEAR(T2.[Date]), MONTH(T2.[Date])+2,0)
The DATESERIAL calculation in this join adds two months to the date, it then returns day zero of the second month which is equivalent to the last day of the month before that. (Hope that made sense).
| Transaction | Date       | Gain/Loss | Change in Gain/Loss |
|-------------|------------|-----------|---------------------|
| 15464       | 31/07/2018 | £500.00   | £700.00             |
| 15464       | 30/06/2018 | -£200.00  |                     |
| 59872       | 31/07/2018 | £1,000.00 | -£1,500.00          |
| 59872       | 30/06/2018 | £2,500.00 |                     |

If you must have figures in the starting month then you can use NZ to turn the NULL values to 0.
, T1.[Gain/Loss]-NZ(T2.[Gain/Loss],0) AS [Change in Gain/Loss]
| Transaction | Date       | Gain/Loss | Change in Gain/Loss |
|-------------|------------|-----------|---------------------|
| 15464       | 31/07/2018 | £500.00   | £700.00             |
| 15464       | 30/06/2018 | -£200.00  | -£200.00            |
| 59872       | 31/07/2018 | £1,000.00 | -£1,500.00          |
| 59872       | 30/06/2018 | £2,500.00 | £2,500.00           |


text:
Q: Calculating subsection total in a table I am newbie to XSLT and I have a problem on calculating the subsection totals in a table. I am using XSLT 1.0. I am able to get the Grand Total from XML, but getting subsections has lot of ifs/else and conditions which its difficult to explain.
Please find the sample table and XML below.
So what am trying to do is compare the Document 1 to Document 2.
If the Recno matches in both document then those record goes into "Same".
If a Rec is there in Document1 and not in Document2 then it will go to "Add" section.
If a Rec is there in Document2 and not in Document1 then it will go to "Delete" section.
I tried searching everywhere but no luck so far. Any pointers are appreciated
My Output HTML Table should look like this:
----------------------------------------------------------------
Section         RecNo         Desc          Qty         Value
----------------------------------------------------------------
Same             111        Desc1           1           $100.00
Same             444        Desc1           1           $200.00
Same             123        Desc1           1           $300.00
---------------------------------------------------------------
                          Same Total                    $600.00
---------------------------------------------------------------
Add             555         Desc1           1           $100.00
Add             999         Desc1           1           $100.00
---------------------------------------------------------------
                           Add Total                    $200.00
---------------------------------------------------------------
Delete          777         Desc1           1           $200.00
Delete          888         Desc1           1           $200.00
---------------------------------------------------------------
                           Delete Total                 $400.00
---------------------------------------------------------------
                         Grand Total                    $1200.00

Here is my XML
<?xml version="1.0" encoding="utf-8"?>
<Logia xmlns="com.configsc">
  <DocHeader xmlns="com.configsc.docheader">
        <Document>
            <Downto>
                <rec_no>111</rec_no>
                <desc>Desc1</desc>
                <qty>1</qty>
                <Value>$200.00</Value>
            </Downto>
            <Downto>
                <rec_no>333</rec_no>
                <desc>Desc1</desc>
                <qty>1</qty>
                <Value>$200.00</Value>
            </Downto>
            <Downto>
                <rec_no>444</rec_no>
                <desc>Desc1</desc>
                <qty>1</qty>
                <Value>$200.00</Value>
            </Downto>
            <Downto>
                <rec_no>555</rec_no>
                <desc>Desc1</desc>
                <qty>1</qty>
                <Value>$200.00</Value>
            </Downto>
            <Downto>
                <rec_no>123</rec_no>
                <desc>Desc1</desc>
                <qty>1</qty>
                <Value>$300.00</Value>
            </Downto>
        </Document>
        <Document>

            <Downto>
                <rec_no>222</rec_no>
                <desc>Desc1</desc>
                <qty>1</qty>
                <Value>$200.00</Value>
            </Downto>
            <Downto>
                <rec_no>111</rec_no>
                <desc>Desc1</desc>
                <qty>1</qty>
                <Value>$200.00</Value>
            </Downto>
            <Downto>
                <rec_no>444</rec_no>
                <desc>Desc1</desc>
                <qty>1</qty>
                <Value>$200.00</Value>
            </Downto>
            <Downto>
                <rec_no>777</rec_no>
                <desc>Desc1</desc>
                <qty>1</qty>
                <Value>$200.00</Value>
            </Downto>
            <Downto>
                <rec_no>888</rec_no>
                <desc>Desc1</desc>
                <qty>1</qty>
                <Value>$200.00</Value>
            </Downto>
            <Downto>
                <rec_no>111</rec_no>
                <desc>Desc1</desc>
                <qty>1</qty>
                <Value>$200.00</Value>
            </Downto>
             <Downto>
                <rec_no>123</rec_no>
                <desc>Desc1</desc>
                <qty>1</qty>
                <Value>$300.00</Value>
            </Downto>
        </Document>
    </Material>
  </DocHeader>
</Logia>

A: I am afraid this may be a little too much for a single SO question. I have decided to simplify your input to the following:
<Logia>
  <DocHeader>
        <Document>
            <Downto>
                <rec_no>111</rec_no>
                <desc>Desc1</desc>
                <qty>1</qty>
                <Value>100.00</Value>
            </Downto>
            <Downto>
                <rec_no>333</rec_no>
                <desc>Desc3</desc>
                <qty>3</qty>
                <Value>300.00</Value>
            </Downto>
            <Downto>
                <rec_no>444</rec_no>
                <desc>Desc4</desc>
                <qty>4</qty>
                <Value>400.00</Value>
            </Downto>
            <Downto>
                <rec_no>555</rec_no>
                <desc>Desc5</desc>
                <qty>5</qty>
                <Value>500.00</Value>
            </Downto>
        </Document>
        <Document>
            <Downto>
                <rec_no>222</rec_no>
                <desc>Desc2</desc>
                <qty>2</qty>
                <Value>200.00</Value>
            </Downto>
            <Downto>
                <rec_no>111</rec_no>
                <desc>Desc1</desc>
                <qty>1</qty>
                <Value>100.00</Value>
            </Downto>
            <Downto>
                <rec_no>444</rec_no>
                <desc>Desc4</desc>
                <qty>4</qty>
                <Value>400.00</Value>
            </Downto>
            <Downto>
                <rec_no>777</rec_no>
                <desc>Desc7</desc>
                <qty>7</qty>
                <Value>700.00</Value>
            </Downto>
            <Downto>
                <rec_no>888</rec_no>
                <desc>Desc8</desc>
                <qty>8</qty>
                <Value>800.00</Value>
            </Downto>
         </Document>
  </DocHeader>
</Logia>

Note the removal of namespaces and the conversion of Value values to numbers.
Applying the following stylesheet:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" omit-xml-declaration="yes" version="1.0" encoding="utf-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:key name="doc1" match="Document[1]/Downto" use="rec_no" />
<xsl:key name="doc2" match="Document[2]/Downto" use="rec_no" />

<xsl:template match="/Logia/DocHeader">

            Section
            RecNo
            Desc
            Qty
            Value

        <xsl:variable name="same" select="Document[1]/Downto[key('doc2', rec_no )]" />
        <xsl:apply-templates select="$same">
            <xsl:with-param name="section">Same</xsl:with-param>
        </xsl:apply-templates>
        <xsl:variable name="same-total" select="sum($same/Value)" />

            Same Total
            <xsl:value-of select="$same-total"/>

        <xsl:variable name="add" select="Document[1]/Downto[not(key('doc2', rec_no ))]" />
        <xsl:apply-templates select="$add">
            <xsl:with-param name="section">Add</xsl:with-param>
        </xsl:apply-templates>
        <xsl:variable name="add-total" select="sum($add/Value)" />

            Add Total
            <xsl:value-of select="$add-total"/>

        <xsl:variable name="delete" select="Document[2]/Downto[not(key('doc1', rec_no ))]" />
        <xsl:apply-templates select="$delete">
            <xsl:with-param name="section">Delete</xsl:with-param>
        </xsl:apply-templates>

        <xsl:variable name="delete-total" select="sum($delete/Value)" />

            Delete Total
            <xsl:value-of select="$delete-total"/>

            Grand Total
            <xsl:value-of select="$same-total + $add-total + $delete-total"/>

</xsl:template>

<xsl:template match="Downto">
    <xsl:param name="section"/>

        <xsl:value-of select="$section"/>
        <xsl:value-of select="rec_no"/>
        <xsl:value-of select="desc"/>
        <xsl:value-of select="qty"/>
        <xsl:value-of select="Value"/>

</xsl:template>

</xsl:stylesheet>

to the above input will result in:

      Section
      RecNo
      Desc
      Qty
      Value

      Same
      111
      Desc1
      1
      100.00

      Same
      444
      Desc4
      4
      400.00

      Same Total
      500

      Add
      333
      Desc3
      3
      300.00

      Add
      555
      Desc5
      5
      500.00

      Add Total
      800

      Delete
      222
      Desc2
      2
      200.00

      Delete
      777
      Desc7
      7
      700.00

      Delete
      888
      Desc8
      8
      800.00

      Delete Total
      1700

      Grand Total
      3000

rendered as:


text:
Q: C++ pointer gets overwritten in for loops Could someone explain why pointers gets overwritten when variables are declared inside a loop?
For example, given the following snippet, and the user inputs 1 and 2. I would expect that the pNums array contain 2 pointers to 2 integers holding the value 1 and 2 respectively.
But instead, the console prints out 2 and 2;
#include <iostream>
using namespace std;

//Input "1 2"
int main() {
    int* pNums[2];
    for(int i = 0; i < 2; i++){
        int num;
        cin >> num;
        pNums[i] = (&num);
    }
    cout << (*pNums[0]) << endl;
    cout << (*pNums[1]) << endl;
}

Why is this the case? And how do I get around it? What if, for example, we don't know how many numbers the user will put in, and instead of a for loop, we have a while loop? Until some conditions are met, we want to keep creating new pointers and store them into a pNums vector?

A: There is only one num, and you are overwriting that. (And then causing Undefined Behavior, but never mind that.)
There are two simple ways to avoid this mistake.
1) Store objects, not pointers:
int nums[2];
for(int i = 0; i < 2; i++){
    cin >> nums[i];
}

2) Use dynamic allocation:
int* pNums[2];
for(int i = 0; i < 2; i++){
    int *p=new int;
    cin >> *p;
    pNums[i] = p;
}

A: for(int i = 0; i < 2; i++){
    int num; //< this is num. It lives here.
    cin >> num;
    pNums[i] = (&num);  //< you have taken the address of num (twice!)
}
// here is when 'num' is destroyed (no longer in scope)

// so this is now pointing at something that doesn't exist.
cout << (*pNums[0]) << endl;

A: The pointers that you are storing in pNums are to two instances of the variable num in the for block. There is one instance of the variable in each for loop iteration and these variables live only until the end of their respective iteration of the for loop body is reached.
Therefore your pointers will be invalid when the for loop exits and so trying to dereference them with e.g. *pNums[0] causes undefined behavior.
Don't store pointer, store values:
#include <iostream>
using namespace std;

//Input "1 2"
int main() {
    int pNums[2];
    for(int i = 0; i < 2; i++){
        int num;
        cin >> num;
        pNums[i] = num;
    }
    cout << pNums[0] << endl;
    cout << pNums[1] << endl;
}

and if you need a variable number of entries in the array, use std::vector.


text:
Q: How to check in for a value in DB through jquery How can i check in for a value in DB on blur event through jQuery.
I want to display a message if value exist in Data base.
I am using Asp.Net with csharp.

A: Jquery runs on client, so you need to go to the server.
Ajax that calls a WebMethod might work for you

A: you can call C# function from your jQuery function like --
var isExist = <%=GetValueFromDB()%>;
GetValueFromDB in the codebehind should return a string result and you can check it in your jQuery. I hope this helps.
    public string GetValueFromDB()
    {
        if(value is there)
          return "your result";
        return "emptystring";
    }

A: Do a webmethod and then do something along
$('#myInput').onblur(function()
{
  $.get('myurl.aspx', {method : 'checkValue', mvalue : $(this).val()},function(data)
      {
        //handle your response
      });
 });


text:
Q: Webpack - How to set hot-reload (watch files) I'm new to webpack and I am having trouble setting up how to make webpack watch my files as I change things in my code. In other words, I would like to have the page reloads everytime I make a change in my code.
I've read couple blogs on how to do it but I cannot seem to make it work.
As of current I am able to bundle it and host it on my localhost with out a problem.
Here's what I have so far:
webpack.config.js
module.exports = {
  entry: [
    './src/index.js'
  ],
  watch: true,
  output: {
    path: __dirname,
    publicPath: '/',
    filename: 'bundle.js'
  },
  module: {
    loaders: [{
      exclude: /node_modules/,
      loader: 'babel',
      query: {
        presets: ['react', 'es2015', 'stage-1']
      }
    }]
  },
  resolve: {
    extensions: ['', '.js', '.jsx']
  },
  devServer: {
    historyApiFallback: true,
    contentBase: './'
  }
};

package.json
{
  "name": "simple-app",
  "version": "1.0.0",
  "description": "demo",
  "main": "index.js",
  "repository": "",
  "scripts": {
    "start": "node ./node_modules/webpack-dev-server/bin/webpack-dev-server.js",
    "test": "mocha --compilers js:babel-core/register --require ./test/test_helper.js --recursive ./test",
    "test:watch": "npm run test -- --watch"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^6.2.1",
    "babel-loader": "^6.2.0",
    "babel-preset-es2015": "^6.1.18",
    "babel-preset-react": "^6.1.18",
    "chai": "^3.5.0",
    "chai-jquery": "^2.0.0",
    "jquery": "^2.2.1",
    "jsdom": "^8.1.0",
    "mocha": "^2.4.5",
    "react-addons-test-utils": "^0.14.7",
    "webpack": "^1.12.9",
    "webpack-dev-server": "^1.16.2"
  },
  "dependencies": {
    "babel-preset-stage-1": "^6.1.18",
    "lodash": "^3.10.1",
    "react": "^0.14.3",
    "react-dom": "^0.14.3",
    "react-redux": "^4.0.0",
    "react-router": "^2.0.1",
    "redux": "^3.0.4",
    "redux-thunk": "^2.1.0"
  }
}

A: I was able to figure it out what I needed to using react-hot-loader if anyone is interested
http://gaearon.github.io/react-hot-loader/getstarted/


text:
Q: Cant Zoom Desired Level In Google Maps To Fit 2 Directions In Screen (I would want to put screenshots put my reputation is low to put them...)
Good Day.I Have two directions(markers) on google maps api(android) between which i want camera to be center,and camera being centered there.But problem is that one marker comes to one edge of screen and another marker to another edge of screen!I don't want it to be like that,i want just to zoom specified level so markers will be center in google maps view and won't be place on edges of screen.I tried to put even 0 zoom level in camera update factory of google maps,but nothing happens at all.Here is my code how do i achieve that
 } finally {
                    com.google.android.gms.maps.model.LatLngBounds.Builder boundsBuilder = new LatLngBounds.Builder();
                    boundsBuilder.include(new LatLng(Double.parseDouble(tolat), Double.parseDouble(tolong)));
                    boundsBuilder.include(new LatLng(Double.parseDouble(fromlat), Double.parseDouble(fromlong)));
                    final LatLngBounds bounds = boundsBuilder.build();
                    map.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 0));
                }

A: you say you tried to put 0 as the zoom level. You mean this call CameraUpdateFactory.newLatLngBounds(bounds, 0) right?
The second parameter is the padding not the zoom level. Set it up (example to 10) and you have a padding to the outer edges.
https://developers.google.com/android/reference/com/google/android/gms/maps/CameraUpdateFactory
I hope it helps.


text:
Q: Trying for .show() and .hide() not working <div id ="instant-view">
<textarea id="upload-data-text" placeholder="Copy & paste your data here"></textarea>
</div>

<script>
$("#instant-view").hide();
</script>

here the the id "#instant-view" not hiding, i am not getting whats going wrong.
i am using jquery though

A: Wrap your code inside document's ready event like,
$(document).ready(function(){
  $("#instant-view").hide();
})

Working Fiddle

A: Add $(function () {});
<script>
$(function () {
    $("#instant-view").hide();
});
</script>

A: You are missing $(document).ready(function(){});
Use,
$(document).ready(function(){
 $("#instant-view").hide();
});

A: use the code inside document ready
$(document).ready(function(){

$("#instant-view").hide();
});

A: Try this
$(window).load(function() {
    $("#instant-view").hide();
});

A: Firstly, make sure you've included jQuery or reference it properly, normally I'd use Google CDN:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

Secondly, if you put your code at the end of your page then it's fine, but if you place your jQuery code in the <head> section then you need to wrap it inside DOM ready handler $(function() {...}); to make sure all DOM elements have been loaded properly.
$(function() {
    $("#instant-view").hide();
});

Your final code should look something like this:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
    $(function() {
        $("#instant-view").hide();
    });
</script>


text:
Q: Socket time-outs and connection duration exceeding allotted time I am pretty new to Python, C# and socket programming. I have a server that sends data to C# clients. After all the data is sent simultaneously to the currently available clients, I want to close the socket and stop waiting for connections. I would also like to close the socket if waiting for a connection exceeds 2 minutes. I have read about socket select tool in Python but I am not sure if that is the right tool to use in this situation and how to apply it.
Here is my server code:
import socket #for sockets
import sys #for exit
import select
import struct
import binascii
import time
from thread import *

HOST = "192.168.137.99" # IP address of RPi
PORT = 8888 # arbitrary non privileged port
#create a TCP stream = SOCK_STREAM, AF_INET is IPv4
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'

try:
    s.bind((HOST,PORT))
except socket.error, msg:
    print 'Failed to create socket, Error code: ' + str(msg[0]) + ', Error      Error Message : ' + msg[1]
    sys.exit();

print 'Socket bind complete'
s.listen(5)
print 'Socket now listening'
timeout = time.time() + 60
print 'Time now is ' + str(time.time()) + ' and timeout is ' + str(timeout)

strarray = ["0x31\n" "0x31\n" "0x30\n" "0x30\n" "0x31\n" "s\n"] #example data

def clientthread(conn):
    #sending message to connected client
    conn.send('Welcome to server\n')
    for i in range(len(strarray)):
            #packet = struct.pack('1B',1)
            string = strarray[i]
            datas = string.encode()
            conn.send(datas)

    conn.shutdown(2)
    conn.close()

while 1:
    # wait to accept connection
    conn ,addr = s.accept()
    #display client info
    print 'Connected with ' + addr[0] + ': ' + str(addr[1])
    #start new thread takes 1st argument as function name to be run, 2nd is$
    start_new_thread(clientthread ,(conn,))

print 'Closing socket now'
s.close()

Here is the C# client side code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;

namespace sockclient_cs
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                TcpClient tcpclnt = new TcpClient();
                Console.WriteLine("Connecting...");
                tcpclnt.Connect("192.168.137.99", 8888);
                Console.WriteLine("Connected");
                NetworkStream stream = tcpclnt.GetStream();
                byte[] first = new byte[80];
                int k = stream.Read(first, 0, 80);
                for (int i = 0; i < k; i++)
                Console.Write(Convert.ToChar(first[i]));
                bool noexit = true;
                while (noexit)
                {

                    Byte[] bb = new byte[1];
                    String responseData = String.Empty;

                    int bytes = stream.Read(bb, 0, bb.Length);
                    ASCIIEncoding ascii = new ASCIIEncoding();
                    responseData = ascii.GetString(bb, 0, bytes);
                    if (responseData == "s")
                    {
                        noexit = false;
                    }
                    Console.Write(responseData);

                }

                tcpclnt.Close();

            }
            catch (Exception e)
            {
                Console.WriteLine("Error...." + e.StackTrace);
            }
        }
    }
}

Here is the screenshots of the output for both the client and server:
Server - as you can see, the code never terminates:

Client - in this case, the output satisfactory:


text:
Q: Distance from a point to a plane in normed spaces How can we calculate the distance from a point to a plane
in normed spaces ? where we are not inner product, for example:
Calculate the distance in $(C[0,1],||\cdot||)$ endowed with the supremum norm $$||f||=\sup_{t\in[0,1]}|f(t)|$$ from the function $f(t)=t^2$ to the linear hull of the functions $g(t)=t$  and  $h(t)=\sin(t)$
Any hints would be appreciated.


text:
Q: Factorial function - design and test I'm trying to nail down some interview questions, so I stared with a simple one.
Design the factorial function.
This function is a leaf (no dependencies - easly testable), so I made it static inside the helper class.
public static class MathHelper
{
    public static int Factorial(int n)
    {
        Debug.Assert(n >= 0);
        if (n < 0)
        {
            throw new ArgumentException("n cannot be lower that 0");
        }

        Debug.Assert(n <= 12);
        if (n > 12)
        {
            throw new OverflowException("Overflow occurs above 12 factorial");
        }

        int factorialOfN = 1;
        for (int i = 1; i <= n; ++i)
        {
            //checked
            //{
                factorialOfN *= i;
            //}
        }
        return factorialOfN;
    }
}

Testing:
    [TestMethod]
    [ExpectedException(typeof(OverflowException))]
    public void Overflow()
    {
      int temp = FactorialHelper.MathHelper.Factorial(40);
    }

    [TestMethod]
    public void ZeroTest()
    {
        int factorialOfZero = FactorialHelper.MathHelper.Factorial(0);
        Assert.AreEqual(1, factorialOfZero);
    }

    [TestMethod]
    public void FactorialOf5()
    {
       int factOf5 = FactorialHelper.MathHelper.Factorial(5);
       Assert.AreEqual(5*4*3*2*1,factOf5);
    }

    [TestMethod]
    [ExpectedException(typeof(ArgumentException))]
    public void NegativeTest()
    {
        int factOfMinus5 = FactorialHelper.MathHelper.Factorial(-5);
    }

I have a few questions:

*

*Is it correct? (I hope so ;) )

*Does it throw right exceptions?

*Should I use checked context or this trick ( n > 12 ) is ok?

*Is it better to use uint istead of checking for negative values?

*Future improving: Overload for long, decimal, BigInteger or maybe generic method?

Thank you

A: It looks right to me, but it would be inefficient with larger numbers. If you're allowing for big integers, the number will keep growing with each multiply, so you would see a tremendous (asymptotically better) increase in speed if you multiplied them hierarchically. For example:
bigint myFactorial(uint first, uint last)
{
    if (first == last) return first;
    uint mid = first + (last - first)/2;
    return myFactorial(first,mid) * myFactorial(1+mid,last);
}
bigint factorial(uint n)
{
    return myFactorial(2,n);
}

If you really want a fast factorial method, you also might consider something like this:

*

*Factor the factorial with a modified Sieve of Eratosthenes

*Compute the powers of each prime factor using a fast exponentiation algorithm (and fast multiplication and square algorithms)

*Multiply all the powers of primes together hierarchically

A: *

*Yes, it looks right

*The exceptions seem OK to me, and also as an interviewer, I can't see myself being concerned there

*Checked. Also, in an interview, you'd never know that 12 just happened to be the right number.

*Uint. If you can enforce something with a signature instead of an exception, do it.

*You should just make it long (or bigint) and be done with it (int is a silly choice of return types here)

Here are some follow-up questions I'd ask if I were your interviewer:

*

*Why didn't you solve this recursively? Factorial is a naturally recursive problem.

*Can you add memoization to this so that it does a faster job computing 12! if it's already done 11!?

*Do you need the n==0 case here?

As an interviewer, I'd definitely have some curveballs like that to throw at you. In general, I like the approach of practicing with a whiteboard and a mock interviewer, because so much of it is being nimble and thinking on your feet.

A: In the for cycle you can start with for (int i = 2...). Multiplying by 1 is quite useless.
I would have throw a single ArgumentOutOfRangeException for both < 0 and > 12. The Debug.Assert will mask the exception when you are using your unit test (you would have to test it in Release mode).


text:
Q: Filtering Data Table with two models in single view using multiple dropdown I started to created my project using MVC and it's really enjoying to create different projects using mvc.
So I created awhile ago the data table that filters data when you selected value in single dropdown
But I'm still curious about filtering data using multiple dropdown and two models in a single view
What I did... first, I created a class that I can be used to display my two data table using two models
This is my class in mvc
 public class MyData
  {
    public IEnumerable<pmTA_ProjectCategory> ProjectCategory { get; set; }
    public IEnumerable<pmTA_FundCategory> FundCategory { get; set; }
  }

After creating my class, I created a code for two data table using one view for Index and view for partial view to call the two data table
this is the codes for view of Index and view of Partial View which the name is "MyPartialView"
For view of Index:
  @using myProject.Models;
  @model MyData

   @Html.Partial("MyPartialView",Model)

  @if (Model.ProjectCategory != null) {

        id
        title

            description

    @foreach (var item in Model.ProjectCategory)
    {

                @Html.DisplayFor(modelItem => item.id)

                @Html.DisplayFor(modelItem => item.title)

                @Html.DisplayFor(modelItem => item.description)

    }

}

For view of Partial View

            id
            code

                title

                description

            --
            --

        @foreach (var item in Model.FundCategory)

        {
            string selectedRow = "";
            if (item.id == ViewBag.fund)
            {
                selectedRow = "success";
            }

                    @Html.DisplayFor(modelItem => item.id)

                    @Html.DisplayFor(modelItem => item.code)

                    @Html.DisplayFor(modelItem => item.title)

                    @Html.DisplayFor(modelItem => item.description)

                    @Html.ActionLink("Edit", "FundCategoryEdit", new { id =
          item.id }, new { @class = "btn btn-primary" })

                    @Html.ActionLink("Select", "Index", new {
            fund_category_id = item.id }, null)

        }

Inorder to Function my view I created codes in controller to display two data table, I declared the name of my class in the controller
this the codes in my controller, the first code is for the partial view datatable and the second code is for the View Index
for partial:
      var viewModel = new MyData();
        viewModel.FundCategory = (from p in db.pmTA_FundCategory

                                  select new
                                  {
                                      id = p.id,
                                      code = p.code,
                                      title = p.title,
                                      description = p.description,
                                      status = p.status
                                  }).ToList()
                  .Select(x => new pmTA_FundCategory()
                  {
                      id = x.id,
                      code = x.code,
                      title = x.title,
                      description = x.description,
                      status = x.status
                  });

For View of Index
    if (fund_category_id != null)
        {

            ViewBag.fund = fund_category_id.Value;
            viewModel.ProjectCategory = (from p in db.pmTA_ProjectCategory
                          join g in db.pmTA_FundCategory
                           on p.fund_category_id equals g.id
                          where p.fund_category_id == fund_category_id
                          select new
                          {
                              id = p.id,
                              title = p.title,
                              description = p.description,
                              title1 = g.title,
                              status = p.status
                          }).ToList()
               .Select(x => new pmTA_ProjectCategory()
               {
                   id = x.id,
                   title = x.title,
                   description = x.description,
                   title1 = x.title1,
                   status = x.status

               });

        }

        return View(viewModel);

They are together in the Index controller but I seperated it in order you to understand my codes
The purpose of the if condition there is for the displaying of my View Index Data table when click the "Select" button of the partial data table based on there ID, you can use the codes above as your reference for showing another data table using other data table...
To display my multiple drop down I always used this codes
Codes for View of Index to display dropdowns

     @Html.DropDownList("id", ViewBag.funds as SelectList, "Select...", new
     { @class = "form-control" })

     @Html.DropDownList("projectcat", ViewBag.proj as SelectList,
    "Select...", new
     { @class = "form-control" })

Codes for dropdown in controller to display the data inside of it based on the database data
for first and second dropdown
     var data1 = from p in db.pmTA_FundCategory

                    select new
                    {
                        id = p.id,
                        code = p.code,
                        title = p.title,
                        description = p.description
                    };

        SelectList list = new SelectList(data1, "id", "title");
         ViewBag.funds = list;

     var data2 = from p in db.pmTA_ProjectCategory

                    select new
                    {
                        id = p.id,
                        title = p.title,
                        description = p.description
                    };

        SelectList list1 = new SelectList(data2, "id", "title");
        ViewBag.proj = list1;

The problem is... How I gonna filter my Partial Data table using multiple drop down without using any plugins but with the help of javascript or any method to filter the data of data table?
Once I selected the value of my multiple dropdown my Partial Data table will display the data corresponds to the multiple dropdown selected...

A: Multiple Table with Multiple Drop Down
1) Add two drop down in your main view like

    @Html.DropDownList("id", (List<SelectListItem>)ViewBag.proj, "--Select id--", new { @onchange = "CallChangefunc1(this.value)" })

    @Html.DropDownList("id", (List<SelectListItem>)ViewBag.funds, "--Select id--", new { @onchange = "CallChangefunc2(this.value)" })

2) Add two partial view 1st with name _GetProjectCategory.cshtml and 2nd with name _GetFundCategory.cshtml
Make sure that
1st partial view @model will be of type @model IEnumerable<WebApplicationMVC1.Controllers.ProjectCategory>
2nd partial view @model will be of type @model IEnumerable<WebApplicationMVC1.Controllers.FundCategory>
Simply add your content in respective partial view.
Make sure both of your partial view contains.
@foreach (var item in Model) { //You table contents }

3) Call both partial view in your main view like

    @{Html.RenderPartial("_GetProjectCategory", Model.ProjectCategories);}

    @{Html.RenderPartial("_GetFundCategory", Model.FundCategories);}

4) Then create a view model like
public class ProjectFundViewModel
{
    public List<ProjectCategory> ProjectCategories { get; set; }
    public List<FundCategory> FundCategories { get; set; }
}

5) Your action method will be (Its sample code and replace by your code).
public ActionResult Index()
{
    //The below query replace by yours
    var projects = db.ProjectCategories.ToList();

    List<SelectListItem> dropDownItems1 = projects.Select(c => new SelectListItem { Text = c.title, Value = c.id.ToString() }).ToList();
    ViewBag.proj = dropDownItems1;

    //The below query replace by yours
    var funds = db.FundCategories.ToList();

    List<SelectListItem> dropDownItems2 = funds.Select(c => new SelectListItem { Text = c.title, Value = c.id.ToString() }).ToList();
    ViewBag.funds = dropDownItems2;

    ProjectFundViewModel viewModel = new ProjectFundViewModel
    {
        ProjectCategories = projects,
        FundCategories = funds
    };

    return View(viewModel);
}

6) Add ajax call to your main view that called when you change any option in respective drop down

7) And finally your ajax call hit below action method that can render respective partial view.
public PartialViewResult GetProjectCategory(int id)
{
    var projects = db.ProjectCategories.ToList();
    var model = projects.Where(x => x.id == id).ToList();
    return PartialView("_GetProjectCategory", model);
}

public PartialViewResult GetFundCategory(int id)
{
    var funds = db.FundCategories.ToList();
    var model = funds.Where(x => x.id == id).ToList();
    return PartialView("_GetFundCategory", model);
}

8) Make sure your main view @model is @model WebApplicationMVC1.Controllers.ProjectFundViewModel not IEnumerable.
Single Table with Multiple Drop Down
1) Add two drop down in your main view with id

    @Html.DropDownList("id", (List<SelectListItem>)ViewBag.ids, "--Select id--", new { @onchange = "CallChangefunc1(this.value)", @id = "dropdown1" })

    @Html.DropDownList("title", (List<SelectListItem>)ViewBag.titles, "--Select title--", new { @onchange = "CallChangefunc2(this.value)", @id = "dropdown2" })

2) Add partial view with name GetFilteredData.cshtml with model @model IEnumerable<WebApplicationMVC1.Controllers.ProjectCategory>.
Make sure your partial view contains.
@foreach (var item in Model) { //You table contents }

3) Call your partial view in main view like

    @{Html.RenderPartial("GetFilteredData", Model.ProjectCategories);}

4) Now your first drop down contains ids and second drop down contains titles from projects category.
public ActionResult Index()
{
    var projects = db.ProjectCategories.ToList();

    List<SelectListItem> dropDownItems1 = projects.Select(c => new SelectListItem { Text = c.id.ToString(), Value = c.id.ToString() }).ToList();
    ViewBag.ids = dropDownItems1;

    List<SelectListItem> dropDownItems2 = projects.Select(c => new SelectListItem { Text = c.title, Value = c.title }).ToList();
    ViewBag.titles = dropDownItems2;

    ProjectFundViewModel viewModel = new ProjectFundViewModel
    {
        ProjectCategories = projects,
    };

    return View(viewModel);
}

5) Add ajax call from main view like

6) And finally your ajax call hit below action method with 2 parameters.
public PartialViewResult GetFilteredData(int? id, string title)
{
    var query = db.ProjectCategories.ToList();

    if (id != null)
        query = query.Where(x => x.id == id).ToList();

    if (!string.IsNullOrEmpty(title))
        query = query.Where(x => x.title == title).ToList();

    return PartialView("GetFilteredData", query);
}


text:
Q: Tikz overlay not working as desired in beamer Consider the following MWE:
 % !TeX program = lualatex
    \documentclass{beamer}
    \usepackage{tikz-feynman}
    \usetheme{metropolis}
    \title{A minimal example}
    \date{\today}
    \author{Matthias Vogelgesang}
    \institute{Centre for Modern Beamer Themes}
    \begin{document}
      \maketitle
      \section{First Section}
      \begin{frame}{First Frame}
       \begin{figure}[H]
    \begin{tabular}{cc}
        \multicolumn{2}{c}{\tikzfeynmanset{
                every plain={blue},
            }
            \feynmandiagram[scale=.5,transform shape] [small, horizontal=a to t1,remember picture] {
                a  -- [plain] t1
                -- [scalar,red] t2
                --[plain]t3
                -- [plain]t1,
                t2 -- [plain] p1 ,
                t3 -- [plain] p2,
            };
            \tikz[overlay,remember picture]{\path (t1) --(t2) coordinate[midway] (m1);
                \draw[thick,red] (m1) --(t1);
            }
        }\\
        \multicolumn{2}{c}{(a) $C_{PRR}$}\\[6pt]
        \tikzfeynmanset{
            every plain={blue},
        }
        \feynmandiagram[scale=.5,transform shape] [small, horizontal=a to t1,remember picture] {
            a  -- [plain] t1
            -- [scalar,red] t2
            --[scalar,red]t3
            -- [plain]t1,
            t2 -- [plain] p1 ,
            t3 -- [plain] p2,
        };
        \tikz[overlay,remember picture]{\path (t1) --(t2) coordinate[midway] (m1);
            \draw[thick,red] (m1) --(t1);
        }
        \tikz[overlay,remember picture]{\path (t2) --(t3) coordinate[midway] (m2);
            \draw[thick,red] (m2) --(t3);
        } &   \tikzfeynmanset{
            every plain={blue},
        }
        \feynmandiagram[scale=.5,transform shape] [small, horizontal=a to t1,remember picture] {
            a  -- [plain] t1
            -- [scalar,red] t2
            --[scalar,red]t3
            -- [plain]t1,
            t2 -- [plain] p1 ,
            t3 -- [plain] p2,
        };
        \tikz[overlay,remember picture]{\path (t1) --(t2) coordinate[midway] (m1);
            \draw[thick,red] (m1) --(t1);
        }
        \tikz[overlay,remember picture]{\path (t2) --(t3) coordinate[midway] (m2);
            \draw[thick,red] (m2) --(t2);
        }
        \\
        (b) $ C_{PMR} $ & (c) $ C_{PPR} $ \\[6pt]
        \tikzfeynmanset{
            every plain={blue},
        }
        \feynmandiagram[scale=.5,transform shape] [small, horizontal=a to t1,remember picture] {
            a  -- [plain] t1
            -- [scalar,red] t2
            --[scalar,red]t3
            -- [scalar,red]t1,
            t2 -- [plain] p1 ,
            t3 -- [plain] p2,
        };
        \tikz[overlay,remember picture]{\path (t1) --(t2) coordinate[midway] (m1);
            \draw[thick,red] (m1) --(t1);
        }
        \tikz[overlay,remember picture]{\path (t2) --(t3) coordinate[midway] (m2);
            \draw[thick,red] (m2) --(t2);
        }
        \tikz[overlay,remember picture]{\path (t3) --(t1) coordinate[midway] (m3);
            \draw[thick,red] (m3) --(t3);
        }
        &       \tikzfeynmanset{
            every plain={blue},
        }
        \feynmandiagram[scale=.5,transform shape] [small, horizontal=a to t1,remember picture] {
            a  -- [plain] t1
            -- [scalar,red] t2
            --[scalar,red]t3
            -- [scalar,red]t1,
            t2 -- [plain] p1 ,
            t3 -- [plain] p2,
        };
        \tikz[overlay,remember picture]{\path (t1) --(t2) coordinate[midway] (m1);
            \draw[thick,red] (m1) --(t1);
        }
        \tikz[overlay,remember picture]{\path (t2) --(t3) coordinate[midway] (m2);
            \draw[thick,red] (m2) --(t3);
        }
        \tikz[overlay,remember picture]{\path (t3) --(t1) coordinate[midway] (m3);
            \draw[thick,red] (m3) --(t3);
        } \\
        (d) $C_{PPP}$ & (e) $ C_{PMP} $
    \end{tabular}
    %   \caption{caption}
\end{figure}
\end{frame}
\end{document}

The above produces the following diagram:

As you can see the overlay are all stacked in the bottom left corner of the slide instead of being applied to each diagram individually. Note that this problem doesn't happen in an article or a book document class.
How to get the overlay to be applied correctly?

A: Your code can be repaired by simply adding
\tikzset{every picture/.append style={remember picture}}

at the beginning of your document. All the remember pictures thus become redundant,
    \documentclass{beamer}
    \usepackage{tikz-feynman}
    \usetheme{metropolis}
    \title{A minimal example}
    \date{\today}
    \author{Matthias Vogelgesang}
    \institute{Centre for Modern Beamer Themes}
    \tikzset{every picture/.append style={remember picture}}
    \begin{document}
      \maketitle
      \section{First Section}
      \begin{frame}{First Frame}
       \begin{figure}[H]
    \begin{tabular}{cc}
        \multicolumn{2}{c}{\tikzfeynmanset{
                every plain={blue},
            }
            \feynmandiagram[scale=.5,transform shape] [small, horizontal=a to t1] {
                a  -- [plain] t1
                -- [scalar,red] t2
                --[plain]t3
                -- [plain]t1,
                t2 -- [plain] p1 ,
                t3 -- [plain] p2,
            };
            \tikz[overlay]{\path (t1) --(t2) coordinate[midway] (m1);
                \draw[thick,red] (m1) --(t1);
            }
        }\\
        \multicolumn{2}{c}{(a) $C_{PRR}$}\\[6pt]
        \tikzfeynmanset{
            every plain={blue},
        }
        \feynmandiagram[scale=.5,transform shape] [small, horizontal=a to t1] {
            a  -- [plain] t1
            -- [scalar,red] t2
            --[scalar,red]t3
            -- [plain]t1,
            t2 -- [plain] p1 ,
            t3 -- [plain] p2,
        };
        \tikz[overlay]{\path (t1) --(t2) coordinate[midway] (m1);
            \draw[thick,red] (m1) --(t1);
        }
        \tikz[overlay]{\path (t2) --(t3) coordinate[midway] (m2);
            \draw[thick,red] (m2) --(t3);
        } &   \tikzfeynmanset{
            every plain={blue},
        }
        \feynmandiagram[scale=.5,transform shape] [small, horizontal=a to t1] {
            a  -- [plain] t1
            -- [scalar,red] t2
            --[scalar,red]t3
            -- [plain]t1,
            t2 -- [plain] p1 ,
            t3 -- [plain] p2,
        };
        \tikz[overlay]{\path (t1) --(t2) coordinate[midway] (m1);
            \draw[thick,red] (m1) --(t1);
        }
        \tikz[overlay]{\path (t2) --(t3) coordinate[midway] (m2);
            \draw[thick,red] (m2) --(t2);
        }
        \\
        (b) $ C_{PMR} $ & (c) $ C_{PPR} $ \\[6pt]
        \tikzfeynmanset{
            every plain={blue},
        }
        \feynmandiagram[scale=.5,transform shape] [small, horizontal=a to t1] {
            a  -- [plain] t1
            -- [scalar,red] t2
            --[scalar,red]t3
            -- [scalar,red]t1,
            t2 -- [plain] p1 ,
            t3 -- [plain] p2,
        };
        \tikz[overlay]{\path (t1) --(t2) coordinate[midway] (m1);
            \draw[thick,red] (m1) --(t1);
        }
        \tikz[overlay]{\path (t2) --(t3) coordinate[midway] (m2);
            \draw[thick,red] (m2) --(t2);
        }
        \tikz[overlay]{\path (t3) --(t1) coordinate[midway] (m3);
            \draw[thick,red] (m3) --(t3);
        }
        &       \tikzfeynmanset{
            every plain={blue},
        }
        \feynmandiagram[scale=.5,transform shape] [small, horizontal=a to t1] {
            a  -- [plain] t1
            -- [scalar,red] t2
            --[scalar,red]t3
            -- [scalar,red]t1,
            t2 -- [plain] p1 ,
            t3 -- [plain] p2,
        };
        \tikz[overlay]{\path (t1) --(t2) coordinate[midway] (m1);
            \draw[thick,red] (m1) --(t1);
        }
        \tikz[overlay]{\path (t2) --(t3) coordinate[midway] (m2);
            \draw[thick,red] (m2) --(t3);
        }
        \tikz[overlay]{\path (t3) --(t1) coordinate[midway] (m3);
            \draw[thick,red] (m3) --(t3);
        } \\
        (d) $C_{PPP}$ & (e) $ C_{PMP} $
    \end{tabular}
    %   \caption{caption}
\end{figure}
\end{frame}
\end{document}

The reason why your code didn't work was that the vertices inside the Feynman diagrams didn't get remembered correctly.
EDIT: Just for completeness: there is an arguably much more straightforward way of producing the same output: just define an "new" style
\tikzset{semidashed straight line/.style={dashed,postaction={decorate,decoration={markings,
         mark=at position 0 with {\coordinate (X0); },
         mark=at position 0.5 with {\draw[thick,solid] (X0) -- (0,0); }}}}}

This way you do not need any overlays. (In your example, you could further simplify that by setting all scalars to this style, like you do repeatedly for the solid lines, but I personally would not do that because you may need a real scalar somewhere.)
    \documentclass{beamer}
    \usepackage{tikz-feynman}
    \usetikzlibrary{decorations.markings}
    \usetheme{metropolis}
    \title{A minimal example}
    \date{\today}
    \author{Matthias Vogelgesang}
    \institute{Centre for Modern Beamer Themes}
    \tikzset{semidashed straight line/.style={dashed,postaction={decorate,decoration={markings,
     mark=at position 0 with {\coordinate (X0); },
     mark=at position 0.5 with {\draw[thick,solid] (X0) -- (0,0); }}}}}
    \begin{document}
      \maketitle
      \section{First Section}
      \begin{frame}{First Frame}
       \begin{figure}[H]
    \begin{tabular}{cc}
        \multicolumn{2}{c}{\tikzfeynmanset{
                every plain={blue},
            }
            \feynmandiagram[scale=.5,transform shape] [small, horizontal=a to t1] {
                a  -- [plain] t1
                -- [semidashed straight line,red] t2
                --[plain]t3
                -- [plain]t1,
                t2 -- [plain] p1 ,
                t3 -- [plain] p2,
            };
        }\\
        \multicolumn{2}{c}{(a) $C_{PRR}$}\\[6pt]
        \tikzfeynmanset{
            every plain={blue},
        }
        \feynmandiagram[scale=.5,transform shape] [small, horizontal=a to t1] {
            a  -- [plain] t1
            -- [semidashed straight line,red] t2
            --[semidashed straight line,red]t3
            -- [plain]t1,
            t2 -- [plain] p1 ,
            t3 -- [plain] p2,
        };
        &   \tikzfeynmanset{
            every plain={blue},
        }
        \feynmandiagram[scale=.5,transform shape] [small, horizontal=a to t1] {
            a  -- [plain] t1
            -- [semidashed straight line,red] t2
            --[semidashed straight line,red]t3
            -- [plain]t1,
            t2 -- [plain] p1 ,
            t3 -- [plain] p2,
        };
        \\
        (b) $ C_{PMR} $ & (c) $ C_{PPR} $ \\[6pt]
        \tikzfeynmanset{
            every plain={blue},
        }
        \feynmandiagram[scale=.5,transform shape] [small, horizontal=a to t1] {
            a  -- [plain] t1
            -- [semidashed straight line,,red] t2
            -- [semidashed straight line,red]t3
            -- [semidashed straight line,red]t1,
            t2 -- [plain] p1 ,
            t3 -- [plain] p2,
        };
        &       \tikzfeynmanset{
            every plain={blue},
        }
        \feynmandiagram[scale=.5,transform shape] [small, horizontal=a to t1] {
            a  -- [plain] t1
            -- [semidashed straight line,red] t2
            --[semidashed straight line,red]t3
            -- [semidashed straight line,red]t1,
            t2 -- [plain] p1 ,
            t3 -- [plain] p2,
        };\\
        (d) $C_{PPP}$ & (e) $ C_{PMP} $
    \end{tabular}
    %   \caption{caption}
\end{figure}
\end{frame}
\end{document}


text:
Q: MQTT Configuration File Mosquitto on Azure Ubunutu VM I'm following this tutorial to configure mosquitto.
This means that I'm storing my local configuration in /etc/mosquitto/conf.d/default.conf. However, I've just now realized that I can put any password/username and it will access mosquitto meaning my config file isn't taken into account. I've just now discovered the /etc/mosquitto/mosquitto.conf and its content can be seen below:
# Place your local configuration in /etc/mosquitto/conf.d/
#
# A full description of the configuration file is at
# /usr/share/doc/mosquitto/examples/mosquitto.conf.example

pid_file /var/run/mosquitto.pid

persistence true
persistence_location /var/lib/mosquitto/

log_dest file /var/log/mosquitto/mosquitto.log

include_dir /etc/mosquitto/conf.d

The contents of my configuration file that I want to use /etc/mosquitto/conf.d/default.conf can be seen below.
allow_anonymous false
password_file /etc/mosquitto/passwd

listener 1883

listener 8883
certfile /etc/letsencrypt/live/20.56.xxx.xxx/cert.pem
cafile /etc/letsencrypt/live/20.56.xxx.xxx/chain.pem
keyfile /etc/letsencrypt/live/20.56.xxx.xxx/privkey.pem

Using the command sudo pkill mosquitto and then sudo mosquitto -c /etc/mosquitto/conf.d -d I stopped mosquitto and restarted it in the background running the new configuration file. When I first ran it (using the /etc/mosquitto/conf.d/default.conf shown above), I got the Error: Connection Refused. I then modified the /etc/mosquitto/conf.d/default.conf file, killed mosquitto and ran it again using the same techinque. The new config file can be seen below.
allow_anonymous false
password_file /etc/mosquitto/passwd

listener 1883

For this version, the password and username protection works!!
Here are the logs for those operations
1610537764: mosquitto version 1.4.15 (build date Tue, 18 Jun 2019 11:42:22 -0300) starting
1610537764: Config loaded from /etc/mosquitto/mosquitto.conf.
1610537764: Opening ipv4 listen socket on port 1883.
1610537764: Opening ipv6 listen socket on port 1883.
1610537764: Opening ipv4 listen socket on port 8883.
1610537764: Opening ipv6 listen socket on port 8883.
1610537764: Error: Unable to load CA certificates. Check cafile "/etc/letsencrypt/live/20.56.121.212/chain.pem".
1610537909: mosquitto version 1.4.15 (build date Tue, 18 Jun 2019 11:42:22 -0300) starting
1610537909: Config loaded from /etc/mosquitto/mosquitto.conf.
1610537909: Opening ipv4 listen socket on port 1883.
1610537909: Opening ipv6 listen socket on port 1883.
1610537909: Opening ipv4 listen socket on port 8883.
1610537909: Opening ipv6 listen socket on port 8883.
1610537912: New connection from xx.xx.2.13 on port 1883.
1610537912: New client connected from xx.xx.2.13 as mqtt_f1f0a02.f7e396 (c1, k60, u'bigBoiTeam').
1610538010: mosquitto version 1.4.15 terminating


text:
Q: How to toggle form element visibility in Play framework 2.0? For example I have some form which looks like this:
@main{
    <fieldset>
    @inputText(myForm"Id"),'_label -> "Id")
    @checkbox(myForm("isEnabled"))
    @inputText(myForm("someOptionvalue"))
    </fieldset>
}

What I need is that if isEnabled is checked - someOptionValue inputText should be shown.
This checkbox is just an example and it can be any other element. I want to know how to show\hide elements depending on other elements. Sorry for my bad English. I hope somebody can help.
add I think  I should use java script but i don't know how inject js functions in play view templates

A: The Play's form elements you used are Play Scala templates used to generate plain html.
For your purposes I think you should just use javascript the way you would any html form. An example would be:
<script type="text/javascript">
  window.onload = function(e) {
    document.getElementById("myCheck").onclick = function() {
      showHideElement();
    };
    showHideElement();
  }

  function showHideElement() {
    var checked = document.getElementById("myCheck").checked;
    var el = document.getElementById("myOptionValue");
    if (checked) {
      el.style.display = 'block'
    } else {
      el.style.display = 'none'
    }
  }
</script>

Your checkbox and input text template should both have id attributes added to them, example:
  @checkbox(myForm("isEnabled"), 'id -> "myCheck")
  @inputText(myForm("someOptionvalue"), 'id -> "myOptionValue")

Just for info you could add more attributes to the tags above like CSS style class, example:
@inputText(myForm("name"),
'id -> "username",
'class -> "classForInputText",
'_id -> "idForTheTopDlElement",
'_class -> "classForTheTopElement",
'size -> 30
)

You can then set the display to none or block


text:
Q: Is it true that the following definition of a convex function cannot be used in a more general way? One definition for convex functions I found on Wikipedia was that 'the line segment between any two points on the graph of the function always lies above or on the graph'. That makes sense. However, am I right in suggesting that this is not a suitable definition for convexity on a particular interval? To explain why I think this, consider the graph $y=x^3$ on the interval $[-0.5,1]$:

This function is clearly not convex on the interval $[-0.5,1]$. However, using the definition above, it does meet the criterion that the line segment between those two points always lies above or on the graph. What the above definition really tells us is that $y=x^3$ is not a convex function. It doesn't say whether the function is convex or concave over a particular interval, and cannot be used as such. Otherwise, we get contradictions such as '$y=x^3$ is convex over the interval $[-0.5,1]$', when it clearly is not.
So this definition helps us show that a function is convex everywhere, or not convex everywhere. It tells us whether a function is a convex function or not a convex function. What it can't tell us is whether a function is convex for every point in an interval. (To show this, we might use the second derivative test, for example.) Is this reasoning correct?

A: You are correct $f(x) = x^3$ is not convex on the interval $[-0.5, 1]$ (I assume you made a typo when you wrote $[0.5,1])$. However, this agrees with the Wikipedia definition: try the points $(-0.5, (-0.5)^3)$ and $(-0.4, (-0.4)^3)$. Is the line segment passing through these points still above the graph? (It's not!) So in fact the Wikipedia definition does tell you if a real valued function defined on an interval is convex. Remember, the definition states "for any two points on the graph."


text:
Q: Blank Cell equal to value Zero in another cell should returns True in python,pandas Below is my data in excel format

*

*Where there is a blank cell it is treating as general

*Where there are amounts, format is "#,##0.00000;(#,##0.00000)"

I have written the below code to calculate the Blank cell equal to value zero from another cell should return True
import pandas as pd
df=pd.read_excel('Book1.xlsx',dtype=str)
df.replace('nan','',inplace=True)

df['True']=''
df.loc[df['Amount_1'] == df['Amount_2'],'True'] = 'True'
df.loc[df['Amount_1'] != df['Amount_2'],'True'] = 'False'
df

    Name    Amount_1    Amount_2    True
0   A1                     0        False
1   A2          0                   False
2   A3                     0.01     False

If I am doing it in excel I am getting True for the first two rows whereas I am getting False here.
My End Result/Expected Result should be:

*

*True for A1 and A2 but I am getting False instead.

*While writing to Excel blank cells should come as blanks.

A: You could give more conditions such as
import pandas as pd

df=pd.read_csv('test.csv',dtype=str) # this is modified for my test.
df=df.fillna('')

df['True'] = ''
df.loc[df['Amount_1'] != df['Amount_2'], 'True'] = 'False'
df.loc[df['Amount_1'] == df['Amount_2'], 'True'] = 'True'
df.loc[(df['Amount_1'] == '') & (df['Amount_2'] == '0'), 'True'] = 'True'
df.loc[(df['Amount_2'] == '') & (df['Amount_1'] == '0'), 'True'] = 'True'
df

where the result is:
    Name    Amount_1    Amount_2    True
0   A1                        0     True
1   A2            0                 True
2   A3                     0.01    False


text:
Q: Tomcat 7 mutual authentication (mTLS) My situation
I have configured Tomcat for mTLS with self-signed certificates and everything works fine (certificate installed on the browser).
Now I'm trying to configure mTLS for Tomcat with third party certificate provider X and it isn't working.
So,
I have a certificate card and a certificate is issued by a certificate provider X.
I've installed all root certificates of X certificate provider to Tomcat's truststore (public CA storage).
I have self-generated certificate on Tomcat's keystore (server certificate storage)
When I navigate via browser to a webapp I'm not getting prompted to select a certificate which is on my certificate card.
My questions
Do I need to replace self-signed certificate with the one signed by third party certificate provider X for it to work?
Or should installing certificate provider X's CA certificates on Tomcat's truststore should be enough?


text:
Q: Why does the escape key have a delay in Python curses? In the Python curses module, I have observed that there is a roughly 1-second delay between pressing the esc key and getch() returning.  This delay does not seem to occur for other keys.  Why does this happen and what can I do about it?
Test case:
import curses
import time

def get_delay(window, key):
    while True:
        start = time.time()
        ch = window.getch()
        end = time.time()
        if ch == key:
            return end-start

def main(stdscr):
    stdscr.clear()
    stdscr.nodelay(1)

    stdscr.addstr("Press ESC")
    esc_delay = get_delay(stdscr, 27)

    stdscr.addstr("\nPress SPACE")
    space_delay = get_delay(stdscr, ord(' '))

    return esc_delay, space_delay

if __name__ == '__main__':
    esc_delay, space_delay = curses.wrapper(main)
    print("Escape delay: {} ms".format(esc_delay*1000))
    print("Space delay: {} ms".format(space_delay*1000))

Results:
Escape delay: 1001.09195709 ms
Space delay: 0.00596046447754 ms

A: Curses deals with "escape sequence"s from your terminal to represent commands to the software These sequences normally begin with an escape character. Consequently, when you hit ESC the curses code doesn't emit anything immediately in case this represents the start of an escape sequence.

A: In order to customize the Esc delay you can set the environment variable ESCDELAY which curses uses to determine the time in milliseconds it waits before it delivers the Escape Key.
In order to define this variable in Python you could for example call the following function prior to your call to curses.wrapper(main):
def set_shorter_esc_delay_in_os():
    os.environ.setdefault('ESCDELAY', '25')

which will set the environment variable to 25ms if it has not been set before.
See also the man page of ncurses (search for ESCDELAY).

A: ESCDELAY=25 ...put this in global.


text:
Q: Matplotlib arrow head in log-log plot I want to draw arrows in a log-log plot that have different lengths but should have a similar-looking head. The head width is indeed the same, but the length of the head seems to scale with the arrow length. How can I get the short-looking head of the right-pointing arrow to look like the other head?
from matplotlib.pyplot import gca,show

ax  = gca()
ax.set_xlim(1e-4,1e4)
ax.set_xscale('log')
ax.set_ylim(1e-4,1e4)
ax.set_yscale('log')

opt = dict(color='r',width=5)

a1  = gca().annotate('',xy=(1e-1,1e-3),xycoords='data',xytext =(1e-1,1e1),textcoords = 'data',arrowprops=opt)
a2  = gca().annotate('',xy=(1e2,1e-3), xycoords='data',xytext =(1e1,1e-3),textcoords = 'data',arrowprops=opt)

show()

A: You can adjust the head and connection style in the arrowprops like this (for the full set of options see the matplotlib docs:
 opt = dict(color='r',
            arrowstyle = 'simple,head_width=.75,head_length=.75',
            connectionstyle = 'arc3,rad=0')

Then to adjust the width of your arrow use the size paramater in annotate:
a1  = gca().annotate('',xy=(1e-1,1e-3),xycoords='data',xytext =(1e-1,1e1),textcoords = 'data',arrowprops=opt,size=20)
a2  = gca().annotate('',xy=(1e2,1e-3), xycoords='data',xytext =(1e1,1e-3),textcoords = 'data',arrowprops=opt,size=20)
show()


text:
Q: Do I need to have two different objects to read and to write in my database using gorm (golang)? gorm tell in the documentation that "Base model definition gorm.Model, including fields ID, CreatedAt, UpdatedAt, DeletedAt, you could embed it in your model, or only write those fields you want":
// Base Model's definition
type Model struct {
  ID        uint `gorm:"primary_key"`
  CreatedAt time.Time
  UpdatedAt time.Time
  DeletedAt *time.Time
}

// Add fields `ID`, `CreatedAt`, `UpdatedAt`, `DeletedAt`
type User struct {
  gorm.Model
  Name string
}

// Only need field `ID`, `CreatedAt`
type User struct {
  ID        uint
  CreatedAt time.Time
  Name      string
}

Following the documentation, I expect to have only one definition of User, so I create an object like that:
type User struct {
  gorm.Model
  ID        uint
  CreatedAt time.Time
  Name      string
}

But if I do a DB.CreateTable(&User{}), I get the following errors from postgres:
(pq: column "id" specified more than once)
(pq: column "created_at" specified more than once)

So I have to have two different objects :
type CreateUser struct {
  gorm.Model
  Name string
}

type RetrieveUser struct {
  gorm.Model
  ID        uint
  CreatedAt time.Time
  Name      string
}

So I can do a DB.CreateTable(&CreateUser{})
It is very ugly and I must be missing something, any idea?

A: Ok, just read the code behind gorm.Model and I got my answer.
type Model struct {
    ID        uint `gorm:"primary_key"`
    CreatedAt time.Time
    UpdatedAt time.Time
    DeletedAt *time.Time `sql:"index"`
}

It means I just learned how inheritance works in go !


text:
Q: Leaflet change map style based on Maritime Borders or own JSON Is it possible to change the maps style after a particular maritime border or a polyline geo JSON?
I'm trying to change the color of the sea after a maritime border. is there any chance to change it? I'm using leaflet js.

I want to change the sea as red color after the red border.

A: If you have a line like this

Just add some points to the start and end, somewhat far away, making a closed line...

...and use that as a polygon.

Please remember that the earth is round, so you cannot simply "colour things differently to the left/right of a line", because you will come back to the other side:

You must decide how to close the area. Maybe you want to cover a whole country, maybe you want to cover half of the earth. You have to choose. For example, this might be perfectly acceptable for your scenario:

A: we can use geo JSON and be using leaflet ajax js.
var geojsonLayer = new L.GeoJSON.AJAX("xxx.geojson", {
            style: function (feature) { // Style option
                console.log("feature", feature);
                return {
                    'weight'    : 1,
                    'color'     : 'black',
                    'fillColor' : 'yellow'
                }
            }
        });
        geojsonLayer.addTo(map);


text:
Q: python: read complicated csv files so, I'm trying to read a weird .csv files which has comma separated values, but since each pair of columns represent a different typology of data these are separated by two commas ',,'. On top of that there are missing values in some specific columns after a certain row (see following minimal example)
row1:

-2.418809,0.004107006,,359.896,1.86897E-07,,359.896,2.958411,,-2.419437,0.1012164,,359.9048,2.095844E-06,,359.9048,-2.049214

row2

-2.41644,0.004659269,,,,,,,,-2.417068,0.1013545,,,,,,

I've tried to address the problem using the approach described in the answers  here but without success because loadtxt can't handle missing values
At the moment I'm trying to read it with numpy.loadtxt specifying only the columns which go on till the end:
import numpy as np
data = np.loadtxt(name,
                  delimiter=',',
                  unpack=True,
                  usecols=(0,1,6,7))

but I'm obtaining an error:
ValueError: could not convert string to float

Does anyone have any idea if there is a simple way to solve this?

A: You have been broken the basic principle of csv
https://en.wikipedia.org/wiki/Comma-separated_values
Complex CSV Solution :
Handling a complex CSV file

A: First step is, if you say the csv uses two commas instead of one, you should pass delimiter=',,' to np.loadtxt.
Second, if you need to customize the parsing of each column, as Aaron said on his comment, you can pass convertersto customize the way the data will be stored. Example, if you want that column 2 gives a zero when it finds and empty string, you do
import numpy as np
data = np.loadtxt(name,
              delimiter=',,',
              converters = {2: lambda x: 0 if x == "" else float(x)}
              unpack=True,
              usecols=(0,1,6,7))

I didn't test the code, but I checked directly from documentation to think how could you do it. If that code doesn't work, it should be something like that anyway.
Hope it helps.

A: In the end I found a non-elegant but working approach: i used genfromtxt which better handles missing data, considering them as NaN by default. Using comma ',' as a delimiter the function reads the double commas ',,' as comma-missing value-comma, so everywhere there is a double comma the output of the function is NaN. that done I just deleted the nan columns applying this answer here
import numpy as np
data = np.genfromtxt(namefile,
                     delimiter=',')
datanew = data[:, ~np.all(np.isnan(data), axis=0)]
data = np.transpose(datanew)


text:
Q: compose chained functions using the same parameter in javascript I am trying to better understand functional composition in ramda.js and currently have a method in a class that looks like this:
const replace = (newItem) => function3(function1(newItem).function2(newItem));

I know in ramda.js for a simpler function like
const replace = (newItem) => function2(function1(newItem));

you could write it like
const replace = compose(function2, function1);

Is there a similar way to do the same with the initial function using functional composition / application or other ramda.js helper methods?

A: Ramda has two functions that should help with this.  The more standard one is lift.  Many functional languages have this concept.  One way to think about it is that it lifts a function which operates on values to create one that operates on containers of those values:
add(3, 5) //=> 8
lift(add)([3], [5]) //=> [8]

Functions can be seen as containers of values too.  Functions which return values of a given type can be considered containers for that type.
So we can lift your function3 to operate not on values, but on containers for those values, and then supply it the input to those functions.  Here's an example with arrays as containers:

const function1 = newItem => `function1(${newItem})`
const function2 = newItem => `function2(${newItem})`
const function3 = (v1, v2) => `function3(${v1}, ${v2})`

const combine = R.lift(function3)(function1, function2)

console.log(combine('foo')) //=> "function3(function1(foo), function2(foo))"
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.js"></script>

The less standard function is converge.  This is focused only on functions, and not on arbitrary containers.  It works similarly in this case.  The function is created in one pass rather than the two for lift.  And that means the initial functions need to be wrapped in an array:

const function1 = newItem => `function1(${newItem})`
const function2 = newItem => `function2(${newItem})`
const function3 = (v1, v2) => `function3(${v1}, ${v2})`

const combine = R.converge(function3, [function1, function2])

console.log(combine('bar')) //=> "function3(function1(bar), function2(bar))"
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.js"></script>

converge is only for functions, but it can work with polyadic functions.  lift will work only with unary ones.  converge is a Ramda-specific function.  I haven't seen it elsewhere.  So, if lift will work for you, I would suggest you choose it instead.

A: So your question is how to write
function1(input).function2(input)

In a functional way. If I am correct, here is how:
First let's create a function method that would give us a method of an object bound to that object:
const method = R.curry((name, object) => R.bind(object[name], object))

Using this function, we can rewrite our expression as
method('function2', function1(input))(input)

But we want something cleaner and more re-usable, right? So let's do some refactoring
method('function2', function1(input))(input)

method('function2')(function1(input))(input)

R.pipe(function1, method('function2'))(input)(input) // or use R.compose

R.converge(R.call, [
  R.pipe(function1, method('function2')),
  R.identity
])(input)

Now we can define our function combine like so
const combine = (fn, name) =>
  R.converge(R.call, [
    R.pipe(fn, method(name)),
    R.identity
  ])

And the expression becomes
combine(function1, 'function2')(input)

I hope my explanation is clear and it solves your problem :)


text:
Q: Undefined references linking sqlite3pp I'm trying to compile sqlite3pp. Source is from http://code.google.com/p/sqlite3pp
1) g++ ../src/*.cpp -c
-> produces 3 .o file sqlite3pp.o, sqlite3ppext.o and testaggregate.o
2) ar crf libsqlite3pp.a *.o
-> generate new file called libsqlite3pp.a
3) g++ -shared *.o -o sqlite3pp.dll
-> multiple undefined reference to sqlite3_*
4) g++ -shared *.o -lsqlite3pp -o sqlite3pp.dll
-> same errors as previous
5) g++ -shared *.o -lsqlite3 -o sqlite.dll
-> undefined reference to sqlite3_open_v2
Why does this last error occur?


text:
Q: Call Meteor helper function when adding elements to DOM I want to call a UI.registerHelper('getTitle', function (type){}); function when adding an element with jQuery's .append($('<h3/>', {'class': 'panel', html: "{{getTitle 'game'}}"}).
The output is: {{getTitle 'game'}}, so it's not interpreted.
How can I do this?
Any help would be greatly appreciated.

A: You can't proceed this way, because {{getTitle "game"}} is not HTML, it's actually Spacebars syntax and it cannot be dynamically interpreted like this.
What you could do is declare the getTitle as a separate function :
function getTitle(type){
  //
}
Template.registerHelper("getTitle",getTitle);

And use it in your DOM insertion code :
var html=getTitle("game");
// ... proceed with insertion via jQuery

Most important, adding HTML via jQuery doesn't sound very meteorish so I advise you to reconsider your design and switch to a template based approach :
<template name="whatever">
  {{#id conditionMet}}
    <h3>{{getTitle "game"}}</h3>
  {{/if}}
</template>

Template.whatever.helpers({
  conditionMet:function(){
    // return some value based on a reactive data source
  }
});


text:
Q: deserialize xml polymorphic list with jackson I have problem deserializing following xml:
<root>
  <apples>
    <apple>
      <id>1</id>
      <weight>0.6</id>
    </apple>
    <apple>
      <id>2</id>
      <weight>0.7</id>
    </apple>
  </apples>
</root>

to java:
public class Root {
  private List<Fruits> fruits;
}

In above xml source other variants may be eg oranges/orange etc. also since this is propertary xml I cannot change it's schema. By default I am using @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT) and @JsonSubTypes({/*fruits subtypes listed*/}). After few unsuccessful attempts I am not sure what is the proper mapping/configuration to solve the problem.

A: Out of the box, Jackson is a JSON parser, not XML.
There are extensions for Jackson that allow for XML conversion. See http://wiki.fasterxml.com/JacksonExtensionXmlDataBinding for more info there. But it seems as though a pure XML parser may be better for this case.
Perhaps the javax.xml.stream.* packages.
i.e. http://www.javacodegeeks.com/2013/05/parsing-xml-using-dom-sax-and-stax-parser-in-java.html for more info.


text:
Q: How to clear server and browser cache in WordPress I have a plugin that randomly displays images on front-end. It's working good on non cache website, but for people using in siteground or wpengine, the same image is showing instead of random. I tried appending the unique id to each image like the below code, but it is not generating the unique id on server cache systems. Instead, it is showing the first time generated id with the same image every time.
<img src="image.png?v=<?php echo mt_rand( 1000, 9999 ); ?>" />

I also added the below code for siteground cache (SG Optimizer WP Plugin), but it still won't work:
if (function_exists('sg_cachepress_purge_cache')) {
    sg_cachepress_purge_cache();
}

Is there any solution to solve this problem? How can I show random image on all server cache websites, too.

A: If you have the same name for images. Then Why not give each image a different name.


text:
Q: Template tags not working in the customizer preview I have a small code to inject some CSS to the single post. And it has an option in the Customizer to enable/disable the CSS. My code is similar to this:
add_action( 'wp_head', function() {
    if ( ! get_theme_mod( 'enable_custom_css' ) ) {
        return;
    }
    if ( is_singular() ) {
        echo '<style>.site-header{ background-image: url(http://placehold.it/300);</style>';
    }
} );

The problem is no matter I turn on or off the settings enable_custom_css, the custom CSS is always not outputted when previewing in the Customizer.
I dig a little bit deeper in the code and found that: when previewing in the Customizer, the function is_singular always returns false.
Do you know any way to make is_singular() work?
Thanks


text:
Q: Nodejs mongodb find and update multiple documents in transaction I have a mongo 4.2 replica set. I have N processes running concurrently and trying to read a collection. This collection is like a queue. I'd like to read 100 elements and update them in a transaction so other processes won't try to read those.
My code goes:
const collection = client.db("test").collection(TEST_COLLECTION);

const session = client.startSession();

try {

    let data = null;

    await session.withTransaction(async () => {
        console.log("starting transaction")

        data = await collection.find({ runId: null }, { _id: 1, limit: 100 }).toArray();

        const idList = data.map(item => item._id.toHexString());

        await collection.updateMany(
            { runId: { $in: idList } },
            { $set: { runId: runId } },
            { session });

        console.log("Successful transaction")
    });

    data.map(item => {
        // process element one by one and update them (no need for transaction here)
    })

} catch (e) {
    console.error("The transaction was aborted due to an unexpected error: " + e);
} finally {
    await session.endSession();
    console.log("Closing transaction")
}

this is the code I've got right now. The thing is that find() won't accept options so I can't pass the session. This means it won't be part of the transaction.
the mongodb documentations states that: When using the drivers, each operation in the transaction must be associated with the session (i.e. pass in the session to each operation).
So I'm assuming that this is actually not transactional only the update part which not solves my problem. Is there any way to include both in my transaction? Any ideas on this? Other/better options?
Thanks
EDIT:
So I was staring at my question for 15 minutes when it hit me. If I update first using the transaction. Then querying with the runId even outside of the transaction I can achieve my goal. Am I right? Is it so easy?
EDIT2:
Edit1 was stupid now I can't limit to 100 items. Back to the start.
EDIT3:
I'am using native mongodb nodejs driver.

A: To use a find in a transaction, pass the session using the session method:
doc = await Customer.findOne({ name: 'Test' }).session(session);

See Transactions in Mongoose


text:
Q: Groovy XML: How to parse, modify and serialize the content of a GSP file. (org.xml.sax.SAXParseException, prefix not bound) Before I ask  this question I will provide some info on what I am actually trying to do:
I need to refactor a large amount of GSP files in my grails project. After I tried writing my own groovy script for that -- and realizing that it is way too much for my current skill level in any language -- I found this article, which helped me a lot with parsing html content.
After a while I had put together my own script to parse an html file, serialize it again and save it to a new file. This is my script:
import groovy.xml.*

@Grab(group='org.ccil.cowan.tagsoup',module='tagsoup', version='1.2' )

def tagsoupParser = new org.ccil.cowan.tagsoup.Parser()
tagsoupParser.setFeature(tagsoupParser.namespacesFeature, false)

def slurper = new XmlSlurper(tagsoupParser)
def xmlFile = 'list.gsp'
def htmlParser = slurper.parse(xmlFile)

/*

TODO: Manipulation code goes here

*/

def outputBuilder = new StreamingMarkupBuilder()
String result = XmlUtil.serialize(outputBuilder.bind{ mkp.yield htmlParser })

result =  result.replaceAll(/<\?.+\?>/, '')

def newFile = new File('neu.html')

newFile.text = result

Note that I do not want an XML prolog in my GSP files; therefore, I remove it using regex (that is not my question, but if anybody knows a more "groovy" way to do this, please let me know!)
Also, I set namespacesFeature to false, since namespaces are useless for my purpose.
Because that worked like a charm with HTML files, I thought I am ready to loop over my folder recursively and find all GSP files with the name list.gsp and refactor them automatically. But when I tried to test it with one list.gsp, the serialization fails because of the unbound prefix g for the element g:set:
The prefix "g" for element "g:set" is not bound.
Now, I kind of understand that what I am trying to do is not the regular purpose of XML parsing and serializing. But in my case, I do not only want the to disable the namespaces feature, but also want the parser to ignore all GSP tags and treat them as regular opening and closing tags; in other words, ignore the double dots in any tag.
The other thing I am concerned of is expression language, such as <%@ page import="<class>" %>. Right now I'm just getting the exception mentioned earlier, but this will probably need to be resolved as well.
Any help is highly apreciated.


text:
Q: How do you 'incrementally' create vector tiles? I am serving my own vector tile layer. In my current setup when a point of interest is added by a user it is stored in PostGis and the relevant zoomtiles are reproduced and written over the previous ones. For high zoomlayers this is fast, however for low zoom (e.g. the world) the processing is demanding as in recreating the vector tiles millions of points of interest are involved.
Is it necessary to 'recalculate' the entire tile? Are there ways to recreate vector tiles in an 'incremental' way which is less processor demanding? This would make sense as the content at lower zooms is >99% the same as the previous vector tile. Does protobuf or other vector tile formats allow such patching? What are existing solutions to my problem?
BTW I am already using a separate tile layer for the points of interest, so it is not like I am recalculating all features. But the points of interest alone can run into millions at world zoom.

A: In the MVT tile encoding, point coordinates are relative to the coordinates of the previous point. So incremental updates would work only if the changed points happen to be the last ones.
Additions would be easier, but would still require rewriting all arrays inside the tile.
In a tile, the layers are just concatenated. So if your client software can handle this, you could add another layer to the tile (maybe even with the same name).


text:
Q: Why is my laptop's graphics performance going down when it is connected with AC power? My HP Omen (Windows 10, Core i7 7th gen, 16GB RAM, Nvidia GeForce GTX 1060 6GB) was so far working great to render even high-end games and applications on high FPS. But now, I am facing problem even with moderate level games and applications.
Before anyone can think of damaged hardware because of heat, let me tell you the peculiarity of the problem: I am experiencing this problem only when the laptop is connected with AC power, not on battery. It's quite opposite of what I expected. It's bad for me because running a high end game and application on battery drains the battery fast.
I have already checked the power options and all graphics options. Graphics card isn't being throttled down when on AC power.
What's actually happening? How to fix this?

A: I don't have experience with HP laptops, but with Dell laptops, if you're using an underpowered AC adapter, the system will throttle down, even with a full battery charge.
Are you using the original AC Adapter?  Do you have a 2nd AC adapter to try?  It's possible that your AC Adapter isn't putting out the full amperage needed.