text:
Q: Shopify ajax cart - Currency not updating without refresh? In Shopify, when i change the currency, the correct and new price is displayed on my products. However, if i add a product via ajax to the cart, it uses the old price.
If i do a:
console.log(cart.currency)

I can see that the currency of the cart is NOT being updated to the newly selected value.
However, if i manually refresh the page, the correct currency is then being displayed?
Any advice on what i can do here? New to shopify so any advice as to where to look is appriciated.


text:
Q: Passing character array? I am having trouble passing my char array to a function. Whenever I try to do so, I get an error displaying the following :

Error 1 error C2664: 'void Print(char)' : cannot convert argument 1 from 'char [22]' to 'char'

I'm not sure what the issue could be. Some advice would be great.
#include <iostream>

using namespace std;

void Print(char);

int main(){
    char arr1[] = { "Hello how are you? / " };
    Print(arr1);
}

void Print(char arr[]){
    for (char i = 0; i != '/'; i++)
    {
        cout << arr[i] << endl;
    }
}

A: 1.Function declaration and definition of Print don't match. According to the declaration, Print accepts char as its argument, that's why compiler complains. Change the declaration to
void Print(char[]);

2.for (char i = 0; i != '/'; i++), the condition i != '/' doesn't check the element of char array, it should be arr[i] != '/'.

A: This program works.
#include <iostream>
#include <string>

using namespace std;

void Print(char *arr);

int main()
{
char arr1[] = { "Hello how are you? / " };
Print(arr1);

    return 0;
}

void Print(char *arr) {

int i = 0;

while (arr[i] != '/')
{
    cout << arr[i] << endl;
    ++i;
}

}

I feel that a while statement is better here than a for statement and you need to use arr as a pointer.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Delphi 7 - TDBGrid style How to use stylized table in Delphi 7?
For example:

A: If you mean which you want themed the TDbGrid component, you can use the Themed DBGrid runtime replacement from Jeremy North's and Andreas Hausladen.

A: I wrote and tested for you this example on Delphi 7 and Windows 8.1
Use Event DrawColumnCell to change color or something else.
procedure TForm1.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect;DataCol: Integer; Column: TColumn; State: TGridDrawState);
begin
  try
    if Column.FieldName = 'FIRST_NAME' then
      DBGrid1.Canvas.Brush.Color := clGreen;
  finally
    DBGrid1.DefaultDrawColumnCell(Rect, DataCol, Column, State);
  end;
end;

Download full example:
file


text:
Q: Determine whether a number "fits" with a group of numbers I need to determine if a single number "fits" with a group of numbers. All the numbers will be percentages, so we'll use decimals.
For example:
The group is: 0.1, 0.25, 0.3, 0.4, 0.9 and we'll test against two single numbers: $y_1$ = 0.2 and $y_2$ = 0.8
The group is all low numbers, except for the one outlier, 0.9.
So I need to know that $y_1$ fits in with the group, but $y_2$ doesn't.
I'm thinking I need to do confidence interval. So I take the median of the group, in this case 0.3, then check to see if the single number is within a tolerance of the median. So in this example, if the single number is "good" it should be within the range 0.3 +/- 0.2. But how do you find that tolerance?
Note: this is not a math homework problem, so I don't get mean or variance or anything just handed to me. All I have to work with are the group of numbers and the single number.

A: On another post I recommended the use of Dixon's ratio test to detect for a single outlier.  For your original data Dixon's ratio is [X(n-1)-X(1)]/[X(n)-X(1)] in  you case this ratio statistic is [0.4-0.1]/[0.9-0.1]=3/8=0.375.  Compare this to the critical value for Dixon's test.  I am pretty sure that values below 0.5 would be below the critical value and hence you would take 0.9 to be an outlier.  Assume then that you have reason to exclude 0.9.  Your data set becomes 0.1 0.25 0.3 0.4 then apply Dixon's test to see if 0.8 is an outlier.  In this case the ratio is 3/7=0.428.  Still likely below the critical value. Now add 0.2 to the adjusted data set.  Dixon's ratio will be [0.3-0.1]/[0.4-0.1]=2/3=0.667.  This can be shown to be above the critical value.  I don't know the critical values for Dixon's test when n=5 but I bet it would go the way I conjectured.  You need the tables for Dixon's ratio which is probably in his 1950 paper.  You can find my 1982 paper in the American Statistician "A Note on the Robustness of Dixon's Ratio in Small Samples" on line and the references are in my paper.


text:
Q: I need report in Separate page Can you please assist me the solution on how to get the record details in separate page by date wise. Currently, I am getting all records together in crystal report 9.2.
I tried a formula like below
 IF Remainder (Record Number, 8) = 0 THEN

    TRUE

ELSE

    FALSE

But in my records details, each record has different columns.


text:
Q: Columns will not sort Vue.js In this codepen I have a Vue table where I am passing in the column name that is being clicked in order to sort by the column. I can console log the column name from the function to see if it is being launched the columns will not sort. What am I missing? Thank you.

var table = new Vue({
  el: '#table',
  data: {
    ascending: false,
    sortColumn: '',
    rows: [{
        id: 1,
        name: "Red"
      },
      {
        id: 2,
        name: "Blue"
      },
      {
        id: 3,
        name: "Green"
      },
      {
        id: 4,
        name: "Brown"
      },
      {
        id: 5,
        name: "Grey"
      },
      {
        id: 6,
        name: "Pink"
      }
    ]
  },
  methods: {
    "sortTable": function sortTable(col) {
      console.log(col)
      if (this.sortColumn === col) {
        this.ascending = !this.ascending;
      } else {
        this.ascending = true;
        this.sortColumn = col;
      }

      var ascending = this.ascending;

      this.rows.sort(function(a, b) {
        if (a[col] > b[col]) {
          return ascending ? 1 : -1
        } else if (a[col] < b[col]) {
          return ascending ? -1 : 1
        }
        return 0;
      })
    }
  },
  computed: {
    "columns": function columns() {
      if (this.rows.length == 0) {
        return [];
      }
      return Object.keys(this.rows[0])
    }
  }
});
table {
  font-family: 'Open Sans', sans-serif;
  width: 750px;
  border-collapse: collapse;
  border: 3px solid #44475C;
  margin: 10px 10px 0 10px;
}

table th {
  text-transform: uppercase;
  text-align: left;
  background: #696969;
  color: #FFF;
  cursor: pointer;
  padding: 8px;
  min-width: 30px;
}

table th:hover {
  background: #A9A9A9;
}

table td {
  text-align: left;
  padding: 8px;
  border-right: 2px solid #696969;
}

table td:last-child {
  border-right: none;
}

table tbody tr:nth-child(2n) td {
  background: #D3D3D3;
}

      ID
      Name

      {{row.id}}
      {{row.name}}

A: javascript is case sensitive, try
ID
Name

note the id and name as the arguments to sortTable - which are the name of the keys in the table (rather than ID and Name)

var table = new Vue({
  el: '#table',
  data: {
    ascending: false,
    sortColumn: '',
    rows: [{
        id: 1,
        name: "Red"
      },
      {
        id: 2,
        name: "Blue"
      },
      {
        id: 3,
        name: "Green"
      },
      {
        id: 4,
        name: "Brown"
      },
      {
        id: 5,
        name: "Grey"
      },
      {
        id: 6,
        name: "Pink"
      }
    ]
  },
  methods: {
    "sortTable": function sortTable(col) {
      console.log(col)
      if (this.sortColumn === col) {
        this.ascending = !this.ascending;
      } else {
        this.ascending = true;
        this.sortColumn = col;
      }

      var ascending = this.ascending;

      this.rows.sort(function(a, b) {
        if (a[col] > b[col]) {
          return ascending ? 1 : -1
        } else if (a[col] < b[col]) {
          return ascending ? -1 : 1
        }
        return 0;
      })
    }
  },
  computed: {
    "columns": function columns() {
      if (this.rows.length == 0) {
        return [];
      }
      return Object.keys(this.rows[0])
    }
  }
});
table {
  font-family: 'Open Sans', sans-serif;
  width: 750px;
  border-collapse: collapse;
  border: 3px solid #44475C;
  margin: 10px 10px 0 10px;
}

table th {
  text-transform: uppercase;
  text-align: left;
  background: #696969;
  color: #FFF;
  cursor: pointer;
  padding: 8px;
  min-width: 30px;
}

table th:hover {
  background: #A9A9A9;
}

table td {
  text-align: left;
  padding: 8px;
  border-right: 2px solid #696969;
}

table td:last-child {
  border-right: none;
}

table tbody tr:nth-child(2n) td {
  background: #D3D3D3;
}

      ID
      Name

      {{row.id}}
      {{row.name}}


text:
Q: How to update xubuntu 14.04 LTS to xubuntu 16.04 LTS How to upgrade xubuntu 14.04 LTS to xubuntu 16.04? I don't want to lose my application data.

A: sudo apt-get update && sudo do-release-upgrade -d

This should do the trick.


text:
Q: How to set an Alias in AVA tests I'm trying to set alias globally in my project without using Webpack, Babel, etc. Right now I have a simple test with AVA.
I'm using module-alias npm package that let me set in package.json my aliases. However, when I try to just create a simple example following the documentation with a basic alias it doesn't find the file:
Error: Cannot find module '@root/my-module.js'

You can reproduce this example with these 3 files:
package.json
{
  "name": "ava-alias",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "ava"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "ava": "^2.4.0",
    "esm": "^3.2.25",
    "module-alias": "^2.2.2"
  },
  "ava": {
    "require": [
      "esm",
      "module-alias"
    ]
  },
  "_moduleAliases": {
    "@root": "."
  }
}

test.js
require('module-alias/register')

import test from 'ava'
//import cube from './my-module.js'  // working
import cube from '@root/my-module.js' // not working

test('cube of 3 is 27', t => {
    t.is(cube(3), 27)
})

my-module.js
export default function cube(x) {
  return x * x * x
}

Save these files to an empty folder and then in that path in your terminal: npm i && npm run test
Maybe I'm missing same basics, thank you so much for time and help!

A: I ran into this same issue.
You can solve this by using module-alias/register inside your Ava config.
Your package.json should look like:
{
  "name": "ava-alias",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "ava"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "ava": "^2.4.0",
    "esm": "^3.2.25",
    "module-alias": "^2.2.2"
  },
  "ava": {
    "require": [
      "esm",
      "module-alias/register"
    ]
  },
  "_moduleAliases": {
    "@root": "."
  }
}


text:
Q: How can I find hole in a 2D matrix? I know the title seems kind of ambiguous and for this reason I've attached an image which will be helpful to understand the problem clearly. I need to find holes inside the white region. A hole is defined as one or many cells with value '0' inside the white region I mean it'll have to be fully enclosed by cell's with value '1' (e.g. here we can see three holes marked as 1, 2 and 3). I've come up with a pretty naive solution:
1. Search the whole matrix for cells with value '0'
2. Run a DFS(Flood-Fill) when such a cell (black one) is encountered and check whether we can touch the boundary of the main rectangular region
3. If we can touch boundary during DFS then it's not a hole and if we can't reach boundary then it'll be considered as a hole
Now, this solution works but I was wondering if there's any other efficient/fast solution for this problem.
Please let me know your thoughts. Thanks.

A: Make some sort of a "LinkedCells" class that will store cells that are linked with each other. Then check cells on-by-one in a from-left-to-right-from-top-to-bottom order, making the following check for each cell: if it's neighbouring cell is black - add this cell to that cell's group. Else you should create new group for this cell. You should only check for top and left neighbour.
UPD:  Sorry, I forgot about merging groups: if both neighbouring cells are black and are from different groups - you should merege tha groups in one.
Your "LinkedCells" class should have a flag if it is connected to the edge. It is false by default and can be changed to true if you add edge cell to this group. In case of merging two groups you should set new flag as a || of previous flags.
In the end you will have a set of groups and each group having false connection flag will be "hole".
This algorithm will be O(x*y).

A: With floodfill, which you already have: run along the BORDER of your matrix and floodfill it, i.e.,
change all zeroes (black) to 2 (filled black) and ones to 3 (filled white); ignore 2 and 3's that come from an earlier floodfill.
For example with your matrix, you start from the upper left, and floodfill black a zone with area 11. Then you move right, and find a black cell that you just filled. Move right again and find a white area, very large (actually all the white in your matrix). Floodfill it. Then you move right again, another fresh black area that runs along the whole upper and right borders. Moving around, you now find two white cells that you filled earlier and skip them. And finally you find the black area along the bottom border.
Counting the number of colours you found and set might already supply the information on whethere there are holes in the matrix.
Otherwise, or to find where they are, scan the matrix: all areas you find that are still of color 0 are holes in the black. You might also have holes in the white.
Another method, sort of "arrested flood fill"
Run all around the border of the first matrix. Where you find "0", you set
to "2". Where you find "1", you set to "3".
Now run around the new inner border (those cells that touch the border you have just scanned).
Zero cells touching 2's become 2, 1 cells touching 3 become 3.
You will have to scan twice, once clockwise, once counterclockwise, checking the cells "outwards" and "before" the current cell. That is because you might find something like this:
22222222222333333
2AB11111111C
31

Cell A is actually 1. You examine its neighbours and you find 1 (but it's useless to check that since you haven't processed it yet, so you can't know if it's a 1 or should be a 3 - which is the case, by the way), 2 and 2. A 2 can't change a 1, so cell A remains 1. The same goes with cell B which is again a 1, and so on. When you arrive at cell C, you discover that it is a 1, and has a 3 neighbour, so it toggles to 3... but all the cells from A to C should now toggle.
The simplest, albeit not most efficient, way to deal with this is to scan the cells clockwise, which gives you the wrong answer (C and D are 1's, by the way)
22222222222333333
211111111DC333333
33

and then scan them again counterclockwise. Now when you arrive to cell C, it has a 3-neighbour and toggles to 3. Next you inspect cell D, whose previous-neighbour is C, which is now 3, so D toggles to 3 again. In the end you get the correct answer
22222222222333333
23333333333333333
33

and for each cell you examined two neighbours going clockwise, one going counterclockwise. Moreover, one of the neighbours is actually the cell you checked just before, so you can keep it in a ready variable and save one matrix access.
If you find that you scanned a whole border without even once toggling a single cell, you can halt the procedure. Checking this will cost you 2(W*H) operations, so it is only really worthwhile if there are lots of holes.
In at most W*H*2 steps, you should be done.
You might also want to check the Percolation Algorithm and try to adapt that one.

A: You can represent the grid as a graph with individual cells as vertexes and edges occurring between adjacent vertexes. Then you can use Breadth First Search or Depth First Search to start at each of the cells, on the sides. As you will only find the components connected to the sides, the black cells which have not been visited are the holes. You can use the search algorithm again to divide the holes into distinct components.
EDIT: Worst case complexity must be linear to the number of cells, otherwise, give some input to the algorithm, check which cells (as you're sublinear, there will be big unvisited spots) the algorithm hasn't looked into and put a hole in there. Now you've got an input for which the algorithm doesn't find one of the holes.

A: Your algorithm is globally Ok. It's just a matter of optimizing it by merging the flood fill exploration with the cell scanning. This will just minimize tests.
The general idea is to perform the flood fill exploration line by line while scanning the table. So you'll have multiple parallel flood fill that you have to keep track of.
The table is then processed row by row from top to bottom, and each row processed from right to left. The order is arbitrary, could be reverse if you prefer.
Let segments identify a sequence of consecutive cells with value 0 in a row. You only need the index of the first and last cell with value 0 to define a segment.
As you may guess a segment is also a flood fill in progress. So we'll add an identification number to the segments to distinguish between the different flood fills.
The nice thing of this algorithm is that you only need to keep track of segments and their identification number in row i and i-1. So that when you process row i, you have the list of segments found in the row i-1 and their associated identification number.
You then have to process segment connection in row i and row i-1. I'll explain below how this can be made efficient.
For now you have to consider three cases:

*

*found a segment in row i not connected to a segment in row i-1. Assign it a new hole identification (incremented integer). If it's connected to the border of the table, make this number negative.

*found a segment in row i-1 not connected to a segment in row i-1. You found the lowest segment of a hole. If it has a negative identification number it is connected to the border and you can ignore it. Otherwise, congratulation, you found a hole.

*found a segment in row i connected to one or more segments in row i-1. Set the identification number of all these connected segments to the smallest identification number. See the following possible use case.

row i-1:   2  333 444 111
row i  :  ****  *** ***

The segments in row i should all get the value 1 identifying the same flood fill.
Matching segments in rows i and row i-1 can be done efficiently by keeping them in order from left to right and comparing segments indexes.
Process segments by lowest start index first. Then check if it's connected to the segment with lowest start index of the other row. If no, process case 1 or 2. Otherwise continue identifying connected segments, keeping track of the smallest identification number. When no more connected segments is found, set the identification number of all connected segments found in row i to the smallest identification value.
Index comparison for connectivity test can by optimized by storing (first-1,last) as segment definition since segments may be connected by their corners. You then can directly compare indexes bare value and detect overlapping segments.
The rule to pick the smallest identification number ensures that you automatically get the negative number for connected segments and at least one connected to the border. It propagates to other segments and flood fills.
This is a nice exercise to program. You didn't specify the exact output you need. So this is also left as exercise.

A: The brute force algorithm as described here is as follow.
We now assume we can write in cells a value different from 0 or 1.
You need a flood fill functions receiving the coordinates of a cell to start from and an integer value to write into all connected cells holding the value 0.
Since you need to only consider holes (cells with value 0 surrounded by cells with value 1), you have to use two pass.
A first pass visit only cells touching the border. For every cell containing the value 0, you do a flood fill with the value -1. This tells you that this cell has a value different of 1 and has a connection to the border. After this scan, all cells with a value 0 belong to one or more holes.
To distinguish between different holes, you need the second scan. You then scan the remaining cells in the rectangle (1,1)x(n-2,n-2) you didn't scan yet. Whenever your scan hit a cell with value 0, you discovered a new hole. You then flood fill this hole with the integer of your choice to distinguish it from the others. After that you proceed with the scan until all cells have been visited.
When done, you may replace the values -1 with 0 because there shouldn't be any 0 left.
This algorithm works, but is not as efficient as the other algorithm I propose. Its advantage is that it's simple and doesn't need an extra data storage to hold the segments, hole identification and eventual segment chaining reference.


text:
Q: Constructing a triagular DAG Inspired by Project Euler problem 67 (https://projecteuler.net/problem=67) I would like to construct a directed acyclic graph of the data.  I have already solved the problem using a 2D array, but am curious as to an algorithm that would build a DAG from the input text.
It seems very similar to a binary tree except that nodes can share children. I had thought of inserting nodes by using a BFS and inserting the node in both of the first two open spots, but this won't work for the edges of the triangle.
Here is a simple visualization of the DAG I would like to build, with all edges directed downward. The numbers showing the order in which the values are read from the file.
                             1
                            / \
                           2   3
                          / \ / \
                         4   5   6

Any input is appreciated.

A: I solved it using a DAG:
public class Problem067 {

    private static BinaryTreeNode<Long> root = null;
    private static LinkedList<LinkedList<BinaryTreeNode<Long>>> data = new LinkedList<LinkedList<BinaryTreeNode<Long>>>();

    private static void readFile() {
        try {
            BufferedReader in = new BufferedReader(new FileReader(
                    "inputs//Problem067.txt"));
            String str;
            while ((str = in.readLine()) != null) {
                LinkedList<BinaryTreeNode<Long>> list = new LinkedList<BinaryTreeNode<Long>>();
                for (String num : str.split(" ")) {
                    list.add(new BinaryTreeNode<Long>(Long.parseLong(num)));
                }
                data.add(list);
            }
            in.close();
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }

    private static void buildTree() {
        root = data.get(0).get(0);

        for (int i = 0; i < data.size() - 1; i++) {
            for (int j = 0; j < data.get(i).size(); j++) {
                data.get(i).get(j).setLeft(data.get(i + 1).get(j));
                data.get(i).get(j).setRight(data.get(i + 1).get(j + 1));
            }
        }
    }

    private static void findMaxRoute(BinaryTreeNode<Long> node) {
        node.setVisited(true);

        if (node.getLeft() == null) {
            return;
        }

        if (!node.getLeft().getVisited()) {
            findMaxRoute(node.getLeft());
        }

        if (!node.getRight().getVisited()) {
            findMaxRoute(node.getRight());
        }

        node.setValue(node.getValue()
                + Math.max(node.getLeft().getValue(), node.getRight()
                        .getValue()));
    }

    public static void main(String[] args) {
        readFile();
        buildTree();
        findMaxRoute(root);
        System.out.println(root.getValue());
    }
}

And here is the tree node:
    public class BinaryTreeNode<T> {
    private BinaryTreeNode<T> father = null;
    private BinaryTreeNode<T> left = null;
    private BinaryTreeNode<T> right = null;
    private T value = null;
    private Boolean visited = false;

    public BinaryTreeNode(T val) {
        value = val;
    }

    public BinaryTreeNode<T> getLeft() {
        return left;
    }

    public void setLeft(BinaryTreeNode<T> left) {
        this.left = left;
    }

    public BinaryTreeNode<T> getRight() {
        return right;
    }

    public void setRight(BinaryTreeNode<T> right) {
        this.right = right;
    }

    public T getValue() {
        return value;
    }

    public void setValue(T value) {
        this.value = value;
    }

    public BinaryTreeNode<T> getFather() {
        return father;
    }

    public Boolean getVisited() {
        return visited;
    }

    public void setVisited(Boolean visited) {
        this.visited = visited;
    }

}


text:
Q: Ruby: More flexibility than Java/C#? Is is that I'm a newbie learning Ruby, or does it really have more ways to write (the same) things than Java/C#? Also, if it is more flexible than Java, are there any linguistic features of Ruby that are generally not used to avoid confusion?
Examples might be parallel assignment and all the different ways to write Strings, perhaps?
Note: I'm not asking for a comparison with Java/C#... just this language question, please...
Edit: I understand that C#, Java and Ruby are strongly typed, and that only Ruby (like Python and others) is dynamically typed (while Java/C# are statically typed). Some of the answers say that dynamically-typed languages are more flexible. Is this necessarily true, and how does it affect syntax? I am only asking about syntactic flexibility.
(PHP is also dynamically typed and it does not seem more flexible than Java/C#, as far as I've seen. Again, I mean in terms of syntax, not in terms of deployment nor any other aspect...)

A: As for me the most used features in Ruby and missing in Java are code blocks/lambdas/closures.
Another great (but maybe dangerous) feature is open classes - you can change whatever class you want - add new method, change old, etc. You can even add method to specific object, not the whole class :).

A: Another dynamic language that's fairly similar to Ruby is Python.  However, in the Zen of Python, one of the rules dictates that "there should be one, and only one, way of doing something".  This is a polar opposite to Ruby which allows so much meta-programming that there are essentially an infinite number of ways to do the same thing.
That said, its somewhat ironic that up until Python 3.0 (aka: 3000) string and unicode values were different types.  While it makes sense, people sometimes get into issues where they're converting between the two a lot to perform text operations.
If you have a choice, I'd almost recommend using Python as your introduction to dynamic languages.  There's nothing wrong with Ruby, but you may find you'll run into fewer situations where the "right" way to do something isn't totally obvious.
In response to PHP being dynamically typed:
PHP's type system is flexible, allowing types to be automatically converted based on what context they're used in.  This doesn't actually make then real dynamic types, however.  The language itself is mostly static and won't allow you to add attributes to objects at runtime, for example (at least, the last time I checked).
Python, and quite possibly Ruby, are actually strongly typed, meaning you can confidently do type comparisons, and can't do PHP tricks like adding numeric strings to get a number.  True dynamic languages also often allow for meta-classing where you can adjust the type of an instance or class, or add attributes to either, all at runtime.

A: Ruby is a dynamic language. C# and Java are both statically typed language with strong typing. C# in v4.0 will add dynamic features but till now, Java and C# have had a completely different and more strict paradigm than dynamic languages such as Ruby and Python.

A: I commented on rkj's answer above regarding lambda's.  This code demonstrates the example you asked for;
def abs(n); (n < 0) ? -n : n; end
def square(n); n * n; end
def average(x, y); (x + y) / 2; end

def fixed_point(x, point, process, test)
  return point if test.call(x, point)
  fixed_point(x, process.call(x, point), process, test)
end

def sqrt(n)
  process = lambda {|n,g| average g, (n/g) }
  test = lambda {|n,g| abs(square(g) - n) < 0.001}
  fixed_point(n, 1.0, process, test)
end

The first point to notice is that the fixed_point method handles the general idea of progressively applying a process to some data until it passes a certain test.  The sqrt function defines the process of finding a square root and the test to determine when we're to be satisfied.  These 'procedures' are then passed just like any other form of data so that fixed_point can work it's magic.
Instead of temporarily storing the process and test the whole thing could be anonymous.  We could rewrite sqrt as;
def sqrt(n)
  fixed_point( n, 1.0,
      lambda {|n,g| average g, (n/g)},
      lambda {|n,g| abs(square(g) - n) < 0.001} )
end

Without this ability, I would have to define both the process and the test as individual functions and create a special sqrt_fixed_point function to call them.  As far as I'm aware Java can do something similar using Functors but I don't know enough to comment.  The consensus I've seen in blogs or similar is that Java makes this so horrendously complicated that you'll get a nosebleed just trying it.
Of course, another option that Ruby gives is metaprogramming.  I could rewrite sqrt so that it rewrites (on the fly) fixed_point using the correct process and test, but this is probably an abuse of the feature :-)
ps. The JoelOnSoftware link is posted deserves repeating; http://www.joelonsoftware.com/items/2006/08/01.html

A: All dynamically typed languages (like Ruby) usually are more flexible than statically typed ones (like Java).  You don't have to fight with the type system, which you often end up doing in statically typed languages.

A: I don't know Java or C#, but I let the fact that you can redefine how + works on numbers talk for itself.


text:
Q: Does VS optimize casting to the same type? int a = (int)5;

Does VS optimize that (remove the cast)? The situation above is trivial but I'm writing some template classes which take arbitrary type arguments in constructor:
template <typename U>
MyClass(U argument)
{
    T a = (T)argument;
}

In most cases the cast is needed to avoid compiler warnings but when T = U then the cast is redundant. Or maybe is there a better way to implement that?

A: Following Oded's hint from comments, I did a test in gcc-4.7.2 and MVSC-2012:
template <typename U, typename T>
void assign1(const T& t, U &u)
{
    u = (U) t; // CAST
}

template <typename U, typename T>
void assign2(const T& t, U &u)
{
    u = t;    // WITHOUT CAST
}

int main()
{
    {
        int t = 12;
        int u = 1;
        assign1(t, u);
    }
    {
        int t = 12;
        int u = 1;
        assign2(t, u);
    }
}

assign1 assembly code (gcc):
!{
!    u = (U) t;
assign1<int, int>(int const&, int&)+3: mov    0x8(%ebp),%eax
assign1<int, int>(int const&, int&)+6: mov    (%eax),%edx
assign1<int, int>(int const&, int&)+8: mov    0xc(%ebp),%eax
assign1<int, int>(int const&, int&)+11: mov    %edx,(%eax)
!}

assign2 assembly code(gcc):
!{
!    u = t;
assign2<int, int>(int const&, int&)+3: mov    0x8(%ebp),%eax
assign2<int, int>(int const&, int&)+6: mov    (%eax),%edx
assign2<int, int>(int const&, int&)+8: mov    0xc(%ebp),%eax
assign2<int, int>(int const&, int&)+11: mov    %edx,(%eax)
!}

They are same in gcc.
assign1 assembly code(MSVC):
001413EE  mov         eax,dword ptr [u]
001413F1  mov         ecx,dword ptr [t]
001413F4  mov         edx,dword ptr [ecx]
001413F6  mov         dword ptr [eax],edx

assign2 assembly code(MSVC):
0014142E  mov         eax,dword ptr [u]
00141431  mov         ecx,dword ptr [t]
00141434  mov         edx,dword ptr [ecx]
00141436  mov         dword ptr [eax],edx

They are same in MSVC, too.
So, both compilers omit the cast.


text:
Q: Is there any case where datetime.fromtimestamp returns an incorrect result using pytz? pytz asks you to use the .astimezone method for all time conversion to and from UTC.  However, in one special case — datetime.fromtimestamp — it looks like you should be able to use the Python library's datetime methods.
It seems to work here:
>>> import datetime
>>> import pytz
>>> ambigtime = 1352017800  # http://www.wolframalpha.com/input/?i=1352017800+unix+time+in+Los+Angeles
>>> amla = pytz.timezone('America/Los_Angeles')
>>> datetime.datetime.fromtimestamp(ambigtime, tz=amla)
datetime.datetime(2012, 11, 4, 1, 30, tzinfo=<DstTzInfo 'America/Los_Angeles' PDT-1 day, 17:00:00 DST>)
>>> datetime.datetime.fromtimestamp(ambigtime + 3600, tz=amla)
datetime.datetime(2012, 11, 4, 1, 30, tzinfo=<DstTzInfo 'America/Los_Angeles' PST-1 day, 16:00:00 STD>)

Are there situations where datetime.fromtimestamp won't give you the correct results with pytz timezones?

A: As far as I know, pytz.timezone() will give you an instance of tzinfo (or rather a subclass thereof), and as such is totally fine to use with datetime.fromtimestamp().
As long as pytz has updated zoneinfo files, you can create localized datetimes using that method. Converting a datetime between two zones however is really loads easier to do with the astimezone() method. If I am correct, it basically switches the tzinfo property on the datetime.


text:
Q: Java- Coloring matching cells in two different JTables I am writing a utility that will compare metadata fields from a SQL database. I am able to get all of the data into a JTable. I am trying to now color each particular cell depending on if they match the cell of another JTable. From my understanding I need to write a CellRenderer (Change the color of specific rows in my JTable). I had thought doing something like the below to compare the two values would be the best solution
for(int i=0;i<col2;i++){
                for(int j=0;j<row2;j++){
                     if(table1.getValueAt(i,j).equals(table2.getValueAt(i,j))){
                        table1.setSelectionBackground(Color.GREEN);
                        table2.setSelectionBackground(Color.GREEN);
                    }else if(!(table1.getValueAt(i, j).equals(table2.getValueAt(i, j)))){
                        table1.setSelectionBackground(Color.RED);
                        table2.setSelectionBackground(Color.RED);
                    }
                }
            }

I know the that the setSelectionBackground is not the method I want to call. I'm confused on how to write the CellRenderer listed in the above post to change the background color of a cell in depending if the contents match each other. Is writing the custom CellRenderer the only option?
EDIT 1:
As of right now, it appears to be taking in the correct color for background but it is coloring the entire table rather than a specific cell. Below is my CellRenderer and one of the for loops for how I think I should be calling the setBackground method
    private class CellRenderer extends DefaultTableCellRenderer {
    @Override
    public Component getTableCellRendererComponent(JTable table, Object value,boolean isSelected,boolean hasFocus,int row, int col){
        super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
        this.setOpaque(true);
        this.setBackground(table.getBackground());
        return this;
    }

    int col1 = table1.getColumnCount()-1;
    int row1 = table1.getRowCount()-1;
    int col2 = table2.getColumnCount()-1;
    int row2 = table2.getRowCount()-1;
    table1.setDefaultRenderer(Object.class, new CellRenderer());
    table2.setDefaultRenderer(Object.class, new CellRenderer());
    if(row1>row2){
        if(col1>col2){
            for(int i=0;i<row2;i++){
                for(int j=0;j<col2;j++){
                    if(table1.getValueAt(i,j).equals(table2.getValueAt(i,j))){
                        color = Color.GREEN;
                        System.out.println(color);

                        table1.setBackground(color);
                        table2.setBackground(color);
                    }else if(!(table1.getValueAt(i, j).equals(table2.getValueAt(i, j)))){
                        color = Color.RED;
                        System.out.println(color);
                        table1.setBackground(color);
                        table2.setBackground(color);
                    }
                }
            }


text:
Q: Clearing input from C program Is there a way to either;
(1) Clear any input from the terminal
(2) take input without the input being saved to the terminal
For example, in this program I enter a string and it checks if any of the letters are the same. Ideally I would want the input string to be cleared so that the hashtags form a rectangle by the 5th guess. I am aware that clearing the entire terminal and reprinting all the rows is an option but I would much rather just clear the line of input after every guess (if this is possible).

A: You can use VT100 escape codes. Most terminals, including xterm, are VT100 aware. For erasing a line, this is ^[[2K. In C this gives:
printf("\33[2K\r");

Some worthwhile subtleties...
\33[2K erases the entire line your cursor is currently on
\033[A moves your cursor up one line, but in the same column i.e. not to the start of the line
\r brings your cursor to the beginning of the line (r is for carriage return N.B. carriage returns do not include a newline so cursor remains on the same line) but does not erase anything


text:
Q: How to divide two columns in Laravel? I am retrieving each ID's rows per page with no problem. I have two columns in the DB's table which is extend and price. I want to use divide math on these columns value. My retrieving code is right below. I also want to add this code a divide math! extend / price
public function show($id)
{
    $estates = allestates::where('id', $id)->first();

    return view('pages.show', ['estates' => $estates]);
}

Thanks for helping me out!

A: You should try this:
public function show($id)
{
    $estates = allestates::where('id', $id)->first();

    $rsltActualPrice = $estates->extend / $estates->price;

    return view('pages.show', compact('estates','rsltActualPrice'));
}

Put $rsltActualPrice this variable in view file like:
{{$rsltActualPrice}}

OR
change your view file code like:
{{$estates->extend / $estates->price}}

Updated Answer
public function show($id)
{
    $estates = allestates::where('id', $id)->first();

print('
');
print_r($estates);
print('
');
exit;

$rsltActualPrice = $estates->extend / $estates->price;

return view('pages.show', compact('estates','rsltActualPrice'));

}

A: Going the accessor way. In your model, create a method
public function getActualPriceAttribute()
{
    return $this->extend / $this->price;
}

Your model now has a "virtual" attribute actualPrice that you can call, for example in a blade file:
{{ $estates->actual_price }}
More on accessors: https://laravel.com/docs/5.7/eloquent-mutators
On a sidenote: $estates = allestates::where('id', $id)->first(); can be shortened to $estates = allestates::find($id);


text:
Q: how to add additional charge for order before 12 pm magento2.2.1 i want to add the option for user have to choose the delivery time before 12pm and add extra charge for it in the cart.
Could you please help me for configure it, i have tried to create a condition in shipping rules but i dont have option for choose time.
if there is free extension please suggest me a link or guide me a way to configure it.


text:
Q: XPages Extension library - select value in toolbar node I´m working on a new user interface for an existing database with Xpages. In the Notes Client the database has an action where the user can set the status for multiple documents. In a Prompt-box the user can choose the status and then the chosen status is set to all selected documents.
In my XPages interface I´ve created the action bar with the toolbar control from the extension library. When I use a hardcoded status, everything works fine, but I don´t know how I can show the user a value picker or something similar, when he clicks on the toolbar action.
Any other concepts to solve my problem are also appreciated. Maybe there are other (better) ways to implement this process in Xpages.
Thanks in advance
Joerg

A: You probably could use a dropdown button in the action bar with the various options. If they need to be configurable you might opt for a repeat node for the dropdown values. You don't want to have popups in a web application - that's a client application UI style


text:
Q: grunt watch & connect I am kinda new to grunt and want to use it with Jekyll and some LESS-compiling.
My problem now is, I already have fully functioning LESS-comipiling with live reload and watch task and can build my jekyll site through grunt, but how do I run something like the jekyll serve or grunt-connect and grunt watch simultaneously?
I want a grunt task that provides the watching of my LESS-files etc, builds the jekyll site and then runs a small web server with grunt-connect or whatever.
My Gruntfile.js so far:
'use strict';
module.exports = function (grunt) {

    grunt.initConfig({
        jshint: {
            options: {
                jshintrc: '.jshintrc'
            },
            all: [
                'Gruntfile.js',
                'js/*.js',
                '!js/scripts.min.js'
            ]
        },
        less: {
            dist: {
                files: {
                    'css/styles.min.css': [
                        'less/app.less'
                    ]
                },
                options: {
                    compress: true,
                    // LESS source map
                    // To enable, set sourceMap to true and update sourceMapRootpath based on your install
                    sourceMap: false,
                    sourceMapFilename: 'css/styles.min.css.map',
                    sourceMapRootpath: '/'
                }
            },
            dev: {
                files: {
                    'css/styles.min.css': [
                        'less/app.less'
                    ]
                },
                options: {
                    compress: false,
                    // LESS source map
                    // To enable, set sourceMap to true and update sourceMapRootpath based on your install
                    sourceMap: true,
                    sourceMapFilename: 'css/styles.min.css.map',
                    sourceMapRootpath: '/'
                }
            }
        },
        uglify: {
            dist: {
                files: {
                    'js/scripts.min.js': [
                        'vendor/bootstrap/js/transition.js',
                        'vendor/bootstrap/js/alert.js',
                        'vendor/bootstrap/js/button.js',
                        'vendor/bootstrap/js/carousel.js',
                        'vendor/bootstrap/js/collapse.js',
                        'vendor/bootstrap/js/dropdown.js',
                        'vendor/bootstrap/js/modal.js',
                        'vendor/bootstrap/js/tooltip.js',
                        'vendor/bootstrap/js/popover.js',
                        'vendor/bootstrap/js/scrollspy.js',
                        'vendor/bootstrap/js/tab.js',
                        'vendor/bootstrap/js/affix.js',
                        'vendor/*.js',
                        'js/_*.js'
                    ]
                },
                options: {
                    // JS source map: to enable, uncomment the lines below and update sourceMappingURL based on your install
                    // sourceMap: 'assets/js/scripts.min.js.map',
                    // sourceMappingURL: '/app/themes/roots/assets/js/scripts.min.js.map'
                }
            }
        },
        watch: {
            less: {
                files: [
                    'less/*.less',
                    'less/bootstrap/*.less'
                ],
                tasks: ['less:dev']
            },
            js: {
                files: [
                    '<%= jshint.all %>'
                ],
                tasks: ['jshint', 'uglify']
            },
            livereload: {
                // Browser live reloading
                // https://github.com/gruntjs/grunt-contrib-watch#live-reloading
                options: {
                    livereload: true
                },
                files: [
                    '_site/*'
                ]
            }
        },
        clean: {
            dist: [
                'css/styles.min.css',
                'css/styles.min.css.map',
                'js/scripts.min.js',
                '_site/*'
            ]
        },
        jekyll: {                             // Task
            options: {                          // Universal options
                bundleExec: true,
                src : '<%= app %>'
            },
            dist: {                             // Target
                options: {                        // Target options
                    dest: '<%= dist %>',
                    config: '_config.yml'
                }
            },
            serve: {                            // Another target
                options: {
                    serve: true,
                    drafts: true
                }
            }
        },
        connect: {
            server: {
                options: {
                    keepalive: true
                }
            }
        }
    });

    // Load tasks
    grunt.loadNpmTasks('grunt-contrib-clean');
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-contrib-less');
    grunt.loadNpmTasks('grunt-jekyll');
    grunt.loadNpmTasks('grunt-contrib-connect');

    // Register tasks
    grunt.registerTask('default', [
        'clean',
        'less:dist',
        'uglify',
        'jekyll:dist'
    ]);
    grunt.registerTask('dev', [
        'watch'
    ]);

};

A: You need to tell connect what directory to serve up in the configuration using the "base" option, in this case it would be the static _site directory. You can also change the port to whatever you want, but you end up navigating to localhost:9009 with my example
connect: {
  server: {
    options: {
      livereload: true,
      base: '_site/',
      port: 9009
    }
  }
}

You will also want to add a watch task for when you change your html templates. Something like this would work.
watch: {
  html: {
    files: ['**/*.html', '!_site/**/*.html'],
    tasks: ['jekyll:dist']
  }
}

Then create a "serve" task like Wallace suggested.
// Start web server
grunt.registerTask('serve', [
'jekyll:dist',
'connect:server',
'watch'
]);

Lastly run "grunt serve" in the command line and navigate to localhost with the port you specified.

As commented by @jiggy

The key change is to not set keepalive to true. Keepalive will block
  all subsequent tasks from running. So long as connect is followed by
  watch the server won't terminate.

A: I spent 2 days desperately trying every gruntfile-configuration I could find on the internet. Never worked. Then I found this https://stackoverflow.com/a/24765175/1541141.
Use grunt-contrib-connect, NOT grunt-connect. grunt-connect is blocking...
Hope it helps.

A: I think the heart of your solution is to create a new task or edit an existing task, like so:
// Start web server
grunt.registerTask('serve', [
    'jekyll:dist',
    'connect:livereload',
    'watch'
]);

...which you would run with a $ grunt serve. less, jshint, uglify and connect are already included under watch.


text:
Q: Show column value on a separate row in Jqgrid I looked here and couldn't find an answer how to do this with Jqgrid. In pure html, this would be colspan. I have 7 columns and the last one is long comment that needs to be shown on a separate line as this:
col 1 | col 2 | col3 | col 4 | col 5 | col6
Col7 blah blah blah

This will repeat for every record in the data set. Is there a way to achieve this in Jqgrid?


text:
Q: Unwanted extra blank space when printing onto continuous roll of paper using AirPrint I'm working on code that prints receipts onto a continuous roll of paper using a receipt printer. The receipts are similar to what you get when you pay with your credit card in a store.
I'm using UIMarkupTextPrintFormatter as you can see below in my code.
But for some reason I keep getting blank space both in the middle and at the end of the printed text. (After printing the last line, the printer keeps rolling an extra few inches of blank paper!)
I inspected the pageCount property and it returns 2, so probably this is where the extra blank space is coming from.
I have also enabled the page range to show the number of pages (for debugging). I should not be getting a page range on the controller. But I am, and it is suggesting that my content goes over 2 pages.
Could you point out where my code falls short? what is the proper way to print my HTML content onto a continuous roll of paper?
My code works perfectly on the printer simulator. I get the exact output that I'm aiming for. No unexpected blank space. But it fails on a real AirPrint compatible receipt printer!
Any suggestion is much appreciated.
UIPrintInteractionController *controller = [UIPrintInteractionController sharedPrintController];
if(!controller){
    DDLogInfo(@"Couldn't get shared UIPrintInteractionController!");
    return;
}

UIPrintInteractionCompletionHandler completionHandler = ^(UIPrintInteractionController *printController, BOOL completed, NSError *error) {
    if(!completed && error)
        DDLogInfo(@"FAILED! due to error in domain %@ with error code %ld", error.domain, (long)error.code);
};

controller.showsPageRange = YES;
controller.showsPaperSelectionForLoadedPapers = YES;

//  Since the we're using a formatter, explicitly set the other properties to nil
controller.printingItem = nil;
controller.printingItems = nil;
controller.printPageRenderer = nil;

UIMarkupTextPrintFormatter *formatter = [[UIMarkupTextPrintFormatter alloc] initWithMarkupText:[self htmlPrintContent]];
formatter.startPage = 0;
formatter.contentInsets = UIEdgeInsetsZero;
controller.printFormatter = formatter;

// Ask for a print job object and configure its settings to tailor the print request
UIPrintInfo *info = [UIPrintInfo printInfo];

// B&W or color, normal quality output for mixed text, graphics, and images
info.outputType = UIPrintInfoOutputGrayscale;

// Select the job named this in the printer queue to cancel our print request.
info.jobName = @"somejobname";

// Make sure we are printing in a portrait orientation.
info.orientation = UIPrintInfoOrientationPortrait;

// We don't need duplex printing so set it to none explicitly
info.duplex = UIPrintInfoDuplexNone;

// Instruct the printing concierge to use our custom print job settings.
controller.printInfo = info;

// Present the standard iOS Print Panel that allows you to pick the target Printer, number of pages, etc.
[controller presentFromRect:self.printButton.frame inView:self.view animated:YES completionHandler:completionHandler];

A: I ended up switching to UISimpleTextPrintFormatter instead of UIMarkupTextPrintFormatter.
All formatting is done using NSAttributedString
Also implemented
- (CGFloat)printInteractionController:(UIPrintInteractionController *)printInteractionController cutLengthForPaper:(UIPrintPaper *)paper

in order to determine the height required for my text.
CGFloat printableWidth = paper.printableRect.size.width;

CGRect attributedStringBoundingRect = [attributedPrintContent boundingRectWithSize:CGSizeMake(printableWidth, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin context:nil];

/* Calculate the margins of the roll */
CGFloat lengthOfMargins = paper.paperSize.height - paper.printableRect.size.height;

/* The cut length is the height of the text, plus margins, plus content insets */
CGFloat cutLength = attributedStringBoundingRect.size.height + lengthOfMargins + formatter.contentInsets.bottom + formatter.contentInsets.top;

Hope this helps...

A: I found that I also needed to subtract the margins from the printable width when calling boundingRectWithSize:options:context:. For example:
func printInteractionController(_ printInteractionController: UIPrintInteractionController, cutLengthFor paper: UIPrintPaper) -> CGFloat {
    let size = CGSize(width: paper.printableRect.width - margin * 2, height: 0)

    let boundingRect = attributedText.boundingRect(with: size, options: [
        .usesLineFragmentOrigin,
        .usesFontLeading
    ], context: nil)

    return boundingRect.height + margin * 2
}


text:
Q: Symfony : ajax call cause server to queue next queries I've a problem with my application when an ajax call on the server takes too much time : it queue all the others queries from the user until it's done server side (I realized that canceling the call client side has no effect and the user still have to wait).
Here is my test case :

Go to another page on the same server

So when the get is fired and then after I click on the link, the server finish serving the first call before bringing me to the other page. My problem is that I want to avoid this behavior.
I'm on a LAMP server and I'm looking in a way to inform the server that the user aborted the query with function like connection_aborted(), do you think that's the way to go ? Also, I know that the longest part of this PHP script is a MySQL query, so even if I know that connection_aborted() can detect that the user cancel the call, I still need to check this during the MySQL query... I'm not really sure that PHP can handle this kind of "event".
So if you have any better idea, I can't wait to hear it.
Thank you.

Update :
After further investigation, I found that the problem happen only with the Symfony framework (that I omitted to precise, my bad). It seems that an Ajax call lock any other future call. It maybe related to the controller or the routing system, I'm looking into it.
Also for those interested by the problem here is my new test case :
-new project with Symfony 1.4.3, default configuration, I just created an app and a default module.
-jquery 1.4 for the ajax query.
Here is my actions.class.php (in my unique module) :
class defaultActions extends sfActions
{
  public function executeIndex(sfWebRequest $request)
  {
    //Do nothing
  }

  public function executeNewpage()
  {
    //Do also nothing
  }

  public function executeWaitingaction(){
    // Wait
    sleep(30);
    return false;
  }

}

Here is my indexSuccess.php template file :

<a href="<?php echo url_for('default/newpage');?>">Go to another symfony action

For the new page template, it's not very relevant... But with this, I'm able to reproduce the lock problem I've on my real application.
Is somebody else having the same issue ?
Thanks.

A: Does it need to be aborted on the server, or do you just want the user redirected immediately?
Perhaps something like AJAXQueue would work for you? (with obvious required changes to your client-side code..)

A: Ok, I finaly figured why the application is waiting : the session system of PHP queue the other query until session is closed. So my ajax call doesn't need to use session I do a $this->getUser()->shutdown() before my action takes too long.
Every details here : http://garethmccumskey.blogspot.com/2009/10/php-session-write-locking-and-how-to.html

A: Hello i have the same problem, with a similar script.
Jquery script
$.ajax({url :'/map/test1',  async:true ,complete: function(){alert("test1")}});
$.ajax({url :'/map/test2',  async:true ,complete: function(){alert("test2")}});

Symfony php
public function executeTest1()
{
 $this->getUser()->shutdown();
 usleep(10000000);
 return $this->renderText("Oki");
}

public function executeTest2()
{
 return $this->renderText("Oki");
}

When the page load, test1 requete is waiting the end usleep(10000000) but test2 is waiting test1's execution ending.
I have juste this problem with symfony.


text:
Q: PostgreSQL превышен предел глубины стека Хочу создать триггер с операцией апдейт, но получаю ошибку при занесении данных в таблицу: "ОШИБКА: превышен предел глубины стека". Не могу понять в чем проблема и как можно исправить. (Суть того, что я пытаюсь сделать. Я хочу занести данные в другую таблицу, после того как в данной таблице на которой триггер был произведен апдейт)
CREATE OR REPLACE FUNCTION schema._trigger_for_sql_()
RETURNS trigger
LANGUAGE plpgsql
AS
$$
DECLARE
BEGIN

IF (TG_OP = 'UPDATE') THEN
    UPDATE _his AS t SET
    _upd = now(),
    _table_size_byte = pg_table_size(_table_name),
    _indexes_size_byte = pg_indexes_size(_table_name),
    _total_size_byte = pg_total_relation_size(_table_name)
    FROM (
            SELECT
                table_schema,
                table_name,
                ('"' || table_schema || '"."' || table_name || '"') AS _table_name
            FROM information_schema.tables
            WHERE table_type = 'BASE TABLE' AND table_schema = TG_TABLE_SCHEMA
            AND table_name = TG_TABLE_NAME
             ) AS all_t
    WHERE t._schema = TG_TABLE_SCHEMA
    AND t._table = TG_TABLE_NAME;
 END IF;
 RETURN NEW;
 END;
 $$;

CREATE TRIGGER trigger_sql
AFTER INSERT OR UPDATE OR DELETE ON schema.table
FOR EACH ROW
EXECUTE FUNCTION schema._trigger_for_sql_()'


text:
Q: What is the reason for $ in Angular What is the reason for the $ used in Angular. Is it a specific RxJS
What is the reason for the $ used in the click$ & interval$ in the example code below:

const click$ = fromEvent(document, 'click').pipe(
  map((e: MouseEvent) => ({
    x: e.clientX,
    y: e.clientY,
    id: Math.random()
  })),
  tap(addHtmlElement),
  mergeMap(coords => subject.pipe(tap(v => setElementText(coords.id, v))))
);

const interval$ = interval(1000).pipe(
  tap(v => subject.next(v)),
  tap(v => setElementText('intervalValue', v))
);

merge(click$, interval$).subscribe();

A: The $ suffix is only a naming convention used for observables. It has no deeper meaning - analogous to naming interfaces with an I prefix (e.g. ICollection).


text:
Q: Why 'fixed' element can't have both 'margin-top' and 'margin-bottom' properties There is element on the page:
#current_colors_container{
    position: fixed;
    margin-bottom: 70px;
    margin-top: 70px;
    width: 23%;
    left: 1.6%; }

If I leave margin-top it doesn't cover up element above while scrolling up, if I leave margin-bottom it doesn't cover up absolute element of page in the bottom while scrolling down.
But both properties doesn't work, works only one of them (first in the list), and I can't get why - I expected it to have both margins while scrolling in both directions.
And my attempt to fix it with JQ doesn't work:
$(window).scroll(function(){
        if($("#current_colors_container").length>0){

            var bottom_nav=$('#bottom_nav').offset().top;
            var container_top=$("#current_colors_container").offset().top
            var color_container=container_top+$("#current_colors_container").height();

         if( bottom_nav<=color_container){
         $("#current_colors_container").css({"margin-top":"", "margin-bottom":"70px"})
         }
   }

});

Is there any pure CSS solution? Or how should I fix my JS function?
UPD
Now, JQ fix works, If I remove margin from ID CSS and provide it through classes (with functions addClass and removeClass) but, this solution makes #container 'jump' (shift quickly) before be fixed above or below other elements, and I don't like this, I would like it just stop floating.


text:
Q: Import from view im working on an app, where i have a Tableview in firstView, and i have a textfield in another .xib.  now loading xib by pushing a button, is no problem,  but how to i add text from the textfield in one xib to the tableview in the firstView.xib ???
can any of you help og give me a link to some help :-D
Rene Skov

A: Here's a link that should help you: CLICK HERE
The best way to do what your wanting to do is to save the text in your textview in a plist or directory since what your working with is small. Then you would need to read from the plist or directory and input into your tableview on your other view. That's how I would do it but there's probably a better way. Good Luck and I how that link helps. :-)
Edit: Oops, I thought you said textview but it's a textfield that your working with. Hummm, since it's just a textfield I would use NSUserDefaults to store the data that is in your textfield.
You would save and read the textfield like so:
NSUserDefaults *textDefault = [NSUserDefaults standardUserDefaults];

[textDefault setObject:yourTextFieldName.text forKey:@"someName"];

NSString *textValue= [textDefault objectForKey:@"someName"];

NSLog(@"Your Text -->%@",textValue);

I hope this helps.


text:
Q: how to cover full button width on hover in html css Button without hover:

Button on hover:

I started to code a website but left with some styling errors.
How can I cover that part left on button while hovering. Every time i hover that part is unhovered.
HTML code for that button(full menu) is :

<!DOCTYPE html>

  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" type="text/css" href="Vendor/css/normalize.css">
  <link rel="stylesheet" type="text/css" href="Vendor/css/grid.css">
  <link rel="stylesheet" type="text/css" href="vendor/css/generic.css" />
  <link rel="stylesheet" type="text/css" href="Resources/css/styles.css">
  <link href="https://unpkg.com/ionicons@4.3.0/dist/css/ionicons.min.css" rel="stylesheet">
  <link rel="stylesheet" type="text/css" href="vendor/css/js-image-slider.css">
  <link href="https://fonts.googleapis.com/css?family=Lato:100,300,300i,400" rel="stylesheet" type="text/css">
  <title>Homepage</title>
  <link rel="apple-touch-icon" sizes="180x180" href="/resources/favicons/apple-touch-icon.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/resources/favicons/favicon-32x32.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/resources/favicons/favicon-16x16.png">
  <link rel="manifest" href="/resources/favicons/site.webmanifest">
  <link rel="mask-icon" href="/resources/favicons/safari-pinned-tab.svg" color="#5bbad5">
  <link rel="shortcut icon" href="/resources/favicons/favicon.ico">
  <meta name="msapplication-TileColor" content="#da532c">
  <meta name="msapplication-config" content="/resources/favicons/browserconfig.xml">
  <meta name="theme-color" content="#ffffff">

funship program details

alumni & fairwell meet-2018

requirment: faculty/other staff

information brochure

download form

student grievance

CSS code for that button (full menu) is :

/*=================================Common=================*/

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html,
body {
  background-color: #f0f0f0;
  color: #555;
  font-family: 'Lato', sans-serif;
  font-weight: 300;
  font-size: 20px;
  text-rendering: optimizeLegibility;
}

p {
  font-weight: 500;
}

/*========================resuable=============*/

.row {
  max-width: 1140px;
  margin: 0 auto;
}

section {
  padding: 15px 0;
}

.box {
  padding: 1%;
}

.list-item a:link,
.list-item a:visited {
  text-decoration: none;
  transition: color 0.2s;
}

.list-item a:hover,
.list-item a:active {
  color: #4285f4;
}

/*==============================Heading====================*/

h1,
h2,
h3 {
  font-weight: 800;
  letter-spacing: 1px;
}

h1 {
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 150%;
  word-spacing: 4px;
}

h2 {
  font-size: 180%;
  word-spacing: 2px;
  text-align: center;
  margin-bottom: 25px;
}

h3 {
  font-size: 80%;
  margin-bottom: 15px;
}

/*====================Button=========================*/

.btn:hover,
.btn:active,
input[type=submit]:hover,
input[type=submit]:active {
  background-color: rgba(204, 204, 204, 0.24);
}

/*==============================main-nav====================*/

.main-nav {
  background-color: #535353;
  border-bottom: 1px solid #393939;
}

.main-nav ul li {
  list-style: none;
  display: inline-block;
  text-transform: uppercase;
  border-right: 1px solid #929292;
  font-size: 50%;
  padding: 10px;
}

.main-nav li a {
  text-decoration: none;
  color: #fff;
}

thanks for the help in advance

A: Its because of newline characters when you use inline-block, add font-size:0 to the ul and font-size:12px to li can fix the problem

/*=================================Common=================*/

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html,
body {
  background-color: #f0f0f0;
  color: #555;
  font-family: 'Lato', sans-serif;
  font-weight: 300;
  font-size: 20px;
  text-rendering: optimizeLegibility;
}

p {
  font-weight: 500;
}

/*========================resuable=============*/

.row {
  max-width: 1140px;
  margin: 0 auto;
  font-size: 0;
}

section {
  padding: 15px 0;
}

.box {
  padding: 1%;
}

.list-item a:link,
.list-item a:visited {
  text-decoration: none;
  transition: color 0.2s;
}

.list-item a:hover,
.list-item a:active {
  color: #4285f4;
}

/*==============================Heading====================*/

h1,
h2,
h3 {
  font-weight: 800;
  letter-spacing: 1px;
}

h1 {
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 150%;
  word-spacing: 4px;
}

h2 {
  font-size: 180%;
  word-spacing: 2px;
  text-align: center;
  margin-bottom: 25px;
}

h3 {
  font-size: 80%;
  margin-bottom: 15px;
}

/*====================Button=========================*/

.btn:hover,
.btn:active,
input[type=submit]:hover,
input[type=submit]:active {
  background-color: rgba(204, 204, 204, 0.24);
}

/*==============================main-nav====================*/

.main-nav {
  background-color: #535353;
  border-bottom: 1px solid #393939;
}

.main-nav ul li {
  list-style: none;
  display: inline-block;
  text-transform: uppercase;
  border-right: 1px solid #929292;
  font-size: 50%;
  padding: 10px;
  font-size: 12px;
}

.main-nav li a {
  text-decoration: none;
  color: #fff;
}
<!DOCTYPE html>

  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" type="text/css" href="Vendor/css/normalize.css">
  <link rel="stylesheet" type="text/css" href="Vendor/css/grid.css">
  <link rel="stylesheet" type="text/css" href="vendor/css/generic.css" />
  <link rel="stylesheet" type="text/css" href="Resources/css/styles.css">
  <link href="https://unpkg.com/ionicons@4.3.0/dist/css/ionicons.min.css" rel="stylesheet">
  <link rel="stylesheet" type="text/css" href="vendor/css/js-image-slider.css">
  <link href="https://fonts.googleapis.com/css?family=Lato:100,300,300i,400" rel="stylesheet" type="text/css">
  <title>Homepage</title>
  <link rel="apple-touch-icon" sizes="180x180" href="/resources/favicons/apple-touch-icon.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/resources/favicons/favicon-32x32.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/resources/favicons/favicon-16x16.png">
  <link rel="manifest" href="/resources/favicons/site.webmanifest">
  <link rel="mask-icon" href="/resources/favicons/safari-pinned-tab.svg" color="#5bbad5">
  <link rel="shortcut icon" href="/resources/favicons/favicon.ico">
  <meta name="msapplication-TileColor" content="#da532c">
  <meta name="msapplication-config" content="/resources/favicons/browserconfig.xml">
  <meta name="theme-color" content="#ffffff">

funship program details

alumni & fairwell meet-2018

requirment: faculty/other staff

information brochure

download form

student grievance


text:
Q: Lemmas on etale cohomology with compact support from the book 'Arithmetic Duality Theorems' I was reading Milne's book "Arithmetic Duality Theorems". On page 166 there are a lot of useful lemmas on the etale cohomology with compact support on S-integers. However, I get confused when I tried to look at Prop 2.3 (a) and (d) at once.
Suppose $X$ is the ring of integers of a totally complex number field $K$. $U\hookrightarrow X$ is an open subscheme, $S=X\setminus U=\{p\}$ has only one finite prime. Consider the sheaf $\mathbb{G}_m$ and its pull-back on the various schemes involved, by (d) of Prop 2.3, we have
$$ H^0(\mathbb{F}_p, \mathbb{G}_m)\to H^1_c(U, \mathbb{G}_m)\to H^1_c(X, \mathbb{G}_m) $$
Here $H^1_c(X, \mathbb{G}_m)=H^1(X, \mathbb{G}_m)$ since $K$ is a totally complex field, but anyway it is finite. Also $H^0(\mathbb{F}_p, \mathbb{G}_m)=\mathbb{F}_p^*$ is finite, therefore $H^1_c(U, \mathbb{G}_m)$ is finite.
If we use (a) of Prop 2.3, we have
$$ H^0(U, \mathbb{G}_m)\to H^0(K_p, \mathbb{G}_m)\to H^1_c(U,\mathbb{G}_m)\to H^1(U,\mathbb{G}_m)$$
Here $K_p$ is the Henselization of $K$ at $p$. Since we have shown $H^1_c(U,\mathbb{G}_m)$ is finite, and since we know $H^0(U, \mathbb{G}_m)$, which is the $S$-units on $X$, is a finite rank abelian group, we should have $H^0(K_p, \mathbb{G}_m)=K_p^*$ is also a finite rank abelian group. This seems absurd to me, since the subfields of $K_p$ which are number fields has infinite rank multiplicative groups.
So I wonder, did I miss anything? Thanks very much in advance!

A: Apologies: (as pointed out by Minhyong Kim),  the answer below does not address the OP's question
$K_p$ is not a number field. It contains a $p$-adic field $Q_p$ and, as such, '$K_p^*$' is not a finitely generated abelian group.


text:
Q: R: Importing vector graphics to a plot - Cannot get grImport to work I am trying to use the grImport package (http://cran.r-project.org/web/packages/grImport/index.html) to import an external vector image into an R plot, e.g. I take this picture:

and then I convert to ps using the convert of ImageMagick:
convert crashed.jpg crashed.ps

I the start R and issue the following commands:
R> library("grImport")
R> PostScriptTrace("crashed.ps", "crashed.xml")
R> myPic = readPicture("crashed.xml")
R> grid.picture(myPic)

and then according to http://cran.r-project.org/web/packages/grImport/vignettes/import.pdf the image is supposed to be displayed. But all I get is an empty plot popping up!
R> sessionInfo()
R version 3.1.3 (2015-03-09)
Platform: x86_64-apple-darwin13.4.0 (64-bit)
Running under: OS X 10.10.3 (Yosemite)

A: This is a fairly old question. Given that it's still unanswered, I thought I'd share some modern tools for incorporating external graphics into R plots.
Preliminaries
Using ImageMagick or equivalent, convert the source .jpg to .pdf. On Linux, this is done using convert crashed.jpg crashed.pdf. We will also use the following base plot throughout the answer:
library( ggplot2 )
g0 <- ggplot( mtcars, aes(disp, mpg) ) + geom_point() + theme_bw()

Importing the image as a plot panel using grImport2
We first use grConvert to convert the .pdf to a .svg, which is then imported and converted to a grob object.
grConvert::convertPicture( "crashed.pdf", "crashed.svg" )
p <- grImport2::readPicture( "crashed.svg" )
g <- grImport2::pictureGrob( p )
gridExtra::grid.arrange( g0, g, nrow=1 )

Overlaying the image on top of an existing plot using cowplot
Unlike the above, this solution works directly with the .jpg:
## Ensure magick is installed for draw_image()
if(!require("magick")) install.packages( "magick" )
cowplot::ggdraw(g0) + cowplot::draw_image("crashed.jpg", x=0.25, y=0.25, scale=0.25)

Using the image as a plot element with the help of egg
This approach also works directly with the .jpg. We load the image and populate a new column in mtcars with the resulting object. The column can then be provided to geom_custom() in a standard ggplot fashion:
mtcars$img <- list(jpeg::readJPEG( "crashed.jpg" ))
g0 + egg::geom_custom( data=mtcars, aes(data=img), grob_fun=grid::rasterGrob,
                      fun_params = list(height=unit(1,"lines")) )


text:
Q: Unsupported major.minor version 52.0 in ubuntu I am using jdk1.8.0_25, and when I check the version of Java with the following command:
java -version

it outputs the following
java version "1.7.0_65"
OpenJDK Runtime Environment (IcedTea 2.5.3) (7u71-2.5.3-0ubuntu0.14.04.1)
OpenJDK 64-Bit Server VM (build 24.65-b04, mixed mode)

Please solve my problem.

A: Maybe you have more than one java JDK installed. Try to check that by
sudo update-alternatives --config javac

A: I got the same error, and while the java version correctly set to 8, my JAVA_HOME env var was still set to 7.
Executing this fixed it for me:
export JAVA_HOME=/usr/lib/jvm/java-8-oracle

A: Run the command />which java to determine where the java command is coming from on the path.
You either need to change to put jdk 1.8 on the path or use the fully qualified path to the java executable.

A: You can install several different java versions on to your system. You can set the default using the update-alternatives command.
Here is a solution to a similiar problem, which is maybe of use for you:
https://askubuntu.com/questions/121654/how-to-set-default-java-version


text:
Q: Android-vision how get stream from camera using G.P.Services vision package in api level 19 I am working with android vision package from google play services. I triying to get frame or bitmap or raw images anyone.
Actually my app can detect faces and draw rectangles around.
I use the oficialsample of google >vision>facetracker .
I want to use it with opencv 2.4.3 donc I am forced to use api level 19 and deprecated camera api.
How I can get the  stream of camera for modify it. I not wont take picture, I tried and is slow.

A: No . I wan to get the bitmap stream from camera before it is send to surface.


text:
Q: Erro ao criar diretório com php mesmo usando o file_exists Beleza pessoal? Estou com um problema que é o seguinte. Utilizo o seguinte código para criar um diretório.
    //verifica se existe diretorio para criar
$dir = 'imagens/'.$id_produto.'/';

if(!file_exists($dir)){
  mkdir($dir, 0777);
}else{
  echo "Erro ao criar diretório";
}

Mas mesmo indo la na pasta e deixando ela limpa, executando esse código ele aponta que o diretório existe. Já exibi separadamente echo file_exists($dir); e ele me retorna 1 como se existisse o diretório. O estranho é que chegou a funcionar normalmente e agora estou com esse problema. alguma idéia?

A: Tente isso
mkdir($dir, 0777, true);

A: Tente usar a função is_dir veja em http://php.net/manual/en/function.is-dir.php
remova a última concatenação na váriavel $dir, segue exemplo abaixo.
$dir = 'imagens/'.$id_produto;
if(!is_dir($dir)){
   mkdir($dir, 0777,true);
    // verifica novamente
    if (!is_dir($dir)){
        echo "erro ao criar";
    } else{
        echo "dir criado agora ".time();
    }
}else{
    echo "dir existe";
}


text:
Q: Is it ever explained why Harry has to cage Hedwig when he travels? Doesn't this seem extremely unnecessary? Hedwig is an Wizarding Owl, she can fly and can travel wherever needed with minimal instruction. Hedwig in particular is very loyal and intelligent. There are more than a few examples where Hedwig isn't confined to a cage while Harry travels and there is no problem. They let her out to fly in CoS when The Weasley brothers rescue Harry with the flying car. She finds Harry in The Leaky Cauldron in PoA without any instruction, she even found her way into the Black house while it was under a Fidelius Charm.  She will find her way to her needed destination without being bodily packaged and trundled there.
Of course it's not just Harry, all students seem to force their owls into cages in order to travel with them. Apparently for no good reason.
One proffered reason for Hogwarts students needing to do this would be because of the protections from outside interference that are placed on the school, but I'd argue that's nonsense. Wizarding owls flock to Hogwarts every morning, and sometimes at other times, to deliver mail. They seem to be one of the few creatures with almost uninhibited access to Hogwarts (except for them being searched regularly in OotP).
The movies usually make poor changes to the story in order to fit things into a film script, but occasionally they change something for the better. It's one of the great changes in the Harry Potter movies when Hedwig-

gets to sacrifice herself to protect Harry instead of the extremely undignified and helpless end in the book.

A: Maybe it is a rule or somethingelse.

*

*Maybe Hogwarts searches peoples baggage. And you must have all of your belongings there so that it can be magically registered.

*Maybe Hedwig can't fly that far in a couple of hours and so it would be better for her to just ride with him.

*

*Maybe it is just a rule made by the ministry to stop owls from flooding the air. Muggles would notice if a bunch of owls were flying across England. If one person is allowed to let his owl fly then everybody would be allowed and there would be possibly hundreds of owls flooding the skies.
This was a response to this qoute in particular.

Of course it's not just Harry, all students seem to force their owls
  into cages in order to travel with them. Apparently for no good
  reason.

Also, if he travels with her he knows where she is there immediately and not wondering if she got hurt along the way.
These are my other theories(since I don't have my books with me and I don't remember a answer in them):
Ease of access
If you keep your owl in a cage, you know where it is most of the time and can access it to send a message when you need to.
Not to spook muggles out
Muggles aren't suppose to know about the wizarding world. If you have a bunch of owls flying around the muggles might start to spook out like they did in the first book when all of the owls were flying around and sitting around the Privet Drive house. Remember students are allowed to do magic.
To keep her safe
People know Hedwig is Harry's owl and she was attacked before, he might keep her in the cage so that she won't attacked or stolen by anyone(his enemies), until he got to somewhere safer.
Also from the wikia:

While living with the Dursleys, Hedwig was locked in her cage for
  months at a time to prevent Harry from sending messages to his "freaky
  little friends."

So it wasn't really him doing it all the time.

During 1995, she was attacked by associates of Dolores Umbridge when
  Umbridge tried to intercept Harry's mail, requiring Dobby and
  Professor Grubby-Plank to nurse her back to health.

He might of wanted to keep her safe.

Snowy Owls are not native to Great Britain, and this caused some
  inconvenience, as she could not always perform tasks for Harry.

A: IIRC the only time Harry 'has to' cage Hedwig is before they are traveling on the Hogwarts' Express when in view of muggles. This would be required so as not to raise suspicion from muggles while getting onto platform 9 3/4. Muggles don't know that the owl is magic and is much more 'trained' than they could imagine. Therefore, they would expect to see it caged in order to travel on a train just like any other pet (e.g. a dog).
Presumably once on the train Harry could let Hedwig out and allow her to fly along with the train for some time (and I could be making it up but I thought he did just that in one of the books). There are examples of students having their pets out of cages on the train (I'm thinking Trevor the toad and Scabbers), so it doesn't seem to be unheard of. The rest of the time Hedwig is probably sleeping in the cage content with not having to fly the journey on her own.
If the question is actually why does he cage Hedwig for the Hogwarts Journey instead of just sending her to fly the journey on her own; I think that's a personal choice, not out of necessity.


text:
Q: Excel VBA: Selecting a Range with an arbitrary amount of Rows, but set columns I'm sure this will be something simple, but I haven't been able to find anything. I have this:
If Not Intersect(Target, Range("AM8:BA")) Is Nothing Then

And then I have the rest of my code with actions. I'm trying to have my macro trigger if any of the cells in that range are changed. I get a syntax error at the BA part. What I'm trying to do is have the range work for any arbitrary amount of rows after 8 in column AM-BA. Ex: BA50, BA1000, etc
I'm sure it's a simple mistake, but I can't find it anywhere. Thanks in advance

A: Consider:
If Not Intersect(Target, Range("AM8:BA" & Rows.Count)) Is Nothing Then


text:
Q: Login page error - dictionary update sequence element #0 has length 0; 2 is required I am getting an error on the login page when I log out.

ValueError at /accounts/login/
dictionary update sequence element #0 has length 0; 2 is required

I do not know why I get this error because I've never had such an error before. What does this error mean and how can I solve it?
traceback
Environment:

Request Method: GET
Request URL: http://127.0.0.1:8000/accounts/login/?next=/

Django Version: 3.1.4
Python Version: 3.8.10
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.humanize',
 'register',
 'customer',
 'financial_analysis',
 'ocr',
 'core',
 'approvals',
 'crispy_forms',
 'ckeditor',
 'rest_framework',
 'requests',
 'ckeditor_uploader',
 'django_filters',
 'activity_log',
 'djmoney',
 'djmoney.contrib.exchange',
 'mathfilters',
 'bootstrap3',
 'phone_field']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback (most recent call last):
  File "C:\Users\USER\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\USER\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\handlers\base.py", line 202, in _get_response
    response = response.render()
  File "C:\Users\USER\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\template\response.py", line 105, in render
    self.content = self.rendered_content
  File "C:\Users\USER\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\template\response.py", line 83, in rendered_content
    return template.render(context, self._request)
  File "C:\Users\USER\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\template\backends\django.py", line 61, in render
    return self.template.render(context)
  File "C:\Users\USER\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\template\base.py", line 168, in render
    with context.bind_template(self):
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.2800.0_x64__qbz5n2kfra8p0\lib\contextlib.py", line 113, in __enter__
    return next(self.gen)
  File "C:\Users\USER\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\template\context.py", line 244, in bind_template
    updates.update(processor(self.request))

Exception Type: ValueError at /accounts/login/
Exception Value: dictionary update sequence element #0 has length 0; 2 is required

register/urls.py
    from django.conf.urls import url
    from django.conf.urls.static import static
    from django.urls import path, include
    from CreditReviewBot import settings
    from . import views
    from .views import update_user

    urlpatterns = [
        url(r'^signup/$', views.signup, name='signup'),
        path('', views.home, name='home'),
        path('accounts/', include('django.contrib.auth.urls')),
        url(r'^accounts/(?P<id>\d+)/update/$', update_user, name="update"),

                  ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

settings.py
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'approvals.views.approval_context_processor',
            ],
        },
    },
]


text:
Q: Exoplayer 2.7.0 , 2.3.1 version conflicts Currently I am using Exoplayer library with version 2.3.1. I want to include Exoplayer version 2.7.0 in same project. How can we do that without conflict?
I tried to include 2.7.1 and 2.3.1 so it's taking updated version by default.

A:
"I tried to include 2.7.1 and 2.3.1 so it's taking updated version by default."

I would suggest just trying to change your app's dependency on Exoplayer 2.3.1 to 2.7.0.

*

*If you don't get compilation / build errors ... and your code works, then you have answered your question.

*If you get compilation errors, examine them carefully, look at the Exoplayer javadocs and release notes, and figure out what changes you need to make your code to use the newer APIs.
If updating your code proves intractable (i.e. too much work), you may well be stuck.  However, it shouldn't be.  It is unlikely that the authors of the library would produce new releases that are so incompatible that upgrading is intractable ... for a skilled engineer.  What is more, the Exoplayer site says:

"Unlike the MediaPlayer API, ExoPlayer is easy to customize and extend, and can be updated through Play Store application updates."

(emphasis added) so they clearly intend upgrading to be simple.
Getting an application to use two separate versions of some library at the same time is unlikely to work.  And it is unlikely that you want your application to have two distinct media player UIs ...


text:
Q: Getting multi-threading to work with a list using python pexpect I wrote a simple python pexpect script to ssh into a machine and perform a action. Now I need to do this action to multiple servers. I am using a list to hit all of the servers concurrently using multi-threading. My issue is due to everything being ran concurrently, each thread is running on the same server name. Is there a way to concurrently have each thread only run one of the listed servers?
    #! /usr/bin/python
#Test script

import pexpect
import pxssh
import threading
import datetime

currentdate = datetime.datetime.now()
easterndate = (datetime.datetime.now() + datetime.timedelta(0, 3600))

#list of servers
serverlist = ["025", "089"]

#server number
sn = 0

ssh_new_conn = 'Are you sure you want to continue connecting'

class ThreadClass(threading.Thread):
  def run(self):

    index = 0
    sn = serverlist[index]
    print sn
    username = '[a username]'
    password = '[a password]'
    hostname = '%(sn)s.[the rest of the host url]' % locals()
    command = "/usr/bin/ssh %(username)s@%(hostname)s " % locals()
    index = index + 1
    now = datetime.datetime.now()

    print command
    p = pexpect.spawn(command, timeout=360)

    ***do some other stuff****

for i in range(len(severlist)):
  t = ThreadClass()
  t.start()

[update]
I may just trying doing this with a parent thread that calls the child thread and so forth....although it would be nice if multi-threading could work from a list or some sort of work queue.

A: The problem has nothing to do with "everything being ran concurrently". You're explicitly setting index = 0 at the start of the run function, so of course every thread works on index 0.
If you want each thread to deal with one server, just pass the index to each thread object:
class ThreadClass(threading.Thread):
    def __init__(self, index):
        super(ThreadClass, self).__init__()
        self.index = index
    def run(self):
        sn = serverlist[self.index]
        print sn
        # same code as before, minus the index = index + 1 bit

for i in range(len(severlist)):
    t = ThreadClass(i)
    t.start()

(Of course you'll probably want to use serverlist instead of severlist and fix the other errors that make it impossible for your code to work.)
Or, more simply, pass the sn itself:
class ThreadClass(threading.Thread):
    def __init__(self, sn):
        super(ThreadClass, self).__init__()
        self.sn = sn
    def run(self):
        print self.sn
        # same code as last version, but use self.sn instead of sn

for sn in severlist:
    t = ThreadClass(sn)
    t.start()

Alternatively, if you really want to use a global variable, just make it global, and put a lock around it:
index = 0
index_lock = threading.Lock()

class ThreadClass(threading.Thread):
    def run(self):
        global index, index_lock
        with index_lock:
            sn = serverlist[index]
            index += 1
        print sn
        # same code as first version

However, you might want to consider a much simpler design, with a pool or executor instead of an explicit worker thread and list of things to work on. For example:
def job(sn):
    print sn
    # same code as first version again

with concurrent.futures.ThreadPoolExecutor() as executor:
    executor.map(job, serverlist)

This will only run, say, 4 or 8 or some other good "magic number" of jobs concurrently. Which is usually what you want. But if you want exactly one thread per server, just pass max_workers=len(serverlist) to the ThreadPoolExecutor constructor.
Besides being a whole lot less code to read, write, get wrong, debug, etc., it also has more functionality—e.g., you can get results and/or exceptions from the servers back to the main thread.


text:
Q: C++: Why is the created vector not passing to the next set of for loops? I have it so that the user defines the size of the vector and then a vector is filled. Then that vector is sorted using bubble sort (homework assignment). However, when the "sorted" vector is displayed, there are different numbers in it than what were in the original creation. How do I first create the vector, display it, then sort it and display it??
#include <iostream>
#include <vector>
#include <cmath>
#include <numeric>
using namespace std;

int main()
{
    int n;
    double average=0.0;
    int median = 0;
    double size = 0.0;
    int i=0;

    cout<<"Vector Length?: "<<endl;
    cin>>n;
    vector<int> data;
    srand(time(NULL));

    //Filling vector
    for (int i=0; i<n; i++)
    {
        data.push_back(rand()%10+1);
    }
    for (int i=0; i<data.size(); i++)
    {
        cout<<"Vector: "<< data[i]<<endl;
    }

    size = data.size();

    //Sorting
    void bubbleSort(vector<int> & data);
    {
        for (int k = 1; k < size; k++)
        {
            for (int i = 0; i<size -1 - k; i++)
            {
                if (data[i] > data[i +1])
                {
                    int temp = data[i];
                    data[i] = data[i + 1];
                    data[i + 1] = temp;
                }
                cout<<"Sorted vector: "<< data[i]<<endl;
            }
        }
    }

A: *

*If you are planning to define function void bubbleSort(vector & data) later you need to declare it before calling it.\
void bubbleSort(vector<int> & data);
  int main()
  {
            // Here your code
             bubbleSort(data);
            //Here your code
  }

*You need to define variables only just before you need it. And if you declare and  never use it, you will get unused variable warnings. So better you can comment all these variables. You can un-comment whenever you need.
//double average=0.0;
//int median = 0;

*You should call your function bubbleSort() from  main() as follows:
bubbleSort(data);

*You are not using the iterator indexes properly to sort the elements of vector. If you change your function bubbleSort as follows it will work
//Sorting
void bubbleSort(vector<int> & data)
{
             int size = data.size();
            for (int k = 1; k < size; k++)
            {
                for (int i = 0; i<size -1 ; i++)
                {
                    if (data[i] > data[k])
                    {
                        int temp = data[i];
                        data[i] = data[k];
                        data[k] = temp;
                    }
                    //cout<<"Sorted vector: "<< data[i]<<endl;
                }
            }
}
complete program for your reference:
#include <iostream>
#include <vector>
#include <cmath>
#include <numeric>
using namespace std;

 //Sorting
 void bubbleSort(vector<int> & data)
    {
         int size = data.size();
        for (int k = 1; k < size; k++)
        {
            for (int i = 0; i<size -1 ; i++)
            {
                if (data[i] > data[k])
                {
                    int temp = data[i];
                    data[i] = data[k];
                    data[k] = temp;
                }
                //cout<<"Sorted vector: "<< data[i]<<endl;
            }
        }
    }

int main()
{
    int n;
    //double average=0.0;
    //int median = 0;
    //double size = 0.0;
    //int i=0;

    cout<<"Vector Length?: "<<endl;
    cin>>n;
   // int n =10;
    vector<int> data;
    srand(time(NULL));

    //Filling vector
    for (int i=0; i<n; i++)
    {
        data.push_back(rand()%10+1);
    }
    for (unsigned int i=0; i<data.size(); i++)
    {
        cout<<"Vector: "<< data[i]<<endl;
    }

    bubbleSort(data);
    std::cout<<"sorted vector"<<"\n";
     for (unsigned int i=0; i<data.size(); i++)
    {
        cout<<"Vector: "<< data[i]<<endl;
    }

}

A: #include <iostream>
#include <vector>
#include <cmath>
#include <numeric>
using namespace std;

void printVector(vector<int> & data)
{
    for (int i=0; i<data.size(); i++)
    {
        cout<<"Vector: "<< data[i]<<endl;
    }
}

//Sorting
void bubbleSort(vector<int> & data);
{
    size = data.size();
    for (int k = 1; k < size; k++)
    {
        for (int i = 0; i<size -1 - k; i++)
        {
            if (data[i] > data[i +1])
            {
                int temp = data[i];
                data[i] = data[i + 1];
                data[i + 1] = temp;
            }
        }
    }
}

int main()
{
    int n;
    double average=0.0;
    int median = 0;
    double size = 0.0;
    int i=0;

    cout<<"Vector Length?: "<<endl;
    cin>>n;
    vector<int> data;
    srand(time(NULL));

    //Filling vector
    for (int i=0; i<n; i++)
    {
        data.push_back(rand()%10+1);
    }
    printVector(data);
    bubbleSort(data);
    printVector(data);

}

A: First off:

*

*make sure to include all necessary header files, e.g. stdlib.h for your used rand() function.

*get rid of all unused variables, like average, median and size.

*declare your bubbleSort function outside of main function, and add additional checkup code to prevent sort if list has not more than one element.

The sort problem is related to this code snippet of yours:
for (int i = 0; i<size -1 - k; i++) { ... }

Simply remove -1

To fix your sort problem, and for better output, use following code:
#include <iostream>
#include <stdlib.h>
#include <vector>
#include <cmath>

using namespace std;

void bubbleSort(vector<int>& data)
{
    if(data.size() <= 1)
        return;

    for(int i=1; i<data.size(); i++)
    {
        for(int j=0; j<data.size()-i; j++)
        {
            if(data.at(j) > data.at(j+1))
            {
                int temp = data.at(j+1);
                data.at(j+1) = data.at(j);
                data.at(j) = temp;
            }
        }
    }
}

int main()
{
    int n;
    vector<int> data;

    cout << "Vector Length?: ";
    cin >> n;

    // Filling vector
    for(int i=0; i<n; i++)
        data.push_back(rand()%10+1);

    cout << "Vector: ";
    for(int i=0; i<data.size(); i++)
        cout << data.at(i) << ", ";

    // Sorting
    bubbleSort(data);

    cout << endl << "Sorted Vector: ";
    for(int i=0; i<data.size(); i++)
        cout << data.at(i) << ", ";

    return 0;
}

Hope this helps ;)


text:
Q: Spring WebFlux + MongoDB: Tailable Cursor and Aggregation I´m new with WebFlux and MongoDB. I´m trying to use aggregation in a capped collection with tailable cursor, but I´m nothing getting sucessful.
I´d like to execute this mongoDB query:
db.structures.aggregate(
   [
     {
        $match: {
            id: { $in: [8244, 8052]}
        }
     },
     { $sort: { id: 1, lastUpdate: 1} },
     {
       $group:
         {
           _id: {id: "$id"},
           lastUpdate: { $last: "$lastUpdate" }
         }
     }
   ]
)

ReactiveMongoOperations gives me option to "tail" or "aggregation".
I´m able to execute aggregation:
    MatchOperation match = new MatchOperation(Criteria.where("id").in(8244, 8052));
    GroupOperation group = Aggregation.group("id", "$id").last("$lastUpdate").as("lastUpdate");
    Aggregation aggregate = Aggregation.newAggregation(match, group);

    Flux<Structure> result = mongoOperation.aggregate(aggregate,
            "structures", Structure.class);

Or tail cursor
    Query query = new Query();
    query.addCriteria(Criteria.where("id").in(8244, 8052));
    Flux<Structure> result = mongoOperation.tail(query, Structure.class);

Is it possible? Tail and Aggregation together?
Using aggregation was the way that I found to get only the last inserted document for each id.
Without aggregation I get:
query without aggregation
With aggregation:
query with aggregation
Tks in advance

A: The tailable cursor query creates a Flux that never completes (never emits onComplete event) and that Flux emits records as they are inserted in the database. Because of that fact I would think aggregations are not allowed by the database engine with the tailable cursor.
So the aggregation doesn't make sense in a way because on every newly inserted record the aggregation would need to be recomputed. Technically you can do a running aggregation where for every returned record you compute the wanted aggregate record and send it downstream.
One possible solution would be to do the aggregations programmatically on the returned "infinite" Flux:
mongoOperation.tail(query, Structure.class)
  .groupBy(Structure::id) // create independent Fluxes based on id
  .flatMap(groupedFlux ->
    groupedFlux.scan((result, nextStructure) -> { // scan is like reduce but emits intermediate results
    log.info("intermediate result is: {}", result);
    if (result.getLastUpdate() > nextStructure.getLastUpdate()) {
        return result;
    } else {
        result.setLastUpdate(nextStructure.getLastUpdate());
        return result;
    }
}));

On the other hand you should probably revisit your use case and what you need to accomplish here and see if something other than capped collection should be used or maybe the aggregation part is redundant (i.e. if newly inserted records always have the lastUpdate property larger then the previous record).