text:
Q: How to store data typed by user into input using Django I'm kinda new to Django and I got stucked.
I want to get user input, and after that, I want to display a value that depends on it.
For example in Django I have if statement which checks input from the user, for the example car model.
So, when the user type is Ibiza I want to display "Seat", user type E92 I want to display "BMW" etc
I want to display car brands in the list that can be cleared or disappear after the user close the tab and re-open.
Which solution is the best? Database in Django? Cookies? Local storage in javascript?

A: Use the Database. That way you have more control of the data.


text:
Q: third largest and smallest number for pairwise swap of number This is the code for finding 3rd largest and 3rd smallest number.
t=no of test cases
num=user input number
if num  is a single digit number it will print impossible.
if the num is 123 then it should store 123,132,213,231,312,321.
Of these the 3rd from the front is 213 and from back is 231.
The problem of my code is that when i input
123 it gives random number with 112,211,133,311...etc
which i don't want.
I want a 3 digit number containing 1,2 and 3.
if the num is 1234 it should have 4321,2134,3124...Not 1143,2211.
The problem method is solve(int num).
In this method i have converted integer num to string num and then stored it in the string treeset which i will again convert it into integer treeset so to find 3rd largest and 3rd smallest number.
iam not sure about primefact method(it gives factorial{length of a number ) whether it has use or not...
public class ThirdSmallestLargest {
public static void main(String[] args) {
    Scanner in=new Scanner(System.in);
    ThirdSmallestLargest tsl=new ThirdSmallestLargest();
    int t,num;
    t=in.nextInt();
    while(t!=0){
        num=in.nextInt();
        tsl.match(num);
        t--;
    }
}
//---------------------Method for finding zero in a number
private void match(int num) {
    int length=(int) (Math.log10(num)+ 1);
    if(length==1){
        System.out.println("Not possible");
    }
    else{
           String s = String.valueOf(num);
           if (s.indexOf('0')<0){
               solve(num);
           }
    }
}
//---------------------method for distinct jumble number
 //NOT DONE CONVERT STRING TREESET TO INTEGER TREESET
private void solve(int num) {
        int length=(int) (Math.log10(num)+ 1);
       TreeSet <String> tsstr=new TreeSet<>();
       Iterator<String> itr=tsstr.iterator();
       //Integer.toString(num);
       char[] chars = Integer.toString(num).toCharArray();
      StringBuilder sb = new StringBuilder(); // doesnt work with 666,7979 types of number
       Random random =  new Random();
       while (tsstr.size() <fact(num)){
       for (int i = 0; i < length; i++) {
       char c = chars[random.nextInt(chars.length)];
           sb.append(c);

        }
        String output = sb.toString();
        sb.setLength(0);//set the length of the char

       // String input=sb.toString();
        //System.out.println(output);
       // if(output.contentEquals("1"))
      // tsstr.add(Integer.toString(num));

        tsstr.add(output);
    }
       System.out.println(tsstr);

}

private int fact(int num) {
    int length=(int) (Math.log10(num)+ 1);
    int i,fact=1;
    for(i=1;i<=length;i++){
       fact=fact*i;
    }
    return fact;
 }
}

A: First, sort the digits.
Let's say input is 111222333444 after sorting. That is the lowest number.
Next number is found by swapping last 3 with first 4, i.e. 111222334344. Said another way, you move the last second-highest digit one position to the right. That is the second-lowest number.
Now there are two cases:

*

*If there were more than one of the highest digit (4), just to it again, i.e. move the last 3 one more to the right: 111222334434.

*If there was only one 4, the 3 is at end and can't move to the right, e.g. 1112223334 → 1112223343, so we move it back, then move the last third-highest digit (2) one position to the right: 1112223343 → 1112223334 → 1112232334
You've now found the third lowest number. To recap:
111222333444 → 111222334344 → 111222334434
1112223334 → 1112223343 → 1112232334
You can skip the middle step. If there is more than one 4, move last 3 two positions right. Otherwise, move last 2 one position right.
For third-highest number you do the same, except reversed:
444333222111 → 444333221121 (last 2 moves two positions right)
4443332221 → 4443323221 (last 3 moves one position right)
I'll leave it to you to write the code for it.

A: Some suggestions to get you going:

*

*Separate your code into the different "functions" you need, like: creating all permutation of all possible combinations of your numbers

*Getting them sorted

In other words: first create a list of all possible numbers; then simply use one of the many ways of getting that list sorted; and then you just decided which "indexes" in that sorted lists are of interst to you.
And: choose better abstractions respectively: don't move "jump" from one level to another. Stick with them.
Meaning: initially, consider your user input to be a string, not a number (of course, you then have to check that this string only contains digits).
You see, if you have a string, you can directly ask for its length; no need to call log() to figure the numbers of chars in a string. Then, you can easily fetch the individual digits from your string - and you get an array of characters. Now you can easily create permutations of those characters; building strings. Finally, you turn all strings into ints for sorting.
But the point is: all of the above steps should be their own distinct functions. Built small methods (which all of them are perfect for being tested on their own) ... and then compose your solution out of that.

redpajama_set_name: RedPajamaStackExchange


text:
Q: consecutive integers that are not the sum of 2 squares. Are there any $n\in\mathbb{N}$ such that no element  $k\in\{n,n+1,n+2,...,n+2017\}$ can be expressed as $a^2+b^2$ for some $a,b\in\mathbb{Z}$?

A: Yes. Let $p_1, p_2, \cdots, p_{2018}$ be distinct primes of the form $4k+3$. By Chinese Remainder Theorem there exists $n$ such that
$$
\begin{aligned}
n &\equiv p_1 &\pmod{p_1^2}\\
n &\equiv p_2 - 1 &\pmod{p_2^2}\\
&\vdots\\
n &\equiv p_{2018} - 2017 &\pmod{p_{2018}^2}.
\end{aligned}
$$
Then $\{n, n+1 , \cdots, n+2017\}$ satisfies your requirements.

A: The set $E$ of numbers of the form $a^2+b^2$ has density zero, in particular there are at most $\frac{CN}{\sqrt{\log N}}$ numbers of such form in $[1,N]$ for large values of $N$. Assuming that there is a number of such form in each interval with length $2018$ gives that the density of $E$ is at least $\frac{1}{2018}$, contradiction.


text:
Q: System.Text.Json: Deserialize JSON is failing (.net core 6 + Ubuntu + Wine) We have .net framework based application which connects with backend using REST API. When we run this application using Wine on Ubuntu 20.04 it works perfectly well. Our requirement is that we need to covert this .net framework based application to .net core 6 first and then run using Wine on Ubuntu.
After this transformation, when we run the application and try to Deserialize JSON returned from REST API, it is failing with following error
Fatal error. Internal CLR error. (0x80131506)
0204:fixme:advapi:RegisterEventSourceW ((null),L".NET Runtime"): stub
0204:fixme:advapi:ReportEventW (CAFE4242,0x0001,0x0000,0x000003ff,00000000,0x0001,0x00000000,003AD66C,00000000): stub
0204:err:eventlog:ReportEventW L"Application: APP.exe\nCoreCLR Version: 6.0.522.21309\n.NET Version: 6.0.5\nDescription: The process was terminated due to an internal error in the .NET Runtime at IP 0144D5A8 (01320000) with exit code 80131506.\n"
0204:fixme:advapi:DeregisterEventSource (CAFE4242) stub
wine: Call from 7BC29F80 to unimplemented function KERNEL32.dll.RaiseFailFastException, aborting
Unhandled exception. System.Runtime.InteropServices.SEHException (0x80004005): External component has thrown an exception.

Strange thing is that this behavior is intermittant. Sometimes Deserialization succeeds as well.
We have seen same behavior with Newtonsoft.Json APIs as well
Code line is as follows:
value = (T)System.Text.Json.JsonSerializer.Deserialize(jsonString, typeof(T));

We are using Wine 7 version.
Appreciate any help on this.


text:
Q: Looking for a django app for running my blog I am looking for a django blog application to run my blog.
I have found following options available:

*

*django-basic-blog

*Byteflow

Can you please share your recommendation.
My basic requirements are:
- Easy to customize
- Having basic blog capabilities

A: django-mingus
Recommended.

A: Try django-diario

A: I recommended Byteflow
This project has great promise.
I myself included in the project soon


text:
Q: I need to traverse through an 8 digit String to check some conditions in VB.Net I need help in Vb.net, how can I traverse through an 8 digit integer and check whether

*

*Three numbers r repeated consecutively like 111,222

*Check whether numbers are consecutively spaced like 123,876 3. Check whether 4 numbers r present

I input the 8 digit as string as its a requirement then convert into a string.
Imports System.console

Public Class residentNumberCheck

    Dim cardNumber As String

    Public Sub inputNumberAndCheck()

        writeline("Enter the 8 Digit Resident Card Number")
        cardNumber = readline()

        While (cardNumber.length() <> 8)
            writeline("The Resident Card Number is Invalid. It does not contain 8 digits... Please enter again")
            cardNumber = readline()
        End While

    End Sub

    Public Sub sameThreeNumber()

        writeline("")
        writeline("...Checking for 3 consecutive numbers...")
        writeline("")

        Dim Num As Integer = Integer.parse(cardNumber)
        Dim temp As Integer = Num

        Dim i As Integer
        Dim j As Integer
        Dim k As Integer
        Dim checker As Boolean = False

        While (Num > 0)

            i = Num Mod 10

            Num = Num \ 10

            j = Num Mod 10

            temp = temp \ 10

            k = temp Mod 10

            Num = temp \ 10

            temp = Num \ 10

            If (i = j And j = k) Then

                writeline("    ****The Number is a Special Number as the Number {0} occurs three consecutive times****", i)
                checker = True

                Return

            End If

        End While

        If (checker = False) Then
            writeline("The Number does not have 3 consecutive numbers")
        End If

    End Sub

    Public Sub ConsecutiveNumber()

        writeline("")
        writeline("...Checking for consecutive digits in increasing or decreasing...")
        writeline("")

        Dim Num As Integer = Integer.parse(cardNumber)
        Dim temp As Integer = Num

        Dim i As Integer
        Dim j As Integer
        Dim k As Integer
        Dim checker As Boolean = False

        While (Num > 0)

            i = Num Mod 10

            Num = Num \ 10

            j = Num Mod 10

            temp = temp \ 10

            k = temp Mod 10

            Num = temp \ 10

            temp = Num \ 10

check1:
            If (i = j + 1) Then
                If (j = k + 1) Then
                    checker = True
                    writeline("    ****The Number is a Special Number as it has {0}, {1}, {2} consecutive numbers****", k, j, i)
                    Return
                End If
            End If
check2:
            If (i = j - 1) Then
                If (j = k - 1) Then
                    checker = True
                    writeline("    ****The Number is a Special Number as it has {0}, {1}, {2} consecutive numbers****", k, j, i)
                    Return
                End If
            End If

        End While

        If (checker = False) Then
            writeline("The Number does not contain consecutive digits in increasing or decreasing")
        End If

    End Sub

    Public Sub checksimilarfourdigits()

        writeline("")
        writeline("...Checking if a number is repeated four times...")
        writeline("")

        Dim Num As Integer = Integer.parse(cardNumber)
        Dim temp As Integer
        Dim x As Integer
        Dim y As Integer

        Dim i As Integer
        Dim j As Integer
        Dim counter As Integer = 0
        Dim checker As Boolean = False

        While (Num > 0)

logic:

            i = Num Mod 10

            Num = Num \ 10

            j = Num Mod 10

            Num = Num \ 10

check:

            If (i = j) Then
                counter = counter + 1
                temp = i
            Else
                temp = j
                GoTo logic
            End If

            If (temp = i) Then
                counter = counter + 1
                x = temp
                y = 0
            End If

            If (temp = j) Then
                counter = counter + 1
                y = temp
                x = 0
            End If

            If (counter >= 4) Then

                If (x = 0) Then

                    writeline("    ****The Number is a Special Number as the number {0} repeats four times or more****", y)
                    checker = True
                    Return
                End If

                If (y = 0) Then
                    writeline("    ****The Number is a Special Number as the number {0} repeats four times or more****", x)
                    checker = True
                    Return
                End If

            End If

        End While

        If (checker = False) Then
            writeline("The Number does not contain 4 equal digits")
        End If

    End Sub

    Public Shared Sub main()
        Dim user As residentNumberCheck = New residentNumberCheck()
        user.inputNumberAndCheck()
        user.sameThreeNumber()
        user.ConsecutiveNumber()
        user.checksimilarfourdigits()

    End Sub

End Class

A: If you want to compact your code you may use Regex class:
        Dim cardNumber As String = TextBox1.Text
' (\d) finds digit (\d)\1 finds digit repeated once, here \1 makes
' reference to first group (), this is, (\d)
' (\d)\1{2,} finds digit repeated at least 2 times
        Dim mc As MatchCollection = New Regex("(\d)\1{2,}").Matches(cardNumber)
        If mc.Count Then ' there are at least 3 consecutive equal #s
            Trace.WriteLine(String.Format("Number {0} occurs {1} times", mc(0).Value, mc(0).Value.Length))
        End If
        mc = New Regex("\d").Matches(cardNumber)
        ' each mc() contains one digit
        Dim incr As Int32=0, indI As Int32 = -1
        Dim decr As Int32=0, indD As Int32 = -1
        For i As Int32 = 0 To mc.Count - 1
            Dim curr As Int32 = Int32.Parse(mc(i).Value)
            If i < mc.Count - 1 Then ' there is a next number
                ' if current+1=next# =>increment count & save index
                If curr + 1 = Int32.Parse(mc(i + 1).Value) Then
                    If indI = -1 Then indI = i
                    incr += 1 : If incr = 2 Then Exit For
                Else
                    incr = 0 : indI = -1
                End If
            End If
            If i Then ' there is a previous #
    ' if current+1=previous# =>previous incr. count & save index
                If curr + 1 = Int32.Parse(mc(i - 1).Value) Then
                    If indD = -1 Then indD = i
                    decr += 1 : If decr = 2 Then Exit For
                Else
                    decr = 0 : indD = -1
                End If
            End If
        Next
        If incr = 2 Then
            Trace.WriteLine(String.Format("{0}{1}{2} Consecutive numbers", mc(indI), mc(indI + 1), mc(indI + 2)))
        ElseIf decr = 2 Then
            Trace.WriteLine(String.Format("{0}{1}{2} Consecutive numbers", mc(indD - 1), mc(indD), mc(indD + 1)))
        End If


text:
Q: Double row with same height in flexbox I've created a table with the first column using two rows, so the following columns will have two rows, but with the same height. Some cells will have 2 or more lines and other none. So, I want them to have the same height, which would be half the height of the first row.
I've tried adding min-width: 50%, but it didn't work.

.double-row {
  display: flex;
  border: 2px solid blue;
}

.col {
  border-right: 1px solid grey;
}

.first-col {
  display: flex;
  align-items: center;
  padding: 10px;
}

.other-col {
  display: flex;
  flex-direction: column;
}

.cell {
  padding: 10px;
  border-bottom: 1px solid grey;
}

.cell.upper {
  background: #00FF002F;
}

.cell.down {
  background: #FF00002F;
}

      Double Row

        Upper Text

      <input type="text">

        Bottom Text

        Bottom Text

        Bottom Text

      <input type="text">

        Bottom Text

https://codepen.io/Agusbeche/pen/ZNvMPb

A: you could just insert

 in the other column for a quick fix. but thats not actually a nice solution, insted you should do this:
add height: 50%; to the children inside col

.double-row {
  display: flex;
  border: 2px solid blue;
}

.col {
  border-right: 1px solid grey;
}

.first-col {
  display: flex;
  align-items: center;
  padding: 10px;
}

.other-col {
  display: flex;
  flex-direction: column;
}

.cell {
  flex-grow: 0;
  height: 50%;
  max-height: 50%;
  padding: 10px;
  border-bottom: 1px solid grey;
  overflow: hidden;
}

.cell.upper {
  background: #00FF002F;
}

.cell.down {
  background: #FF00002F;
}

      Double Row

        Upper Text

      <input type="text">

        Bottom Text

        Bottom Text

        Bottom Text

        Bottom Text

        Bottom Text

      <input type="text">

        Bottom Text

A: You can add flex: 1 to the cell so that the rows share equal spaces. Also add overflow: auto so that any extra content will be scrolled if needed. If you want the three columns to share the horizontal space equally just add flex: 1 to the col - see demo below:

.double-row {
  display: flex;
  border: 2px solid blue;
}

.col {
  border-right: 1px solid grey;
  flex: 1; /* if columns must share equal space */
}

.first-col {
  display: flex;
  align-items: center;
  padding: 10px;
}

.other-col {
  display: flex;
  flex-direction: column;
}

.cell {
  padding: 10px;
  border-bottom: 1px solid grey;
  flex: 1; /* equal rows */
  overflow: auto; /* overflow if content is more */
}

.cell.upper {
  background: #00FF002F;
}

.cell.down {
  background: #FF00002F;
}

input {
  width: 100%; /* added */
}

      Double Row

        Upper Text

      <input type="text">

        Bottom Text

        Bottom Text

        Bottom Text

      <input type="text">

        Bottom Text

Without the overflow and equalling the height with the largest cell does not work properly with flexbox though - see the below demo with min-height: 50% to the other-cell cell. The container as a whole does not grow:

.double-row {
  display: flex;
  border: 2px solid blue;
}

.col {
  border-right: 1px solid grey;
  flex: 1; /* if columns must share equal space */
}

.first-col {
  display: flex;
  align-items: center;
  padding: 10px;
}

.other-col {
  display: flex;
  flex-direction: column;
}

.other-col .cell {
  min-height: 50%; /* added */
}

.cell {
  padding: 10px;
  border-bottom: 1px solid grey;
  flex: 1; /* equal rows */
}

.cell.upper {
  background: #00FF002F;
}

.cell.down {
  background: #FF00002F;
}

input {
  width: 100%; /* added */
}

      Double Row

        Upper Text

      <input type="text">

        Bottom Text

        Bottom Text

        Bottom Text

      <input type="text">

        Bottom Text

We can switch to CSS grids since the layout here has 2D behavior - to get the desired layout we can use a 3x2 grid with each cell occupying 1fr space (which means the rows will grow to be equal) - see demo below:

.double-row {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr; /* 3 equal columns */
  grid-template-rows: 1fr 1fr; /* 2 equal rows */
  border: 2px solid blue;
}

.col {
  border-right: 1px solid grey;
}

.first-col {
  display: flex;
  align-items: center;
  padding: 10px;
  grid-row: 1 / span 2; /* occupy the first two rows */
}

.other-col {
  display: contents; /* promote the 'cell' to grid item */
}

.first-col + .other-col .cell {
  border-right: 1px solid grey; /* border fix */
}

.cell {
  padding: 10px;
  border-bottom: 1px solid grey;
}

.cell.upper {
  background: #00FF002F;
  grid-row: 1; /* place in first row */
}

.cell.down {
  background: #FF00002F;
}

input {
  width: 100%; /* added */
}

      Double Row

        Upper Text

      <input type="text">

        Bottom Text

        Bottom Text

        Bottom Text

      <input type="text">

        Bottom Text


text:
Q: Convert DAO to ADO I am trying to create a function that will check all the check boxes in a form with a
datasheet subform.
Since we moved to Office 2013 this code stopped working and it seems that moving to ADO is the only way.
Private Sub Toggle_Click()
    Dim sfrm
    Dim cn As ADODB.Connection
    Dim rs As ADODB.Recordset
    sfrm = Me.Subform
    Set cn = CurrentProject.Connection
    'Dim rs As DAO.Recordset
    'Set rs = Me.Subform.Form.RecordsetClone
  rs.Open Me.Recordset
    If (theTop = 0) Then
    Else
        Me.Subform.Form.AllowAdditions = False
        Dim i As Integer
        If (theHeight = 0) Then
            If (sfrm![Ready?] = -1) Then
                sfrm![Ready?] = 0
                sfrm![Timestamp] = Null
            Else
                sfrm![Ready?] = -1
                sfrm![Timestamp] = Date
            End If
        Else
            On Error Resume Next
            For i = theTop To rs.RecordCount
                'If (i = 1) Then
                'Else

                'End If
                'rs.MoveLast
             'Do While Not rs.BOF
                If (sfrm![Ready?] = -1) Then
                    sfrm![Ready?] = 0
                    sfrm![Timestamp] = Null
                Else
                    sfrm![Ready?] = -1
                    sfrm![Timestamp] = Date
                End If

                 'Me.Subform.Form.Recordset.MoveNext
                 rs.MoveNext
                 'Debug.Print sfrm![Routing Number]
               'Loop
            Next
        End If
        Me.Subform.Form.AllowAdditions = True
    End If

End Sub

A:
it seems that moving to ADO is the only way

With Access 2013, DAO remains the preferred way to interact with Access database objects from within the Access application itself. In my opinion it would be wise for you to investigate why the previous DAO code is failing (and how you might fix it) before embarking on a wholesale conversion of DAO code to ADO.
I just did a test in Access 2013. With [ParentTable}

[ChildTable]

and a form like this

I could toggle the [Selected?] status of the current subform records with the following code:
Option Compare Database
Option Explicit

Private Sub cmdToggleChildren_Click()
    Dim rst As DAO.Recordset
    Set rst = Me.ChildSubform.Form.Recordset
    If Not (rst.BOF And rst.EOF) Then
        rst.MoveFirst
        Do Until rst.EOF
            rst.Edit
            rst![Selected?] = Not rst![Selected?]
            rst.Update
            rst.MoveNext
        Loop
    End If
    Set rst = Nothing
End Sub


text:
Q: How to refer to a value in Sql View Query --
-- Table structure for table `emp`
--

CREATE TABLE `emp` (
  `Emp_id` int(11) NOT NULL,
  `Name` varchar(30) DEFAULT NULL,
  `Sup_id` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `emp`
--

INSERT INTO `emp` (`Emp_id`, `Name`, `Sup_id`) VALUES
(1, 'Mark 18', NULL),
(2, 'Iron Man', 1),
(3, 'Hulk', NULL),
(4, 'Ant-Man', 2);

--
-- Indexes for dumped tables
--

--
-- Indexes for table `emp`
--
ALTER TABLE `emp`
  ADD PRIMARY KEY (`Emp_id`),
  ADD KEY `Sup_id` (`Sup_id`);

--

this is my table DESC
i want output as this
like in case of iron man
iwant out put like this
2 Iron Man  Mark 18
this means it want to check the Emp_id and Dispaly correspond name of Emp _id
DESc Stucture
+--------+-------------+------+-----+---------+-------+
| Field  | Type        | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| Emp_id | int(11)     | NO   | PRI | NULL    |       |
| Name   | varchar(30) | YES  |     | NULL    |       |
| Sup_id | int(11)     | YES  | MUL | NULL    |       |
+--------+-------------+------+-----+---------+-------+

Values Inside Table
+--------+----------+--------+
| Emp_id | Name     | Sup_id |
+--------+----------+--------+
|      1 | Mark 18  |   NULL |
|      2 | Iron Man |      1 |
|      3 | Hulk     |   NULL |
|      4 | Ant-Man  |      2 |
+--------+----------+--------+

Output format i want
+--------+----------+--------+
| Emp_id | Name     | Sup_id |
+--------+----------+--------+
|      1 | Mark 18  |NULL    |
|      2 | Iron Man |MArk 18 |
|      3 | Hulk     |   NULL |
|      4 | Ant-Man  |Iron Man|
+--------+----------+--------+

A: Just LEFT JOIN table on itself:
SELECT e.Emp_id, e.Name, es.Name AS Sup_name FROM emp AS e LEFT JOIN emp AS es ON e.Sup_id = es.Emp_id


text:
Q: How to deal with interface errors in Eclipse Ive just installed a fresh new Eclipse "Neon". I've mentioned that some elements of the UI are looking strange like the main-menu or some widgets like the dropdown-menues within the config-menues (see screenshots).
How can I deal with it so that eclipse stops looking like its broken?
My Java-Version is
java version "1.8.0_91"
Java(TM) SE Runtime Environment (build 1.8.0_91-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.91-b14, mixed mode)

A: After searching the web for a solution I found that the error must based on a problem with GTK-3.0 in eclipse.
When launching eclipse like this export SWT_GTK3=0; ./eclipse It will work perfectly. Just if anybody has similar issues.


text:
Q: Ember Component Bindings Not Propagating I'm expirencing some weirdness with Ember components. First problem I'm seeing is that class attribute binding is not working. I'm also witnessing properties some how being unbound after the first time they are mutated. This is just a simple tabs component that I am building. Here's a repro http://emberjs.jsbin.com/uDUfONi/2/edit
JS
App = Ember.Application.create();

App.IndexRoute = Ember.Route.extend({
  model: function() {
    return ['red', 'yellow', 'blue'];
  }
});

App.IndexController = Ember.Controller.extend({
  selectedTab: '',

  initialTab: function () {
    var name = this.get( 'model' ).get('firstObject');
    this.set( 'selectedTab', name );
    return name;
  }.property()

});

App.MyTabComponent = Ember.Component.extend({
  tagName: 'li',
  isSelected: false,

  tabChanged: function () {
    if ( this.get( 'selectedTab' ) !== this.get( 'name' ) ) {
      this.set( 'isSelected', false );
    } else {
      this.set( 'isSelected', true );
    }
  }.observes('selectedTab'),

  checkInitialTab: function () {
    if ( this.get( 'initialTab' ) === this.get( 'name' ) ) {
      this.set( 'isSelected', true);
    } else {
      this.set( 'isSelected', false );
    }
  }.on( 'didInsertElement' ),

  actions: {
    selectTab: function () {
      if ( this.get( 'selectedTab' ) !== this.get( 'name' ) ) {
        this.set( 'selectedTab',  this.get( 'name' ) );
      }
    }
  }
});

Templates

A: Okay, had to consult with another Emberino on this one.
It came down to the fact that there were nested li element.  When you defined the tagName on the component it injects the component with that tag.  Unfortunately it was breaking ember/html/somewhere/Idunno.
http://emberjs.jsbin.com/uDUfONi/10/edit

App.MyTabComponent = Ember.Component.extend({
  tagName: 'li',
  classNameBindings: ['isSelected:active', ':clickable'],
  isSelected: function(){
    return this.get('selectedTab') === this.get('name');
  }.property('selectedTab', 'name'),

  click: function () {
    this.set('selectedTab', this.get('name'));
  }

});

instead of the li being defined twice:

App.MyTabComponent = Ember.Component.extend({
  tagName: 'li',
  .....
});

A: Yeah, it's definitely the double li that is somehow breaking things.  I have no idea exactly how...
I just commented out the tagName : 'li', line and the {{isSelected}} value in the template starts showing the right thing.
http://emberjs.jsbin.com/uDUfONi/12/edit


text:
Q: how to link db2 table column to another object? I am new to DB2 and I'm working with an IBM i series system. I have an object with a special column "X". I want to store data for X in another object whenever some criteria satisfied and I can get data from the original object for both special records(which data have been stored in another object) and normal data (which values stored in the original object).
How can I link this column to another object? can DB2 data link: data-link help me in this situation? if yes, how can I implement that? I can't find a complete tutorial on how to do this.
I will appreciate any help.


text:
Q: Shell script to convert the date format in a file I would like to convert the date format in file, using a shell script.
Input:
S.no|Name|Joining_Date|Address
1|asdasd|09/18/2018|asdas
2|asd|09/18/2018|asdasd
3|asdas|09/18/2018|aadadw

Output:
S.no|Name|Joining_Date|Address
1|asdasd|18/09/2018|asdas
2|asd|18/09/2018|asdasd
3|asdas|18/09/2018|aadadw

Below are the scripts which have tried
Input File:
cat datesep.txt  :
asdasd|asdasd|asdasd|30/08/2018|sadasd
asdasd|asdasd|asdasd|12/09/2018|sadasd
asdasd|asdasd|asdasd|23/06/2018|sadasd
asdasd|asdasd|asdasd|26/10/2018|sadasd
asdasd|asdasd|asdasd|23/09/2018|sadasd
asdasd|asdasd|asdasd|12/07/2018|sadasd

cat test.sh
#!/bin/bash
date +'%d-%m-%y'
DATE=`date +%d`
MONTH=`date +%m`
YEAR=`date +%y`
echo "${MONTH}/${DATE}/${YEAR}"

cat test1.sh
#!/bin/bash
SOURCEDATE=`awk -F '|' '{print $4}' /home/work/datesep.txt`
TEMP=$SOURCEDATE
echo $TEMP
DATE=`cut -c 1-2 ${TEMP}`
MONTH=`cut -c 4-5 ${TEMP}`
YEAR=`cut -c 7-10 ${TEMP}`
echo "${MONTH}/${DATE}/${YEAR}"

cat test2.sh
#!/bin/bash
awk -F '|' '{print $4}' /home/work/datesep.txt > /home/work/temp.txt
TEMP=$SOURCEDATE
echo $TEMP
DATE=`cut -c 1-2 /home/work/temp.txt`
MONTH=`cut -c 4-5 /home/work/temp.txt`
YEAR=`cut -c 7-10 /home/work/temp.txt`
echo "${MONTH}/${DATE}/${YEAR}"

cat test3.sh
#!/bin/bash
awk -F '|' '{print $4}' /home/work/datesep.txt > /home/work/temp.txt
TEMP=/home/work/temp.txt
COUNT=`cat ${TEMP} | wc -l`
echo $COUNT
echo $TEMP
LINE_NUM=1
while read LINE
do
        DATE=`awk -F '/' '{print $1}' LINE`
        MONTH=`awk -F '/' '{print $2}' LINE`
        YEAR=`awk -F '/' '{print $3}' LINE`
        echo "${MONTH}/${DATE}/${YEAR}"
        ((LINE_NUM++))
done < $TEMP

cat test4.sh
#!/bin/bash
awk -F '|' '{print $4}' /home/work/datesep.txt > /home/work/temp.txt
TEMP=`/home/work/temp.txt`
for LOOP in `/home/work/temp.txt `
do
        DATE=`awk -F '/' '{print $1}' $LOOP`
        MONTH=`awk -F '/' '{print $2}' $LOOP`
        YEAR=`awk -F '/' '{print $3}' $LOOP`
        echo "${MONTH}/${DATE}/${YEAR}"
done

A: Working from the first set of given input and expected output in the question and assuming that you'd just want to swap the month and day in the date in the third |-delimited field.
$ awk -F '|' -v OFS='|' 'NR > 1 { split($3, a, "/"); $3 = sprintf("%s/%s/%s", a[2],a[1],a[3]) } 1' <file
S.no|Name|Joining_Date|Address
1|asdasd|18/09/2018|asdas
2|asd|18/09/2018|asdasd
3|asdas|18/09/2018|aadadw

This awk command treats each input line as a record with |-delimited fields.  It takes the 3rd such field on each line (except the first line) and splits it on / into the array a.  It then reassembles the field using the a array into the wanted format and order using sprintf() (which works like printf() but returns the generated string instead of outputting it).  The lone 1 at the end causes each line to be outputted (it's a short way of writing { print }).


text:
Q: IOS Anyway to have NSAttributedString throughout app. Swift I have a font which is super skinny. In photoshop, I have added stroke to the font which makes it look more appealing. When transferring it to iOS I couldn't add a stroke unless I used NSAttributedString. By using the NSAttributedString I got one of my UILabels to look exactly how it looks in photoshop however the issue is that I will have hundreds of UILabels by the time my app is finished. Is there a way where I don't have to manually connect each UILabel to its respective controller and set its attributedText one by one. Any suggestions would help.

A: I was just searching and then I stumbled upon this question. I think you want a category for UILabel. I have one very helpful method from my old Cocoapod library called GPKit https://github.com/glennposadas/gpkit-ios that I made before. But this code below is updated and documented.
import UIKit

/// Category for UILabel helper functions
extension UILabel {
    /// A helper function for setting up the normal properties of the label.
    /// This means that the label has no special attributes.
    /// This uses the system font.
    func setup(_ text: String, fontSize: CGFloat, weight: UIFont.Weight = .regular, italic: Bool = false, textColor: UIColor = .lalaDarkGray, numberOfLines: Int = 1, textAlignment: NSTextAlignment = .natural) {
        self.font = italic ? UIFont.italicSystemFont(ofSize: fontSize) : UIFont.systemFont(ofSize: fontSize, weight: weight)
        self.text = text
        self.textColor = textColor
        self.numberOfLines = numberOfLines
        self.textAlignment = textAlignment
    }

    /**
     Sets up the label with two different kinds of attributes in its attributed text.

     - Author: Glenn

     - Important:
         - primaryString = "Total:"
         - secondaryString = "123"
         - This means that the function will concat the secondary string into the primary string and highlights the secondary string.
         - Using the highlightedText means the highlightedText itself is in the primaryString.

     - parameters:
        - primaryString: the normal attributed string.
        - secondaryString: the bold or highlighted string.
        - highlightedText: this one is like the secondary string, if this is provided, then the secondaryString is ignored. This is to be used if the highlighted text is not to be concatinated at the end of the primaryString
     */
    func setAttributedText(
        primaryString: String,
        textColor: UIColor,
        font: UIFont,
        secondaryString: String = "",
        secondaryTextColor: UIColor? = nil,
        secondaryFont: UIFont? = nil,
        highlightedText: String? = nil,
        textAlignment: NSTextAlignment = .center,
        numberOfLines: Int = 1,
        lineHeightMultiple: CGFloat = 1) {

        var textToBeHighlighted = ""
        var completeString: String!

        self.numberOfLines = numberOfLines

        if let highlightedText = highlightedText {
            textToBeHighlighted = highlightedText
            completeString = primaryString
        } else {
            if secondaryString.hasValidValue() {
                textToBeHighlighted = secondaryString
                completeString = "\(primaryString) \(secondaryString)"
            } else {
                completeString = primaryString
            }
        }

        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.alignment = textAlignment
        paragraphStyle.lineHeightMultiple = lineHeightMultiple

        let completeAttributedString = NSMutableAttributedString(
            string: completeString, attributes: [
                .font: font,
                .foregroundColor: textColor,
                .paragraphStyle: paragraphStyle
            ]
        )

        let secondStringAttribute: [NSAttributedString.Key: Any] = [
            .font: secondaryFont ?? font,
            .foregroundColor: secondaryTextColor ?? textColor,
            .paragraphStyle: paragraphStyle
        ]

        let range = (completeString as NSString).range(of: textToBeHighlighted)

        completeAttributedString.addAttributes(secondStringAttribute, range: range)

        self.attributedText = completeAttributedString
    }
}

You can use it in every label you have like so:
internal lazy var label_Total: UILabel = {
    let label = UILabel()
    label.setAttributedText(
        primaryString: "Total".localized(),
        textColor: .gray,
        font: UIFont.systemFont(ofSize: 14.0),
        secondaryString: "",
        secondaryTextColor: .blue,
        secondaryFont: UIFont.systemFont(ofSize: 14.0, weight: customFontWeight)
    )
    return label
}()

A: Based on @AdamPro13 suggestion, you could create a protocol extension for your NSAttributedString:
So, create NSAttributedStringExtension.swift with something like that:
protocol NSAttributedStringExtension {
    static func attributed(string:String, font:UIFont, color:UIColor) -> NSAttributedString
}

extension NSAttributedString : NSAttributedStringExtension {
    class func attributed(string:String, font:UIFont, color:UIColor) -> NSAttributedString {

        let attrs = [NSFontAttributeName:font, NSForegroundColorAttributeName:color]
        return NSAttributedString(string: string, attributes: attrs)
    }
}

And you could make several different functions for different label types.
Just apply then on your label (rough code):
let label:UILabel
let font:UIFont
let color:UIColor
label.attributedText = NSAttributedString.attributed("test", font: font, color: color)

Note: the font and colour you could setup in your protocol extension function

A: If you're using storyboard and want to use UILabels as normal, then you can try creating a UILabel subclass as shown below and using it in your storyboards as a custom class. This will effectively replace the text with the attributedText you want although you wont see it until runtime.
class CustomLabel: UILabel {
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }

    func commonInit() {
        let attrs = [NSFontAttributeName: UIFont.boldSystemFontOfSize(19),
                     NSForegroundColorAttributeName: UIColor.blueColor()]
        attributedText = NSAttributedString(string: text!, attributes: attrs)
    }
}


text:
Q: Why is the default value of a function 1? I noticed that the constructor with parentheses behaves differently, at least for floats and ints.
// int a, b{}, c = T(), d = T{}, e();
float a, b{}, c = T(), d = T{}, e();
endl(std::cout << a << ", " << b << ", " << c << ", " << d << ", " << e);

// 0, 0, 0, 0, 1

It's not a default constructor, the parentheses were parsed as part of the type. I printed the types, and e has type float (&)() (or just float() with proper forwarding), so I think it's a default-constructed function. The result of calling it has a type, but calling it results in the linker error you'd expect. Its value would be 0 if it were a function pointer. Why would its value be 1, or how does it end up as 1 when it's printed?

A: float e();

This declares e as a function that returns float and takes no arguments. So This decays to a function pointer which decays to bool which prints 1 unless boolalpha is set.

A: It's not a function pointer, it's literally a function (albeit an undefined one).
By streaming the expression e, which decays, you're creating a pointer to that function, and said pointer is valid because it points to the function you've declared called e. Hence, 1.
You're right to say that if you declared a function pointer to begin with, and made it nullptr, you'd see 0 instead by streaming it. But functions and function pointers are two different things.


text:
Q: How to display a html source code saved inside a  tag of external / shared location page in my local html page? I have a shared external HTML file, inside that html file : a full html source code has written inside a  tag. Please help me to read that html source code inside the  tag and display it in another html file which i need to save in my system locally.
there will be changes in html source code inside the  tag, so without referring there i need to load the html source code in my page load, automatically.
how can i make it possible


text:
Q: Python why we cant random decimal values My Code:
import random
randomlist = []
for i in range(0,100):
    n = random.randint(1.0,2.0)
    randomlist.append(n)
print(randomlist)

From Above Code :
n = random.randint(1.0,2.0)

Its Correct
But When
n = random.randint(0.1,1.0)
n = random.randint(0.001,1.001)

Gives An Error
> Traceback (most recent call last):   File
> "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py",
> line 31, in <module>
>     start(fakepyfile,mainpyfile)   File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py",
> line 30, in start
>     exec(open(mainpyfile).read(),  __main__.__dict__)   File "<string>", line 4, in <module>   File
> "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.8/random.py",
> line 248, in randint
>     return self.randrange(a, b+1)   File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.8/random.py",
> line 212, in randrange
>     raise ValueError("non-integer arg 1 for randrange()") ValueError: non-integer arg 1 for randrange()

[Program finished]

How Its Possible?

A: Randint gives a random integer
An integer is a non-decimal number.
Just use random.uniform


text:
Q: How to bind with usercontrol Suppose I have usercontrol with textbox:
<UserControl x:Class="WpfApp5.UserControl1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             ...
             d:DesignHeight="450" d:DesignWidth="800">
    <Grid>
        <TextBox Name="MyTextBox" Height="30"/>
    </Grid>
</UserControl>

From the mainwindow I want to bind this TextBox to diffrerent properties, I need something like:
<Window x:Class="WpfApp5.MainWindow"
        ...
        Title="MainWindow" Height="200" Width="200">
    <Grid DataContext="{Binding Source={StaticResource Locator}, Path=MyViewModel}">
        <UserControl MyTextBox.Text="{Binding Prop1}"/>
        <UserControl MyTextBox.Text="{Binding Prop2}"/>
        <UserControl MyTextBox.Text="{Binding Prop3}"/><!---->
    </Grid>
</Window>

how to achive that?


text:
Q: I am imitating of Pocoyo smile He watched Pocoyo.
Pocoyo smiled in the cartoon.
He was imitating him smile.

"I am imitating of Pocoyo smile."
"I am imitating Pocoyo smile."

He said.
Do I need to add "of" after imitating?

A: "He was imitating him smile."  is incorrect.  Some correct examples:

He was imitating his smile. (if the emphasis is on the smile itself)
He was imitating him smiling. (if the emphasis is on the act of smiling)
He was imitating his smiling (if the emphasis is on the act of specifically Pocoyo smiling)

Or as a direct quote:

"I am imitating Pocoyo's smile," he said.  (first use, above)
"I am imitating Pocoyo's smiling," he said.  (second use, above)
"I am imitating how Pocoyo smiles," he said.  (third use, above)


text:
Q: Extract a single dplyr tbl_df row as a vector How can one extract a single row from a tbl_df as a vector?  Simple subsetting with [] brackets yields a 1-row tbl_df:
library(dplyr)
dat <- as_data_frame(mtcars)

dat[2, ]

Source: local data frame [1 x 11]

    mpg   cyl  disp    hp  drat    wt  qsec    vs    am  gear  carb
  (dbl) (dbl) (dbl) (dbl) (dbl) (dbl) (dbl) (dbl) (dbl) (dbl) (dbl)
1    21     6   160   110   3.9 2.875 17.02     0     1     4     4

A similar problem to Extract a dplyr tbl column as a vector, but with (I think) some different solutions.

A: From Introduction to dplyr: "All of the dplyr functions take a data frame (or tibble) as the first argument." So no need to convert mtcars into a tibble. Furthermore, as.numeric() is more concise than unlist(., use.names = FALSE).
library(dplyr)
mtcars %>%
  slice(2) %>%
  as.numeric()

A: Using the dplyr %>% operator
library(dplyr)
as_tibble(mtcars) %>%
           slice(2) %>%
           unlist(., use.names=FALSE)

Or we can use c with recursive=TRUE
as_tibble(mtcars) %>%
          slice(2) %>%
          c(., recursive=TRUE) %>%
          unname

A: Wouldn't
as.numeric(mtcars[2,])
be the simplest answer?


text:
Q: Array wont iterate properly and check values - Javascript I am using JavaScript to make a little application where the user inputs some numbers and it stores it in an array. The application then prints out 1 to 40 on the screen in green. If any number that is stored in the array is equal to 1 to 40 then when it comes on the screen it will be red not green.
var nums = document.getElementById('numbers').value;
var numArray = [];
numArray = nums.split(" ");

for (n = 1; n < 41; n++) {
    if (n === numArray[n]) {
        document.write('
' + n + '

');
    }
    else {
        document.write('
' + n + ' not in array

');
    }
}

The code above is just one attempt. I have also tried nested forloops, but that will print 1-40 check if it exists. and then print it out again. until it is done.
So, how can I make it just iterate 1-40 and if it exists in the array print something different on screen? Ive been stuck on this for ages!
Thanks in advance.

A: Use the Array.indexOf method to search an array for a value. You must also cast the number you are searching for as a string. Here is a working loop:
for (n = 1; n < 41; n++) {
    if (numArray.indexOf(n.toString()) >=0) {
        document.write('
' + n + '

');
    }
    else {
        document.write('
' + n + ' not in array

');
    }
}

I hope this helps!


text:
Q: How to expose TypeScript modules in NodeJS? I have a library that I'm building in TypeScript. I'd like to include this library in both TypeScript and JavaScript Node projects. What is the general strategy to do this? Should I compile and have two versions or is there some other strategy I should be using?

A:
I'd like to include this library in both TypeScript and JavaScript Node projects. What is the general strategy to do this?

Compile with the following to get the js output:

*

*--module commonjs --outDir ./dist
This should make your project consumable by JS projects. To make it consumable by TS projects you need to generate a declaration file. This can be done using https://github.com/SitePen/dts-generator See usage for details : https://github.com/SitePen/dts-generator#usage
Note: There is discussion on removing the dts-generator dependency : https://github.com/Microsoft/TypeScript/issues/2338

A: In most cases I have seen you have a /dist/ folder where the compiled JavaScript is located.
Usually there is also a minified version like yourfilename.min.js - the rest is either outside or in a /src/ folder, so outside you have only the license/readme.md, package.json left and maybe the file for Grunt/Gulp (it is considered polite to - if you use a taskrunner - include a Grunt/Gulp file for compiling the typescript and minify the .js file afterwards, as far as I got it)

A: If you want to preserve the TypeScript advantages when using it in TypeScript projects, then you obviously have to expose a TypeScript version of the code so the TypeScript compiler can see the TypeScript declarations for your interface.
But, if you want people to be able to use your library in plain Javascript projects (that don't compile TypeScript into JS), then you have to offer a version that has a plain Javascript interface and where the code has already been compiled into plain JS.
So, if you want both of those advantages, then you have to offer two separate versions.  The plain JS version can obviously just be a compiled version of the TypeScript (compiled into plain JS).


text:
Q: Is there anything wrong with this implementation of sleep? For a long time I've been using the following function to make current thread sleep for some time:
class Utils {

static public sleep(int ms) {
  try {
     Thread.sleep(ms);
  } catch(InterruptedException x) {}
}

}

But since I'm siliently ignore the exception I wonder if there can be situations this function will become evil?

A: If you're not using interrupts in your own code, you should keep the interrupt state with:
catch(InterruptedException x) {
    Thread.currentThread.interrupt();
}

or you can deal with it higher up by throwing InterruptedException. This immediately lets callers know there's an interrupt, otherwise it can be checked sometime later with isInterrupted().
If you must sleep for the full time, then you can continue sleeping after the interrupt, and reinterrupt the thread afterwards. See guava's Uninterruptibles.sleepUninterruptibly for an implementation of this.
By not clearing the interrupt status of the thread, you're preventing your code from interfering with anything else that might be using interrupts. So if in the future you want to interrupt a thread, you don't have obscure bugs where sometimes it works, and sometimes it doesn't.
If you will never use interrupts, it might be possible to completely ignore it, but it's nice to keep the flexibility just in case.


text:
Q: Return byte[] from ASP.net MVC 4 WEB API controller I have a controller method which returns byte[].
[ActionName("testbytes")]
public byte[] GetTestBytes() {
    var b = new byte[] {137, 80, 78, 71};
    return b;
}

when i hit the api, i get following result.
<base64Binary xmlns="http://schemas.microsoft.com/2003/10/Serialization/">iVBORw==</base64Binary>

Also when i hit this api from custom HttpClient, i get 10 bytes as a response.
Following is the code of custom HttpClient.
public async Task<byte[]> GetTestBytes() {
    var uri = "apiPath/testbytes";
    using (var client = new HttpClient())
    {
        var httpResponse = await client.GetAsync(uri, HttpCompletionOption.ResponseContentRead);
        if (httpResponse.IsSuccessStatusCode) {
            var bytes = await httpResponse.Content.ReadAsByteArrayAsync();
        }
        return bytes;
    }
    return null;
}

I am expecting 4 bytes while i am receiving 10 bytes in response.

A: @Markand: When you are hitting API, the response returned will be wrapped by double quotes ("responsebodygoeshere")
So following byte array

var b = new byte[] {137, 80, 78, 71};

is serialized as "iVBORw=="
Due to this when calling httpResponse.Content.ReadAsByteArrayAsync();
you will get bytes representation of "iVBORw==" (which will be 10 bytes) and not for iVBORw==
Optionally you can read response content as string and then trim the quotes and then convert it to the byte[] (There may be better approach. :))
i.e. var response = httpResponse.Content.ReadAsStringAsync().Trim('"')
then call following method to get bytes
var bytesResponse =  Convert.FromBase64String(response);


text:
Q: PHP rearrange items in an array by categories I have a file that looks like this, that takes data from a JSON file and outputs it:
<?php
$game = "Test";
$itemsArray = json_decode(file_get_contents("http://test.com/stamps.json"), true);

echo "
";
echo "
Image	Name	Difficulty	Description
";

foreach ($itemsArray as $item) {
    $name = $item['name'];
    $stamps = $item['stamps'];

    if ($name == $game) {
        foreach ($stamps as $stampData) {

            $stampID = $stampData['stamp_id'];
            $stampName = $stampData['name'];
            $stampLevel = $stampData['rank_token'];
            $stampDescription = $stampData['description'];
            $stampMember = $stampData['is_member'];
            $stampID = $stampData['stamp_id'];

            if ($stampMember == "true") {
                $stampMember = "Yes";
            } else {
                $stampMember = "No";
            }

            echo "
";

            echo "";
            echo "Coming soon";
            echo "	";

            echo "";
            print_r($stampName);
            echo "	";

            echo "";
            print_r(ucwords($stampLevel));
            echo "	";

            echo "";
            print_r($stampDescription.".");
            echo "	";

            echo "
";

        }
    }
}

echo "
";
?>

However, it outputs the data in the order it is in the JSON file. Which is all mixed up.
I was wondering if there was a way that I could sort the output it by the categories that $stampData['rank_token'] holds.
$stampData['rank_token'] holds the categories easy, medium, hard, and extreme. Is there a way that I can make this script output the categories in this order: easy, medium, hard, extreme?
Small example of the array after the JSON decode:
Array
(
[13] => Array
        (
            [name] => Blah blah
            [description] => Blah blah blah
            [parent_group_id] => 8
            [display] => Blah : Blah
            [stamps] => Array
                (
                    [73] => Array
                        (
                            [stamp_id] => 73
                            [name] => Blah
                            [is_member] =>
                            [rank] => 1
                            [description] => Blah blah blah
                            [rank_token] => easy
                        )

                    [80] => Array
                        (
                            [stamp_id] => 80
                            [name] => Blah
                            [is_member] =>
                            [rank] => 2
                            [description] => Blah blah blah
                            [rank_token] => medium
                        )

                 )
          )
)

A: See PHP's usort
function my_compare($a, $b) {
  if ($a["rank_token"] > $b["rank_token"]) return 1;
  if ($a["rank_token"] < $b["rank_token"]) return -1;
  return 0;
}

usort($stampData, "my_compare");


text:
Q: Time-based OTP does not work on 2 computers using PyOTP Background
I've been working on a project that requires OTP for authentication and I've been able to get it mostly working, except for a few minor details. I've been using PyOTP to use Time-Based OTP codes sent to Google Authenticator for this.
The Issue
I've run into a problem when I'm executing the program on 2 computers. One computer is my laptop (which I have at home), and the other is my work PC.
My issue is that, whenever I am trying to authenticate the codes at work, my program returns that the codes aren't valid. They are shown as being valid at home however. I created the program on my home laptop.
Attempts to fix
I've made sure both computers and my phone's clocks were synced up before this was an idea. Timing is not an issue.
Both computers and my phone use the same "secret key", so that is not an issue.
I made a second key and linked it up with Google Authenticator along with the first key, and that didn't work (I believed the hashes may not be the same, and I believe that may still be an issue).
Hunches
I know that PyOTP does use SHA hashing (where exactly in the module, I don't know!), and I know SHA hashing doesn't produce the same hash across different devices, so I am wondering if that is the issue, that the hashes aren't the same. I also know MD5 hashing does work across devices, so it may be the case that it is the hashing that may need to be changed.
If anyone can help with this, please let me know! I will update this with the results of whatever methods are used!

A: If you want to understand how TOTP actually works, check out these articles. The 1st one explains the gist of it. 2nd and 3rd go into all the technical details. Link to the 1st part:
https://prezu.ca/post/2021-07-30-totp-1/
From there just click Next to get to part 2 and then Next to get to part 3.


text:
Q: Java KeyStore duplicate aliases I have a Java KeyStore with couple of entries sharing the same alias (duplicates). When I do a getEntry(...) or getCertificate(...) or getKey(...), I always get the first entry in all the cases. How do I always get the ones that I want?
I have tried exporting the first entry to an external file (using keytool), and then deleting the first entry from the original KeyStore, and then importing back the exported entry with a different alias. This would work if the entry is a Trusted Certificate. But it wouldn't work if it is a PrivateKeyEntry or a SecretKeyEntry.
Is there any feasible solution/fix to handle this scenario?

A: There is one way of fixing the duplicate aliases. Since there is no direct way of fixing this issue, we can fix the duplicate aliases manually. You can run this code below to fix the duplicate aliases occurrences, (it is a one time thing).
public static void removeDuplicateAliases() throws NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException, KeyStoreException,
        UnrecoverableEntryException
{
    final String KEYSTORE_TYPE = "KEYSTORE_TYPE";
    final String KEYSTORE_PATH = "KEYSTORE_PATH";
    final char[] KEYSTORE_PASSWORD = "KEYSTORE_PASSWORD".toCharArray();

    KeyStore ks = KeyStore.getInstance(KEYSTORE_TYPE);
    ks.load(new FileInputStream(new File(KEYSTORE_PATH)), KEYSTORE_PASSWORD);

    Enumeration<String> aliases = ks.aliases();

    Map<String, List<KeyStore.Entry>> keyStoreEntriesMap = new LinkedHashMap<String, List<KeyStore.Entry>>();

    while (aliases.hasMoreElements())
    {
        String alias = aliases.nextElement();

        KeyStore.Entry entry = null;

        try
        {
            entry = ks.getEntry(alias, new KeyStore.PasswordProtection(KEYSTORE_PASSWORD));
        }
        catch (UnsupportedOperationException e)
        {
            entry = ks.getEntry(alias, null);
        }

        if (!keyStoreEntriesMap.containsKey(alias))
        {
            List<KeyStore.Entry> aliasEntry = new ArrayList<KeyStore.Entry>();
            aliasEntry.add(entry);

            keyStoreEntriesMap.put(alias, aliasEntry);
        }
        else
        {
            keyStoreEntriesMap.get(alias).add(entry);
        }
    }

    for (Map.Entry<String, List<KeyStore.Entry>> entry : keyStoreEntriesMap.entrySet())
    {
        if (entry.getValue().size() > 1)
        {
            System.out.println("Multiple entries found under same alias - \'" + entry.getKey() + "\'");

            int counter = 1;
            for (KeyStore.Entry each : entry.getValue())
            {
                ks.deleteEntry(entry.getKey());

                String newAlias = entry.getKey() + "-" + counter;

                if (each instanceof TrustedCertificateEntry)
                    ks.setEntry(newAlias, each, null);
                else
                    ks.setEntry(newAlias, each, new KeyStore.PasswordProtection(PASSWORD));

                System.out.println("\t(" + counter + " of " + entry.getValue().size() + ") Entry moved to new alias \'" + newAlias + "\'");

                counter++;
            }

            System.out.println();
        }
    }

    ks.store(new FileOutputStream(new File(KEYSTORE_PATH)), PASSWORD);

    System.out.println("Done!!");
}

What this basically does is group all the entries that have common aliases, and moves/creates a new entry with a new alias (incremental counter appended to the existing alias) and deletes all the original entries.
You can see the new aliases in your console.
P.S: It is advised to have your original KeyStore backed-up.

A: Instead of using KeyStore.deleteEntry (which causes problems for private keys), use KeyStore.setCertificateEntry(Alias, Certificate).


text:
Q: Non-standard HTTP headers 'X-Forwarded-Host' etc appear in the HTTP response We have an application deployed on the AWS. In front, an AWS load balancer accepts all of incoming HTTP requests; EC2 instances are directly behind this balancer. On individual instance, a HAproxy receives all requests and delegates then to the real application server based on Java(In our special case, haproxy and business application server are on the same EC2 instance, the haproxy doesn't play load balance roles just for relaying http requests, in other words, haproxy and application server are one-to-one mapping).
When we tried to fire up a http call to this system:
Request
GET /token HTTP/1.1
Host: xxx.xxx.xxx.xxx

Response
HTTP/1.1 403 Forbidden
X-Forwarded-Proto: https
X-Forwarded-For: xxx.xxx.xxx.xxx
X-Forwarded-Port: 443
X-Forwarded-Host: xx.xx.xx.xxx
Date: Wed, 09 Dec 2015 22:04:06 GMT
Server: WSO2-PassThrough-HTTP

In my understanding, X-Forwarded-* should only appear on the server side in order for servers to identify where incoming requests are from when there are proxies in-between. I don't know why those headers appear in the response as well. It made me have concerns on leaking the internal IPs to potential malicious clients.
The following is code snippets for haproxy settings:
frontend worker
bind :443 ssl crt xxx crt xxx crt xx accept-proxy no-sslv3 no-tls-tickets
mode http
acl forwarded hdr_cnt(X-Forwarded-Host) gt 0
acl trusted src 127.0.0.0/24
capture request header X-Forwarded-For len 64
default_backend worker
http-request deny if METH_TRACE
http-request set-header X-Forwarded-Host %[dst] unless forwarded trusted
http-request set-header X-Forwarded-Port %[dst_port]
http-request set-header X-Forwarded-Proto https if { ssl_fc }
option forwardfor if-none
reqidel ^X-Forwarded-For:.* unless trusted
rspadd Strict-Transport-Security:\ max-age=63072000;\ includeSubdomains;\ preload
use_backend xxx.xxx.xxx if { ssl_fc_sni -i xxx.xxx.xxx }
use_backend xxx.xxx.xxx if { ssl_fc_sni -i xxx.xxx.xxx }

Please advise why those non-standard headers appear in the http responses and if this is risky for the security.

A: AWS ELBs automatically add the X-Forwarded-For, X-Forwarded-Port, and X-Forwarded-Proto request headers, per the AWS ELB docs; they do not use the X-Forwarded-Host header.  Thus this rule in your haproxy config is a little suspect:
acl forwarded hdr_cnt(X-Forwarded-Host) gt 0

Instead, you might try:
acl forwarded hdr_cnt(X-Forwarded-For) gt 0

The X-Forwarded-Host request header is more unusual; unless your backend server (WS02, from the looks of it) needs that header, you might remove that, and other X-Forwarded-* rules from your haproxy config altogether, since those values should be coming from the AWS ELB.  That is, you might remove these altogether:
http-request set-header X-Forwarded-Host %[dst] unless forwarded trusted
http-request set-header X-Forwarded-Port %[dst_port]
http-request set-header X-Forwarded-Proto https if { ssl_fc }

As for whether it's a security concern -- only for HTTP requests, not HTTPS requests.  And that's only because, without SSL, it's possible for someone to possibly intercept and eavesdrop on those response headers.  Such an attacker would already know the client's IP address (and thus the value for X-Forwarded-For), would know the TCP destination port (and thus the value for X-Forwarded-Port), and would know that it's not SSL (and thus would know X-Forwarded-Proto: http).  Ideally, though, as you point out, these headers would not appear in the response at all.  (It's unusual for HTTP servers to echo X-Forwarded-* request headers like these in their response; I was thus trying to read the WS02 docs to see if it could be configured to do something like that.)
Thus while you research this, you could have haproxy remove these response headers, using something like:
rspdel ^X-Forwarded-.*:.*

Hope this helps!


text:
Q: setInterval in javascript based on changes made I'm having an issue with a javascript requirement. I have a html calling a script perpetually every 1500ms using setInterval.
 var t = setInterval(loadData(),1500);

The loadData function calls a script which returns a JSON as a list, what I want to do is to change from a fixed interval to a variable interval. For instance, if there are no changes made between two calls to the script, I must set another value for the interval. I heard I could use jquery linq to compare the length of the list at the beginning and the list when refreshing to change the time value. I also heard I could save the value of count in a cookie to compare always.
Any idea please? I would be grateful. Thanks in advance.

A: I'm guessing you're trying to do:
var speed = 1500,
    t = setInterval(loadData, speed);

function loadData() {
    if (something == true) {
        something = false;
        speed = 3000;
        clearInterval(t);
        t = setInterval(loadData, speed);
    }else{
        //do something
    }
}

You should just reference the function, adding the parenthesis runs the function immediately. When using a variable for the speed, you'll need to clear and run the interval function again to change the speed.

A: if the interval is variable, then you can't use setInterval, which period won't be changed after the first call. You can use setTimeout to alter the period:
var period=1500
var timer;
var callback = function() {
    loadData();
    timer = setTimeout( callback, period )
};

var changePeriod = function( newPeriod ) {
    period = newPeriod;
}

//first call
callback();

now, you just need to call changePeriod( ms ) to change the period afterwards


text:
Q: NoReverseMatch: with arguments '(u'',)' and keyword arguments '{}' not found.in Django Admin I found a better error message (see below).
I have a model called App in core/models.py. The error occurs when trying to access a specific app object in django admin. Even on an empty database (after syncdb) with a single app object.
Seems core_app_history is something django generated. Any help is appreciated.
Here is the exception:
NoReverseMatch at /admin/core/app/251/
Reverse for 'core_app_history' with arguments '(u'',)' and keyword arguments '{}' not found.
Request Method: GET
Request URL:    http://weblocal:8001/admin/core/app/251/
Django Version: 1.5.4
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'core_app_history' with arguments '(u'',)' and keyword arguments '{}' not found.
Exception Location: /opt/virtenvs/django_slice/local/lib/python2.7/site-packages/django/template/defaulttags.py in render, line 426
Python Executable:  /opt/virtenvs/django_slice/bin/python
Python Version: 2.7.3
Python Path:
['/opt/src/slicephone/cloud',
'/opt/virtenvs/django_slice/local/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg',
'/opt/virtenvs/django_slice/local/lib/python2.7/site-packages/pip-1.2.1-py2.7.egg',
'/opt/virtenvs/django_slice/local/lib/python2.7/site-packages/distribute-0.6.35-py2.7.egg',
'/opt/virtenvs/django_slice/lib/python2.7',
'/opt/virtenvs/django_slice/lib/python2.7/plat-linux2',
'/opt/virtenvs/django_slice/lib/python2.7/lib-tk',
'/opt/virtenvs/django_slice/lib/python2.7/lib-old',
'/opt/virtenvs/django_slice/lib/python2.7/lib-dynload',
'/usr/lib/python2.7',
'/usr/lib/python2.7/plat-linux2',
'/usr/lib/python2.7/lib-tk',
'/opt/virtenvs/django_slice/local/lib/python2.7/site-packages']
Server time:    Fri, 11 Oct 2013 22:06:43 +0000

And it occurs in /django/contrib/admin/templates/admin/change_form.html
32
{% trans "History" %}

Here is the (possible) relevant urls:
/admin/core/app/    HANDLER: changelist_view
/admin/core/app/add/    HANDLER: add_view
/admin/core/app/(.+)/history/   HANDLER: history_view
/admin/core/app/(.+)/delete/    HANDLER: delete_view
/admin/core/app/(.+)/   HANDLER: change_view

A: My guess would be you have a view referenced somewhere in your urlconf which can't be imported, which would cause reverse to fail.  Try reversing a different view from the shell.

A: This could be caused by having an entry with an empty primary key, which could happen if your model has a field like
id = models.CharField(blank=True, primary_key=True)

A: I am going to comment on this as I had EXACTLY the same issue and this was the only link I could find that pointed me in the right direction. Actually it didn't point me in the right direction but at least it made me feel less alone :)
Note my code did work sometimes. In fact my wrong code is still working happily on a production server.
My problem was in admin I had overridden my render_change_form. When I called the super method instead of doing
return super(ReceiptAdmin, self).render_change_form(request, context, *args, **kwargs)

I had inadvertently done
return super(ReceiptAdmin, self).render_change_form(request, context, args, kwargs)

I find this out when I stepped through the code and noticed what my parent method was being passed didn't look right. It mystifies me why it works sometimes. This incorrect call was copied and pasted from some other code which is also failing locally but not on live.
Anyway, there if any use for anybody else.


text:
Q: SQL - How to use a value from INSERTed table I am trying to insert a new location record in my db ... and then reuse the value of the newly created id in a select statement's where clause later on.
But I'm getting a syntax error.
Code:
USE Widgets;
GO
DECLARE     @userPrincipalName VARCHAR(100),
            @displayName VARCHAR(100),
            @domainName VARCHAR(100),
            @locationId INT,
            @uname VARCHAR(100);
DECLARE     @newLocationId TABLE (
            id INT
            );

-- CREATE NEW LOCATION, FLAG AS PRIMARY

IF NOT EXISTS (SELECT *
                FROM Locations
                WHERE LocationName = 'outer-space')
    BEGIN
        INSERT INTO Locations
        OUTPUT Inserted.ID INTO @newLocationId
        SELECT 'out-space' ,'the final frontier', 60, 1
    END

-- MUCH LATER IN THE SQL CODE:

IF NOT EXISTS (SELECT *
                FROM LocationEnvironment
                WHERE LocationId = @newLocationId.id
                )
    BEGIN
        INSERT INTO LocationEnvironment
        SELECT 1, id
        FROM @newLocationId
    END

The error is "Must declare scalar variable" and it dies on there WHERE clause in the SELECT statement.
I also tried something like this:
IF NOT EXISTS (SELECT *
                FROM LocationEnvironment
                WHERE LocationId = id
                FROM @newLocationId
                )

But that doesn't work either.
Any tips would be appreciated.

A: I think you need to update your WHERE clause in the -- MUCH LATER IN THE SQL CODE section to select from your temporary table:
WHERE LocationId = @newLocationId.id

Should be:
WHERE LocationId = (select top 1 id from @newLocationId)

Or if there might be multiple values in your table variable:
WHERE LocationId in (select id from @newLocationId)

A: Add a GO statement just before -- MUCH LATER IN THE SQL CODE:
This will send the above statements to the server.


text:
Q: Custom Feedback form in magento 2 How to create a footer link in custom theme and how to set path to that link ?
I have created custom feedback module which contains form for feedback.
Now I need to set link in custom theme and want to set path for the link.
The path should refer from my feedback module** Please help me
=> Custom Module:layout file
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">

        <title>
            Sample
        </title>

       <referenceContainer name="footer">
            <block class="Magento\Framework\View\Element\Template" template="X_Y::form.phtml"/>
        </referenceContainer>

</page>

form.phtml

    Feedback
.....
....
....

While clicking link it will show a popup. So here I have mentioned id, Now I have declared my link in custom theme, But How do I specify this id in link

A: To add new links to footer links, use this code in <Vendor>\theme>\Magento_Theme\layout\default.xml
<referenceBlock name="footer_links">
    <block class="Magento\Framework\View\Element\Html\Link\Current" name="your-link-name">
        <arguments>
            <argument name="label" xsi:type="string">Title</argument>
            <argument name="path" xsi:type="string">path-of-your-page</argument>
        </arguments>
    </block>
</referenceBlock>

A:
app/design/frontend/CustomName/customtheme/Magento_Theme/layout :

<?xml version="1.0"?>
<page layout="3columns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<update handle="default_head_blocks"/>

<referenceBlock name="footer_links">
<block class="Magento\Framework\View\Element\Html\Link\Current" name="custom-page">
<arguments>
<argument name="label" xsi:type="string">Title of your page</argument>
<argument name="path" xsi:type="string">url-key-of-your-page</argument>
</arguments>
</block>
</referenceBlock>

</page>

Create your default.xml on this above path and try it. It will works.


text:
Q: If $f:X\to S$ is a universal homeomorphism, is $f':X\times_S X\to X$ a nil-immersion? If $f:X\to S$ is a universal homeomorphism, is $f':X\times_S X\to X$ always a nil-immersion? This seems to be easy, yet possibly I miss something. Should I give references to this fact in a paper?

A: In general, the answer is no. As Brian Conrad points out in the comments above, purely inseparable field extensions do not have this property. However (and maybe this is what you were getting at?), it is true that if $X\to S$ is a universal homeomorphism, then the diagonal $X\to X\times_SX$ is a nilimmersion.


text:
Q: Isomorphism between a sub-ring to $\Bbb Q$, the rational field Let $R$ be a commutative ring with an identity, which contains $\Bbb Z$, the integer field, as a sub-ring with the same identity element.
Let $I$ be a maximal ideal in $R$.
I need to prove that if $\Bbb Z/(I \cap \Bbb Z)$ it not a field, then $R/I$ contains a sub-field that is isomorphic to $\Bbb Q$, the rational field.
I can prove that $\Bbb Z/(I \cap \Bbb Z)$ is infinite, but I don't know how to continue on.

A: You can write $I\cap\mathbb{Z}=n\mathbb{Z}$, with $n\ge0$. Since
$$
\frac{\mathbb{Z}}{I\cap\mathbb{Z}}\cong\frac{\mathbb{Z}+I}{I}
$$
embeds in $R/I$ which is a domain, this tells you something about $n$. Next, the hypothesis that $\mathbb{Z}/n\mathbb{Z}$ is not a field tells you precisely what $n$ is.
Conclude something about the characteristic of $R/I$, which is a field, so it contains a minimum subfield.


text:
Q: Control a SWF file using backend programing? I have been search for a few days now for a way to work on this.
Basically I could like to send flashvars to my swf file using some backend language like PHP or Python, then execute it and capture the output.
I looked up to Ming but it seems that this is only a lib for create SWF file, not much on manipulate already created file.
Thank you!

A: If you need to do it 'on load basis', you can simply provide flash vars (for example put some flashvars depending on situation and embed the swf into html).
But if you need to have almost real time control over the flash, you have a few options:

*

*socket connections - very hard (not to say impossible) to implement with php, and a kind of complex job

*make the swf make a call to php, and get some information; then execute what you need depending on that information

I would advise you to use the second option - chose the action depending on situation, and let the swf client get it itself (either save it in file, db or calculate it realtime - it's up to you; the important is that you don't pass it to client, client makes query to get it).


text:
Q: How to access and test an internal (non-exports) function in a node.js module? I'm trying to figure out on how to test internal (i.e. not exported) functions in nodejs (preferably with mocha or jasmine). And i have no idea!
Let say I have a module like that:
function exported(i) {
   return notExported(i) + 1;
}

function notExported(i) {
   return i*2;
}

exports.exported = exported;

And the following test (mocha):
var assert = require('assert'),
    test = require('../modules/core/test');

describe('test', function(){

  describe('#exported(i)', function(){
    it('should return (i*2)+1 for any given i', function(){
      assert.equal(3, test.exported(1));
      assert.equal(5, test.exported(2));
    });
  });
});

Is there any way to unit test the notExported function without actually exporting it since it's not meant to be exposed?

A: EDIT:
Loading a module using vm can cause unexpected behavior (e.g. the instanceof operator no longer works with objects that are created in such a module because the global prototypes are different from those used in module loaded normally with require).  I no longer use the below technique and instead use the rewire module.  It works wonderfully.  Here's my original answer:
Elaborating on srosh's answer...
It feels a bit hacky, but I wrote a simple "test_utils.js" module that should allow you to do what you want without having conditional exports in your application modules:
var Script = require('vm').Script,
    fs     = require('fs'),
    path   = require('path'),
    mod    = require('module');

exports.expose = function(filePath) {
  filePath = path.resolve(__dirname, filePath);
  var src = fs.readFileSync(filePath, 'utf8');
  var context = {
    parent: module.parent, paths: module.paths,
    console: console, exports: {}};
  context.module = context;
  context.require = function (file){
    return mod.prototype.require.call(context, file);};
  (new Script(src)).runInNewContext(context);
  return context;};

There are some more things that are included in a node module's gobal module object that might also need to go into the context object above, but this is the minimum set that I need for it to work.
Here's an example using mocha BDD:
var util   = require('./test_utils.js'),
    assert = require('assert');

var appModule = util.expose('/path/to/module/modName.js');

describe('appModule', function(){
  it('should test notExposed', function(){
    assert.equal(6, appModule.notExported(3));
  });
});

A: I have been using a different approach, without any dependencies:
Have a __testing export with all the local functions I want to test, which value depends on NODE_ENV, so it's only accessible on tests:
// file.ts
const localFunction = () => console.log('do something');
const localFunciton2 = () => console.log('do something else');
export const exportedFunction = () => {
    localFunction();
    localFunciton2();
}
export const __testing = (process.env.NODE_ENV === 'test') ? {
    localFunction, localFunction2
} : void 0;

// file.test.ts
import { __testing, exportedFunction } from './file,ts'
const { localFunction, localFunction2 } = __testing!;
// Now you can test local functions

A: The rewire module is definitely the answer.
Here's my code for accessing an unexported function and testing it using Mocha.
application.js:
function logMongoError(){
  console.error('MongoDB Connection Error. Please make sure that MongoDB is running.');
}

test.js:
var rewire = require('rewire');
var chai = require('chai');
var should = chai.should();

var app = rewire('../application/application.js');

var logError = app.__get__('logMongoError');

describe('Application module', function() {

  it('should output the correct error', function(done) {
      logError().should.equal('MongoDB Connection Error. Please make sure that MongoDB is running.');
      done();
  });
});

A: Working with Jasmine, I tried to go deeper with the solution proposed by Anthony Mayfield, based on rewire.
I implemented the following function (Caution: not yet thoroughly tested, just shared as a possibile strategy):
function spyOnRewired() {
    const SPY_OBJECT = "rewired"; // choose preferred name for holder object
    var wiredModule = arguments[0];
    var mockField = arguments[1];

    wiredModule[SPY_OBJECT] = wiredModule[SPY_OBJECT] || {};
    if (wiredModule[SPY_OBJECT][mockField]) // if it was already spied on...
        // ...reset to the value reverted by jasmine
        wiredModule.__set__(mockField, wiredModule[SPY_OBJECT][mockField]);
    else
        wiredModule[SPY_OBJECT][mockField] = wiredModule.__get__(mockField);

    if (arguments.length == 2) { // top level function
        var returnedSpy = spyOn(wiredModule[SPY_OBJECT], mockField);
        wiredModule.__set__(mockField, wiredModule[SPY_OBJECT][mockField]);
        return returnedSpy;
    } else if (arguments.length == 3) { // method
        var wiredMethod = arguments[2];

        return spyOn(wiredModule[SPY_OBJECT][mockField], wiredMethod);
    }
}

With a function like this you could spy on both methods of non-exported objects and non-exported top level functions, as follows:
var dbLoader = require("rewire")("../lib/db-loader");
// Example: rewired module dbLoader
// It has non-exported, top level object 'fs' and function 'message'

spyOnRewired(dbLoader, "fs", "readFileSync").and.returnValue(FULL_POST_TEXT); // method
spyOnRewired(dbLoader, "message"); // top level function

Then you can set expectations like these:
expect(dbLoader.rewired.fs.readFileSync).toHaveBeenCalled();
expect(dbLoader.rewired.message).toHaveBeenCalledWith(POST_DESCRIPTION);

A: The trick is to set the NODE_ENV environment variable to something like test and then conditionally export it.
Assuming you've not globally installed mocha, you could have a Makefile in the root of your app directory that contains the following:
REPORTER = dot

test:
    @NODE_ENV=test ./node_modules/.bin/mocha \
        --recursive --reporter $(REPORTER) --ui bbd

.PHONY: test

This make file sets up the NODE_ENV before running mocha. You can then run your mocha tests with make test at the command line.
Now, you can conditionally export your function that isn't usually exported only when your mocha tests are running:
function exported(i) {
   return notExported(i) + 1;
}

function notExported(i) {
   return i*2;
}

if (process.env.NODE_ENV === "test") {
   exports.notExported = notExported;
}
exports.exported = exported;

The other answer suggested using a vm module to evaluate the file, but this doesn't work and throws an error stating that exports is not defined.

A: I have found a quite simple way that allows you to test, spy and mock those internal functions from within the tests:
Let's say we  have a node module like this:
mymodule.js:
------------
"use strict";

function myInternalFn() {

}

function myExportableFn() {
    myInternalFn();
}

exports.myExportableFn = myExportableFn;

If we now want to test and spy and mock myInternalFn while not exporting it in production we have to improve the file like this:
my_modified_module.js:
----------------------
"use strict";

var testable;                          // <-- this is new

function myInternalFn() {

}

function myExportableFn() {
    testable.myInternalFn();           // <-- this has changed
}

exports.myExportableFn = myExportableFn;

                                       // the following part is new
if( typeof jasmine !== "undefined" ) {
    testable = exports;
} else {
    testable = {};
}

testable.myInternalFn = myInternalFn;

Now you can test, spy and mock myInternalFn everywhere where you use it as testable.myInternalFn and in production it is not exported.

A: Essentially you need to merge the source context with the test cases - one way to do this would be using a small helper function wrapping the tests.
demo.js
const internalVar = 1;

demo.test.js
const importing = (sourceFile, tests) => eval(`${require('fs').readFileSync(sourceFile)};(${String(tests)})();`);

importing('./demo.js', () => {
    it('should have context access', () => {
        expect(internalVar).toBe(1);
    });
});

A: you can make a new context using vm module and eval the js file in it, sort of like repl does. then you have access to everything it declares.

A: This is not recommended practice, but if you can't use rewire as suggested by @Antoine, you can always just read the file and use eval().
var fs = require('fs');
const JsFileString = fs.readFileSync(fileAbsolutePath, 'utf-8');
eval(JsFileString);

I found this useful while unit testing client-side JS files for a legacy system.
The JS files would set up a lot of global variables under window without any require(...) and module.exports statements (there was no module bundler like Webpack or Browserify available to remove these statements anyway).
Rather than refactor the entire codebase, this allowed us to integrate unit tests in our client-side JS.

A: eval doesn't really work on its own (it will only work with top-level function or var declarations), you can't capture top-level variables that are declared with let or const into the current context with eval, however, using a vm and running it in the current context will allow you to access all top-level variables after its execution...
eval("let local = 42;")
// local is undefined/undeclared here

const vm = require("vm")
vm.runInThisContext("let local = 42;");
// local is 42 here

...although declarations or assignments in the "imported" module could clash with anything already declared/defined in the current context by the time the vm starts if they share the same name.
Here's a mediocre solution. This will add a small bit of unnecessary code to your imported modules/units however, and your test suite would have to run each file directly in order to run its unit tests in this manner. Running your modules directly to do anything but its run unit tests would be out of question without even more code.
In the imported module, check if file is the main module, if so, run tests:
const local = {
  doMath() {return 2 + 2}
};

const local2 = 42;

if (require.main === module) {
  require("./test/tests-for-this-file.js")({local, local2});
}

Then in the test file/module that imports the target module:
module.exports = function(localsObject) {
  // do tests with locals from target module
}

Now run your target module directly with node MODULEPATH to run its tests.


text:
Q: arsort() not stable Edit: This question seems to be a duplicate of Preserve key order (stable sort) when sorting with PHP's uasort
Someone has been using arsort() to sort an array parsed from HTTP_ACCEPT_LANGUAGE under the assumption that it is a stable sort. But it's not: https://bugs.php.net/bug.php?id=53553. Now I have a bug and I am a bit at a loss how to fix the bug without resorting to hacks.
I have this header from a mobile client:
HTTP_ACCEPT_LANGUAGE: de-CH, en-US

and this gets parsed to:
Array (
    [de-CH] => 1
    [en-US] => 1
)

After parsing arsort($array, SORT_NUMERIC) is used to sort the languages corresponding to their q values. But because German and English has the same q value, arsort() swaps German and English. How can I sort the array so that the insertion order is preserved?

A: You don't need to sort the array if you're only looking for the preferred language:
<?php

function findPrefferedLanguage($languages) {
  foreach ($languages as $lang => $weight) {
    if (empty($key) || ($weight > $languages[$key])) {
      $key = $lang;
    }
  }

  return $key;
}

$foo = array('es' => .6, 'en' => 1, 'fr' => 1, 'de' => .5);

var_dump(findPrefferedLanguage($foo)); // en

Hastily tested... there's probably some edge-cases that will generate errors/warnings.

A: Your problem isn't the unstable nature of the sort functions, but rather that you have two elements which have the same value, but you're expecting one to be sorted before the other.
If de-CH should be weighted higher than en-US, indicating that the client prefers German over English, then don't give them both values of 1.

A: Crazy enough PHP :)
It is already mentioned in the documentation
http://php.net/manual/en/function.arsort.php

If two members compare as equal, their relative order in the sorted array is undefined.

And funny enough, it works differently in PHP 7


text:
Q: Fetch Firebase/Geofire data only after getting user location I'm developing a app that uses GeoFire to only get data from Firebase that are in 10km radius from the user location. And then populate a CollectionView.
The problem:
When internet is slow it loads the CollectionView with no data. Probably because the mobile didn't have time to get an accurate user location yet.
I have my fetchData() function inside ViewDidLoad().
How can I do to execute fetchData() function only after user location has been finished?
Desired flow:
 - Launch App
 - Get user location
 - Populate the CollectionView with data only after getting user location
 - Load CollectionView

A: Put your fetch data function outside ViewDidLoad
func fetchData(){
   etc.
}

call it when location comes through in:
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
   guard let location = manager.location else {return}
   etc.
   fetchData()
}


text:
Q: Issue with AJAX URL for file having as issue with my url in my AJAX script. I need the file data.xml to be loaded but unsure of how to attach it. The current code isn't working.
$.ajax({
    type: "GET",
    url: "data.xml",    <--- issue here
    dataType: "xml",

Here is what my folder structure looks like. I need to attach data.xml to update.js
Website
├── app.py
├── data2.xml
├── data.xml  <-- File that needs to be attached
├── Dockerfile
├── __pycache__
│   ├── Crypto.cpython-38.pyc
│   ├── lxml.cpython-38.pyc
│   ├── ScprAG.cpython-38.pyc
│   └── scraper.cpython-38.pyc
├── requirements.txt
├── scraper.py
├── static
│   ├── css
│   │   ├── 404.css
│   │   └── main.css
│   ├── images
│   │   └── favicon.png
│   └── js
│       ├── plugin.js
│       └── update.js   <-- AJAX Script
└── templates
    ├── 404.html
    ├── disclaimer.html
    ├── index.html
    └── layout.html


text:
Q: In what way is my array index an 'Illegal string offset'? When "future-proofing" code by testing it on PHP 5.4, I get a warning I don't understand.
function __clone() {
  $this->changed = TRUE;
  foreach ($this->conditions as $key => $condition) {
    if (
    $condition['field']
    instanceOf QueryConditionInterface) {
      $this->conditions[$key]['field'] = clone($condition['field']);
    }
  }
}

I broke out $condition['field'] into its own row to reduce the amount of code to focus on. About that specific line, PHP has this to say

Warning: Illegal string offset 'field' in DatabaseCondition->__clone()

And I just can't see how 'field', is an illegal string offset. I'm guessing that I'm just missing something obvious, but if the community can't find a problem, I'll file a bug report.
I interpret the warning as "Under no circumstances is 'field' a valid key". This error would have made sense if I had tried to us for example an array as a key.

A: Without more knowledge about the creation of the conditions array/iterator, I can only assume that you should first check if the offset exists.
if(isset($condition['field']) && $condition['field'] instanceOf QueryConditionInterface)

Using isset in this situation is enough and faster than array_key_exists, the only difference is, if $condition['field'] is NULL isset will return falls, array_key_exists will return true, cause the key exists. But because you only want to work on fields that are an instance of QueryConditionInterface, you will running fine with isset.

A: The warning looks like its saying that $condition is a string. Without any knowledge of the code I don't whether that makes any sense.


text:
Q: Define a default value for an argument in python function based on another argument? At the moment, I have a some code which takes an input_file, in.csv, converts it to a dataframe, performs some operations, and then outputs two new files out_1.csv and out_2.csv into the same directory as the original in.csv. I'm trying to wrap this code in a function, which can take two parameters:

*

*input_file: which takes the form of a filepath, e.g.
home/me/a/b/in.csv

*output_path: where the default value is the directory of the input file, i.e. home/me/a/b/, but which can be specified so
out_1.csv and out_2.csv go there instead.
some pseudocode for this may look like:
import pandas as pd

def function(input_file, output_file = "input file directory"):

#convert this input csv to a dataframe
in_df = pd.DataFrame(pd.read_csv(input_file))

#some operations to in_df.
out_1_df = in_df.iloc[1:]
out_2_df = in_df.iloc[2:]

#write these files out to the output path
out_1_df.to_csv("output_path/out_1_df")
out_2_df.to_csv("output_path/out_2_df")

I hope I've not been too abstract/unclear about what I'm trying to achieve, and I've missed something or can improve on the question to let me know. As always, thanks for any help!


text:
Q: Mixing RewriteRule and ProxyPass in Apache I was working on debugging an issue today related to mixing mod_proxy and mod_rewrite together and I ended up having to use balancer://mycluster in the RewriteRule in order to stop receiving a 404 error from Apache. I have two questions:
1) Is there any other way to get the rewritten URL to go through the balancer without adding balancer://mycluster into the RewriteRule?
2) Is there a way to define all the parameters I defined in ProxyPass (stickysession=JSESSIONID|jsessionid scolonpathdelim=On lbmethod=bytraffic nofailover=Off) in either the <Proxy> or RewriteRule? I'm concerned the requests that match the new RewriteRule won't load balance in the same fashion as those that go through ProxyPass (like /app1/something.do)?
Below are the relevant sections of the httpd.conf. I am using Apache 2.2.
<Proxy balancer://mycluster>
    Order deny,allow
    Allow from all

    BalancerMember ajp://my.domain.com:8009 route=node1
    BalancerMember ajp://my.domain.com:8009 route=node2
</Proxy>

ProxyPass /app1 balancer://mycluster/app1 stickysession=JSESSIONID|jsessionid scolonpathdelim=On lbmethod=bytraffic nofailover=Off
ProxyPassReverse /app1 ajp://my.domain.com:8009/app1

...
RewriteRule ^/static/cms/image/(.*)\.(.*) balancer://mycluster/app1/$1.$2 [P,L]

A: Looks like I can use the ProxySet directive so the URL's that match the RewriteRule load balance in the same fashion.
<Proxy balancer://mycluster>
    Order deny,allow
    Allow from all

    BalancerMember ajp://my.domain.com:8009 route=node1
    BalancerMember ajp://my.domain.com:8009 route=node2

    ProxySet stickysession=JSESSIONID|jsessionid scolonpathdelim=On lbmethod=bytraffic nofailover=Off
</Proxy>


text:
Q: c++ memory allocation and rewriting the vector class I'm doing an assignment in c++ where we have to rewrite the std::vector class that inherits from an abstract Container class. We have to write methods for 'Vector' such as begin(), end(), push_back(), etc...
Many of the basic std::vector Member functions found here: http://www.cplusplus.com/reference/vector/vector/

My question is multi-faceted mainly because I am a beginner and the memory of computers is fascinating. Also, sorry if this question is super specific or has similar answers on here but I'm really stuck because this is the first time I've dealt with memory.

Here are my Container and Vector class implementations:
template <typename T>
class Container {
    protected:
        T* elem;
        int cap;
    public:
        virtual T& operator[](int i) = 0;
        virtual int size() = 0;
        ~ Container() { delete[] elem; }
};

template <typename T>
class Vector: public Container<T> {
    protected:
        using Container<T>::elem;
        using Container<T>::cap;
    private:
        int sz;
    public:
        // constructors
        Vector(); // default constructor
        Vector(int n); // fill constructor #1
        Vector(int n, T fill_val); // fill constructor #2
/*      // ~ Vector(); // destructors
unsure if the above is correct, because of the Container destructor
*/
        // overloaded operators
        T& operator[](int i); // subscript overloading '[]'
        T& operator=(const Vector<T>& V); // assignment overloading '='
        // access methods
        T& front(); //returns a reference to the first element
        T& back(); //returns a reference to the last element
        // iterator methods
        T* begin(); // returns memory address of the first element
        T* end(); // returns memory address at the end
        // size methods
        int size() { return sz; }
        int capacity() { return cap; }
};

Part 2.
When/why do I need the destructor? I've tried to read up on destructors on Stack, but I feel more confused than clarified. I'm assuming the SegFault is coming from memory needing to be deallocated, and I know I'm supposed to be learning how to dynamically allocate memory with this assignment. The constructors and destructors are crucial for this process but can someone break it down as simply as possible for me?

EDIT:
I've fixed the segmentation fault by implementing Fureeish's answer. My code has been updated above.
The only remaining inquiry is to the destructor and its purpose. Do I need to implement one for Vector or will it be called automatically by Container?

A: You decided to manage the memory by yourself, but you never allocated any. You're missing some news here and there. For example, given a:
Vector(int n, T fill_val) {
    sz = n;
    cap = 2*n;
    for(int i = 0; i < sz; i++) {
        elem[i] = fill_val;
    }
}

the for() loop iterates over elem, which is an uninitialized pointer. You treat it like a pointer to a dynamically allocated array, but it simply points to some garbage value. Remember - first allocate, then work on (only when you decide to manage the memory yourself. Typically you should prefer using standard implementations).
The correct version should look like this:
Vector(int n, T fill_val) {
    sz = n;
    cap = 2*n;
    elem = new T[cap]; // or cap-1, depending on what you do with `end()`.
    for(int i = 0; i < sz; i++) {
        elem[i] = fill_val;
    }
}

The fact that you never encountered this problem while using other constructors is just you being extremely lucky and undefined behavior being sneaky


text:
Q: RavenCoin formula for calculate mining-reward and energy consumption I am looking for a method to calculate the electricity consumption of mining RavenCoin cryptocurrency based on mining pool and RVN historical data.
I already have a way to calculate energy consumption for ETH cryptocurrency. It looks like this:
There is my data from mining-pool:

Time
Amount_ETH

1618710061
0.010070637700427251

1617431750
0.011975315390814143

1616214353
0.012943374560661717

1615004532
0.013340149012868608

1613758264
0.015813750809731825

Moreover, I have historical data for ETH corresponding to the current time from the table.
I use the data from the website:  link
There is formula to calculate:
myMiningReward = (hashpower / hashrate) * (blockreward + transactionFee / blockCount) * (time / blockTime)

Now to calculate energy consumption I use data on GPU cards from the page: link
My question is what formula to use to get the same effect for the RavenCoin cryptocurrency. I have the same data in terms of mining pool data and historical data.