text:
Q: Strong form of Urysohn Lemma Let $A$ and $B$ are two disjoint closed subsets of a connected normal space $X$. Prove there exists a continuous function $f:X\rightarrow [0,1]$ s.t. $f(A)=\{0\}, \space f(B)=\{1\}.$  Also $\forall r\in \mathbb{Q}\cap[0,1]$ , the interior of $f^{-1}(r)$ is not empty.

This is an exercise in my textbook and it's about the strong form of the Urysohn lemma. The proof for the lemma in the text book uses the dyadic rationals, so I'm trying to apply it to the above case, but have made no progress.
Any help will be appreciated.

A: This is a very challenging proof. The correct statement of Urysohn's Lemma has $A\subseteq f^{-1}(0)$ and $B\subseteq f^{-1}(1)$. If this is the lemma I'm thinking of then it is formally stated as:

Let $A$,$B$ be disjoint closed sets in a normal space $X$. Then for each diadic rational $r \in [0,1]$ there exists an open set $U_r$ such that $A\subseteq U_0$, $B\subseteq (X\setminus U_1)$ and for $r<s$, $\overline{U_r} \subseteq U_s$.

Since Urysohn's lemma provides an equivalent definition of a normal space, we begin by assuming we have a normal space, $X$ with disjoint, nonempty closed sets $A$ and $B$. Let $D\subset [0,1]$ be the set of all dyadic rationals contained in $[0,1]$. Then by the lemma we gain a collection of open sets $\{U_r\}_{r\in D}$ with all the properties outlined in the lemma. Let $f:X\to [0,1]$ be a function defined by $$f(x) = \Biggl\{\begin{array}\text{inf}\{r \mid x \in U_r\} &  x \in X\setminus B \\ 1 & x \in B \end{array}$$ We know there exists $U_0 \in \{U_r\}_{r\in D}$ such that $A\subseteq U_0$. Then $f(a) = 0$ holds for all $a \in A$, so $$f(A) = 0 \implies A = f^{-1}(0) \implies A\subseteq f^{-1}(0)$$ By definition of $f$ it should also be clear that $$f(B) = 1 \implies B = f^{-1}(1) \implies B \subseteq f^{-1}(1)$$ It remains to be shown that $f$ is continuous and that the interior of $f^{-1}(r)$ is nonempty (I'm assuming this $r$ you mentioned is dyadic?) To prove $f$ is continuous we first need two intermediate results:

$\text{If} \space x \in \overline{U_r}\space \text{then} \space f(x)\leq r \tag 1 $

and

$\text{If} \space x \notin U_r \space \text{then} \space f(x)\geq  r \tag 2 $

Both results can be established in a couple lines. Proof by contradiction gets you there quickly. Once you have these two results, choose any $x \in X$ and let $(a,b) \subseteq [0,1]$ be an interval where $f(x) \in (a,b)$. Use the density of $D$ in $[0,1]$ to claim the existence of dyadic rationals $s,t$ such that $$a<s<f(x)<t<b$$
Next apply result $(2)$ to put $x \in U_t$ and apply $(1)$ to deduce $x \notin \overline{U_s}$. Combine the two observations to see $x \in U_t \setminus \overline{U_s}$. For another point $y \in U_t \setminus \overline{U_s}$ we can again use both of our results to show $f(y) \in [s,t]\subset(a,b)$. It might seem weird to do all this stuff, but once done we can conclude that $U_t\setminus \overline{U_s}$ is an open neighborhood of $x$ such that $f\left( U_t\setminus \overline{U_s} \right) \subset (a,b)$ and $U_t\setminus \overline{U_s} \subseteq f^{-1}\big((a,b)\big)$, demonstrating the continuity of $f$. This should serve as a somewhat detailed sketch to help you on your way to completing the proof, but you still need to verify my claims.
Can you proceed from here using the lemma and what we know about the continuity of $f$ to show that the interior of $f^{-1}(r)$ is nonempty?

A: It seems the following.
First of all, in current formulation the claim is wrong. Indeed, let  $X=\{0,1\}$ be a two-point discrete space, $A=\{0\}$,  and $B=\{1\}$. Then there exists a unique map $f:X\to [0,1]$  such that $f(A)=\{0\}$ and $f(B)=\{1\}$ and it is clear that $f^{-1}(r)=\varnothing$ for each point $r$ different from $0$ or $1$. So we shall need some kind of connectivity of the space $X$.  The usual connectivity suffices, because a continuous image of a connected space is connected, and a connected subset $C$ of the segment $[0,1]$ such that $0,1\in C$ coincides with the segment $[0,1]$.
Next we remark that the question reduces  to the case $X=[0,1]$, $A=\{0\}$ and $B=\{1\}$. Indeed, since $A$ and $B$ are disjoint closed subsets of a normal space $X$, there exists a continuous function $g:X\rightarrow [0,1]$ such that $g(A)=\{0\}$ and $g(B)=\{1\}.$ Now let $h: [0,1]\to [0,1]$ be a continuous function such that $h(0)=0$, $h(1)=1$, and for each rational point $r\in [0,1]$ , the interior of $h^{-1}(r)$ is not empty. Put $f=h\circ g$. Then $f:X\to [0,1]$ is a continuous function, $f(A)=\{0\}$, $h(B)=\{1\},$ and and for each rational point $r\in [0,1]$ , the interior of $f^{-1}(r)$ is not empty.
There is a well-known example of Cantor staircase function $c:[0,1]\to [0,1]$ which has all the reqired properties instead of that the interior of $c^{-1}(r)$ is not empty only for each dyadic rational point $r\in [0,1]$.
As my experiense shows, usually for applications  of such construction it suffices to demand that the property holds only for a (dense)  set  of dyadic rational points of the segment $[0,1]$ instead of the set of all its rational points. Moreover, by Sierpiński Theorem, for each countable metric space $A$ without isolated points there is a homeomorphism $t$ from the space $X$ to the space of rationals. Unfortunately, we may not always extend the homeomorhism $t$ to the whole segment $[0,1]\subset A$, for instance, because it may not preserve the linear order from $[0,1]$. Neverteless, by Lavrentiev's Theorem [Kech 3.9], $t$ can be extended to a homeomorphism between $G_\delta$-sets.
Update. It is well known that (see, for instance [JW]) that for each countable dense subsets $D$ and $E$ of the space $\Bbb R$ of the reals (endowed with the standard topology) there exists a homeomorphism $H$  of the space $\Bbb R$ such that $H(D)=E$ and this can be proved by standard back and forth argument. Considering the segment $[0,1]$ as a compactification of the space $\Bbb R$ and using the monotonicity of homeomorphisms of $\Bbb R$, we see that there exists a homeomorphism $i$ of $[0,1]$  such that $i(0)=0$, $i(1)=1$, and $i(\Bbb D_1)=\Bbb Q_1$, where ($\Bbb D_1$) $\Bbb Q_1$ is the sets of (dyadic) rationals of the segment $[0,1]$. So we can complete our construction of the map $f$ by putting $f=i\circ c\circ g$.
References
[Kech] A. Kechris. Classical Descriptive Set Theory, – Springer, 1995.
[JW] Just and Weese.  Discovering modern Set Theory.


text:
Q: Can the Ansible raw ssh module be used like "expect"? In other words, can the ansible "expect" module be used over a raw SSH connection?
I'm trying automate some simple embedded devices that do not have a full Python or even shell.  The ansible raw module works fine for simple commands, but I'd like to drive things in an expect-like manner.
Can this be done?

A: The expect module is written in python, so no, that won't work.
Ansible does have a model for interacting with devices like network switches that similarly don't run python; you can read about that in the How Network Automation Is Different. I don't think that will offer any sort of immediate solution to your problem, but it suggests a way of pursuing things if it was really important to integrate with Ansible.
It would probably be simpler to just use the actual expect program instead of Ansible.

A: With Ansible 2.7 and up, you can use the cli_command module. It's kind of like 'expect' and it does not need python on the target.
https://docs.ansible.com/ansible/latest/modules/cli_command_module.html
- name: multiple prompt, multiple answer (mandatory check for all prompts)
  cli_command:
    command: "copy sftp sftp://user@host//user/test.img"
    check_all: True
    prompt:
      - "Confirm download operation"
      - "Password"
      - "Do you want to change that to the standby image"
    answer:
      - 'y'
      - <password>
      - 'y'

redpajama_set_name: RedPajamaStackExchange


text:
Q: MSChart Show Only Inserted Dates, no blanks I've been searching how to fix this behavior with MS Chart for a few days now and unfortunately everything I've found so far is not helping.
I have a Horizontal Bar Chart that I'm loading with sales data in a specific time frame. This data is already "Massaged" into how I want it using a Date Dimension table so that I can shove zeroes where no data exists.
This means my data always has exactly the required amount of points requested at all times regardless of it being Daily, Weekly, Monthly or Yearly. You ask for 7 days you get 7 rows, you ask for 12 weeks you get 12 rows you ask for 3 months you get 3 rows. Always (Yearly may be a beginning of time situation at the moment so we won't talk about that one.)

Now Daily works fine but the moment I switch to the other modes the chart completely ignores the fact I'm giving it a very specific number of points and instead puts in every date in the calendar in between my data points.

As I said I've tried various solutions I could find but they either make things worse or cause errors.

*

*At first I was databinding the chart but then switched to manually inserting the points

*I've set IsXValueIndexed to true and that just caused the chart to show no values at all...

*Adding AlignDataPointsByAxisLabel causes errors about needing to all be non-empty and unique

*IntervalOffset values seem to do nothing

    Private Sub LoadChart()

        Dim oDT As New DataTable
        Dim sqlCmd As New SqlCommand

        Dim sSQLDateCTE As String = "WITH Date_CTE as ( " & _
                "SELECT [Date] as SaleDate " & _
                "FROM [DateDimension] "
        Dim sWHEREDateCTE As String = "WHERE [Date] BETWEEN DATEADD({0},-{1},GETDATE()) AND GETDATE() "
        Dim sSQLSUM As String = "), SUM_CTE as ( " & _
                "SELECT F01 as UPCCode, F254 as SaleDate, SUM(F64) as UnitsSold " & _
                "FROM {0} " & _
                "WHERE F1034 = 3 AND F64 <> 0 AND F01 = @UPCCode " & _
                "AND F254 IN (SELECT saledate FROM Date_CTE) " & _
                "GROUP BY F01,F254) " & _
                "Select DC.SaleDate ,ISNULL(SC.UnitsSold,0) as UnitsSold " & _
                "FROM Date_CTE as DC " & _
                "LEFT OUTER JOIN SUM_CTE as SC " & _
                "ON SC.SaleDate = DC.SaleDate " & _
                "ORDER BY DC.SaleDate ASC "

        Dim sSQL As String = ""

        Try

            Dim PeriodRow As DataRow = oAppEnv.dtPeriods.Select(String.Format("DPPeriodID = {0}", cboPeriods.SelectedValue)).FirstOrDefault

            Dim DurationRow As DataRow = oAppEnv.dtDurations.Select(String.Format("DDDurationID = '{0}'", cboDuration.SelectedValue)).FirstOrDefault

            Select Case PeriodRow.Item("DPPeriodAbbrev")
                Case "D"
                    sWHEREDateCTE = String.Format(sWHEREDateCTE, "DD", DurationRow.Item("DDDurationLength"))
                    sSQLSUM = String.Format(sSQLSUM, "RPT_ITM_D")
                    sSQL = sSQLDateCTE & sWHEREDateCTE & sSQLSUM
                Case "W"
                    sWHEREDateCTE = String.Format(sWHEREDateCTE, "WW", DurationRow.Item("DDDurationLength")) & " AND Weekday = 1 "
                    sSQLSUM = String.Format(sSQLSUM, "RPT_ITM_W")
                    sSQL = sSQLDateCTE & sWHEREDateCTE & sSQLSUM
                Case "M"
                    sWHEREDateCTE = String.Format(sWHEREDateCTE, "MM", DurationRow.Item("DDDurationLength")) & " AND [DAY] = DATEPART(Day,getdate()) "
                    sSQLSUM = String.Format(sSQLSUM, "RPT_ITM_M")
                    sSQL = sSQLDateCTE & sWHEREDateCTE & sSQLSUM
                Case "Y"
                    '????

            End Select

            sqlCmd.CommandText = sSQL

            sqlCmd.Parameters.AddWithValue("@UPCCode", sUPCCode)

            oDT = oAppEnv.oLogiDM.GetSQLData(sqlCmd)

            ctSalesData.ChartAreas.Clear()
            ctSalesData.ChartAreas.Add("Sales")
            ctSalesData.Series.Clear()
            ctSalesData.Series.Add("Sales")
            ctSalesData.Series("Sales").ChartType = Charting.SeriesChartType.Bar
            'ctSalesData.Series(0).IsXValueIndexed = True
            'ctSalesData.ChartAreas(0).AxisX.IntervalOffsetType = Charting.DateTimeIntervalType.Days
            'ctSalesData.ChartAreas(0).AxisX.IntervalOffset = -1

            If oDT IsNot Nothing Then

                '//Get the Date range.

                Dim oSortDV As DataView = oDT.DefaultView
                oSortDV.Sort = "UnitsSold DESC"

                'ctSalesData.DataSource = oDT

                For Each row In oDT.Rows
                    ctSalesData.Series(0).Points.AddXY(row.item("SaleDate"), row.item("UnitsSold"))
                Next
                'ctSalesData.AlignDataPointsByAxisLabel()

                ctSalesData.Series(0).CustomProperties = "PixelPointWidth = 15"
                ctSalesData.Series(0).IsValueShownAsLabel = True

                Dim MinDate As Date = oDT.Rows(0).Item("SaleDate")
                Dim Maxdate As Date = oDT.Rows(oDT.Rows.Count - 1).Item("SaleDate")

                ctSalesData.ChartAreas(0).AxisX.Minimum = MinDate.ToOADate
                ctSalesData.ChartAreas(0).AxisX.Maximum = Maxdate.ToOADate

                If oDT.Rows.Count > 14 Then
                    Dim ZoomDate As Date = oDT.Rows(14).Item("SaleDate")
                    ctSalesData.ChartAreas(0).AxisX.ScaleView.Zoom(MinDate.ToOADate, ZoomDate.ToOADate)
                End If

                ctSalesData.Series(0).XValueType = Charting.ChartValueType.Date

                ctSalesData.ChartAreas(0).AxisX.Interval = 1
                ctSalesData.ChartAreas(0).AxisY.Minimum = 0

                ctSalesData.ChartAreas(0).AxisY.Maximum = Math.Ceiling(oSortDV(0).Item("UnitsSold") / 10) * 10

                If ctSalesData.ChartAreas(0).AxisY.Maximum = oSortDV(0).Item("UnitsSold") Then
                    ctSalesData.ChartAreas(0).AxisY.Maximum += 10
                End If

                ctSalesData.ChartAreas(0).CursorX.AutoScroll = True

                ctSalesData.ChartAreas(0).AxisX.ScaleView.SizeType = Charting.DateTimeIntervalType.Number
                ctSalesData.ChartAreas(0).AxisX.ScrollBar.ButtonStyle = Charting.ScrollBarButtonStyles.SmallScroll

                ctSalesData.ChartAreas(0).AxisX.ScaleView.SmallScrollSize = 20
                'ctSalesData.Series(0).XValueMember = "SaleDate"
                'ctSalesData.Series(0).YValueMembers = "UnitsSold"
                ctSalesData.ChartAreas(0).AxisX.ScrollBar.IsPositionedInside = False

            End If

        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

*

*Also tried changing the points to be a generic counter

        Dim iCnt As Integer = 0
        For Each row In oDT.Rows
             ctSalesData.Series(0).Points.AddXY(iCnt, row.item("UnitsSold"))
             ctSalesData.Series(0).Points(iCnt).AxisLabel = row.item("SaleDate")
             iCnt += 1
        Next

But I think that just broke my zoom code since it's all date based.
So; How the hell do I get rid of these blank wastes of space and show only the data points that I insert?

A: So for anyone who is/was/will experience the same issue, so far the only way I've been able to get around this annoyance is to do the Generic Counter thing I mentioned previously but rework my zoom code.

Here's the reworked code for anyone interested.
    Private Sub LoadChart()

        Dim oDT As New DataTable
        Dim sqlCmd As New SqlCommand

        Dim sSQLDateCTE As String = "WITH Date_CTE as ( " & _
                "SELECT [Date] as SaleDate " & _
                "FROM [DateDimension] "
        Dim sWHEREDateCTE As String = "WHERE [Date] BETWEEN DATEADD({0},-{1},GETDATE()) AND GETDATE() "
        Dim sSQLSUM As String = "), SUM_CTE as ( " & _
                "SELECT F01 as UPCCode, F254 as SaleDate, SUM(F64) as UnitsSold " & _
                "FROM {0} " & _
                "WHERE F1034 = 3 AND F64 <> 0 AND F01 = @UPCCode " & _
                "AND F254 IN (SELECT saledate FROM Date_CTE) " & _
                "GROUP BY F01,F254) " & _
                "Select DC.SaleDate ,ISNULL(SC.UnitsSold,0) as UnitsSold " & _
                "FROM Date_CTE as DC " & _
                "LEFT OUTER JOIN SUM_CTE as SC " & _
                "ON SC.SaleDate = DC.SaleDate " & _
                "ORDER BY DC.SaleDate ASC "

        Dim sSQL As String = ""

        Try

            Dim PeriodRow As DataRow = oAppEnv.dtPeriods.Select(String.Format("DPPeriodID = {0}", cboPeriods.SelectedValue)).FirstOrDefault

            Dim DurationRow As DataRow = oAppEnv.dtDurations.Select(String.Format("DDDurationID = '{0}'", cboDuration.SelectedValue)).FirstOrDefault

            Select Case PeriodRow.Item("DPPeriodAbbrev")
                Case "D"
                    sWHEREDateCTE = String.Format(sWHEREDateCTE, "DD", DurationRow.Item("DDDurationLength"))
                    sSQLSUM = String.Format(sSQLSUM, "RPT_ITM_D")
                    sSQL = sSQLDateCTE & sWHEREDateCTE & sSQLSUM
                Case "W"
                    sWHEREDateCTE = String.Format(sWHEREDateCTE, "WW", DurationRow.Item("DDDurationLength")) & " AND Weekday = 1 "
                    sSQLSUM = String.Format(sSQLSUM, "RPT_ITM_W")
                    sSQL = sSQLDateCTE & sWHEREDateCTE & sSQLSUM
                Case "M"
                    sWHEREDateCTE = String.Format(sWHEREDateCTE, "MM", DurationRow.Item("DDDurationLength")) & " AND [DAY] = DATEPART(Day,getdate()) "
                    sSQLSUM = String.Format(sSQLSUM, "RPT_ITM_M")
                    sSQL = sSQLDateCTE & sWHEREDateCTE & sSQLSUM
                Case "Y"
                    '????

            End Select

            sqlCmd.CommandText = sSQL

            sqlCmd.Parameters.AddWithValue("@UPCCode", sUPCCode)

            oDT = oAppEnv.oLogiDM.GetSQLData(sqlCmd)

            ctSalesData.ChartAreas.Clear()
            ctSalesData.ChartAreas.Add("Sales")
            ctSalesData.Series.Clear()
            ctSalesData.Series.Add("Sales")
            ctSalesData.Series("Sales").ChartType = Charting.SeriesChartType.Bar
            ctSalesData.Series(0).IsXValueIndexed = True
            'ctSalesData.ChartAreas(0).AxisX.IntervalOffsetType = Charting.DateTimeIntervalType.Days
            'ctSalesData.ChartAreas(0).AxisX.IntervalOffset = -1

            If oDT IsNot Nothing Then

                '//Get the highest sold item so we can set the Y axis to bigger than the biggest

                Dim oSortDV As DataView = oDT.DefaultView
                oSortDV.Sort = "UnitsSold DESC"

                'ctSalesData.DataSource = oDT
                Dim iCnt As Integer = 0
                For Each row In oDT.Rows
                    ctSalesData.Series(0).Points.AddXY(iCnt, row.item("UnitsSold"))
                    ctSalesData.Series(0).Points(iCnt).AxisLabel = row.item("SaleDate")
                    iCnt += 1
                Next
                'ctSalesData.AlignDataPointsByAxisLabel()

                ctSalesData.Series(0).CustomProperties = "PixelPointWidth = 15"
                ctSalesData.Series(0).IsValueShownAsLabel = True

                'Dim MinDate As Date = oDT.Rows(0).Item("SaleDate")
                'Dim Maxdate As Date = oDT.Rows(oDT.Rows.Count - 1).Item("SaleDate")

                ctSalesData.ChartAreas(0).AxisX.Minimum = 0
                ctSalesData.ChartAreas(0).AxisX.Maximum = oDT.Rows.Count + 1

                If oDT.Rows.Count > 21 Then
                    Dim ZoomDate As Date = oDT.Rows(14).Item("SaleDate")
                    ctSalesData.ChartAreas(0).AxisX.ScaleView.Zoom(0, 22)
                End If

                'ctSalesData.Series(0).XValueType = Charting.ChartValueType.Date

                ctSalesData.ChartAreas(0).AxisX.Interval = 1
                ctSalesData.ChartAreas(0).AxisY.Minimum = 0

                ctSalesData.ChartAreas(0).AxisY.Maximum = Math.Ceiling(oSortDV(0).Item("UnitsSold") / 10) * 10

                If ctSalesData.ChartAreas(0).AxisY.Maximum = oSortDV(0).Item("UnitsSold") Then
                    ctSalesData.ChartAreas(0).AxisY.Maximum += 10
                End If

                ctSalesData.ChartAreas(0).CursorX.AutoScroll = True

                ctSalesData.ChartAreas(0).AxisX.ScaleView.SizeType = Charting.DateTimeIntervalType.Number
                ctSalesData.ChartAreas(0).AxisX.ScrollBar.ButtonStyle = Charting.ScrollBarButtonStyles.SmallScroll

                ctSalesData.ChartAreas(0).AxisX.ScaleView.SmallScrollSize = 21
                ''ctSalesData.Series(0).XValueMember = "SaleDate"
                ''ctSalesData.Series(0).YValueMembers = "UnitsSold"
                ctSalesData.ChartAreas(0).AxisX.ScrollBar.IsPositionedInside = False

            End If

        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

Still would be nice to get the Date method to behave properly though as this is an annoying workaround.


text:
Q: How to get array of equal lenght since data have empty fields I have a .dat file formatted as a table as follow:
Dy MxT   MnT   AvT   HDDay  AvDP
1  88    59    74          53.8
3  77    55    66          39.6
9  86    32*   59       6  61.5
3  77    55    66          39.6

I created a List of string for each line as follow:
1  88    59    74          53.8

After splitting the string by empty spaces i get arrays of different length since the field "HDDay" does not always have values.
For example the result after split(" +") the line nr. 1 is:
array[0] //1
array[1] //8
array[2] //59
array[3] //74
array[4] //53.8

But i want:
array[0] //1
array[1] //8
array[2] //59
array[3] //74
array[4] //"" ==> empty value
array[5] //53.8

This is what i have tryed to do:
    Charset charset = Charset.forName("ISO-8859-1");
    //get list of String
    List<String> result = Files.readAllLines(Paths.get(path), charset);

    for(int i = 1; i < result.size(); i++){
        //Exclude empty line
        if(!result.get(i).isEmpty()){
            //splitting each line by space
            String[] values = result.get(i).split("\\s+");
            for(int k = 0; i < values.length; k++){
                System.out.println(values[k]);
            }
        }
    }

I need that because after i want to create a java object to parse in json and return it to client.

A: There are a few things you can try.
1st option: Since its a .dat file and it looks mostly structural, you can either have a pipe(|) or a (,) separation just like you have it for any csv file.
2nd option: If you have control over the number of spaces in between you can put in a limit in the regex code and split by the limit.
For eg:
String s = "1  88    59    74          53.8";
String[] stringArray = s.split("\\s{2,5}");

If you see here, I have specified 2 to be the minimum characters of space, and 5 to be the maximum characters of space. If it finds a space even after 5 characters, it should get you the desired output.

A: If your .dat files always have the same format, so you may use the method substring of java.lang.String class in each string line, after you discover the length of each column, of course, then map each piece as a property for each one.
for example:
1  88    59    74          53.8

will have something like this:
String Dy = line.substring(0,2);
String Mxt = line.substring(6, 6);

and so on. If it is empty, it will not be a problem. Transforming it into an array is the same way.


text:
Q: Which Mapper code is more memory efficiency? I want to build a Mapreduce which has
Input:

key1\t3,2|17412|553|15186,19199|15186,3947|15186,5938|15186,15517
  key2\t925|10295|65182555,7344|7344,925|10295,7344|3,2                            key3\t8747|18466|13289|3,2|13289,5106|12222,5106|5106,6374
........

Output:min \t (2,3) which is the intersection between every element of value1, every element of value2, ....and valueN.
So, I design my mappers so that
mapper1 will contains intersections between values of key1, key2, key3,
mapper2 will contains intersections between values of key4, key5, key6...
.......
Then my Reducers again take results from these mappers to find final intersections. So, basically my mapper and reducer use the same code. In my code, I find intersection sequentially, i.e., first find intersection between value1 and value2, then the result will be used to intersect with value3, and so on.
My Mapper.
Mapper-Code1:
public static class MapAPP extends Mapper<Text, Text, Text, Text>{
    public static int j=0,k=0;
    public static List<String> min_pre = new ArrayList<>();
    public static List<String> min_current = new ArrayList<>();
    public static Set<String> min_p1 = new HashSet<>();
    public static Set<String> min_c1 = new HashSet<>();
    public static List<String> min_result = new ArrayList<>();
    public static Boolean no_exist_min=false;

    public void map(Text key, Text value, Context con) throws IOException, InterruptedException
    {
        String[] v=value.toString().split("\t");
        // aggregate min
        if (no_exist_min==false){
            if (j==0){
                    min_pre= Arrays.asList(v[1].toString().trim().split("\\|"));
                    j=1;
                 }else{
                    min_current= Arrays.asList(v[1].toString().trim().split("\\|"));
                    for (String p: min_pre){
                       min_p1 = new HashSet<String>(Arrays.asList(p.split(",")));
                       for (String c: min_current){
                           min_c1 = new HashSet<String>(Arrays.asList(c.split(",")));
                           min_c1.retainAll(min_p1);
                           if (!min_c1.isEmpty()){
                               Joiner m_comma = Joiner.on(",").skipNulls();
                               String buff = m_comma.join(min_c1);
                               if (!min_result.contains(buff))
                                    min_result.add(buff);
                           }
                       }
                    }
                    if (min_result.isEmpty()){
                        no_exist_min=true;
                    } else {
                        min_pre=new ArrayList(min_result);
                        min_result.clear();
                    }
            }
        }
    }

    protected void cleanup(Context con) throws IOException, InterruptedException {
        Joiner m_pipe = Joiner.on("|").skipNulls();
        if (no_exist_min==true){
            con.write(new Text("min"), new Text("no_exist"));
        }else {
            String min_str = m_pipe.join(min_pre);
            con.write(new Text("min"), new Text(min_str));
        }
    }
}

My Reducer (is almost same as Mapper):
public static class ReduceAPP extends Reducer<Text, Text, Text, Text>
{
    public void reduce(Text key, Iterable<Text> values, Context con) throws IOException, InterruptedException
    {
        List<String> pre = new ArrayList<>();
        List<String> current = new ArrayList<>();
        Set<String> p1 = new HashSet<>();
        Set<String> c1 = new HashSet<>();
        List<String> result = new ArrayList<>();
        Joiner comma = Joiner.on(",").skipNulls();
        Joiner pipe = Joiner.on("|").skipNulls();
        Boolean no_exist=false;
        int i=0;
        // aggregate
        for(Text value: values){
             if (value.toString().trim()=="no_exist"){
                 no_exist=true;
                 break;
                }
             if (i==0){
                    pre= Arrays.asList(value.toString().trim().split("\\|"));
                    i=1;
             }else{
                    current= Arrays.asList(value.toString().trim().split("\\|"));
                    for (String p: pre){
                       p1 = new HashSet<String>(Arrays.asList(p.split(",")));
                       for (String c: current){
                           c1 = new HashSet<String>(Arrays.asList(c.split(",")));
                           c1.retainAll(p1);
                           if (!c1.isEmpty()){
                               String buff = comma.join(c1);
                               if (!result.contains(buff))
                                    result.add(buff);
                           }
                       }
                    }
                    if (result.isEmpty()){
                        no_exist=true;
                        break;
                    }
                    pre=new ArrayList(result);
                    result.clear();
             }

        }
        if (no_exist==true){
            con.write(key, new Text("no_exist"));
        }
        else{
            String preStr = pipe.join(pre);
            con.write(key, new Text(preStr));
        }
    }
    public static <T> Set<T> union(Set<T> setA, Set<T> setB) {
        Set<T> tmp = new TreeSet<T>(setA);
        tmp.addAll(setB);
        return tmp;
    }
}

I run perfectly on small input files but always out of memory in large files (~450Mb text file). So, I doubt that my java code is not memory efficiency. In my Reducers, I used all local variables and these variables will be destroyed when these Reducer functions finish, so I do not worry about Reducers. But in my Mapper, I have to use static variables. In my Mapper-code1, I used all static variables whereas in my Mapper-code2, I tried to use as least static variables as possible.
I have two questions?
1) In my Mapper-code1, every static variable is shared between mappers or it is exclusively for 1 mapper? For example, Suppose I have 5 mappers, Will there be 1 min_pre list created and shared between 5 mappers or will there be 5 min_pre lists for 5 mappers?
What I want is the latter. How to design my mapper so that if I have 5 mappers, there will be 5 min_pre lists?
2) Mapper-code1 and Mapper-code2, which consumes less memory?
Mapper-Code2:
public static class MapAPP extends Mapper<Text, Text, Text, Text>{
    public static int j=0,k=0;
    public static List<String> min_pre = new ArrayList<>();
    public static List<String> min_result = new ArrayList<>();
    public static Boolean no_exist_min=false;

    public void map(Text key, Text value, Context con) throws IOException, InterruptedException
    {
        String[] v=value.toString().split("\t");
        // aggregate min
        if (no_exist_min==false){
            if (j==0){
                    min_pre= Arrays.asList(v[1].toString().trim().split("\\|"));
                    j=1;
                 }else{
                    List<String> min_current= Arrays.asList(v[1].toString().trim().split("\\|"));
                    for (String p: min_pre){
                       Set<String> min_p1 = new HashSet<String>(Arrays.asList(p.split(",")));
                       for (String c: min_current){
                           Set<String> min_c1 = new HashSet<String>(Arrays.asList(c.split(",")));
                           min_c1.retainAll(min_p1);
                           if (!min_c1.isEmpty()){
                               Joiner m_comma = Joiner.on(",").skipNulls();
                               String buff = m_comma.join(min_c1);
                               if (!min_result.contains(buff))
                                    min_result.add(buff);
                           }
                       }
                    }
                    if (min_result.isEmpty()){
                        no_exist_min=true;
                    } else {
                        min_pre=new ArrayList(min_result);
                        min_result.clear();
                    }
            }
        }
    }

    protected void cleanup(Context con) throws IOException, InterruptedException {
        Joiner m_pipe = Joiner.on("|").skipNulls();
        if (no_exist_min==true){
            con.write(new Text("min"), new Text("no_exist"));
        }else {
            String min_str = m_pipe.join(min_pre);
            con.write(new Text("min"), new Text(min_str));
        }
    }
}


text:
Q: Can nonstationarity be told from the autocorrelation function? Here "stationarity" means the first and second moments don't change over time.
From a page of Time Series: Theory and Methods, by Peter J. Brockwell, Richard A. Davis

In this chapter we shall examine the problem of selecting an
  appropriate model for a given set of observations $\{X_t t = 1, ..., n
> \}$. If the data (a) exhibits no apparent deviations from stationarity
  and (b) has a rapidly decreasing autocorrelation function, we
  shall seek a suitable ARMA process to represent the mean-corrected
  data. If not, then we shall first look fo r a transformation of the
  data which generates a new series with the properties (a) and (b).

From a page of Time Series: Theory and Methods, by Peter J. Brockwell, Richard A. Davis

Trend and seasonality are usually detected by inspecting the graph of the
  (possibly transformed) series. However they are also characterized by sample
  autocorrelation functions which are slowly decaying and nearly periodic
  respectively.

From wikipedia

non-stationarity is often indicated by an autocorrelation plot with very slow decay.

My questions:
Why should a stationary ARMA process have a rapidly decreasing autocovariance function?
Should  a stationary AR process also have a rapidly decreasing autocovariance function?
Why is non-stationarity often indicated by an autocorrelation plot with very slow decay and values near 1 at small lags?
Why are trend and seasonality characterized by autocorrelation functions that are slowly decaying and nearly periodic, respectively?

A: (1) A stationary ARMA process has a "rapidly" decaying acf because the acf shows the extent to which previous observations predict the current observation. An AR(1) model would have one significant lag, and AR(2) would have two significant lags....and so on.
Strictly speaking, an ACF cannot tell you whether the time series is non-stationary. You can no more discern whether or not a series is non-stationary by looking at the ACF than you can by just graphing the series. That is to say, it's just sort of obvious. GDP, for example, obviously exhibits a trend...but you should still use tests - ADF, KPSS, etc. - to properly diagnose the non-stationarity. The slow decaying ACF works the same way. It is not a proper diagnosis per-se, but it is a pretty obvious clue.
(2) Yes, a stationary ARMA process should have a rapidly decaying ACF. How rapidly depends on the process. Do not assume that just because the ACF doesn't decay after one or two lags that it is non-stationary. You may also have a fractionally integrated series - something you should also test for.
(3) The ACF looks very slow because effects of previous innovations on a stationary series die out over time. This is why the AR / MA coefficients of less than one are important. You can think of these coefficients as "discount factors" for the influence that previous innovations are having on the current period. They decay because the the structure of the series is such that last period matters the most, two periods ago matters a little less, three periods ago matters less than two periods but is still significant, until you go far enough back that innovations from several periods ago no longer influence current observations. In a non-stationary series, there is no decay.
(4) Slowly decaying is answered above. Seasonality doesn't necessarily imply non-stationarity. It just means that there is some periodicity in the the observations that you must take into account. If you have a monthly consumer spending time series, you might see some seasonality. Every twelve months there is a huge spike in consumer spending around the holidays. That periodicity needs to be taken into account when modeling the time series.

A: It is possible to get a general formula for stationary ARMA(p,q) autocovariance function. Suppose $X_t$ is a (zero mean) stationary solution of an ARMA(p,q) equation:
$$\phi(B)X_t=\theta(B)Z_t$$
Multiply this equation by $X_{t-h}$, $h>q$, take expectations and you will get
$$r(h)-\phi_1r(h-1)-...-\phi_pr(h-p)=0$$
This is a recursive equation, which has a general solution. If all the roots $\lambda_i$ of polynomial $\phi(z)=1-\phi_1z-...-\phi_pz^p$ are different,
$$r(h)=\sum_{i=1}^pC_i\lambda_i^{-h}$$
where $C_i$ are constants which can be derived from the initial conditions. Since $|\lambda_i|>1$ to ensure stationarity it is very clear why the autocorrelation function (which is autocovariance function scaled by a constant) is decaying rapidly (if $\lambda_i$ are not close to one).
I've covered the case of unique real roots of the polynomial $\phi(z)$, all other cases are covered in general theory, but formulas are a bit messier. Nevertheless the terms $\lambda^{-h}$ remain.
Answers to question 2 and 3 more or less follow from this formula. For $AR(1)$ process $r(h)=c\phi_1^h$ and when $\phi_1$ is close to one, i.e. close to non-stationarity, you get the behaviour you describle. The same goes for general formula, if the process is nearly unit-root one of the roots $\lambda_i$ is close to 1 and it dominates other terms, producing the slow decay.

A: As @Clayton pointed out sample autocorrelation function cannot tell if series is non-stationary.
Problem is that there is various levels of non-stationarity, deterministic OR stochastic trends are just one way time series to be non-stationary.
Non-constant variance can be also problem even when expected value is independent of time since confidence intervals based on simple sample statistics are invalid.


text:
Q: Converter webapp into short url Do you know how to rewrite the http://domain .com/application/index.pl into http://app.domain .com ?
I already have the A record on my public DNS server set.
I tried tons of script.
The running service is CentOS, PHP, PERL and MySQL.

A: You should create an other <VirtualHost> config in your Apache config ( assuming you're using Apache). In the app.domain.com <VirtualHost> section, use Proxy / http://domain_com/application to allow access to primary host.
More info about proxying in Apache:  https://httpd.apache.org/docs/2.4/en/mod/mod_proxy.html


text:
Q: How to interpret this mediation analysis? I am performing a mediation analysis using PROCESS by Andrew Hayes, and I don't understand what this output means. I want to see whether rumination mediates the relationship between co-rumination (X) and relationship satisfaction (Y), however I don't understand the indirect effect. Path B is negative, and the indirect effect is negative whereas the direct effect is positive. How to interpret this?
Path A= .12, p=.03
Path B = -.61, p=.0001
Direct effect = b=.41, p=.002

A: "How to interpret this? Path A= .12, p=.03 Path B = -.61, p=.0001 Direct effect = b=.41, p=.002"
a*b is negative and it is (-.0732); c' path (direct effect) is 0.41. And all are significantly different from zero. As you can see the direct effect and the indirect effect have two different sign. This is a typical case of inconsistent mediation (MacKinnon, Fairchild, and Fritz (2007). This has been well addressed in other threads very much! you might be benefited looking into it.
The most important thing to notice is that, in case of suppression effect (another name for inconsistent mediation); the only requirement is the direct effect to be larger in magnitude than the indirect effect. This is clear in your output and you can claim inconsistent mediation. So it means without using jargons "An increase in a decreases b which in turn increases c". You decide if this makes sense, as you know what each variable means and I don't. Please note that in case of inconsistent mediation ab/c does not make sense, so do not report it.

A: According to my knowledge, path "a" says what is the expected change in your mediator variable, when your independent variable increases by 1 unit. So in your case, it would be that increase in co-rumination (X), increases rumination (M).
Path "b" says what is the expected change in your dependent variable when mediator increases by 1 unit (controlling for X). So in your case, it would be that increase in rumination (M) decreases satisfaction (Y).
Then, it makes sense that indirect effect is negative when you multiply a*b (positive time negative values gives the negative). Looking at your output, it seems that the indirect effect is significant because the confidence interval does not include 0.
This is, to me, a bit strange that you have a positive relationship between co-rumination and satisfaction but I know nothing about the theory.
Maybe this paper would help you understand mediation more
https://www.sciencedirect.com/science/article/pii/S0005796716301887


text:
Q: puppet chown/chmod against files under a directory in batch In puppet, you can chown/chmod a single file by doing:
file {
    '/var/log/mylog/test.log':
    ensure  => 'present',
    mode    => '0644',
    owner    => 'me';
}

Two questions on this:

*

*ensure=>'present' is gonna make sure '/var/log/mylog/test.log' exists, if it doesn't it creates it. Is there any way I can make it do actions if file exists, if file doesn't exist, don't bother to create/delete it, just ignore it and carry on.

*Let's say I have 3 files under /var/log/mylog/, I want to chown/chmod against them all in a batch instead of having 3 file resource sections in my puppet code. Can I do something like below(of coz, the code below doesn't exist, it's in my dream now ^_^ ):
files {
    '/var/log/mylog/*.log':
    ensure  => 'present',
    mode    => '0644',
    owner    => 'me';
}

A: *

*If you want to specify to take a given action if file exists, if file doesn't exist etc. you have no choice (to my knownledge) currently than to use the exec resource with creates +  onlyif or unless directives.
You could use for instance (see reference doc)
 exec { "touch /var/log/mylog/test.log":
    path    => "/usr/bin:/usr/sbin:/bin",
    user    => "${yourmodule::params::user}",
    group   => "${yourmodule::params::group}",
    creates => "/var/log/mylog/test.log",
    unless  => "test -f /var/log/mylog/test.log"
 }

 file { '/var/log/mylog/test.log':
    ensure  => 'present',
    mode    => "${${yourmodule::params::mode}",
    owner   => "${yourmodule::params::user}",
    group   => "${yourmodule::params::group}",
    require => Exec["touch /var/log/mylog/test.log"]
 }

*No. Again, you'll have to use an execresource.


text:
Q: Django web application deployed on Heroku using Gunicorn - Half of the requests fail randomly (error code 500) I deployed a Django web application on Heroku using gunicorn wsgi server. Everything works fine in local.
That's my procfile web: gunicorn traineau.wsgi
To keep it simple when I push one of the buttons in the app it's supposed to simply do Prod1=Prod1+1. in Python and then returns it to JS using
return HttpResponse(json.dumps(raw_dict), content_type="application/json") and display the updated Prod value in the app.
Prod1 is a global variable since I need it in other functions.
When I run my app and click that button a couple times, half the requests I make fail with error code 500 (Internal Server Error) but randomly. ex: 1ok, 3fail, 2ok, 5fail. At the end with a big enough sample it's pretty close the 50% fail.
I know Gunicorn is a prefork worker model and heroku sets per default 2 WEB_CONCURRENCY.
I set the WEB_CONCURRENCY to 1 in the CONFIG_VAR of Heroku and it doesn't help.
If I restart the application a couple times without restarting the dyno, instead of the error code 500, it will eventualy alternate between 2 ranges of values. Example 1-2-3-4-20-21-5-6-7-22-23, etc.
If I restart the dyno, we're back with 50% fails.
I use the free Dyno. I tried to upgrade to Hobby and it didn't change anything.
=== web (Free): gunicorn traineau.wsgi (1)
web.1: up 2018/06/06 18:25:08 +0200 (~ 2m ago)

Since this application is for only 1 user (for training purposes), would it be better to use Something else then Gunicorn? Would it solve my problem if I use uWSGI for instance?


text:
Q: SfBApplication *sfb = SfBApplication.sharedApplication; SfBApplication *sfb = SfBApplication.sharedApplication;
the sfb   always return nil,can you help me ?why?

A: From the documentation you can read that the return value is :
Shared application instance or @a nil if initialization fails
Have you followed the instructions from here ?
Especially the import part :
#import <SkypeForBusiness/SkypeForBusiness.h>
#import "SfBConversationHelper.h"

Have you also added the ConversationHelperClass to your source ?

A: Have you configured your AVSession? I had SFB crashed before I configured it.


text:
Q: Windows 10 PATH / Environmental Variable headaches So I tried to install Windows 10 Debug SDK for KD.exe and it's supposed to be recognized in CMD after a reboot..however command not recognized. Command NEVER recognized, I always have to manually find out what environmental paths were SUPPOSED to be applied, am I installing software wrong? NPM had this issue too, Chocolatey etc. So I'm frustrated in thinking perhaps it's my environment however I  have tried this on three different machines, so I can therefore Isolate that I MUST be doing something wrong.
Please, how do I get programs to properly install the appropriate Environment Path? In Windows XP it used to be so easy and straight forward..


text:
Q: How do I make images show up in UWP version of my Xamarin.Forms application I have a simple Xaml like this:
...
    <ContentPage.Content>
        <Grid Padding="0,40,0,0">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>

            <Image  Grid.Row ="0" Source="iMobile"
                        HorizontalOptions="CenterAndExpand"
                        WidthRequest="260" HeightRequest="129"/>
        </Grid>
    </ContentPage.Content>

The image iMobile shows up on Android and ios. For Android I have the different sizes for the image in the separate drawable folders. For ios, I have the different sizes of the image in the Assets catalog.
I have tried to do same for UWP but nothing seems to work. Here are some of the things I have tried doing:

*

*I have added the image to the root directory for the UWP project but that doesn't work.

*I added the image to the Assets directory but that did not work.

*I tried adding .scale-100, .scale-200 and .scale-400 to the name of the image file (tried them all separately) but that did not work.

*I also tried putting the image in a directory named scale-100 but that did not work either.
Any ideas what might be causing my issue and how I can fix this? It is super frustrating that something this trivial is taking so much of my time.
Update:
I tried using a URL as the source instead of iMobile and this does not work for UWP either but it does work for Android, and idea why this might be?

A:
How do I make images show up in UWP version of my Xamarin.Forms application

Please refer Images in Xamarin.Forms official document. Xamarin form support Native resolutions.

UWP image file names can be suffixed with .scale-xxx before the file extension, where xxx is the percentage of scaling applied to the asset, e.g. myimage.scale-200.png. Images can then be referred to in code or XAML without the scale modifier, e.g. just myimage.png. The platform will select the nearest appropriate asset scale based on the display's current DPI.

If you placed image file in the UWP Assets folder, you could use the following xaml, And please note the default blank xamarin app iamge file' color is white, we need set black background to highlight them.
<Grid BackgroundColor="Black">
    <Image>
        <Image.Source>
            <OnPlatform x:TypeArguments="FileImageSource">
                <On Platform="UWP" Value="Assets/LargeTile.png" />
                <On Platform="iOS" Value="LargeTile.png" />
                <On Platform="Android" Value="LargeTile.png" />
            </OnPlatform>
        </Image.Source>
    </Image>
</Grid>


text:
Q: Coloring edges in GraphPlot I'm a little stuck with graph drawing part of my research — I can't use the Graph function for plotting my graphs, because my graph is a multi-graph. Graph is convenient because it colors edges quite easily.
Since I have a 3-regular (or even 4-regular) graph, where there are 3 (or 4) perfect matching, I want each of the matching to be colored differently.
What's the best way to color a group of edges (each perfect matching with it's own color) in the given adjacency list in GraphPlot? To simplify it, we can assume, that groups goes one by one (e.g. we have 6 edges: 3 groups of two edges, following each other
{1<->2, 3<->4, 1<->3, 2<->4, 1<->2, 3<->4}

In Graph, I've constructed a nice lambda function, that wraps all elements of a list in a  Style function, that colors the edge. But in a GraphPlot I can't wrap edges in a Style function.
There's an EdgeRenderingFunction, wich draws all the edges. How do I put three different EdgeRenderingFunctions for the one edge-set? Or is that the wrong way to go?
Any ideas, how to do that?
Answer:
The labeled answer is absolutely correct. Little generalization of what I needed and how to implement it:
  GraphPlot[{{1 -> 2, 1}, {3 -> 4, 1}, {1 -> 3, 2}, {2 -> 4, 2}, {1 -> 2, 3},
             {3 -> 4, 3}}, MultiedgeStyle -> .2,
             ImagePadding -> 10,
             EdgeRenderingFunction -> (Switch[#3, 1, {Red, Line[#1]},
             2, {Blue, Line[#1]}, 3, {Green, Line[#1]},
             4, {Dashed, Line[#1]}] &), VertexLabeling -> True,
             Method -> "CircularEmbedding"]

A: l = {{1, 3}, {3, 4}};
GraphPlot[{1 -> 2, 3 -> 4, 1 -> 3, 2 -> 4, 1 -> 2, 3 -> 4},
 EdgeRenderingFunction -> (If[
     Intersection[l, {#2}] != {}, {Red, Arrow[#1, .1]},
                                  {Blue,Arrow[#1, .1]}] &)]

Edit
Using edge labels:
l = {1, 3};
GraphPlot[{{1 -> 2, 1}, {3 -> 4, 2}, {1 -> 3, 3}, {2 -> 4, 4}, {1 -> 2, 5}, {3 -> 4, 6}},
 EdgeRenderingFunction -> (If[
     Intersection[l, {#3}] != {}, {Red, Arrow[#1, .1]}, {Blue, Arrow[#1, .1]}] &)]

A: I interpreted the problem as requiring two different colors if the edges were duplicated:
normal[{x_, y_}] := 0.03*{-y, x}/Norm[{x, y}];
GraphPlot[{1 -> 2, 3 -> 4, 1 -> 3, 2 -> 4, 1 -> 2, 3 -> 4},
  VertexLabeling -> True,
  EdgeRenderingFunction -> (If[Length[#1] > 2,
  norm = normal[First[#1] - Last[#1]]; {Red,
  Arrow[{First[#1] + norm, Last[#1] + norm}, .08], Blue,
  Arrow[{First[#1] - norm, Last[#1] - norm}, .08]},
  Arrow[#1, .08]] &)]


text:
Q: Problems using webcam in python, openCV File "C:\Users\Rahul\AppData\Local\Programs\Python\Python36\lib\site-packages\cv2\__init__.py", line 3, in <module>
    from .cv2 import *
ImportError: numpy.core.multiarray failed to import

I uninstalled opencv-python and re-installed it again

A: Ensure that you do not have conflicting versions of numpy in different locations in storage as this seems that the issue is not cv2 but numpy, which is needed when making use of the opencv library


text:
Q: Express  not working I have installed express globally using the command
npm install -g express-generator@4

after which if i am doing
express .No project is created,surprisingly no errors also.
where is the actual issue?

A: Create the express project is following:
$ mkdir myapp
$ cd myapp
$ npm init
entry point: index.js
$ npm install express --save

Or:
$ npm install express-generator -g
$ express myapp

A: If we install nodejs from apt-get package manager,we get this issue.
try uninstalling it first,sudo apt-get remove nodejs.
goto nodejs main site and download the source.
Try installing nodejs from source,set the path variable,and there you go.


text:
Q: How to select shifted time periods in MDX? I am beginner in MDX. I am trying to calculate the increase in revenue from the previous year using the Adventure Works cube in a way that I will have a column that will show the difference in revenue between 2 years. Until now I was able to calculate the difference manually using:
(KpiValue("Revenue"), [Date].[Fiscal Year].&[2009]) - KpiValue("Revenue"),
[Date].[Fiscal Year].&[2008]

(KpiValue("Revenue"), [Date].[Fiscal Year].&[2008]) - KpiValue("Revenue"),
[Date].[Fiscal Year].&[2007]

(KpiValue("Revenue"), [Date].[Fiscal Year].&[2007]) - KpiValue("Revenue"),
[Date].[Fiscal Year].&[2006]

Can you suggest me more efficient way to calculate this. I think I can use the Parallel Processing function but I am struggling to understand how it works.
Thank you!
Edit:
Here is the code I use:
with member [diff] as
(KPIValue("Revenue"), [Date].[Fiscal Year].&[2008]) -
(KPIValue("Revenue"), [Date].[Fiscal Year].&[2007])

Select
{diff} on 0
FROM [Adventure works]

A: Try to use the PrevMember:
With
Member [Measures].[Diff] as
[Measures].[Revenue] - ([Date].[Fiscal Year].PrevMember,[Measures].[Revenue])

Select
[Measures].[Diff] on 0,
[Date].[Fiscal Year].[Year].Members on 1
From [Adventure Works]


text:
Q: Internal Error when using angularCompilerOptions.baseUrl I have an Angular 14 project (generated by angular CLI) in Intellij, everything is working as expected, but with relative imports from components.
Now I would like all imports from the same base directory, so I just tried to :

*

*add angularCompilerOptions.baseUrl = "./" in the tsconfig.json

*add compilerOptions.baseUrl = "./" in the tsconfig.json

*update imports automatically with Intellij, new imports are now defined from src

Sample: import { environment } from "src/environments/environment";)
But now when I run ng serve, I got this error:
⠙ Generating browser application bundles (phase: setup)...file:///xxx/frontend/node_modules/@angular/compiler-cli/bundles/chunk-4NRCP3Y6.js:124
    throw new Error(`Internal Error: absoluteFrom(${path}): path is not absolute`);
          ^

Error: Internal Error: absoluteFrom(src/app/app.component.ts): path is not absolute
    at absoluteFrom (file:///media/xxx/frontend/node_modules/@angular/compiler-cli/bundles/chunk-4NRCP3Y6.js:124:11)
    at file:///xxx/frontend/node_modules/@angular/compiler-cli/bundles/chunk-J6AVV3MN.js:5740:57
    at Array.reduce (<anonymous>)
    at ComponentDecoratorHandler.analyze (file:///xxx/frontend/node_modules/@angular/compiler-cli/bundles/chunk-J6AVV3MN.js:5739:51)
    at TraitCompiler.analyzeTrait (file:///xxx/frontend/node_modules/@angular/compiler-cli/bundles/chunk-J6AVV3MN.js:3388:30)
    at analyze (file:///xxx/frontend/node_modules/@angular/compiler-cli/bundles/chunk-J6AVV3MN.js:3359:34)
    at async Promise.all (index 0)

What is going on ?
UPDATE: I rollbacked my changes to get something working, and then I updated only ONE import starting from "src" and this time the error is :
./src/main.ts - Error: Module build failed (from ./node_modules/@ngtools/webpack/src/ivy/index.js):
Error: Internal Error: absoluteFrom(src/app/components/shared/report-list/stacktrace-dialog/stacktrace-dialog.component.ts): path is not absolute

UPDATE 2: I have no idea why, with a new test, I have now another behaviour...
If we just update tsconfig with:
angularCompilerOptions.baseUrl = "./"   # or "."

Then it compiles (and works) with the following warning, and Intellij marks the import as invalid.
./src/app/app.component.ts - Warning: Invalid dependencies have been reported by plugins or loaders for this module. All reported dependencies need to be absolute paths.
Invalid dependencies may lead to broken watching and caching.
As best effort we try to convert all invalid values to absolute paths and converting globs into context dependencies, but this is deprecated behavior.
Loaders: Pass absolute paths to this.addDependency (existing files), this.addMissingDependency (not existing files), and this.addContextDependency (directories).
Plugins: Pass absolute paths to fileDependencies (existing files), missingDependencies (not existing files), and contextDependencies (directories).
Globs: They are not supported. Pass absolute path to the directory as context dependencies.
The following invalid values have been reported:
 * "src/app/core/services/theme.service.ts"

If I also change the tsconfig with
compilerOptions.baseUrl = "./"  # or "."

Then I got the above warning twice, but at least Intellij recognizes the imports since it reads this value in tsconfig.
It looks like something is unstable, I even not added code since the first test, I just re-organize files in directories.
Do not work on stackblitz either:
https://stackblitz.com/edit/angular-ivy-f2uafy?file=src/app/test/test.component.ts

A: try add this
 angularCompilerOptions.baseUrl = "./src" in the tsconfig.json


text:
Q: Excluding products from multiple categories in collection I have a rather specific problem regarding product collections and excluding multiple categories. The following code example does almost exactly what I want to achieve: getting a product collection with the most sold products and excluding all categories that contain the word "free". There is only 1 problem: I can only filter on 1 product category, since products can have multiple categories there are still products shown that had a category containing the word free. Is there a way the filter away all products that have at least 1 category containing the word free?
        $freeCategories = array();
        $rootId = Mage::app()->getStore($storeId)->getRootCategoryId();
        $categories = Mage::getModel('catalog/category')
            ->getCollection()
            ->addFieldToFilter('path', array('like'=> "1/$rootId/%"))
            ->addFieldToFilter('name', array('like' => '%free%'));

        foreach($categories as $category){
            $freeCategories[] = $category->getId();
        }

        $storeId = Mage::app()->getStore()->getId();
        $products = Mage::getResourceModel('reports/product_collection')
            ->addOrderedQty()
            ->addAttributeToSelect('*')
            ->setStoreId($storeId)
            ->addStoreFilter($storeId)
            ->setOrder('ordered_qty', 'desc') //best sellers on top*/
            ->setPageSize($amount)
            ->joinField('category_id', 'catalog/category_product', 'category_id', 'product_id = entity_id', null, 'left')
            ->addAttributeToFilter('category_id', array('nin' => array('finset' => $freeCategories)));

        Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($products);
        Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($products);
        Mage::getSingleton('cataloginventory/stock')->addInStockFilterToCollection($products);

A: I have had this issue before, and I solved it by working the problem the other way round.
First get a list of product ids, of products in the given categories, and then exclude those products :)
The following code is a snippet form my Dynamic Category Products Extension, where a rule can load all products not in a category (exactly what you are doing ;) )
$this->getValue() contained an array of category ids (which you get from your initial collection already)
Please ask if you need any clarification on the code.
                $value = explode(',',$this->getValue());
                // since a product can appear in multiple categories,
                // we must eliminate via the product ids of any
                // products that has the given category id in it.
                $subCollection = mage::getModel('catalog/product')
                    ->getCollection();
                $subCollection->joinField(
                        'category_id',
                        'catalog/category_product',
                        'category_id',
                        'product_id=entity_id',
                        null,
                        'left'
                );

                $subCollection->addAttributeToFilter(
                    'category_id',
                    array(
                        'in' => $value)
                );
                // remove all columns, and only get the entity_id
                // so it will work as a subquery for IN/NIN
                $subSelect = $subCollection->getSelect();
                $subSelect->reset(Zend_Db_Select::COLUMNS);
                $newColumns = array(
                    '0' => array(
                        'e',
                        'entity_id',
                        null));
                $subSelect->setPart(
                    Zend_Db_Select::COLUMNS,
                    $newColumns
                );
                $this->getHelper()->debug("Category ID subquery:" . $subSelect);
                $collection->getSelect()->where(
                    'e.entity_id NOT IN (?)',
                    new Zend_Db_Expr($subSelect->__toString())
                );

Also note that you do not need to do a foreach on your category colelction.
Simpy do: $category->getAllIds(), which will be much more efficient.
Hope  this helps.


text:
Q: Deserialization of a JSON using Gson I am receiving a JSON from a server that resembles the following syntax and I require some  assistance deserializing & parsing it. I have done a lot of reading on this and have found that using GSON is really useful! ( I Will post any updates to my code here)
(Corrected JSON):
    [{
    "name" : "Zone1",
    "types" : [{"datatype":"string","brand":"string","index":0},
            {"datatype":"string","value":"int32,"index":1},
            {"datatype":"string","url":"string,"index":2}]
    "data" : [["gucci",2,"www.whoami12345.com"]]
   },
   {
   "name" : "Zone2",
   "types" : [{"datatype":"string","brand":"string","index":0},
            {"datatype":"string","value":"int32,"index":1},
            {"datatype":"string","url":"string,"index":2}]
   "data" : [["nike", 23,"www.nike.com"]]
  }]

I found this site Link pretty neat because it explains how to use gson and explains deserialisation well. My understanding of the JSON that I have is that it is an array and the data field is an array of Arrays.
My question is how do I go about parsing this? I have a function that will take a string searching for a specific zone name. After the deserialisation takes place and an entry matches the correct zone, the datatype and url are supposed to be returned. From that article, my understanding is that I should be using a JSONArray. Any feedback would be appreciated. Below is some code of what I have started
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;

String name;

public class data{
    String brand;
    int num;
    int url;
 }

public class types{
    String datatype;
    int value;
    String url;
}

public types Deserialiser(String json, String zone){ // this is the json string that will be passed into the function

JsonObject jsonObject = json.getAsJsonObject();
JsonArray jsonArray = jsonObject.getAsJsonArray();
int index = -1;
for (int i = 0; i<jsonArray.size();i++){
   String temp = jsonArray.get(i).get("name");
   if (temp.equals(zone){
      index =i;
      break;
   }

}

....

types jsonTypes = new types();
// set everything else
return jsonTypes;
}

A: Valid JSON (I think):
[{"name"  : "Zone1",
   "types" : ["datatype":"string","value":"int","url":"string"],
   "data"  : [["gucci",2,"www.whoami12345.com"]]},
  {"name"  : "Zone2",
   "types" : ["datatype":"string","value":"int","url":"string"],
   "data"  : [["nike", 23,"www.nike.com"]]}
]

Nope -- wrong missing "object" brackets
Try again:
[{"name"  : "Zone1",
   "types" : [{"datatype":"string","value":"int","url":"string"}],
   "data"  : [["gucci",2,"www.whoami12345.com"]]},
  {"name"  : "Zone2",
   "types" : [{"datatype":"string","value":"int","url":"string"}],
   "data"  : [["nike", 23,"www.nike.com"]]}
]

Ah!! Much better!


text:
Q: Watson Conversation_Nodes that has no response So I wrote this JSON code just like the following
{
  "context": {
    "action": {
      "dates": "$dates",
      "command": [
        "check-dates"
      ]
    },
    "output": {
      "text": {
        "values": [
          "$dates, Do you want to pick this as a designated date?"
        ]
      }
    }
  },
  "output": {}
}

The problem is that this doesn't count as a response as I've expected and I tried to erase that last "output" thing but it just pops out whenever I click the node again for some reasons. Any suggestion is more than a welcome :D Thanks

A: Your JSON have some incorrect syntax. You have not closed all JSON values in the context
For have some answer:
{
  "context": {
    "action": {
      "dates": "$dates",
      "command": [
        "check-dates"
      ]
    }
  },
  "output": {
    "text": {
      "values": [
        "Your answer here."
      ],
      "selection_policy": "sequential"
    }
  }
}

If you don't want one response for the user, give the [] empty like:
{
  "context": {
    "action": {
      "dates": "$dates",
      "command": [
        "check-dates"
      ]
    }
  },
  "output": {
    "text": {
      "values": [
        ""
      ],
      "selection_policy": "sequential"
    }
  }
}

I recommend, for you make sure if your Syntax from your JSON is correct here.


text:
Q: Ethernet problem in Ubuntu 14.04 pardon my total lack of knowledge as I'm a first time user of Ubuntu. I recently installed Ubuntu 14.04 in a machine which already runs Windows 7 HB. I have an ethernet connection which I use to be online. After booting ubuntu and trying to access the internet, I see the message on the right telling me that LAN is connected. But, when I try to access any webpage on firefox, it just doesn't load. Also, I've pinged www.google.com, which gives me an error, "Unknown Host".
Please Help.
Thanks in anticipation.
P.S: I'm a rookie so please give me steps to check if you're asking for any thing specific.


text:
Q: Lua: string.gsub pattern(s) to permit multiple pattern replacement This topic has been partially handled before by another user in thread:
Lua string.gsub with Multiple Patterns
I'm having issues and I believe it is with my pattern (second) argument.  Here is my example of the gsub code I'm trying to use:
local dateCode = "MMM/dd-YYYY:ss"

--dateCode = dateCode:gsub(".*", {["%/"] = "s", ["%-"] = "n", ["%:"] = "c"}) --original code but removed after @Etan's comments.
dateCode = dateCode:gsub(".*", {["/"] = "s", ["-"] = "n", [":"] = "c"})

print(dateCode)

MMM/dd-YYYY:ss  --printed

MMMsddnYYYYcss  --desired

I believe that I shouldn't be looking over all characters like I currently have it, but I'm not sure what pattern I should be using for the dateCode variable.
The idea is to replace the keys with the first alpha character that it begins with.

A: Since you want a select set of characters to be replaces, put them in a character set as the pattern:
dateCode = dateCode:gsub("[/:-]", {["/"] = "s", ["-"] = "n", [":"] = "c"})

What happens currently is, with the pattern .* in place, it matches the entire string. Since the string "MMM/dd-YYYY:ss" has no indexed value in the hash table (second argument), no replacement actually occurs.


text:
Q: Linear dependence of set of linear combinations of linearly independent vectors I came across this problem:

Given the set of linearly independent vectors $\{u,v,w\} \subseteq \mathbb{R}^n$, determine whether or not the following set of vectors is linearly dependent: $\{u-v-w, 2u+w, 3u+v+3w\}$

There's a theorem which says that if at least one of the vectors in a set is a linear combination of other vectors, then the set is linearly dependent. In this particular question, I had to go through all of the three vectors $\{u-v-w, 2u+w, 3u+v+3w\}$ and check whether any of them is a linear combination of others (and I think the answer is that the set is linearly independent).
But is there more efficient way of doing this? I tried checking linear dependence using matrix, that is, checking for a non-trivial solution of the following system:
$$\begin{bmatrix}
(u_1-v_1-w_1) & (2 u_1 + w_1)  & (3 u_1 + v_1 + 3 w_1) & 0\\
(u_2-v_2-w_2) & (2 u_2 + w_2)  & (3 u_2 + v_2 + 3 w_2) & 0\\
& \vdots
\\
(u_n-v_n-w_n) & (2 u_n + w_n)  & (3 u_n + v_n + 3 w_n) & 0
\end{bmatrix}$$
But I have no idea how to do this because I don't know the components of the vectors $u, v, w$ and I don't know $n$.

A: Suppose
$$
\DeclareMathOperator{Null}{Null}
\DeclareMathOperator{Span}{Span}
\lambda_1\cdot(u-v-w)+\lambda_2\cdot(2u+w)+\lambda_3\cdot(3u+v+3w)=\mathbf 0\tag{1}
$$
Then
$$
(\lambda_1+2\lambda_2+3\lambda_3)\cdot u
+
(-\lambda_1+\lambda_3)\cdot v
+
(-\lambda_1+\lambda_2+3\lambda_3)\cdot w
=
\mathbf0\tag{2}
$$
Since $\{u,v,w\}$ is linearly independent (2) implies
\begin{align*}
\lambda_1+2\lambda_2+3\lambda_3 &= 0 \\
-\lambda_1+\lambda_3&= 0 \\
-\lambda_1+\lambda_2+3\lambda_3 &= 0
\end{align*}
which is equivalent to the equation $A\vec\lambda=\mathbf 0$ where
$$
A=
\begin{bmatrix}
1 & 2 & 3 \\
-1 & 0 & 1 \\
-1 & 1 & 3
\end{bmatrix}
$$
But $\DeclareMathOperator{Rank}{Rank}\Rank(A)=2$ and we see that
$$
\Null(A)=
\Span
\left\{
\begin{bmatrix}
1\\-2\\ 1
\end{bmatrix}
\right\}
$$
Hence the equation (1) is solved by $\lambda_1=1$, $\lambda_2=-2$, and $\lambda_3=1$ and we see that $\{u-v-w, 2u+w, 3u+v+3w\}$ is linearly dependent.

A: The information that $u$, $v$ and $w$ belong to $\mathbb{R}^n$ is irrelevant; it's even better thinking to those vector in an arbitrary $n$-dimensional space $V$. You can complete $\{u,v,w\}$ to a basis of $V$, say to the set $\{u,v,w,z_4,\dots,z_n\}$ and there is a unique linear map $f\colon V\to\mathbb{R}^n$ such that
\begin{align}
f(u)&=e_1\\
f(v)&=e_2\\
f(w)&=e_3\\
f(z_k)&=e_k &&(4\le k\le n)
\end{align}
and this map is bijective, because it sends a basis to a basis. Thus a set of vectors $\{x_1,x_2,\dots,x_m\}$ is linearly independent if and only if $\{f(x_1),\dots,f(x_n)\}$ is linearly independent in $\mathbb{R}^n$.
This shows that it's not restrictive to assume $u=e_1$, $v=e_2$ and $w=e_3$, so you just need to check whether the set
$$
\left\{
\begin{bmatrix}1\\-1\\-1\\0\\\vdots\\0\end{bmatrix},
\begin{bmatrix}2\\0\\1\\0\\\vdots\\0\end{bmatrix},
\begin{bmatrix}3\\1\\3\\0\\\vdots\\0\end{bmatrix}
\right\}
$$
is linearly independent which is clearly equivalent to showing that the matrix
$$
\begin{bmatrix}
1&2&3\\
-1&0&1\\
-1&1&3
\end{bmatrix}
$$
has rank $3$. The rank is easily computed with Gaussian elimination:
$$
\begin{bmatrix}
1&2&3\\
-1&0&1\\
-1&1&3
\end{bmatrix}
\to
\begin{bmatrix}
1&2&3\\
0&2&4\\
0&3&6
\end{bmatrix}
\to
\begin{bmatrix}
1&2&3\\
0&1&2\\
0&3&6
\end{bmatrix}
\to
\begin{bmatrix}
1&2&3\\
0&1&2\\
0&0&0
\end{bmatrix}
$$
so the rank is $2$ and the three given vectors are linearly dependent. If you go on with backwards elimination, you reach
$$
\begin{bmatrix}
1&0&\color{red}{-1}\\
0&1&\color{red}{2}\\
0&0&0
\end{bmatrix}
$$
so you conclude that
$$
3u+v+3w=\color{red}{-1}(u-v-w)+\color{red}{2}(2u+w)
$$

A: Forget what space $u,v,w$ live in; the only important thing is that they are linearly independent. Therefore they form a basis of the subspace $V=\langle u,v,w\rangle$ spanned by themselves (they are a spanning set by definition of $V$, and independent by hypothesis). This means that the operation of formation of linear combinations $L:(a,b,c)\mapsto au+bv+cw$ is an isomorphism $\def\R{\Bbb R}\R^3\to V$ so it has an inverse isomorphism $L^{-1}:V\to\R^3$ which is expression of vectors of $V$ in coordinates on the basis $[u,v,w]$. Now directly form the definition
$$ \begin{align}
L^{-1}(u−v−w)&=(1,-1,-1), \\L^{-1}(2u+w)&=(2,0,1), \\ L^{-1}(3u+v+3w)&=(3,1,3).
\end{align}
$$
Since an isomorphism preserves linear dependence or independence, the question whether the vectors $u−v−w$, $2u+w$, $3u+v+3w$ of $V$ are linearly dependent is equivalent to the question whether their images $(1,-1,-1)$, $(2,0,1)$, and $(3,1,3)$ in $\R^3$ under the isomorphism $L^{-1}$ are linearly dependent.
Thus a somewhat abstract question in $\R^n$ is translated into a concrete question in$~\R^3$. To actually answer that question, one has to set up and find all solutions of a $3\times 3$ system of linear equations, which is exactly the system in the answer by Brain Fitzpatrick. Since there are actually non-zero solutions, the given vectors are linearly dependent. I won't repeat that (easy) computation; the main point I want to make is that the reduction to a problem in $\R^3$ results directly from the expression of relevant vectors in coordinates with respect to an appropriate basis (here $[u,v,w]$), which is why for computations the spaces of the form $\R^k$ are of such a central importance, and why the notion of basis (of a space or of a subspace) is so important.


text:
Q: Show that ${\rm Hom}(G,\mathbb{C}^{\star}) \cong G \cong {\rm Hom}(G,\mathbb{Q}/\mathbb{Z})$ How can I show that ${\rm Hom}(G,\mathbb{C}^{\star}) \cong G \cong {\rm Hom}(G,\mathbb{Q}/\mathbb{Z})$, where $G$ is finite abelian group, $\mathbb{C}$ is the set of complex number, $\mathbb{Q}$ is the set of rational, $\mathbb{Z}$ is the set of integers and ${\rm Hom}(A,B)$ is the set of all homomorphisms from a group $A$ to a group $B$.

A: $\newcommand{Hom}{\text{Hom}}$
Since $G$ is a finite direct sum of finite cyclic groups, and $\Hom$ commutes with finite direct sums (in either variable), it suffices to show the result for $G = \mathbb{Z}/n\mathbb{Z}$.
The key fact is that for any $n \in \mathbb{N}$, both $\mathbb{Q}/\mathbb{Z}$ and $\mathbb{C}^*$ contain a unique cyclic subgroup of order $n$ (for $\mathbb{Q}/\mathbb{Z}$, a generator is $\frac{1}{n} + \mathbb{Z}$, and for $\mathbb{C}^*$, a generator is a primitive $n^\text{th}$ root of unity). Thus e.g. if $H \subseteq \mathbb{Q}/\mathbb{Z}$ is the cyclic subgroup of order $n$, then any homomorphism from $\mathbb{Z}/n\mathbb{Z}$ to $\mathbb{Q}/\mathbb{Z}$ must land in $H$, i.e. $\Hom(\mathbb{Z}/n\mathbb{Z}, \mathbb{Q}/\mathbb{Z}) = \Hom(\mathbb{Z}/n\mathbb{Z}, H)$. But $H \cong \mathbb{Z}/n\mathbb{Z}$, so $\Hom(\mathbb{Z}/n\mathbb{Z}, H) \cong \Hom(\mathbb{Z}/n\mathbb{Z}, \mathbb{Z}/n\mathbb{Z}) \cong \mathbb{Z}/n\mathbb{Z}$.

A: First you have to define a group action, say $\ast$, on the set $Hom(G, \mathbb{C}^\ast)$ as follows:
$$
(\rho \ast \phi) (g):= \rho(g) \phi(g), \quad \forall \rho, \phi \in Hom(G, \mathbb{C}^\ast), g\in G,
$$
where the multiplication in the right is the multiplication in $\mathbb{C}$. Then since $G$ is a finite group you see that every element of $Hom(G, \mathbb{C}^\ast)$ is of finite order, and so lies in the unit circle $\mathbb{T}$. On the other hand the subgroup of all finite order elements of $\mathbb{T}$ is isomorphic to $\mathbb{Q}/\mathbb{Z}$.
To prove the first isomorphism, note that since $G$ is a finite abelian group you can write it in the form $G\simeq \mathbb{Z}/n_1 \mathbb{Z}\oplus \cdots, \oplus \mathbb{Z}/n_k \mathbb{Z}$ for some positive integers $n_1,\cdots, n_k$. Then it is easy to define the first isomorphism using the generators of the right hand side. For example let $\phi$ be the homomorphism sending the generator of $\mathbb{Z}/n_1 \mathbb{Z}$ to $e^{2\pi /n_1}$.

A: Ideas for the first:
$${\rm Hom}(C_n,{\Bbb C}^*) \cong  {\rm Hom}(C_n,C_n) = C_n,$$
$${\rm Hom}(G\times H,A) = {\rm Hom}(G,A)\times {\rm Hom}(H,A).$$
Where $C_n=$cyclic group, $A=$ abelian group.

A: Embed $\mathbb Q/\mathbb Z$ into $\mathbb C^*$ by the composite map
$$ \mathbb Q/\mathbb Z \hookrightarrow \mathbb R/\mathbb Z \xrightarrow{\exp(\tau i -)} \mathbb C^* $$
It is easy to see that an element of finite order in $\mathbb C^*$ must lie in $\mathbb Q/\mathbb Z$, so the first statement is equivalent to the second. By the fundamental theorem of finite abelian groups and the fact that $\operatorname{Hom}$ converts coproducts in the first variable to products, it suffices to prove the statement for finite cyclic groups, which is easy.


text:
Q: Keep getting this message: Exception in thread "main" java.lang.RuntimeException: java.sql.SQLException: ResultSet closed Whenever I get to the part of saving the table- it asks me for the ID number but then it comes up with the following error:
"Exception in thread "main" java.lang.RuntimeException: java.sql.SQLException: ResultSet closed"
I can't figure out what the problem is.
Should I use the same ResultSet variable name for all functions?
public class Events {

    public static void ambush(int mymovement) {
        try {
            Connection conn = DriverManager.getConnection(DatabaseConstants.Database);
            Statement statement = conn.createStatement();

            System.out.println("You have been ambushed" + "\n" +
                    " You have moved 1 mile" + "\n"
                    + "Your health, ammunition and supplies have reduced by 40%.");

            System.out.println("Enter your ID to save your progress: ");
            Scanner id = new Scanner(System.in);
            int myid = id.nextInt();

              ResultSet ambush = statement.executeQuery("SELECT * FROM " + DatabaseConstants.Table_Troops
                    + " WHERE " + DatabaseConstants.Column_ID + " = " + myid);

            while (ambush.next()) {
                statement.execute("UPDATE " + DatabaseConstants.Table_Troops + " SET " +
                        DatabaseConstants.Column_Health + " = " + (ambush.getInt(DatabaseConstants.Column_Health) - 40) + ", " +
                        DatabaseConstants.Column_Supplies + " = " + (ambush.getInt(DatabaseConstants.Column_Supplies) - 40) + ", " +
                        DatabaseConstants.Column_Ammo + " =  " + (ambush.getInt(DatabaseConstants.Column_Ammo)- 40) + ", " +
                        DatabaseConstants.Column_Location + " = " + (ambush.getInt(DatabaseConstants.Column_Location) + mymovement) +
                        " WHERE " + DatabaseConstants.Column_ID + " = " + myid);

                if (mymovement == 10) {
                    System.out.println("You have moved 10 miles - you have completed the mission");
                    System.out.println("Your session will now be terminated");
                    System.exit(0);
                } else if (ambush.getInt(DatabaseConstants.Column_Health) == 0) {
                    System.out.println("Your health is 0%");
                    System.out.println("Your session will now be terminated");
                    System.exit(0);
                } else if (ambush.getInt(DatabaseConstants.Column_Supplies) == 0) {
                    System.out.println("Your supplies are 0%");
                    System.out.println("Your session will now be terminated");
                    System.exit(0);
                } else if (ambush.getInt(DatabaseConstants.Column_Ammo) == 0) {
                    System.out.println("Your ammunition is at 0%");
                    System.out.println("Your session will now be terminated");
                    System.exit(0);
                } else if (mymovement < 10) {
                    System.out.println("Your progress has been saved - You will be re-directed to the main menu");
                    DatabaseConstants.showMenu();
                }

            }
            ambush.close();
            statement.close();
            conn.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public static void fire(int mymovement) {
        try {
            Connection conn = DriverManager.getConnection(DatabaseConstants.Database);
            Statement statement = conn.createStatement();

            System.out.println("Your journey has been affected by fire" + "\n" +
                    " You have moved 2 miles" + "\n"
                    + "Your health and supplies have reduced by 30%. Your ammunition has stayed the same");

            System.out.println("Enter your ID to save your progress: ");
            Scanner id = new Scanner(System.in);
            int myid = id.nextInt();

            ResultSet fire = statement.executeQuery("SELECT * FROM " + DatabaseConstants.Table_Troops
                    + " WHERE " + DatabaseConstants.Column_ID + " = " + myid);

            while (fire.next()) {
                statement.execute("UPDATE " + DatabaseConstants.Table_Troops + " SET " +
                        DatabaseConstants.Column_Health + " = " + (fire.getInt(DatabaseConstants.Column_Health) - 30) + ", " +
                        DatabaseConstants.Column_Supplies + " = " + (fire.getInt(DatabaseConstants.Column_Supplies) - 30) + ", " +
                        DatabaseConstants.Column_Ammo + " =  " + (fire.getInt(DatabaseConstants.Column_Ammo)) + ", " +
                        DatabaseConstants.Column_Location + " = " + (fire.getInt(DatabaseConstants.Column_Location) + mymovement) +
                        " WHERE " + DatabaseConstants.Column_ID + " = " + myid);

                if (mymovement == 10) {
                    System.out.println("You have completed the mission");
                    System.out.println("Your session will now be terminated");
                    System.exit(0);
                } else if (fire.getInt(DatabaseConstants.Column_Health) == 0) {
                    System.out.println("Your health is 0%");
                    System.out.println("Your session will now be terminated");
                    System.exit(0);
                } else if (fire.getInt(DatabaseConstants.Column_Supplies) == 0) {
                    System.out.println("Your supplies are 0%");
                    System.out.println("Your session will now be terminated");
                    System.exit(0);
                } else if (fire.getInt(DatabaseConstants.Column_Ammo) == 0) {
                    System.out.println("Your ammunition is at 0%");
                    System.out.println("Your session will now be terminated");
                    System.exit(0);
                } else if (mymovement < 10) {
                    System.out.println("Your progress has been saved - You will be re-directed to the main menu");
                    DatabaseConstants.showMenu();
                }

            }
            fire.close();
            statement.close();
            conn.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    public static void badweather(int mymovement) {
        try {
            Connection conn = DriverManager.getConnection(DatabaseConstants.Database);
            Statement statement = conn.createStatement();

            System.out.println("You journey has been affected by bad weather" + "\n" +
                    " You have moved 3 mile" + "\n"
                    + "Your health and supplies have reduced by 20%.");

            System.out.println("Enter your ID to save your progress: ");
            Scanner id = new Scanner(System.in);
            int myid = id.nextInt();

            ResultSet badweather = statement.executeQuery("SELECT * FROM " + DatabaseConstants.Table_Troops
                    + " WHERE " + DatabaseConstants.Column_ID + " = " + myid);

            while (badweather.next()) {
                statement.execute("UPDATE " + DatabaseConstants.Table_Troops + " SET " +
                        DatabaseConstants.Column_Health + " = " + (badweather.getInt(DatabaseConstants.Column_Health) - 20) + ", " +
                        DatabaseConstants.Column_Supplies + " = " + (badweather.getInt(DatabaseConstants.Column_Supplies) - 20) + ", " +
                        DatabaseConstants.Column_Ammo + " =  " + (badweather.getInt(DatabaseConstants.Column_Ammo) - 20) + ", " +
                        DatabaseConstants.Column_Location + " = " + (badweather.getInt(DatabaseConstants.Column_Location) + mymovement) +
                        " WHERE " + DatabaseConstants.Column_ID + " = " + myid);

                if (mymovement == 10) {
                    System.out.println("You have moved 10 miles - you have completed the mission");
                    System.out.println("Your session will now be terminated");
                    System.exit(0);
                } else if (badweather.getInt(DatabaseConstants.Column_Health) == 0) {
                    System.out.println("Your health is 0%");
                    System.out.println("Your session will now be terminated");
                    System.exit(0);
                } else if (badweather.getInt(DatabaseConstants.Column_Supplies) == 0) {
                    System.out.println("Your supplies are 0%");
                    System.out.println("Your session will now be terminated");
                    System.exit(0);
                } else if (badweather.getInt(DatabaseConstants.Column_Ammo) == 0) {
                    System.out.println("Your ammunition is at 0%");
                    System.out.println("Your session will now be terminated");
                    System.exit(0);
                } else if (mymovement < 10) {
                    System.out.println("Your progress has been saved - You will be re-directed to the main menu");
                    DatabaseConstants.showMenu();
                }

            }
            badweather.close();
            statement.close();
            conn.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    public static void noEvent (int mymovement) {
        try {
            Connection conn = DriverManager.getConnection(DatabaseConstants.Database);
            Statement statement = conn.createStatement();

            System.out.println("Your journey has not been affected by any adverse event" + "\n" +
                    " You have moved 4 mile2" + "\n"
                    + "Your health and supplies have reduced by 10%.");

            System.out.println("Enter your ID to save your progress: ");
            Scanner id = new Scanner(System.in);
            int myid = id.nextInt();

            ResultSet noEvent = statement.executeQuery("SELECT * FROM " + DatabaseConstants.Table_Troops
                    + " WHERE " + DatabaseConstants.Column_ID + " = " + myid);

            while (noEvent.next()) {
                statement.execute("UPDATE " + DatabaseConstants.Table_Troops + " SET " +
                        DatabaseConstants.Column_Health + " = " + (noEvent.getInt(DatabaseConstants.Column_Health) - 10) + ", " +
                        DatabaseConstants.Column_Supplies + " = " + (noEvent.getInt(DatabaseConstants.Column_Supplies) - 10) + ", " +
                        DatabaseConstants.Column_Ammo + " =  " + (noEvent.getInt(DatabaseConstants.Column_Ammo) - 10) + ", " +
                        DatabaseConstants.Column_Location + " = " + (noEvent.getInt(DatabaseConstants.Column_Location) + mymovement) +
                        " WHERE " + DatabaseConstants.Column_ID + " = " + myid);

                if (mymovement == 10) {
                    System.out.println("You have moved 10 miles - you have completed the mission");
                    System.out.println("Your session will now be terminated");
                    System.exit(0);

                } else if (noEvent.getInt(DatabaseConstants.Column_Health) == 0) {
                    System.out.println("Your health is 0%");
                    System.out.println("Your session will now be terminated");
                    System.exit(0);

                } else if (noEvent.getInt(DatabaseConstants.Column_Supplies) == 0) {
                    System.out.println("Your supplies are 0%");
                    System.out.println("Your session will now be terminated");
                    System.exit(0);

                } else if (noEvent.getInt(DatabaseConstants.Column_Ammo) == 0) {
                    System.out.println("Your ammunition is at 0%");
                    System.out.println("Your session will now be terminated");
                    System.exit(0);

                } else if (mymovement < 10) {
                    System.out.println("Your progress has been saved - You will be re-directed to the main menu");
                    DatabaseConstants.showMenu();

                }
            }
            noEvent.close();
            statement.close();
            conn.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }
}

A: The code is interleaving the ResultSet and Statement instances.
Please refer to:
java.sql.Statement API:
By default, only one ResultSet object per Statement object can be open at the same time. Therefore, if the reading of one ResultSet object is interleaved with the reading of another, each must have been generated by different Statement objects. All execution methods in the Statement interface implicitly close a current ResultSet object of the statement if an open one exists.


text:
Q: More KDE-esque audio control in Ubuntu/GNOME menu bar? or PulseAudio-cum-Gnome integration? KDE's volume/audio options on the system bar looks like this:

It allows easy management of each application's volume and output. GNOME's system menu only features a volume slider for the currently selected audio output. More functionality is found in Settings > Sound. Not only is this inconvenient, it lacks any way to change audio output on a per application basis. You can only select one output at a time, for all applications. To change each audio outputs per application in Gnome, software like PulseAudio Volume Control is required. This is not convenient and annoying, since it's easy to accidentally adjust the wrong settings by scrolling through them in PulseAudio.
I am looking for a way to implement a KDE-esque audio control for Ubuntu/GNOME system menu.

A: You can use a GNOME shell extension called 'Volume Mixer'.

Shell Volume Mixer is an extension for GNOME Shell allowing separate configuration of PulseAudio devices and output switches. It features a profile switcher to quickly switch between pinned profiles and devices.


text:
Q: Using Transients I am new to the transient concept. But I am not sure about the efficient method to use it. I really liked it as it removed the duplicate queries that I had.

*

*I have set set_transient( 'pgggo_acf_list_transient', $pgggo_qry, 12 * 7000 ); is that too high?

*What if there is an admin update on the WordPress site and query that was set transient is modified. Will it get automatically updated?

*Where should I not use transient?

A:
I have set set_transient( 'pgggo_acf_list_transient', $pgggo_qry, 12 *
  7000 ); is that too high?

12 * 7000 is just over 23 hours. Whether or not that's too high (or low) depends entirely on your specific needs. The expiry time should be based on how often the data needs to be refreshed.

What if there is an admin update on the WordPress site and query that
  was set transient is modified. Will it get automatically updated?

No. That's the point of transients.

Where should I not use transient?

When you don't want the data to persist over multiple requests (page loads), over a span of hours, days or longer.

If you use a transient set to 23 hours to avoid making duplicate queries, it means the result of that query will be exactly the same for all users, for all requests, for 23 hours.
'Duplicate queries' is an issue where you are performing the same query multiple times during the same request. This is inefficient because the result of that query is not going to change during a single request. To prevent duplicate queries you should store the result of the query for the duration of the request in a variable so that you don't needlessly query the data again. The Object Cache API is designed for this.
Setting a transient saves the value to the database. You would only do this if you needed to store the data for longer periods of time. This is overkill for preventing duplicate queries, because you're not just preventing the query from being repeated during a request. You're preventing the query from being repeated for an entire day.


text:
Q: Use WM_SETTEXT to replace contents of window whilst maintaining window scroll position I'm building an application that sends RTF text to a third-party window. It basically provides auto-correct functionality within a primitive third-party IDE.
I can set the contents of this window (i.e. the corrected code), but doing so sets the window's scroll position to the top. This is very annoying because then the user has to scroll down to where they were before the autocorrect kicked in.
I can set the cursor to the correct position (down on the page), but this doesn't prevent the window from scrolling to the top.
Any suggestions?

A: WM_SETTEXT is the wrong message to use when replacing a small portion of the text. You use WM_SETTEXT to set the entire text content of the control.
What you want is to select the word that needs to be corrected. Use EM_SETSEL for that. And then use EM_REPLACESEL to replace the text with the corrected version. I expect that will also have the happy effect of fixing the problem of unwanted scrolling.


text:
Q: How to print a table row wise in SQL Server? I have created a function that outputs the table of a number, Here is my UDF scalar function:
create function fntable(@a int)
returns varchar(250)
as begin
declare @b int, @c varchar(250),@e varchar(50)=''
set @b=1
while (@b<=10)
begin
set @c=@a*@b
set @e=@e+@c
set @b=@b+1
end
return @e
end

It displays what i want, but it displays the result in a single row, as per my knowledge. I want to display the rows in multiple rows. How can i do this ? i want to print a table of a number.

A: You need a table-valued function. Using your code as is, this roughly translates to:
create function fntable(@a int)
returns @e table(c int)
as begin
    declare @b int = 1
    while (@b <= 10)
    begin
        insert into @e values (@a * @b)
        set @b += 1
    end

    return
end

Note, however, in this particular case the number of iterations is a constant 10 and the whole thing can be done inline in a single query, without a loop simply by manually expanding the loop. This can be then saved as an inline table-valued function, which can in turn be referenced from other queries.
create function fntable(@a int)
returns table as
return (
    select @a * 1 as c
    union all
    select @a * 2 as c
    union all
    select @a * 3 as c
    union all
    select @a * 4 as c
    union all
    select @a * 5 as c
    union all
    select @a * 6 as c
    union all
    select @a * 7 as c
    union all
    select @a * 8 as c
    union all
    select @a * 9 as c
    union all
    select @a * 10 as c
)

A: Change
set @e=@e+@c

to
set @e=@e+@c + CHAR(10)


text:
Q: Close pretty photo slideshow on click of last slide I am using pretty photo jquery plugin to display slide show, last slide is 'Enter site', when user click on this slide, slide show should stop and user will be redirected to home page of website. How can I implement this.
I tried to use onclick event of  and  tag but none of them are getting called. I even tried to register onclick event from jQuery using 'on' function but no luck.
Thanks in advance.

A: Since the callback function is called when prettyPhoto is closed, you need to use:
changepicturecallback, which is called everytime an item is shown/changed.
In this function you have to read the current item and evaluate if it's the last one.
Try this piece of code:
$("a[rel^='prettyPhoto']").prettyPhoto({
  animationSpeed:'normal',
  slideshow:5000,
  show_title: true,
  allow_resize: true,
  autoplay_slideshow: true,
  social_tools: false,
  deeplinking: false,
  callback: function(){
      console.log('pretty photo is closed')
  },
  image_markup: '<img id="fullResImage" class="fullResImage" src="{path}" />',
  changepicturecallback: function(){
      var currentSlide = ($('.pp_gallery').find('li').index($('.selected'))+1);
      var myArray = jQuery('.currentTextHolder').text().split('/');
      if(currentSlide == myArray[1]){
        /* Make redirect to your HP */
      }
  }
});


text:
Q: Querydsl: How do I sort by a date without the time fraction? My starting point was:
Predicate predicate = (...);
OrderSpecifier<?>[] orderSpecifiers = createOrderSpecifiers();
entityRepository.findAll(predicate, orderSpecifiers);

+
private OrderSpecifier<?>[] createOrderSpecifiers() {

    final OrderSpecifier<?>[] orderSpecifiers = new OrderSpecifier<?>[2];
    /***********************************************************/
    /***********************************************************/
    /***********************************************************/
    orderSpecifiers[0] = QEntity.entity.dateToBeSortedBy.desc();
    /***********************************************************/
    /***********************************************************/
    /***********************************************************/
    orderSpecifiers[1] = QEntity.entity.entity2.id.asc();

    return orderSpecifiers;
}

and I wanted to sort by dateToBeSortedBy ignoring the time fraction of dateToBeSortedBy.
I will post my solution as an answer to this question.

A: private OrderSpecifier<?>[] createOrderSpecifiers() {

    final OrderSpecifier<?>[] orderSpecifiers = new OrderSpecifier<?>[4];
    /***********************************************************************/
    /***********************************************************************/
    /***********************************************************************/
    orderSpecifiers[0] = QEntity.entity.dateToBeSortedBy.year().desc();
    orderSpecifiers[1] = QEntity.entity.dateToBeSortedBy.month().desc();
    orderSpecifiers[2] = QEntity.entity.dateToBeSortedBy.dayOfMonth().desc();
    /***********************************************************************/
    /***********************************************************************/
    /***********************************************************************/
    orderSpecifiers[3] = QEntity.entity.entity2.id.asc();

    return orderSpecifiers;
}

Maybe someone finds this useful.