text:
Q: How can I position overlapping divs to look like a stack of papers? I want to layer multiple divs, such that each successive one is offset up and to the left of the one in front of it. It should roughly look like a stack of papers. I've tried playing around with absolute positioning and z-index, but the positioning doesn't seem to play nicely. Here's a Fiddle

.box{
  width:100px;
  height:100px;
  border-style:solid;
  border-color: #D3D3D3;
  position:absolute;
}

.first{
  background-color:yellow;
  z-index:10;
  bottom:0;
  right:0;
}

.second{
  background-color:blue;
  z-index:9;
  bottom:10;
  right:10;
}

.third{
  background-color:red;
  z-index:8;
  bottom:20;
  right:20;
}

.background{
  height:100%;
  background-color:green;
  position:relative;
  z-index:0;
}

.container{
  border-style:solid;
  border-color:black;
  width:300px;
  height:300px;
  position:relative
}

A: Positions in CSS have to be given with a unit. You cannot say bottom: 10; — you have to say bottom: 10px;
Put the px in and it works fine.

A: I forked your JSFiddle... Is this what you are trying to achieve? https://jsfiddle.net/aewwq1np/
I positioned each one in the same spot then offset each one with margin-top and margin-left
I also used a some box shadow to add some depth. I use this to play with the box-shadow: http://www.cssmatic.com/box-shadow
e.g.
.second {
  bottom:10px;
  right:10px;
  margin-top: 20px;
  margin-left:4px;
  -webkit-box-shadow: -2px -12px 61px -9px rgba(0,0,0,0.75);
  -moz-box-shadow: -2px -12px 61px -9px rgba(0,0,0,0.75);
  box-shadow: -2px -12px 61px -9px rgba(0,0,0,0.75);
}


text:
Q: search product based on metafield shopify I'm wondering if there's a way to search for a product based on the metafield value.
I've 3 dropdowns, i.e. Year/Make/Model.
I have 3 metafields also, i.e. inventory.year, inventory.make & inventory.model (inventory is NAMESPACE & year, make, model are KEY). I need to search for products based on these 3 metafields.
Thanks

redpajama_set_name: RedPajamaStackExchange


text:
Q: Equality in AM GM Inequality In AM GM inequality for nonnegative real numbers $a_1,a_2,\ldots,a_n$, How to show that if equality holds then $a_1=a_2=\ldots=a_n,$ using method of induction?

A: Edit Sorry, I read now that you wanted a proof using induction. The proof below does not. I let it stand, since I think it is a nice proof, and someone might thing it is helpful.
For two terms, the statement follows by expanding
$$
0\leq (a_1-a_2)^2,
$$
and noting that the inequality is an equality precisely when $a_1=a_2$.
Now suppose, to get a contradiction, that not all $a_i$, $1\leq i\leq n$ are equal and that the AM equals the GM, i.e.
$$
\frac{a_1+a_2+a_3+\cdots+a_n}{n}=(a_1a_2\cdots a_n)^{1/n}.
$$
We can without loss of generality assume that $a_1\neq a_2$. Then, if we replace $a_1$ and $a_2$ by their arithmetic mean,
$$
\tilde{a}_1=\frac{a_1+a_2}{2},\quad \tilde{a}_2=\frac{a_1+a_2}{2},
$$
we get $n$ numbers $\tilde{a}_1$, $\tilde{a}_2$, $a_3$, $\ldots$, $a_n$, that has the same arithmetic mean as the original one, but what happens with the geometric mean? From the AM-GM inequality with two terms
$$
\tilde{a}_1\tilde{a}_2=\Bigl(\frac{a_1+a_2}{2}\Bigr)^2 > a_1a_2.
$$
Note the strict inequality (which is a result of the case of two terms).
Hence,
$$
\frac{\tilde{a}_1+\tilde{a}_2+a_3+\cdots+a_n}{n}=
\frac{a_1+a_2+a_3+\cdots+a_n}{n}=(a_1a_2\cdots a_n)^{1/n}<(\tilde{a}_1\tilde{a}_2a_3\cdots a_n)^{1/n}
$$
contradicting the AM-GM inequality.

A: Requesting everyone to kindly point out the flaw in my reasoning in the comments to this answer..
$n=1$ and $n=2$ are easy to prove cases. Assuming the hypothesis to be true for $n=k$ where $k>2$
we get $AM=GM=a_1$
For $n=k+1$, we can create $(k+1)$ subsets of $k$ numbers, for each of which, the hypothesis implies that all elements of the subsets are equal as long as $AM=GM=b_i$ without any need to worry about whether $b_i=a_1$ or not for any $i$ between $1$ and $k+1$.
Note that any two subsets differ in just one element and hence have $k-1$ common elements. Equality of all elements in two such subsets would imply $a_1=a_2=...=a_{k+1}$ which is the desired result.
This seems to be a reasonable line of thought to me. Am I missing something?


text:
Q: Closed-contour integral of a derivative Suppose a function $f(z)$ is single-valued everywhere and holomorphic inside a closed contour $C$, except for one pole. The derivative $ g(z) = \frac{ \partial f}{\partial z}$  also has the same pole. I have a naive question about the integral
$$ \int_C dz  g(z) $$
This is the integral around a closed contour of the derivative of a single valued function, so it should be zero. But if done with the residues it should be nonzero because of the pole inside $C$.
So is it zero or not?

A: You cannot say that that integral is non-zero simply because there is a pole. For example the integral of $\frac 1 {z^{2}}$ over the unit circle is $0$. Answer: YES, the integral is $0$.


text:
Q: how to display G map by repeater and markers from database I want to display google map inside repeater from database values comes, i searched on google and reached to this result but not working with me i don't know if it have something missing or not can you help me please.

<body>
    <form id="form1" runat="server">

    <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>

        <asp:Literal runat="server" ID="Literal1"></asp:Literal>

     <script type="text/javascript">

        var markers = [
        <asp:Repeater ID="rptMarkers" runat="server">
        <ItemTemplate>
                 {

                "title": '<%# Eval("City") %>',
                 "lat": '<%# Eval("Latitude") %>',
                 "lng": '<%# Eval("Longitude") %>'

             }
    </ItemTemplate>
    <SeparatorTemplate>
        ,
    </SeparatorTemplate>
    </asp:Repeater>
    ];

    </script>
    </body>

Here my code behind aspx.cs,
 public class Markers
{
    public string City { get; set; }
    public string Latitude { get; set; }
    public string Longitude { get; set; }
}

void GetData(string strRsult)
{
    XmlDataDocument xmlDataDoc = new XmlDataDocument();
    xmlDataDoc.LoadXml(strRsult);

    Literal1.Text = "<script type=\"text/javascript\">var markers = [";

    foreach (XmlNode n in xmlDataDoc.DocumentElement.GetElementsByTagName("Property"))
    {
        if (n.HasChildNodes)
        {
          List<Markers> markers = new List<Markers>();
            foreach (XmlNode childNode in n)
            {
                if (childNode.Name == "GEOData")
                {
                    Literal1.Text += "title: '" + childNode.Attributes["City"].Value + "', lat: '" + childNode.Attributes["Longitude"].Value + "', lng: '" + childNode.Attributes["Latitude"].Value + "'}";
                }

            }

            Literal1.Text += "];</script>";

        }

    }

XML file

- <AVSearch_PropertyDetails RequestedCurrency="EUR">
- <Property IDHotel="10000" PropertyCode="10000" Hotelname="REZ:Online HOTEL" StarCategory="0" ImageIdentifier="RHN_10000" NumberOfRooms="80" CheckinTime="00:00" CheckoutTime="23:59" Email="info@r-h-n.com" Status="0" StatusInfo="">
- <GEOData CountryCode="DE" CountryName="Germany" City="Duesseldorf" IDCity="32" Zip="40472" Street="Wanheimer Street 45" Longitude="6.7932130" Latitude="51.2871870">
- <Distances>
  <Distance Type="1" Distance="0.50" />
  <Distance Type="2" Distance="1.81" />
  </Distances>
  </GEOData>
- <Descriptions>
  <Description IDLanguage="4" IDType="1" Text="This is the test hotel used for testing and debugging purposes only. Please do not book this hotel." />
  <Description IDLanguage="4" IDType="4" Text="This is a testhotel" />
  <Description IDLanguage="4" IDType="3" Text="Terms & conditions EN" />
  </Descriptions>
`

A: Download Google Map DLL in your project from codeplex GoogleMapControl.
Register DLL in your page:
<%@ Register Assembly="Artem.Google" Namespace="Artem.Google.UI" TagPrefix="artem" %>

Here is the steps to create Google Map dynamically in repeater control.
First download Artem.Google.dll from this link and put down DLL in bin folder.
ASPX Page Code:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GmapRepeater.aspx.cs" Inherits="GmapRepeater" %>

 <!DOCTYPE html>
 <%@ Register Assembly="Artem.Google" Namespace="Artem.Google.UI" TagPrefix="artem" %>

  <html xmlns="http://www.w3.org/1999/xhtml">
   <head runat="server">
 <title></title>
   </head>
   <body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager runat="server"></asp:ScriptManager>
<asp:Repeater ID="rptMarkers" runat="server" OnItemDataBound="rptMarkers_ItemDataBound">
    <ItemTemplate>
        <artem:GoogleMap ID="GMap" runat="server"></artem:GoogleMap>
    </ItemTemplate>
</asp:Repeater>
</div>
</form>

ASPX.CS Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Artem.Google.UI;

 public partial class GmapRepeater : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        GetData();
    }
}
protected void rptMarkers_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        Markers loData = (Markers)e.Item.DataItem;
        GoogleMap GMap = (GoogleMap)e.Item.FindControl("GMap");

        GMap.MapType = Artem.Google.UI.MapType.Roadmap;
        GMap.ApiVersion = "v2";
        GMap.Latitude = Convert.ToDouble(loData.Latitude);
        GMap.Longitude = Convert.ToDouble(loData.Longitude);
        GMap.Zoom = 18;
        GMap.EnableMapTypeControl = false;
        GMap.Height = 200;
        GMap.Width = 195;

        Marker loMarker = new Marker();
        loMarker.Position.Latitude = Convert.ToDouble(loData.Latitude);
        loMarker.Position.Longitude = Convert.ToDouble(loData.Longitude);
        loMarker.Clickable = true;
        loMarker.Info = "Marker Information";
        loMarker.Title = "Title of your Marker";
        loMarker.Visible = true;

        GMap.Markers.Add(loMarker);
    }
}
 private void GetData()
{
    XmlDataDocument xmlDataDoc = new XmlDataDocument();
    xmlDataDoc.Load(Server.MapPath("~/Files/XMLFile.xml"));
    List<Markers> markers = new List<Markers>();

    foreach (XmlNode n in xmlDataDoc.DocumentElement.GetElementsByTagName("Property"))
    {
        if (n.HasChildNodes)
        {
            foreach (XmlNode childNode in n)
            {
                if (childNode.Name == "GEOData")
                {
                    Markers loObj = new Markers();
                    loObj.City = Convert.ToString(childNode.Attributes["City"].Value);
                    loObj.Longitude = Convert.ToString(childNode.Attributes["Longitude"].Value);
                    loObj.Latitude = Convert.ToString(childNode.Attributes["Latitude"].Value);
                    markers.Add(loObj);
                }
            }
        }
    }

    if (markers != null && markers.Count > 0)
    {
        rptMarkers.DataSource = markers;
        rptMarkers.DataBind();
    }
}
}

Markers Entity Class:
public class Markers
{
     public string City { get; set; }
     public string Latitude { get; set; }
     public string Longitude { get; set; }
}

Please let me know if you have any questions.


text:
Q: Pass a value to exported function using require If I export a function like this:
const foo = "text";
const bar = function() {
    ...
}

module.exports = {
    foo,
    bar,
};

Is there any way to run the function bar when importing using require, e.g.
const { bar } = require('./myExports.js')('argForBar');

??
(currently when I do this I get the error TypeError: require(...) is not a function)

A: The syntax of your import statement is a destructuring assignment, which is just syntactic sugar for declaring a variable(s) from an object property. You can either call bar after the assignment to get a new object, or you can do as Kevin Jantzer suggests and call the method in in the same line:
const bar = require('./myExports.js').bar('argForBar');

const { bar, foo } = require('./myExports.js');
const barInstance = bar('argForBar');

A: require('./myExports') returns an object, so you can't just invoke it like a function. If you export just an object with two fields, you will always get that 'require(...) is not a function' error.
You have alternatives like:
const bar = require('./myExports.js').bar('argForBar');

which doesn't need destructuring,or:
const {barF} = require('./myExports.js');
const bar = barF('argForBar');

Which destructures the bar function into the barF const, then call it.
Is there a problem with any of those?
At worst, you can do this trick, and export a function which happens to have properties, instead of a plain object:
const foo = "text";
const bar = function() {
    ...
}

const exported = function(param){
    return bar(param)
}

exported.foo = foo;
exported.bar = bar;

module.exports = exported;

This way, you make the module callable as the bar function, while it still is an object with the foo and bar properties. But this is completely convoluted and I don't feel is what you're looking for.


text:
Q: dynamic text in  tag what would be the impact on SEO of changing the text of the <h1> dynamically on the server side each time the web page loads?
I'm not talking about changing the whole text, just part of it, for example if the header contains some fixed text (with keywords of course), and also contains the current date or time/the current number of logged on users/the count of items current in stock/whatever.
how would that affect my ranking? is it bad? doesn't make a difference?
thanks.

A: i don't think that element you need should be H1, since semantically, H1 is most important heading on a page which can but shouldn't contain anything that isn't of crucial importance like that number of logged in users o time.
Personally, i would use H1 just for important heading which contains important keywords.
Otherwise, you can put wanted H1 and perhaps a Paragraph and put them in a DIV altogether for such purpose where paragraph contains content irrelevant to page and still harness the value of a H1 and content you want in virtually the same spot.

A: You can use dynamic text in H1, but you need to make sure that no duplicates is allowed. Its not recommended to have duplicate H1 across the site.
You can use dynamic text in H1, but make it a template based.
For Example: If you have categories in your shopping cart and want to display the name of the category in H1...follow a templated structure like
"category-name | Keyword or Company Name"
By doing so, you do not have duplicate tiles, and can achieve uniform structure across the site
Similarly for product pages
"category-name | product-name | Website Name or Company Name"
If you have a long titles with dates and numbers and query string, format in a way which can be read by users and searchbots, and remember the semantics

A: The fact that h1 tags affect SEO is far from being a myth, but with SEO evolving the way it is, it's becoming fairly useless. It's the same thing with meta information and such practices: after the Panda and Penguin, and other reforms Google is making right now, all SEO methods that are easy to abuse of are becoming less and less important for being ranked in Google. Back in the day people could rank at the top by repeating a keyword hundreds of times on a page, in the same way that properly written h1s ranked sites very well. We're far from those times now, Google is aware of the fact that people can abuse of these simple practices, so anything from h1 text, to meta, and even to backlinks, is taking less importance in search engines by the day.
Rather than focusing on h1s, which you shouldn't be putting much effort in, focus on writing good content, and on updating that content as frequenly as possible. Good luck :)


text:
Q: Angle bisector related question The internal bisectors of the angles of a triangle ABC meet the sides in D,E,and F.Show that area of the triangle DEF is equal to $\frac{2\Delta\times abc}{(b+c)(c+a)(a+b)}$,here $\Delta $is area of triangle ABC
If I choose B as origin,C as$(a,0)$,$a$ is side length BC.what should i take coordinates of A,can i get answer with this approach or any better approach?

A: Hint: If $D\in BC$, $E\in CA$, and $F\in AB$, then $\frac{AB}{BC}=\frac{AD}{DC}$.  We have similar conditions for $E$ and $F$.  Then, calculate $\frac{[AEF]}{[ABC]}$, $\frac{[BFD]}{[ABC]}$, and $\frac{[CDE]}{[ABC]}$, where $[P]$ is the area of a geometric object $P$.

A: Let $D,E,F$ be on $BC,CA,AB$ respectively.
Now, since we know that
$$BD:DC=c:b,\quad AF:FB=b:a$$
the area of $\triangle{BDF}$ is
$$\Delta\times \frac{c}{b+c}\times \frac{a}{a+b}=\frac{ac}{(a+b)(b+c)}\Delta.$$
Similarly, we can have
$$[\triangle{CED}]=\frac{ab}{(c+a)(b+c)}\Delta,\quad [\triangle{AEF}]=\frac{bc}{(a+b)(c+a)}\Delta.$$
Thus, the area of $\triangle{DEF}$ is
$$[\triangle{ABC}]-[\triangle{BDF}]-[\triangle{CED}]-[\triangle{AEF}]=\frac{2abc}{(a+b)(b+c)(c+a)}\Delta.$$


text:
Q: Correct understanding of a .NET stack trace with delegates I'm trying to get a deeper understanding of each frame in a .NET stack trace. Most stack traces are easy to understand. I also know about packages like Ben.Demystifier to make it even more readable. Here's an example of a stack frame I'm trying to understand better:
Microsoft.AspNetCore.Mvc.Controllers.ControllerBinderDelegateProvider.<>c__DisplayClass0_0.<<CreateBinderDelegate>g__Bind|0>d.MoveNext()

As I understand this, the Microsoft.AspNetCore.Mvc.Controllers part is the namespace, ControllerBinderDelegateProvider is a class, and MoveNext() is a method. What about the <>c__DisplayClass0_0.<<CreateBinderDelegate>g__Bind|0>d part can someone help explain what this cover?

A: The <>c__DisplayClass0_0.<<CreateBinderDelegate>g__Bind|0>d part is generated by the C# compiler. In the cited case, it is specifically generated for the local function Bind in the method CreateBinderDelegate that belongs to the class ControllerBinderDelegateProvider, and which sits under the namespace Microsoft.AspNetCore.Mvc.Controllers.
To understand the various part of the name, follow GeneratedNames.MakeLocalFunctionName in the compiler/Roslyn source code. It calls the main workhorse method MakeMethodScopedSynthesizedName.
The implementation details may change over time, but for now, here's a rough breakdown of <>c__DisplayClass0_0.<<CreateBinderDelegate>g__Bind|0>d, which you can see as being composed of several parts:

*

*<>c__DisplayClass0_0

*<CreateBinderDelegate>g__Bind|0

*<...>d or <<CreateBinderDelegate>g__Bind|0>d
Note that in the third case, the second one is embedded.
All the synthesized names created by MakeMethodScopedSynthesizedName have the following pattern based on parameter names:
"<" methodName? ">" kind
  ( "__" suffix suffixTerminator? )?
  ( methodOrdinal ("#" methodGeneration )?
  | entityOrdinal ("#" entityGeneration )?
  | methodOrdinal ("#" methodGeneration )?
    "_"
    entityOrdinal ("#" entityGeneration )?
  )?

In the above pattern, anything in quotes ("...") is a literal, parentheses ((...)) are used for grouping, ? means optional, | means or, and identifiers like methodName and suffix represent the value of MakeMethodScopedSynthesizedName arguments.
The <>c__DisplayClass0_0 part is generated by a call to GeneratedNames.MakeLambdaDisplayClassName:
MakeMethodScopedSynthesizedName(GeneratedNameKind.LambdaDisplayClass,
                                methodOrdinal, generation,
                                suffix: "DisplayClass",
                                entityOrdinal: closureOrdinal,
                                entityGeneration: closureGeneration);

Since methodName is null, the synthesized name starts with <>, the c comes from GeneratedNameKind.LambdaDisplayClass, the suffix is clearly DisplayClass and the 0_0 comes from assuming that methodOrdinal and generation are zero for that call.
You can follow the sources to see how the other parts are built with a variation of arguments to MakeMethodScopedSynthesizedName, but in brief:

*

*The <CreateBinderDelegate>g__Bind|0 part is generated by a call to GeneratedNames.MakeLocalFunctionName.
MakeMethodScopedSynthesizedName(GeneratedNameKind.LocalFunction, methodOrdinal, methodGeneration, methodName, localFunctionName, GeneratedNameConstants.LocalFunctionNameTerminator, lambdaOrdinal, lambdaGeneration);

*The <...>d part is generated by GeneratedNames.MakeStateMachineTypeName where the ... comes from the methodName value:
MakeMethodScopedSynthesizedName(GeneratedNameKind.StateMachineType, methodOrdinal, generation, methodName);


text:
Q: Best way to link into SVG content I have some software that generates SVG images with numerous elements, such as boxes and circles. These are usually displayed in combination with HTML, either by inlining it or loading it from elsewhere.
Ideally, it would be nice to provide each SVG element with "id=" attributes in order to support URL fragments addressing those specific elements. For example, http://mypage.html#svgfrag.
Unfortunately, this seems to be less functional than the HTML equivalent. SVG 1.1 (at https://www.w3.org/TR/SVG/linking.html#LinksIntoSVG) makes the following statement: "If the SVG fragment identifier addresses any element other than a 'view' element, then the document defined by the closest ancestor 'svg' element is displayed in the viewport using the view specification attributes on that 'svg' element.", but I cannot even get that to work in the latest Firefox. The standard doesn't define any way of going-to, selecting, or otherwise highlighting a specific element, and going to the ancestor SVG element is too  primitive.
NB: I'm using fragments on the HTML document rather than a specific SVG image displayed within it. Also, each SVG image may be constrained with scrollbars if the content is bigger than the HTML page.
Anyone have suggestions or advice for achieving something along the lines that I'm after -- something that would draw an end-user's attention to the relevant piece in a specific SVG image? Is it even possible at the moment?


text:
Q: pandas how to add details to csv before writing a data frame I need to write to a csv file that have 3-5 lines(rows) of details about the file, following which 3 rows of blank lines  before I can append to data frame.
Here is how the file looks like. (Note: lines having '#' are comments for demonstration)
some details
some more details
some details that were not covered in last two details
#blankline1
#blankline2
#blankline3
A1;B;C  #headers
1231;1241;abc
1232;1242;abd
1233;1243;abe
1234;1244;abf
.
.
.

Here is what I've tried so far:
import pandas as pd

file_name = 'my_csv_file.csv'

df1 = pd.Dataframe({"some details":})
df2 = pd.DataFrame({"some more details":})
df3 = pd.DataFrame({"some details that were not covered in last two details'})
df4 = pd.DataFrame({"\n\n\n\":}) #write 3 blank lines
df5 = pd.DataFrame({"A":[1231 1232 1233 1234]
                    "B":[1241 1242 1243 1244]
                   "headers":[abc abd abe abf] }

df1.to_csv(file_name, sep=';', mode='a', index=False)
df2.to_csv(file_name, sep=';', mode='a', index=False)
df3.to_csv(file_name, sep=';', mode='a', index=False)
df4.to_csv(file_name, sep=';', mode='a', index=False)
df5.to_csv(file_name, sep=';', mode='a', index=False)

but this doesn't seem to work. Can anyone help me with this?

A: You could use a string template and leave {} to insert the dataframe into. The whole thing becomes more readable. Useful things to do: 1) Use """ for multi-line strings and 2) Use comments to remember why you do something.
import pandas as pd

df = pd.DataFrame({
    "A": [1231, 1232, 1233, 1234],
    "B": [1241, 1242, 1243, 1244],
    "C": ['abc', 'abd', 'abe', 'abf']
})

# Setups the template that the client requested with 3-5 rows of information
# Followed by 3 blank rows and the dataframe
template = """\
some details
some more details
some details that were not covered in last two details

{}"""

with open('test.txt', 'w') as fp:
    fp.write(template.format(df.to_csv(index=False)))

test.csv:
some details
some more details
some details that were not covered in last two details

A,B,C
1231,1241,abc
1232,1242,abd
1233,1243,abe
1234,1244,abf

Note: Data from user Taras


text: Q: Retrieve Apple in-app purchase transaction tax amount I am implementing the API backend for Apple in-app purchases receipt validation. I wish to record the transaction including tax in a transactions table in my database for record keeping. How can I be able to retrieve the transaction details; amount paid and tax amount. Can my iOS developer pass me the tax amount in their REST call to my API for receipt validation. Or perhaps, with the transaction reference (unique_identifier or transaction_id) I'm able to make a REST call to apple after the fact. My Apple/iOS knowledge itself is very limited. Thank you.


text:
Q: How to compute MRR @n? Supposed given a query, our system return 10 recommendation result
doc1, doc2, ... doc10

if the ground truth says relevant document says the relevant document is doc100 (which is in position 100), does the reciprocal rank should be 1/100 ? I think it's hard to push the system to return 100 document.
But if i only include recommendation result which had the relevant document in position below top10, I think that is a Naive approach. And i don't really understand the concept of MRR@10, MRR@5, etc.
Can someone please explain to me? Thank you

A: The MRR in that case is defined to be zero.
The reasoning is this: imagine you didn't have any more documents; how would you tell the difference between it being on the next page or not being returned at all?
The goal of these low rank MRR is to model the first page or a website that can only fit three recommendations. To the user there's no difference between documents that appear just after the cutoff and a hundred ranks deeper.


text:
Q: Size CSS grid rows based on a particular column's `min-content` height I have a 2x3 grid, consisting of 1 2x1 and 4 1x1 elements. I want to show the whole 2x1 cell, and make the 1x1 cells y-scrollable for anything past the min-content height of the 2x1 cell. That is to say, I want the whole grid to be the minimum height that it takes for the 2x1 cell not to overflow. Is there any way I can achieve this? Currently, I am using grid.

:not(html, body, .container) {
  padding: .5em;
  border: 1px solid goldenrod;
  border-radius: .25em;
}

.container {
  display: grid;
  grid:
    "chart details-a details-b" 200px
    "chart details-c details-d" 200px
    / 1fr 2fr 2fr;
  gap: .5em;
}

.chart {
  grid-area: chart;
}

[class^=details] {
  overflow-y: auto;
}

.details-a {
  grid-area: details-a;
}

.details-b {
  grid-area: details-b;
}

.details-c {
  grid-area: details-c;
}

.details-d {
  grid-area: details-d;
}

    this

    thing

    here

    must

    be

    a

    chart

    but

    is

    it

    a

    chart

    We need to crystallize a plan business impact strategic high-level 30,000 ft view our competitors are jumping the shark. Gain traction UI, but game-plan. Can you run this by clearance? hot johnny coming through . Canatics exploratory investigation data masking 360 degree content marketing pool but conversational content so streamline you better eat a reality sandwich before you walk back in that boardroom. Unlock meaningful moments of relaxation red flag cta yet message the initiative, and blue sky thinking we can't hear you . When does this sunset? pulling teeth a better understanding of usage can aid in prioritizing future efforts onward and upward, productize the deliverables and focus on the bottom line we need to make the new version clean and sexy. Agile commitment to the cause yet closer to the metal so pipeline, yet land the plane for quick win, but shoot me an email. In an ideal world take five, punch the tree, and come back in here with a clear head we want to see more charts you gotta smoke test your hypothesis or you must be muted for paddle on both sides. Service as core &innovations as power makes our brand herding cats, so quick win, for high-level, for horsehead offer. Good optics increase the pipelines. We need a paradigm shift. This is not the hill i want to die on. We need to make the new version clean and sexy circle back but due diligence best practices i'm sorry i replied to your emails after only three weeks, but can the site go live tomorrow anyway? and 360 degree content marketing pool. Have bandwidth deploy to production but hit the ground running nor 60% to 30% is a lot of persent nor if you're not hurting you're not winning business impact and poop. Currying favour let's take this conversation offline nor that is a good problem to have this is a no-brainer anti-pattern. Have bandwidth workflow ecosystem yet drill down, net net.

    I'm baby knausgaard synth farm-to-table, squid paleo woke slow-carb four loko street art cronut iPhone butcher humblebrag direct trade hella. Salvia coloring book cornhole cloud bread migas glossier microdosing leggings cray live-edge distillery yuccie ennui swag. Pinterest subway tile actually fixie, lo-fi prism poke taxidermy tofu. Helvetica activated charcoal roof party shaman wayfarers drinking vinegar stumptown tacos man braid small batch actually direct trade. Migas gentrify tumeric salvia gluten-free slow-carb swag. Raw denim umami authentic thundercats fanny pack, locavore four dollar toast polaroid vexillologist quinoa lo-fi poutine. Fixie biodiesel everyday carry YOLO humblebrag. Bushwick offal brunch green juice, messenger bag tattooed freegan truffaut iceland banjo. Bitters everyday carry typewriter letterpress cardigan franzen. Hexagon cray lomo stumptown keytar, normcore drinking vinegar helvetica polaroid 8-bit VHS mlkshk shabby chic. Slow-carb stumptown man bun copper mug, mlkshk vinyl succulents poutine mixtape health goth fanny pack cornhole roof party. IPhone occupy put a bird on it kale chips, tacos artisan salvia cold-pressed marfa selvage tote bag. Messenger bag small batch affogato kickstarter, pork belly adaptogen drinking vinegar vinyl bicycle rights truffaut. Meditation lumbersexual sustainable wolf, semiotics YOLO chartreuse. Seitan fixie venmo truffaut gluten-free master cleanse chambray raclette prism, cliche af DIY cray fanny pack. Single-origin coffee 3 wolf moon salvia, shoreditch vegan put a bird on it kogi leggings sriracha retro yuccie man bun green juice live-edge cred. Ethical raclette sustainable chambray you probably haven't heard of them squid.

    Okay, hello, it's the Martian. Young money. Excuse my charisma, vodka with a spritzer. So misunderstood but what's the world without enigma? I lost my mind, it's somewhere out there stranded. I need a Winn-Dixie bag full of money right now to the VIP section. Just talked to moms, told her she the sweetest. Talking to myself because I am my own consultant. Paper chasin', tell that paper "Look, I'm right behind ya." Real G's move in silence like lasagna. People say I'm borderline crazy, sorta kinda. Got the Maserati dancing on the bridge. You pop'em cause we pop'em like Orville Redenbacher. But what should I scream for? This is my theme park. You're a goon but what's a goon to a goblin? I don't owe you like two vowels. Even Gwen Stefani said she couldn't doubt me. Met a female dragon, had a fire conversation. Approving million-dollar deals from my iPhone. Flyer than Beetlejuice, Beetlejuice, Beetlejuice. I got summer hating on me cause I'm hotter than the sun. Got Spring hating on me cause I ain't ever sprung. I parallel park in that red-and-yellow thing, old school Atlanta Hawk. And my chain Toucan Sam, that tropical colors, you can't match that, gotta be abstract. Quick Draw McGraw, I went to art school. I'm about to go Andre the Giant. Gotta handful of stacks, better grab an umbrella. I'm counting all day like a clock on the wall. I'm too clean for the choir.

    Zombie ipsum reversus ab viral inferno, nam rick grimes malum cerebro. De carne lumbering animata corpora quaeritis. Summus brains sit, morbo vel maleficia? De apocalypsi gorger omero undead survivor dictum mauris. Hi mindless mortuis soulless creaturas, imo evil stalking monstra adventus resi dentevil vultus comedat cerebella viventium. Qui animated corpse, cricket bat max brucks terribilem incessu zomby. The voodoo sacerdos flesh eater, suscitat mortuos comedere carnem virus. Zonbi tattered for solum oculi eorum defunctis go lum cerebro. Nescio brains an Undead zombies. Sicut malus putrid voodoo horror. Nigh tofth eliv ingdead.

What I have:
______
|@|a|b|
|@|a|b|
| |c|d|
|_|c|d|

What I want:
______
|@|a|b|
|@|c|d|

A: Given that HTML structure you can make your own 'grid' by first ensuring container has the height of chart by positioning that relative within container but then positioning the other elements absolute.
Positions and dimensions are calculated involving a CSS variable which holds the desired gap between elements.

* {
  margin: 0;
}

 :not(html, body, .container) {
  padding: .5em;
  border: 1px solid goldenrod;
  border-radius: .25em;
  box-sizing: border-box;
}

.container {
  --gap: .5em;
  --hg: calc(var(--gap) / 2);
  position: relative;
  display: inline-block;
  width: 100vw;
}

.container>* {
  margin: 0;
}

.chart {
  grid-area: chart;
  width: calc(20% - var(--hg));
}

[class^=details] {
  overflow-y: auto;
  position: absolute;
  height: calc(50% - var(--hg));
  width: calc(40% - (var(--hg) * 3 / 2));
  display: inline-block;
  overflow: auto;
}

.details-a {
  top: 0;
  left: calc(20% + var(--hg));
}

.details-b {
  top: 0;
  right: 0;
}

.details-c {
  bottom: 0;
  left: calc(20% + var(--hg));
}

.details-d {
  bottom: 0;
  right: 0;
}

    this

 thing

 here

 must

 be

 a

 chart

 but

 is

 it

 a

 chart

    We need to crystallize a plan business impact strategic high-level 30,000 ft view our competitors are jumping the shark. Gain traction UI, but game-plan. Can you run this by clearance? hot johnny coming through . Canatics exploratory investigation data
    masking 360 degree content marketing pool but conversational content so streamline you better eat a reality sandwich before you walk back in that boardroom. Unlock meaningful moments of relaxation red flag cta yet message the initiative, and blue
    sky thinking we can't hear you . When does this sunset? pulling teeth a better understanding of usage can aid in prioritizing future efforts onward and upward, productize the deliverables and focus on the bottom line we need to make the new version
    clean and sexy. Agile commitment to the cause yet closer to the metal so pipeline, yet land the plane for quick win, but shoot me an email. In an ideal world take five, punch the tree, and come back in here with a clear head we want to see more charts
    you gotta smoke test your hypothesis or you must be muted for paddle on both sides. Service as core &innovations as power makes our brand herding cats, so quick win, for high-level, for horsehead offer. Good optics increase the pipelines. We need
    a paradigm shift. This is not the hill i want to die on. We need to make the new version clean and sexy circle back but due diligence best practices i'm sorry i replied to your emails after only three weeks, but can the site go live tomorrow anyway?
    and 360 degree content marketing pool. Have bandwidth deploy to production but hit the ground running nor 60% to 30% is a lot of persent nor if you're not hurting you're not winning business impact and poop. Currying favour let's take this conversation
    offline nor that is a good problem to have this is a no-brainer anti-pattern. Have bandwidth workflow ecosystem yet drill down, net net.

    I'm baby knausgaard synth farm-to-table, squid paleo woke slow-carb four loko street art cronut iPhone butcher humblebrag direct trade hella. Salvia coloring book cornhole cloud bread migas glossier microdosing leggings cray live-edge distillery yuccie
    ennui swag. Pinterest subway tile actually fixie, lo-fi prism poke taxidermy tofu. Helvetica activated charcoal roof party shaman wayfarers drinking vinegar stumptown tacos man braid small batch actually direct trade. Migas gentrify tumeric salvia
    gluten-free slow-carb swag. Raw denim umami authentic thundercats fanny pack, locavore four dollar toast polaroid vexillologist quinoa lo-fi poutine. Fixie biodiesel everyday carry YOLO humblebrag. Bushwick offal brunch green juice, messenger bag
    tattooed freegan truffaut iceland banjo. Bitters everyday carry typewriter letterpress cardigan franzen. Hexagon cray lomo stumptown keytar, normcore drinking vinegar helvetica polaroid 8-bit VHS mlkshk shabby chic. Slow-carb stumptown man bun copper
    mug, mlkshk vinyl succulents poutine mixtape health goth fanny pack cornhole roof party. IPhone occupy put a bird on it kale chips, tacos artisan salvia cold-pressed marfa selvage tote bag. Messenger bag small batch affogato kickstarter, pork belly
    adaptogen drinking vinegar vinyl bicycle rights truffaut. Meditation lumbersexual sustainable wolf, semiotics YOLO chartreuse. Seitan fixie venmo truffaut gluten-free master cleanse chambray raclette prism, cliche af DIY cray fanny pack. Single-origin
    coffee 3 wolf moon salvia, shoreditch vegan put a bird on it kogi leggings sriracha retro yuccie man bun green juice live-edge cred. Ethical raclette sustainable chambray you probably haven't heard of them squid.

    Okay, hello, it's the Martian. Young money. Excuse my charisma, vodka with a spritzer. So misunderstood but what's the world without enigma? I lost my mind, it's somewhere out there stranded. I need a Winn-Dixie bag full of money right now to the VIP
    section. Just talked to moms, told her she the sweetest. Talking to myself because I am my own consultant. Paper chasin', tell that paper "Look, I'm right behind ya." Real G's move in silence like lasagna. People say I'm borderline crazy, sorta kinda.
    Got the Maserati dancing on the bridge. You pop'em cause we pop'em like Orville Redenbacher. But what should I scream for? This is my theme park. You're a goon but what's a goon to a goblin? I don't owe you like two vowels. Even Gwen Stefani said
    she couldn't doubt me. Met a female dragon, had a fire conversation. Approving million-dollar deals from my iPhone. Flyer than Beetlejuice, Beetlejuice, Beetlejuice. I got summer hating on me cause I'm hotter than the sun. Got Spring hating on me
    cause I ain't ever sprung. I parallel park in that red-and-yellow thing, old school Atlanta Hawk. And my chain Toucan Sam, that tropical colors, you can't match that, gotta be abstract. Quick Draw McGraw, I went to art school. I'm about to go Andre
    the Giant. Gotta handful of stacks, better grab an umbrella. I'm counting all day like a clock on the wall. I'm too clean for the choir.

    Zombie ipsum reversus ab viral inferno, nam rick grimes malum cerebro. De carne lumbering animata corpora quaeritis. Summus brains sit, morbo vel maleficia? De apocalypsi gorger omero undead survivor dictum mauris. Hi mindless mortuis soulless creaturas,
    imo evil stalking monstra adventus resi dentevil vultus comedat cerebella viventium. Qui animated corpse, cricket bat max brucks terribilem incessu zomby. The voodoo sacerdos flesh eater, suscitat mortuos comedere carnem virus. Zonbi tattered for
    solum oculi eorum defunctis go lum cerebro. Nescio brains an Undead zombies. Sicut malus putrid voodoo horror. Nigh tofth eliv ingdead.

A: You can make use of grid-row and grid-column properties in relation to your initial template for columns.

.wrapper {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
}
.wrapper > .special:nth-child(1) {
  grid-column: 1;
  grid-row: 1;
}
.wrapper > .special:nth-child(2) {
  grid-column: 1;
  grid-row: 2;
}

@

@

A

B

C

D


text:
Q: IOC with MVC and WCF I'm fairly across the concept of IOC containers, however I am having a little bit of difficulty in understanding how I would use one in the context of my application.
I am building an application that will have an MVC web front end and also a WCF service for outside applications to be built upon.
My question is, do I have to setup an IOC such as Windsor for both, or is there a way to setup them up so that they share the same container?

A: I'm assuming the MVC application and WCF services are separate applications.  That is to say, they are a separate codebase, hosted in separate IIS sites, etc.  If that is the case, then you will likely need separate containers unless you do something like putting your container in a shared assembly that both the WCF and MVC applications reference.  This would really only be advantagous if the two applications both have the same dependencies.

A: Depending on the size of the site and service, you might have IOC in both projects, but they can't really share the same container. Adding IOC to MVC is fairly straight forward, but it's considerable more tricky to add to WCF. If you'd like to add IOC to your WCF service, I'd suggest using something like CommonServiceFactory, which handles all of the plumbing for you. It can be a bit tricky to setup, because it relies on the CommonServiceLibrary abstraction, rather than on Windsor itself - but once you get up and rolling it's really easy to use.


text:
Q: Asp.NET MVC3 Application Error using Active Reports 6 I have a MVC3 app which works 100% on localhost, however, when I deploy the application, and upon accessing the Reports (by the way, I am using ActiveReports 6) i get "Sorry, an error occurred while processing your request." Any help? does this have to do with the autentication or folder permissions?
EDIT:
I have a standard license of Active Report without the WebViewer. Hence, I export the report to PDF and then send it to the browser via Response.BinaryWrite(memStream);


text:
Q: Quicklisp overriding default systems I have a slightly modified version of cl-json that I use for a poorly implemented server parser. When I try to (ql:quickload :cl-json) it naturally loads the file that they have stored on their server as opposed to my modified version stored on my local hard drive.
I considered turning it into an ASDF module, but all of my source code has references like (json:decode...) which would no longer work.
How do I tell quicklisp "Do not download from the server, instead use that directory over there"?

A: Quicklisp comes with a mechanism to do precisely that. Just place your version of cl-json in ~/quicklisp/local-projects/ and be done with it.
But I'm left wondering why would you think symbols that specify the package would stop to work? They won't. Or that quicklisp has anything to do with that?

A: I was able to find this link here with the following recommendation:

with the type conf4, for instance 42-asd-link-farm.conf, containing
the line:
(:directory "/home/luser/.asd-link-farm/")
If you want all the subdirectories under /home/luser/lisp/ to be
recursively scanned for .asd files, instead use:
(:tree "/home/luser/lisp/")

Using the (:tree ...) command would make it easy to never worry about that again.


text:
Q: Putting log files into Hive I have an unstructured file which has data like:
file.log:
2014-03-13 US Texas   334    4.985
2014-03-13 US    Minnesota   534    6.544

The log file is not tab separated as some fields are tab separated and some are not.
How can I put it into a Hive table?
Hive table schema is:
create table file (dateFact string, country string, state string, id int, value string);
How can I load the log file into the Hive table using Python and or Hadoop commands ?
Thanks!

A: The question is probably a duplicate.
please check this link and also this blog.
According to the above 2 links, you cannot have multiple delimiters, It is not supported.
But there is a work around. It can be achieved by using a RegExSerde .
You need to figure out a regex pattern for your business needs and keep that in serde properties.

A: With the RegexSerDe, you can use \s+ to match multiple whitespace types (single spaces, multi spaces, tabs).
I don't have my hive instance in front of me to test, but you should get the idea from the code below.
CREATE TABLE file.log (
  dateFact STRING,
  country STRING,
  state STRING,
  id STRING,
  value STRING
)
ROW FORMAT SERDE 'org.apache.hadoop.hive.contrib.serde2.RegexSerDe'
WITH SERDEPROPERTIES  (
"input.regex" = "([0-9]{4}-[0-9]{2}-[0-9]{2})\s+(\w+)\s+(\w+)\s+(\d+)\s+([\d.]+)",
"output.format.string" = "%1$s %2$s %3$s %4$s %5$s"
)
STORED AS TEXTFILE;


text:
Q: PostgreSQL/VBA: transaction block fail check or process During a transaction block, if part of it fails or gets interrupted what is the best way to handle this?
I am thinking intermediate queries (see code comments) to confirm that the previous query was successful. Or is there a better way?
Sub SetDataProcessPriorities()

Dim cCon As New ADODB.Connection
Set cCon = Application.Run("Personal.xlsb!ConnectToPg")
Call Application.Run("Personal.xlsb!SendPgQueryOnly", "begin;", cCon)

Call Application.Run("Personal.xlsb!SendPgQueryOnly", "delete from data_proc_pri;", cCon)
    'intermediate select query here?
Call Application.Run("Personal.xlsb!SendPgQueryOnly", "insert into data_proc_pri                                              select * from data_proc_pri_store;", cCon)
    'intermediate select query here?
Call Application.Run("Personal.xlsb!SendPgQueryOnly", "commit;", cCon)
End Sub

I'm open to a VBA (sorry) or PostgreSQL (or both) focused solution.
Bonus question: What do you call this type of programming? Infrastructure programming?
Personal workbook code if you need it:
Sub SendPgQueryOnly(sSql As String, Optional cCon As ADODB.Connection, Optional sOdbcName As String = "[omitted]")
sCaller = "SendPgQueryOnly"

    Dim cnDB As New ADODB.Connection

    Dim rsRecords As New ADODB.Recordset

    If IsMissing(cCon) Or cCon Is Nothing Then
        cnDB.Open sOdbcName
        rsRecords.CursorType = 2 'adOpenDynamic
        rsRecords.Open sSql, cnDB
    Else
        rsRecords.CursorType = 2 'adOpenDynamic
        rsRecords.Open sSql, cCon 'use the passed connection obj
    End If

cleanup:
    Set rsRecords = Nothing
    Set cnDB = Nothing
End Sub

Function ConnectToPg(Optional sOdbcName As String = "[omitted]") As ADODB.Connection
    sCaller = "ConnectToPg"

    Dim cnDB As New ADODB.Connection

    cnDB.Open sOdbcName
    Set ConnectToPg = cnDB
    End Function

A: For transactional control you can use the BeginTrans, CommitTrans, and RollbackTrans Methods on a Connection object
https://msdn.microsoft.com/en-us/library/ms680895(v=vs.85).aspx
Whilst one has a degree of programming style and latitude given the specific problem I guess one could query the database using some Select queries to ensure that the database state was changed as expected;  if as expected then commit and if not then rollback.


text:
Q: How do iterate over parts of this complex data structure? I have an object that I printed with Data::Dumper:
$VAR1 = {
          'record' => [
                      {
                        'text' => 'booting kernel',
                        'version' => '2',
                        'iso8601' => '2011-06-23 11:57:14.250 +02:00',
                        'event' => 'system booted',
                        'modifier' => 'na'
                      },
                      {
                        'text' => 'successful login',
                        'subject' => {
                                     'sid' => '999',
                                     'uid' => 'user',
                                     'audit-uid' => 'user',
                                     'tid' => '0 0 unknown',
                                     'ruid' => 'user',
                                     'rgid' => 'gsp',
                                     'pid' => '999',
                                     'gid' => 'gsp'
                                   },
                        'version' => '2',
                        'iso8601' => '2011-06-23 11:58:00.151 +02:00',
                        'event' => 'login - local',
                        'return' => {
                                    'retval' => '0',
                                    'errval' => 'success'
                                  },
                        'host' => 'unknown'
                      },
                    ],
          'file' => {
                    'iso8601' => '2011-06-23 11:57:40.064 +02:00'
                  }
        };

I want to print each value navigating such an hash. For what I understood is an hash with two keys (record, file) and record points to an array of hashes.
Can you please help reaching each value of this structure?
I tried:
my @array=$VAR1{'record'};
foreach (@array) {
    print $_{'text'};
}

… but it does not work.

A: If you just want to iterate over it, you can do something like this:
iterate($VAR1);

sub iterate {
    my $input = shift;
    unless (ref $input) {
        print "$input\n";
    } elsif (ref $input eq 'ARRAY') {
        iterate($_) for @$input;
    } elsif (ref $input eq 'HASH') {
        for (keys %$input) {
            print "$_\n";
            iterate($input->{$_});
        }
    } else {
        print ref $input,"\n";
    }
}

This doesn't exactly pretty print it like Data::Dumper does, but the technique might be useful if you want to do anything else with an arbitrary nested structure you don't know much about.

A: $VAR1{record} is an array reference, not an array. To get to the array, you need to dereference:
my @array = @{ $VAR1->{record} };

Each element in the array is a hash reference, so:
for my $record ( @array ) {
    print $record->{text};
}

A: $VAR1 is a reference. You need to dereference it.
$VAR1->{record} is a reference. You need to dereference it too.
$_ is also a reference, so you need to dereference that.
perldoc perlreftut
my @array = @{ $VAR1->{'record'} };
foreach (@array) {
    print $_->{'text'};
}


text:
Q: Python plot multiple circle on grid with legend I want to plot on a grid of N by M, circles of various color and same size. On a x,y location, can be a circle or nothing.
I would like to have a x label for each column (that would be here a week), and an ylabel (that would be here a subject).
For now, I found a way to plot the circles using subplots, but I can't manage to had the text nor the grid.
Here is my code to draw the circles:
import matplotlib.pyplot as plt
from matplotlib.patches import Wedge
from plotly.graph_objs import *
from matplotlib.gridspec import GridSpec

def dual_half_circle(center, radius, angle=0, ax=None, colors=('w','k'), **kwargs):
    """
    Add two half circles to the axes *ax* (or the current axes) with the
    specified facecolors *colors* rotated at *angle* (in degrees).
    """
    if ax is None:
        ax = plt.gca()
    kwargs.update(transform=ax.transAxes, clip_on=False)
    theta1, theta2 = angle, angle + 180
    w1 = Wedge(center, radius, theta1, theta2, fc=colors[0], **kwargs)
    w2 = Wedge(center, radius, theta2, theta1, fc=colors[1], **kwargs)
    for wedge in [w1, w2]:
        ax.add_artist(wedge)
    return [w1, w2]

Here is a code to display everything (I removed the color conditions):
DF = pd.DataFrame(np.random.choice([True, False], size = (15, 10)))

fig, ax = plt.subplots()
for ii in range(0,DF.shape[1]):
    for jj in range(0,DF.shape[0]):
        if DF[ii][jj]:
            dual_half_circle((ii, -1*jj), radius=0.3, colors=('b','g'), angle=90, ax=ax)
            ax.axis('equal')

for ii in range(0,DF.shape[1]):
    plt.annotate(xy= (ii, 1), s= 'W'+str(ii), fontsize = 100, verticalalignment='center', horizontalalignment='center')

for jj in range(0,DF.shape[0]):
    plt.annotate(xy =(-1, -1*jj),s= 'subj '+str(jj), fontsize = 100, verticalalignment='center', horizontalalignment='center')

plt.show()

And here is the result, where I don't have the annotation nor the grid
Result
Should I change from subplot to classical plot to be able to add what I want?
Thank you for your help!

A: Try the following. (I still don't understand the thing with the grid, so I left that out)
import matplotlib.pyplot as plt
from matplotlib.patches import Wedge
import pandas as pd
import numpy as np

def dual_half_circle(center, radius, angle=0, ax=None, colors=('w','k'), **kwargs):
    """
    Add two half circles to the axes *ax* (or the current axes) with the
    specified facecolors *colors* rotated at *angle* (in degrees).
    """
    if ax is None:
        ax = plt.gca()
    theta1, theta2 = angle, angle + 180
    w1 = Wedge(center, radius, theta1, theta2, fc=colors[0], **kwargs)
    w2 = Wedge(center, radius, theta2, theta1, fc=colors[1], **kwargs)
    for wedge in [w1, w2]:
        ax.add_artist(wedge)
    return [w1, w2]

DF = pd.DataFrame(np.random.choice([True, False], size = (15, 10)))

fig, ax = plt.subplots(figsize=(8,13))
for ii in range(0,DF.shape[1]):
    for jj in range(0,DF.shape[0]):
        if DF[ii][jj]:
            dual_half_circle((ii, -1*jj), radius=0.3, colors=('b','g'), angle=90, ax=ax)
            ax.axis('equal')

for ii in range(0,DF.shape[1]):
    plt.annotate(xy= (ii, 1), s= 'W'+str(ii), fontsize = 10, verticalalignment='center', horizontalalignment='center')

for jj in range(0,DF.shape[0]):
    plt.annotate(xy =(-1, -1*jj),s= 'subj '+str(jj), fontsize =10, verticalalignment='center', horizontalalignment='right')

ax.set_xlim(-1,10)
ax.set_ylim(-15,3)
plt.axis("off")
plt.plot([-1,10], [-15,3], alpha=0)
plt.tight_layout()
plt.show()


text:
Q: What's LinkObject error about, and what may have caused it? I've been running a simulation on a server, using parallezation, suddenly I got this error message:
LinkObject::linkw:     Unable to write data to closed link
    LinkObject[/usr/local/Wolfram/Mathematica/11.3/Executables/wolfram
      -subkernel -noinit -nopaclet -wstp, 96, 11].

Kernels::rdead:     Subkernel connected through KernelObject[11, local] appears dead.

LaunchKernels::clone:     Kernel KernelObject[11, local, <defunct>] resurrected as
    KernelObject[17, local].

Afterwards, the programme starts giving several errors of the type
Inverse::luc: Result for Inverse of badly conditioned matrix
                7            6            7           7            6
    {{1.56499 10 , 3.88419 10 , 1.47829 10 , 1.4474 10 , 3.59235 10 ,
                7           7            6                    7            7
      1.36722 10 , 1.4207 10 , 3.52609 10 , <<30>>, 1.33088 10 , 1.36087 10 ,
                6            7
      3.37759 10 , 1.28548 10 }, <<40>>, {<<42>>}} may contain significant
     numerical errors.

Inverse::luc: Result for Inverse of badly conditioned matrix
              7            6            7            7            6
    {{2.516 10 , 6.16733 10 , 2.37715 10 , 2.11168 10 , 5.17626 10 ,
                7            7            6                    7
      1.99515 10 , 2.15432 10 , 5.28077 10 , <<30>>, 1.82282 10 ,
                7            6            7
      1.86818 10 , 4.57938 10 , 1.76509 10 }, <<40>>, {<<42>>}} may contain
     significant numerical errors.

Inverse::luc: Result for Inverse of badly conditioned matrix
                7           6           7            7            6
    {{3.17716 10 , 7.6422 10 , 3.0029 10 , 2.71563 10 , 6.53206 10 ,
                7           7            6                    7            7
      2.56668 10 , 2.6591 10 , 6.39608 10 , <<30>>, 2.46368 10 , 2.45544 10 ,
               6            7
      5.9062 10 , 2.32076 10 }, <<40>>, {<<42>>}} may contain significant
     numerical errors.

General::stop: Further output of Inverse::luc
     will be suppressed during this calculation. From KernelObject[17, local]: Inverse::luc: Result for Inverse of badly conditioned matrix
               7           6            7            7            6
    {{2.2294 10 , 5.6294 10 , 2.10524 10 , 1.92622 10 , 4.86383 10 ,
                7            7            6            7
      1.81894 10 , 1.99442 10 , 5.03605 10 , 1.88334 10 , <<14>>,
                7            7           6            7
      1.91667 10 , 2.03254 10 , 5.1323 10 , 1.91934 10 }, <<26>>} may contain
     significant numerical errors. From KernelObject[15, local]: Inverse::luc: Result for Inverse of badly conditioned matrix
               7           6            7            7            6
    {{2.2294 10 , 5.6294 10 , 2.10524 10 , 2.03207 10 , 5.13112 10 ,
               7            7            6          7                    7
      1.9189 10 , 1.97817 10 , 4.99502 10 , 1.868 10 , <<14>>, 1.98409 10 ,
                7            6            7
      1.91763 10 , 4.84215 10 , 1.81083 10 }, <<26>>} may contain significant (...)

Until the 1st message, the simulation had been running for a couple of days without any problem.
First, are both related? If so, what may have caused this? If not, what caused the 1st one?
Is there a way to find out? Or how to solve it?


text:
Q: Can I read whole NTFS directory tree into RAM at once? Since this quesiton yielded no useful answers and some comments please see my other question that got spot on anwer: How exactly "Everything Search" can give me immediately searchable list of 2bln files on my 4TB HDD in less than 10 seconds?
Only way I know of reading directories is to recursively descend into each directory but that's too slow if I want to find file anywhere on the whole disk quickly.
There's windows program "Everything Search" http://www.voidtools.com/ that does that faster than I assume is possible by recursive descent (it reads filenames of almost 2bln files on 4TB HDD in less than 10 seconds).
I know I could build index ahead of time but can it be done just by reading whole directory tree of a disk into ram in one operation and parsed there?
EDIT
Since my question proved to be confusing here's what I want to do:
https://msdn.microsoft.com/en-us/library/07wt70x2(v=vs.110).aspx?cs-save-lang=1&cs-lang=cpp#code-snippet-1
// For Directory::GetFiles and Directory::GetDirectories
// For File::Exists, Directory::Exists
using namespace System;
using namespace System::IO;
using namespace System::Collections;

// Insert logic for processing found files here.
void ProcessFile( String^ path )
{
   Console::WriteLine( "Processed file '{0}'.", path );
}

// Process all files in the directory passed in, recurse on any directories
// that are found, and process the files they contain.
void ProcessDirectory( String^ targetDirectory )
{

   // Process the list of files found in the directory.
   array<String^>^fileEntries = Directory::GetFiles( targetDirectory );
   IEnumerator^ files = fileEntries->GetEnumerator();
   while ( files->MoveNext() )
   {
      String^ fileName = safe_cast<String^>(files->Current);
      ProcessFile( fileName );
   }

   // Recurse into subdirectories of this directory.
   array<String^>^subdirectoryEntries = Directory::GetDirectories( targetDirectory );
   IEnumerator^ dirs = subdirectoryEntries->GetEnumerator();
   while ( dirs->MoveNext() )
   {
      String^ subdirectory = safe_cast<String^>(dirs->Current);
      ProcessDirectory( subdirectory );
   }
}

int main( int argc, char *argv[] )
{
   for ( int i = 1; i < argc; i++ )
   {
      String^ path = gcnew String(argv[ i ]);
      if ( File::Exists( path ) )
      {

         // This path is a file
         ProcessFile( path );
      }
      else
      if ( Directory::Exists( path ) )
      {

         // This path is a directory
         ProcessDirectory( path );
      }
      else
      {
         Console::WriteLine( "{0} is not a valid file or directory.", path );
      }

   }
}

I want to get same information but without calling Directory::GetDirectories multiple times. Solution I'm looking for doesn't look anyway like this code. This code is just illustration of what information I want read of the disk (names of all files in directories) not how I'd like to do it (I don't want recursion and as many system calls as there are directories).
EDIT 2 (For the people that consider this question too broad):
I'm asking how to do that either on Windows or Linux operating systems. I'll accept answer in any language because I'm most interested what system calls I need to make (and how to parse the results of those calls) to get NTFS directory tree of a whole drive into RAM with fewer system calls than one per each directory on the drive.
I'll also accept the answer that points me to Windows or Linux library that does exactly that.

A: if you have sufficient amount of RAM then go ahead and do it. But I recommend you to load disk in parts instead of whole disk that will also improve your time efficiency.


text:
Q: How to install Ansible in Amazon Linux EC2? I pick this Amazon Linux: Amazon Linux AMI 2017.09.1 (HVM), SSD Volume Type - ami-1a033c7a.
I installed Ansible using the command:
sudo pip install ansible,

it shows install completes.when I run ansible --version, it shows:
ansible 2.4.1.0
  config file = None
  configured module search path = [u'/home/ec2-
user/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/local/lib/python2.7/site-
packages/ansible
  executable location = /usr/local/bin/ansible
  python version = 2.7.12 (default, Nov  2 2017, 19:20:38) [GCC 4.8.5
20150623 (Red Hat 4.8.5-11)]

Why config file = None? Shouldn't it shows /etc/ansible/ansible.cfg? I do not see /etc/ansible/hosts, not even folder /etc/ansible. Did I install correctly, where is the folder /etc/ansible?

A:
why config file = None?

Because at the time of running ansible --version no config file was found.

shouldn't it shows /etc/ansible/ansible.cfg?

No. It should show the ansible.cfg actually being used.
Per documentation, Ansible tries to find the config file in:

*

*ANSIBLE_CONFIG (an environment variable)

*ansible.cfg (in the current directory)

*.ansible.cfg (in the home directory)

*/etc/ansible/ansible.cfg

ansible --version will show you the exact path to the one being used.
Strictly speaking the last point is not always true, as package managers and virtual environment managers might cause the /etc directory to be located elsewhere.

did I install correctly

You didn't mention any error or warning during the installation and ansible --version returned a proper response.
There is no reason not to believe it's installed properly.

where is the folder /etc/ansible?

It's not existing on your system. There is no default inventory file, nor configuration file created by the installation package.
Create one.

A: Here I answer the question myself.
There are many ways to install ansible, and then you get difference default settings, depending on the OS. Many tutorials just assume the ansible_hosts and ansible.cfg already in /etc/ansible, which is not correct if you install ansible using pip.
In fact, if you install ansible using pip, then you will not see ansible.cfg and ansible_hosts in /etc/ansible. Even the folder /etc/ansible does not exist. but never mind, you can create these two files yourself as follows:
suppose you want to store ansible_hosts and ansible.cfg in /home/ec2-user, then you can:
echo <remote_host> /home/ec2-user/ansible_hosts
export ANSIBLE_INVENTORY=/home/ec2-user/ansible_hosts
wget https://raw.githubusercontent.com/ansible/ansible/devel/examples/ansible.cfg
mv ansible.cfg /home/ec2-user/
export ANSIBLE_CONFIG=/home/ec2-user/ansible.cfg

then if ansible --version, you will see
ansible 2.4.1.0
  config file = /home/ec2-user/ansible.cfg
....

and if you test ansible ad-hoc command (my remote_host is ubuntu, so I use -u ubuntu, you can change it to be yours):
ansible all -m ping -u ubuntu

then you see ansible ping remote_host successfully.
This shows ansible does work.


text:
Q: How to implement "like" functionality of Facebook in Android I am working on gallery app in which there are lots of images, I want to give functionality to the user that he can like any image within the app and it should reflect in his Facebook profile. For this I want to use the newest SDK(3.0.1).
If he is not logged in, app should take it to the login page of Facebook otherwise by clicking the like button it should reflect in the account of current user.
Please help me to sort out the problem, any help would be appreciable.
Thanks in advance.

A: Its all right there in Facebook docs :
https://developers.facebook.com/docs/getting-started/facebook-sdk-for-android/3.0/
What you are describing is 100% possible, just play with examples in the link above.


text:
Q: Can't find servers in Data Connection in Visual Studio 2012? http://msdn.microsoft.com/en-us/data/jj193542
I'm following the tutorial in the link above, and when I get to the step "Connect to either LocalDb ((localdb)\v11.0) or SQL Express (.\SQLEXPRESS), depending on which one you have installed" in the "Where's my data" section, the server name drop down is blank. I have LocalDB installed, and the program is writing to a database since following the previous steps of the tutorial I created two tables that were saved, but for some reason I can't add a connection to any server in Database Explorer.
I'm using Visual Studio 2012 Express for Desktop.

A: If it's blank it means you never set it up before so add it manually, if you are not sure what to put as the server name you can try .


text:
Q: Magento Coupon code doesnot work when From or To Date is specified I have a strange issue in my promotional rules.  When I select From Date or To Date or both when creating a shopping cart price rule in Magento, Magento says coupon is invalid.
As soon as, I removed those dates and apply the coupon, it works like a charm.
Is anyone facing the same kinda issue?
Awaiting the response.

*

*Version: CE 1.7.0.2

*Replaced the Checkout module of Magento core with the default one.

Any help is really appreciated.


text:
Q: Asterisk No Audio in Extension I have an inbound number that I want to connect to my cell. The problem I'm having is that unless I use the music on hold flag, I don't get any audio.
For example:
exten => 1**********,1,Dial(SIP/1**********@flowroute,30,m)

The above works great, ot rings on my cell and the call is connected and we can talk.
Now when I remove the music flag or try an ring flag because I need the ringing sound, it connects to my cell, but when I answer, all I get is silence:
exten => 1**********,1,Dial(SIP/1**********@flowroute,30)
exten => 1**********,1,Dial(SIP/1**********@flowroute,30,r)

Neither of the above works.
Anyone encountered this or have a fix?
[SOLVED]
I added progressinband=yes to sip.conf under the general area. Now when I call with no flags, it rings and there is audio after I pick up.

A: Do a SIP trace and see which of "180 Ringing" and/or "183 Session Progress" responses that 1** peer sends you when you dial it without "m" or "r", in what order, and which has SDP. If it differs from cases where you do get ringback, then the problem is the calling peer, and you need to try different progressinband settings for that peer (yes / no / never) to work around it.
It's very strange that you get silence after answering when you don't use "m" in Dial(). NAT problem?


text:
Q: What if a conjecture were provably unprovable? Suppose we found a proof that "The Twin Prime Conjecture cannot be proven", without any conclusion as to the conjecture itself being true or false.
Is it then possible for the conjecture to be true?  or, must the conjecture then be false for some reason?  or, must this proof of unprovability be flawed?
(I'm using this specific example to help understand if any similar simple conjectures could be provably unprovable.  I have my doubts on whether a simple conjecture can be provably unprovable since, instead of making conclusions for an infinite number of inputs like the Halting Theorem does, we are here talking about just one true/false conclusion.)

A: There is an important issue with statements of the form "$X$ is unprovable": in what system is $X$ unprovable? We assume here that $X$ is some consistent statement written in some formal language.
Statements provable with no non-logical axioms are known as logical validities. Few interesting mathematical statements are phrased as logical validities. So the fact that $X$ is unprovable without non-logical axioms tells very little about $X$. On the other hand, if $T$ is the conjunction of some finite set of axioms sufficient to prove $X$, then $T \to X$ is a logical validity.
What if $X$ is unprovable from some larger set of non-logical axioms? That mainly tells us that those axioms are not strong enough to prove $X$. In other words, the fact that $X$ is unprovable from a set of axioms often tells us both about $X$ and about that system of axioms.  As long as $X$ is consistent, we could always choose a stronger set of consistent axioms that is able to prove $X$ (e.g. we could take $X$ itself as an axiom).
In many concrete examples, the unprovable of $X$ from some system of axioms tells us more about the system of axioms than it tells us about $X$. For example, the combinatorial principle in Goodstein's theorem is unprovable in Peano arithmetic. The main interest in this is that, when we really look at the result, it shows us something new about provability in Peano arithmetic. It also helps us understand the combinatorial principle more deeply, but in this case we already have a very good understanding of the combinatorial principle which comes from its proof in ZFC.
This is a common pattern in mathematical logic. When we examine the proof that a principle is unprovable in a particular system, it often tells us as much or more about the system as it tells us about the principle - particularly when we scrutinize the unprovability proof intensively to try to extract the general method.

A: If a conjecture X is unprovable that can be translated to the following:
if X is true no contradiction can be derived
if X is false no contradiction can be derived
Both of these must be true because otherwise X would not be unprovable (we could merely choose one of the appropriate routes and eventually find a contradiction)
That being said it becomes evident then that the truth/false value of X is independent of the system of proving being used.
So once something has become unprovable in a fixed system of mathematics. It becomes meaningless to ask if the statement is true or false in that same system.
Hope that clarifies a thing or two :)


text:
Q: SuperResolution using MNIST not working properly I am new to Deep Learning and I made a model that pretends to upscale a 14x14 image to a 28x28. For that, I trained the newtork using MNIST repository as a first attempt to solve this problem.
For making the model structure I followed this paper: https://arxiv.org/pdf/1608.00367.pdf
import numpy as np
from tensorflow.keras import optimizers
from tensorflow.keras import layers
from tensorflow.keras import models
import os
import cv2
from tensorflow.keras.callbacks import TensorBoard
from tensorflow.keras import initializers
import matplotlib.pyplot as plt
import pickle
import time

# Tensorboard Stuff:
NAME = "MNIST_FSRCNN_test -{}".format(
    int(time.time()))  # This is the name of our try, change it if it's a
# new try.
tensorboard = TensorBoard(log_dir='logs/{}'.format(NAME))  # defining tensorboard directory.

# Path of the data
train_small_path = "D:/MNIST/training/small_train"
train_normal_path = "D:/MNIST/training/normal_train"

test_small_path = "D:/MNIST/testing/small_test"
test_normal_path = "D:/MNIST/testing/normal_test"

# Image reading from the directories. MNIST is in grayscale so we read it that way.
train_small_array = []
for img in os.listdir(train_small_path):
    try:
        train_small_array.append(np.array(cv2.imread(os.path.join(train_small_path, img), cv2.IMREAD_GRAYSCALE)))
    except Exception as e:
        print("problem with image reading in train small")
        pass
train_normal_array = []
for img in os.listdir(train_normal_path):
    try:
        train_normal_array.append(np.array(cv2.imread(os.path.join(train_normal_path, img), cv2.IMREAD_GRAYSCALE)))
    except Exception as e:
        print("problem with image reading in train normal")
        pass
test_small_array = []
for img in os.listdir(test_small_path):
    try:
        test_small_array.append(cv2.imread(os.path.join(test_small_path, img), cv2.IMREAD_GRAYSCALE))
    except Exception as e:
        print("problem with image reading in test small")
        pass

test_normal_array = []
for img in os.listdir(test_normal_path):
    try:
        test_normal_array.append(cv2.imread(os.path.join(test_normal_path, img), cv2.IMREAD_GRAYSCALE))
    except Exception as e:
        print("problem with image reading in test normal")
        pass

train_small_array = np.array(train_small_array).reshape((60000, 14, 14, 1))
train_normal_array = np.array(train_normal_array).reshape((60000, 28, 28, 1))

test_small_array = np.array(test_small_array).reshape((10000, 14, 14, 1))
test_normal_array = np.array(test_normal_array).reshape((10000, 28, 28, 1))

training_data = []
training_data.append([train_small_array, train_normal_array])

testing_data = []
testing_data.append([test_small_array, test_normal_array])

# ---SAVE DATA--
# We are saving our data
pickle_out = open("X.pickle", "wb")
pickle.dump(y, pickle_out)
pickle_out.close()
# for reading it:
pickle_in = open("X.pickle", "rb")
X = pickle.load(pickle_in)
# -----------

# MAKING THE NETWORK
d = 56
s = 12
m = 4
upscaling = 2

model = models.Sequential()
bias = True

# Feature extraction:
model.add(layers.Conv2D(filters=d,
                        kernel_size=5,
                        padding='SAME',
                        data_format="channels_last",
                        use_bias=bias,
                        kernel_initializer=initializers.he_normal(),
                        input_shape=(None, None, 1),
                        activation='relu'))

# Shrinking:
model.add(layers.Conv2D(filters=s,
                        kernel_size=1,
                        padding='same',
                        use_bias=bias,
                        kernel_initializer=initializers.he_normal(),
                        activation='relu'))

for i in range(m):
    model.add(layers.Conv2D(filters=s,
                            kernel_size=3,
                            padding="same",
                            use_bias=bias,
                            kernel_initializer=initializers.he_normal(),
                            activation='relu'),
              )

# Expanding
model.add(layers.Conv2D(filters=d,
                        kernel_size=1,
                        padding='same',
                        use_bias=bias,
                        kernel_initializer=initializers.he_normal,
                        activation='relu'))

# Deconvolution
model.add(layers.Conv2DTranspose(filters=1,
                                 kernel_size=9,
                                 strides=(upscaling, upscaling),
                                 padding='same',
                                 use_bias=bias,
                                 kernel_initializer=initializers.random_normal(mean=0.0, stddev=0.001),
                                 activation='relu'))

# MODEL COMPILATION
model.compile(loss='mse',
              optimizer=optimizers.RMSprop(learning_rate=1e-3),
              metrics=['acc'])

model.fit(x=train_small_array, y=train_normal_array,
          epochs=10,
          batch_size=1500,
          validation_split=0.2,
          callbacks=[tensorboard])

print(model.evaluate(test_small_array, test_normal_array))

# -DEMO-----------------------------------------------------------------
from PIL import Image
import PIL.ImageOps
import os

dir = 'C:/Users/marcc/OneDrive/Escritorio'
os.chdir(dir)

myImage = Image.open("ImageTest.PNG").convert('L')  # convert to black and white
myImage = myImage.resize((14, 14))

myImage_array = np.array(myImage)

plt.imshow(myImage_array, cmap=plt.cm.binary)
plt.show()

myImage_array = myImage_array.astype('float32') / 255
myImage_array = myImage_array.reshape(1, 14, 14, 1)

newImage = model.predict(myImage_array)
newImage = newImage.reshape(28,28)
plt.imshow(newImage, cmap=plt.cm.binary)
plt.show()

The problem that I have is that with 10 epochs it seems to work, it transforms this image:14x14 MNIST
into this one:
10 epochs 28x28
But when I make 20 epochs I get20 epochs 28x28
I want to know what happens. First I thought that maybe the model was overfitting, but when I check the loss function of training and validation it doesn't seem to overfit:
training and validation loss

A: I used your code and tried to reproduce the error, but it worked fine for me.
I loaded the mnist images and resized them to (14, 14) using skimage.transform.resize.
The training during 200 epochs gives :

Epoch 1/200 32/32 - 6s 91ms/step -
loss: 4380.9126 - acc: 0.1659 - val_loss: 3406.4109 - val_acc: 0.3661
Epoch 2/200 32/32 - 3s 80ms/step -
loss: 2827.0591 - acc: 0.5598 - val_loss: 2255.1472 - val_acc: 0.6366
...
Epoch 199/200 32/32 - 3s
86ms/step - loss: 149.0597 - acc: 0.8035 - val_loss: 191.1202 -
val_acc: 0.8072
Epoch 200/200 32/32 -
3s 85ms/step - loss: 145.8007 - acc: 0.8035 - val_loss: 207.3333 -
val_acc: 0.8072

val_loss tends to fluctuate between epochs but it decreases globally.
Some results :
Here is the code to plot the figures:
     def plot_images(num_img):
      fig, axs = plt.subplots(2, 2)
      my_normal_image = test_normal_array[num_img, :, :, 0]
      axs[0, 0].set(title='input normal image')
      axs[0, 0].imshow(my_normal_image, cmap=plt.cm.binary)
      axs[1, 0].set(title = 'small img')
      my_resized_image = resize(my_normal_image, anti_aliasing=True, output_shape=(14, 14))
      axs[1, 0].imshow(my_resized_image, cmap=plt.cm.binary)
      axs[0, 1].set(title='super resolution')
      my_super_res_image = model.predict(my_resized_image[np.newaxis, :, :, np.newaxis])[0, :, :, 0]
      axs[0, 1].imshow(my_super_res_image, cmap=plt.cm.binary)
      axs[1, 1].set(title='small resized')
      my_rr_image = resize(my_resized_image, output_shape=(28, 28), anti_aliasing=True)
      axs[1, 1].imshow(my_rr_image, cmap=plt.cm.binary)
      plt.show()

    index = 8
    plot_images(np.argwhere(y_test==index)[0][0])
    index = 4
    plot_images(np.argwhere(y_test==index)[0][0])

In addition, here is also how I build the dataset :
    (x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
    train_normal_array = np.expand_dims(x_train, axis=3)
    test_normal_array = np.expand_dims(x_test, axis=3)
    train_small_array = np.zeros((train_normal_array.shape[0], 14, 14, 1))
    for i in tqdm.tqdm(range(train_normal_array.shape[0])):
      train_small_array[i, :, :] = resize(train_normal_array[i], (14, 14), anti_aliasing=True)
    test_small_array = np.zeros((test_normal_array.shape[0], 14, 14, 1))
    for i in tqdm.tqdm(range(test_normal_array.shape[0])):
      test_small_array[i, :, :] = resize(test_normal_array[i], (14, 14), anti_aliasing=True)
    training_data = []
    training_data.append([train_small_array.astype('float32'), train_normal_array.astype('float32') / 255])

    testing_data = []
    testing_data.append([test_small_array.astype('float32'), test_normal_array.astype('float32') / 255])

Note that I do not divide train_small_array and test_small_array by 255 as resize does the job.


text:
Q: Showing the AppBar on right click on GridView item In WinRT Applications, when you right click a ListBoxItem the AppBar is shown. But when you right click a GridViewItem the AppBar doesn't appear. Can this be configured?
If not is it beter to work with a ListBox instead of GridView and customize the templates. Or should I implement it With a RightTapped command.
(I work with MVVM Light, since Caliburn.Micro is currently not working)
Example of RightTappedCommand:

 public sealed class RightTapped
    {
        #region Properties

        #region Command

        ///
        /// GetCommand
        ///
        ///
        ///
        public static ICommand GetCommand(DependencyObject obj)
        {
            return (ICommand)obj.GetValue(CommandProperty);
        }

        ///
        /// SetCommand
        ///
        ///
        ///
        public static void SetCommand(DependencyObject obj, ICommand value)
        {
            obj.SetValue(CommandProperty, value);
        }

        ///
        /// DependencyProperty CommandProperty
        ///
        public static readonly DependencyProperty CommandProperty =
            DependencyProperty.RegisterAttached("Command", typeof(ICommand), typeof(RightTapped), new PropertyMetadata(null, OnCommandChanged));

        #endregion Command

        #region CommandParameter

        ///
        /// GetCommandParameter
        ///
        ///
        ///
        public static object GetCommandParameter(DependencyObject obj)
        {
            return (object)obj.GetValue(CommandParameterProperty);
        }

        ///
        /// SetCommandParameter
        ///
        ///
        ///
        public static void SetCommandParameter(DependencyObject obj, object value)
        {
            obj.SetValue(CommandParameterProperty, value);
        }

        ///
        /// DependencyProperty CommandParameterProperty
        ///
        public static readonly DependencyProperty CommandParameterProperty =
            DependencyProperty.RegisterAttached("CommandParameter", typeof(object), typeof(RightTapped), new PropertyMetadata(null, OnCommandParameterChanged));

        #endregion CommandParameter

        #region HasCommandParameter

        private static bool GetHasCommandParameter(DependencyObject obj)
        {
            return (bool)obj.GetValue(HasCommandParameterProperty);
        }

        private static void SetHasCommandParameter(DependencyObject obj, bool value)
        {
            obj.SetValue(HasCommandParameterProperty, value);
        }

        private static readonly DependencyProperty HasCommandParameterProperty =
            DependencyProperty.RegisterAttached("HasCommandParameter", typeof(bool), typeof(RightTapped), new PropertyMetadata(false));

        #endregion HasCommandParameter

        #endregion Propreties

        #region Event Handling

        private static void OnCommandParameterChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
        {
            SetHasCommandParameter(o, true);
        }

        private static void OnCommandChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
        {
            var element = o as FrameworkElement;
            if (element != null)
            {
                if (e.NewValue == null)
                {
                    element.RightTapped -= FrameworkElementKeyUp;
                }
                else if (e.OldValue == null)
                {
                    element.RightTapped += FrameworkElementKeyUp;
                }
            }
        }

        private static void FrameworkElementKeyUp(object sender, RightTappedRoutedEventArgs e)
        {
            var o = sender as DependencyObject;
            var command = GetCommand(sender as DependencyObject);

            var element = e.OriginalSource as FrameworkElement;
            if (element != null)
            {
                // If the command argument has been explicitly set (even to NULL)
                if (GetHasCommandParameter(o))
                {
                    var commandParameter = GetCommandParameter(o);

                    // Execute the command
                    if (command.CanExecute(commandParameter))
                    {
                        command.Execute(commandParameter);
                    }
                }
                else if (command.CanExecute(element.DataContext))
                {
                    command.Execute(element.DataContext);
                }
            }
        }

        #endregion
    }
In Xaml, something like this:
common:Tapped.Command="{Binding ShowAppBar}"

A: You can just do myAppBar.IsOpen = true.

A: It depends on the gridview selection mode, the right-click is used for selecting items. If you set the selectionmode property to None the appbar will open on right-click.


text:
Q: How to write maximum value of tree view in odoo? I have one tree view have 3 columns . I wanted to get maximum of each column in function field ?
class feeder_data(osv.Model):
    _name = "feeder.data"
    _rec_name= "company_id1"
    _columns = {
        'company_id1': fields.many2one('res.company', 'Substation', required=True),
        'combine2':fields.one2many('data.value','combine','Details'),
        'max_mw': fields.function(_amount_line, string='Subtotal',type='integer'),
           }
class data_value(osv.Model):
    _name = "data.value"
    _rec_name = "mega_wat"
    _columns={
        'Hours':fields.integer('Hours'),
        'mega_wat':fields.integer('Mega Watts'),
        'combine':fields.many2one('feeder.data','details'),
    }

Here I do have tree view in data.value. In this class I have mega_wat field here I will enter values in hourly_feeder class i have one field as max_wt i wanted to have function field with max of mega_wat in it

A: First, create the max function in your model:
def _get_max_of_tree(self,cr,uid,ids,context=None):
    res={}
    for o in self.browse(cr, uid, ids, context):
        res[o.id] = max(0.col1 , o.col2, o.col3)
    return res

then create a function field for it
_columns = {
            ...
            'mymax' : fields.function(_get_max_of_tree, type='float'),
            ...
           }

EDIT:
In you situation, it should be like this:
class feeder_data(osv.Model):
    _name = "feeder.data"
    _rec_name= "company_id1"

    def _amount_line(self,cr,uid,ids,context=None):
        res={}
        for fd in self.browse(cr, uid, ids, context):
            res[fd.id] = max([dv.mega_wat for dv in fd.combine2])
        return res

    _columns = {
        'company_id1': fields.many2one('res.company', 'Substation', required=True),
        'combine2':fields.one2many('data.value','combine','Details'),
        'max_mw': fields.function(_amount_line, string='Subtotal',type='integer'),
           }

A: Use Built in Max function.
Help on built-in function max in module builtin:
max(...)
    max(iterable[, key=func]) -> value
    max(a, b, c, ...[, key=func]) -> value

    With a single iterable argument, return its largest item.
    With two or more arguments, return the largest argument.

Or you can define your own function.
def max_number(a, b, c):
    Max = a
    if b > Max:
        Max = b
    if c > Max:
        Max = c
    return Max

Your functional fields should be like this,
def _amount_line(self, cr, uid, ids, field_names, arg=None, context=None):
    res = {}
    for obj in self.browse(cr, uid, ids, context=context):
        max = 0
        for data in obj.combine2:
            if data.mega_wat > max:
                max = data.mega_wat

        res[obj.id] = max
    return res