text:
Q: Conditions for a binary matrix where all of its rows are different Given a $(0, 1)$ matrix of order $n\times m$, we say the matrix is valid if it satisfies the following rules:

*

*Each column has exactly two ones.

*All columns are different.

Question: Given a fixed $n$, what is the maximum $m$ such that it's impossible to construct a valid matrix with less than $m$ columns where all $n$ rows are different? Let's call $m^*$ to such maximum $m$.
I write $(a, b)_c$ to mean that at column $c$ its two $1$s are placed on the rows $a$ and $b$, and I also say that $a$ and $b$ are connected by the column $c$. If the row $r$ has $k$ ones, I say that the degree of $r$ is $k$, and I also say that a row is empty if its degree is $0$.
The trivial facts are that for $n=1$ no valid matrix is possible and that for $n=2$ no matrix with two different rows is possible. So I'm interested on $n\geq 3$ only.

A: This problem have the property that two rows are equal iff they are both empty or if they have both degree $1$ and connected by the same column (that means that any row with degree $\geq 2$ is guaranteed to be unique). With these properties in mind, this problem can be translated to a graph problem in the following way (the graph doesn't need to be connected):

*

*Take each row as a vertex.

*Take each column as an edge.

A valid matrix with $m$ columns and all rows different is a graph with $m$ edges, with at most one isolated vertex and without isolated edges. $m^*$ is then the size of a graph of lowest possible size that still have these properties.
Any such graph can be minimized by removing, for each connected component, any excedent edge until the component becomes a tree. Which means the optimal graph must be a forest. Since the number of edges is irrespective of the specific arrangement of each tree, let's consider that each component is a star graph.
Since any tree of order $x+1$ have $x$ edges under the above procedure, the question is if the optimal graph is one with a maximum number of components/trees (so reducing each $x$), or if there's an "optimal balance" between the number of components and the order of each component.
That's the core of the question.
We can turn this question as an optimization problem in the following way: let $e\in\{0, 1\}$ be a variable that represents the existance of an isolated vertex ($e=0$ means no isolated vertex exists in the graph; $e=1$ means one isolated vertex exists in the graph), and $h_x$ a variable whose value is the number of components with exactly $x$ edges. Since components consisting on a single edge aren't allowed, and no component can have more than $n$ vertices, then $2\leq x\leq n-1$.
So the problem is: $$
\begin{split}
\min\quad& m=\sum_{i=2}^{n-1} ih_i\\
\text{s.t.}\quad&
n=e+\sum_{i=2}^{n-1} (i+1)h_i
\end{split}
$$
which has been solved here (but I'd like to know how to shorten the proof or if any other approach is possible): Maximizing a sum of products restricted to another sum of products
The conclusion is that to minimize the number of edges you have to maximize the number of components, which requires maximizing the number of components of order 3 (e.g., claws), and using at most one isolated vertex (when $n$ doesn't divide $3$) and at most one component of order 4 (when the remainder of $n/3$ is 2).
All of this means that it's impossible to build a valid matrix with less than $m^*=\lfloor 2n/3\rfloor$ columns such that all rows are different.


text:
Q: How to find angle between two vectors on canvas? I need to find the angle between two vectors on my canvas.
I have attached some examples below:

Could you advise me some formula? I have problems with school math :)

A: Basically you need to make the point which connects your two vectors the origin, where x=0 and y=0.
Take a look at this picture:

Now we can say that the x and y values of the points A, B and C are:

*

*A = 0|0

*B = 0|-6

*C = 5|2

To calculate the arctangent of both we can utilize the Math.atan2() function. Please note that the first parameter for atan2 must be the y value.
var firstAngle = Math.atan2(-6, 0);
var secondAngle = Math.atan2(2, 5);

and get the difference of them by subtraction
var angle = secondAngle - firstAngle;

This will return a radian value you can convert to degrees like this:
angle = angle * 180 / Math.PI;

A: First you'll need to normalize the two vectors.
Once that's done you can do
angle = arcos(v1•v2)

where "angle" is the angle you want to find, "arcos" is the inverse of cosine function and the "•" is the dot product operator
Be careful, this will return only the relative and raw angle. You won't be able to know which vector is on the left and which one is on the right.

A: If you need 2D (z=0) and 3D support, you could use the Dot product
const dot = (p1, p2) => p1.x * p2.x + p1.y * p2.y + p1.z * p2.z;

With a square magnitude (magSq), we can calc the magnitude: mag = Math.sqrt(magSq)
const magSq = ({x, y, z}) => x ** 2 + y ** 2 + z ** 2;
const mag = Math.sqrt(magSq(p));

Now we can calc the Dot product and "normalize" it afterwards.
Now use acos() to get the angle:
const angle = Math.acos(dot(p1, p2) / Math.sqrt(magSq(p1) * magSq(p2)));

We could also use Math.hypot(), a dedicated JS function for mag:
const mag = (p) => Math.hypot(p.x, p.y, p.z);

… and get the angle:
const angle = Math.acos(dot(p1, p2) / (mag(p1) * mag(p2)));

Example:

let a = {x: 0, y: -6, z: 0};
let b = {x: 5, y: 2, z: 0}; // set z != 0 for 3D

let dot = (p1, p2)=>  p1.x * p2.x + p1.y * p2.y + p1.z * p2.z;
let magSq = ({x, y, z}) => x ** 2 + y ** 2 + z ** 2;

let angle1 = Math.acos(dot(a, b) / Math.sqrt(magSq(a) * magSq(b)));
console.log('1. Angle:', angle1);                                        // 1.9513027

// ... or
let mag = ({x, y, z}) => Math.hypot(x, y, z);

let angle2 = Math.acos(dot(a, b) / (mag(a) * mag(b)))
console.log('2. Angle:', angle2);                                        // 1.9513027

A: Old question. But I found good solution. Let say we have 4 points form 2 vectors. Points (P0, P1, P2, P3), then the angle of P0P1 and P2P3 is:
function angle2Vectors(ps) {
  const v1 = { x: ps[1].x - ps[0].x, y: ps[1].y - ps[0].y };
  const v2 = { x: ps[3].x - ps[2].x, y: ps[3].y - ps[2].y };
  const l1_l2 = len(ps[1], ps[0]) * len(ps[3], ps[2]);
  const v1_v2 = v1.x * v2.x + v1.y * v2.y;
  const cos = v1_v2 / (len(ps[1], ps[0]) * len(ps[3], ps[2]));
  const angCos = Math.acos(cos) * (180 / Math.PI);
  const _v1_v2_ = v1.x * v2.y - v2.x * v1.y;
  const sin = _v1_v2_ / l1_l2;
  const angSin = Math.asin(sin) * (180 / Math.PI);
  return angCos * Math.sign(angSin);
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to add a new element to the numbered array I'm trying to add a new element to the numbered array, which already has elements in it. One element added, but if I try to add the next one it only replace existed one.
$arr = mixOfArray($arr_assoc_woman);
if(in_array($userName, $arr_assoc_man)) {
    $rand = array_rand($arr, 1);
    echo "
$userName + $arr_assoc_woman[$rand] = Happy Couple!
";
} else {
    $numb = count($arr_assoc_man);
    print($numb);
    $arr_assoc_man[$numb] = $userName;
    $arr_assoc_man += $arr_assoc_man;
    $arr = mixOfArray($arr_assoc_woman);
    $rand = array_rand($arr, 1);
    echo "
$userName + $arr_assoc_woman[$rand] = Happy Couple!
";
}

A: try using [] instead of your define key if it's auto numbering.
replace $arr_assoc_man[$numb] to $arr_assoc_man[]

A: you are using an indexed array.In indexed array php numbers each array element automatically, beginning from 0 (first element of an array) upto number of elements. To add a new element to the end of the array, use a pair of empty
square brackets like this:
$arr_assoc_woman[] = "$value";
php uses the next available number, so this becomes $arr_assoc_woman[(here is the number assigned by php)].

A: To add an extra element to the current array you can use array_push() function.
<?php
    $stack = array("orange", "banana");
    array_push($stack, "apple", "raspberry");

    print_r($stack);
?>


text:
Q: How to prevent yq removing comments and empty lines? Here Edit yaml objects in array with yq. Speed up Terminalizer's terminal cast (record) I asked about how to edit yaml with yq. I received the best answer. But by default yq removes comments and empty lines. How to prevent this behavior?
input.yml
# Specify a command to be executed
# like `/bin/bash -l`, `ls`, or any other commands
# the default is bash for Linux
# or powershell.exe for Windows
command: fish -l

# Specify the current working directory path
# the default is the current working directory path
cwd: null

# Export additional ENV variables
env:
  recording: true

# Explicitly set the number of columns
# or use `auto` to take the current
# number of columns of your shell
cols: 110

execute
yq -y . input.yml

result
command: fish -l
cwd: null
env:
  recording: true
cols: 110

A: In some limited cases you could use diff/patch along with yq.
For example if input.yml contains your input text, the commands
$ yq -y . input.yml > input.yml.1
$ yq -y .env.recording=false input.yml > input.yml.2
$ diff input.yml.1 input.yml.2 > input.yml.diff
$ patch -o input.yml.new input.yml < input.yml.diff

creates a file input.yml.new with comments preserved but
recording changed to false:
# Specify a command to be executed
# like `/bin/bash -l`, `ls`, or any other commands
# the default is bash for Linux
# or powershell.exe for Windows
command: fish -l

# Specify the current working directory path
# the default is the current working directory path
cwd: null

# Export additional ENV variables
env:
  recording: false

# Explicitly set the number of columns
# or use `auto` to take the current
# number of columns of your shell
cols: 110

A: This is improvement of How to prevent yq removing comments and empty lines? comment.
In mine case was no enough diff -B and diff -wB as it still does not keep blank lines and keep generate an entire file difference as a single chunk instead of many small chunks.
Here is example of the input (test.yml):
# This file is automatically generated
#

content-index:

  timestamp: 1970-01-01T00:00:00Z

  entries:

    - dirs:

        - dir: dir-1/dir-2

          files:

            - file: file-1.dat
              md5-hash:
              timestamp: 1970-01-01T00:00:00Z

            - file: file-2.dat
              md5-hash:
              timestamp:

            - file: file-3.dat
              md5-hash:
              timestamp:

        - dir: dir-1/dir-2/dir-3

          files:

            - file: file-1.dat
              md5-hash:
              timestamp:

            - file: file-2.dat
              md5-hash:
              timestamp:

If try to edit a field and generate the difference file:
diff -B test.yml <(yq -y ".\"content-index\".timestamp=\"2022-01-01T00:00:00Z\"" test.yml)

It does keep remove blank lines:
5,7c2
<
<   timestamp: 1970-01-01T00:00:00Z
<
---
>   timestamp: '2022-01-01T00:00:00Z'

Adds everywhere null instead of an empty field and changes the rest of timestamp fields (which means you have to use '...' to retain these as is):
17,19c8,9
<               md5-hash:
<               timestamp: 1970-01-01T00:00:00Z
<
---
>               md5-hash: null
>               timestamp: '1970-01-01T00:00:00+00:00'

The -wB flags changes the difference file from a single chunk into multiple chunks, but still does remove blank lines.
Here is a mention of that diff issue: https://unix.stackexchange.com/questions/423186/diff-how-to-ignore-empty-lines/423188#423188
To fix that you have to use it with grep:
diff -wB <(grep -vE '^\s*$' test.yml) <(yq -y ".\"content-index\".timestamp=\"2022-01-01T00:00:00Z\"" test.yml)

But nevertheless it still does remove comments:
1,2d0
< # This file is automatically generated
< #

Here is solution for that: https://unix.stackexchange.com/questions/17040/how-to-diff-files-ignoring-comments-lines-starting-with/17044#17044
So the complete oneliner is:
diff -wB <(grep -vE '^\s*(#|$)' test.yml) <(yq -y ".\"content-index\".timestamp=\"2022-01-01T00:00:00Z\"" test.yml) | patch -o - test.yml 2>/dev/null

Where 2>/dev/null stands to ignore patch warnings like:
Hunk #1 succeeded at 6 (offset 4 lines).

To avoid it in real code, you can use the -s flag instead:
... | patch -s -o ...

Update:

CAUTION:
This is the previous implementation and has an issue with a line addition to the yaml file and left as an example of implementation. Search for more reliable implementation in the Update 2 section.

There is a better implementation as a shell script for GitHub Actions pipeline composite action.
GitHub Composite action: https://github.com/andry81-devops/gh-action--accum-content
Bash scripts (previous implementation):
Implementation: https://github.com/andry81-devops/gh-workflow/blob/ee5d2d5b6bf59299e39baa16bb85357cf34a8561/bash/github/init-yq-workflow.sh
Example of usage: https://github.com/andry81-devops/gh-workflow/blob/9b9d01a9b60a65d6c3c29f5b4b200409fc6a0aed/bash/cache/accum-content.sh
The implementation can use 2 of yq implementations:

*

*https://github.com/kislyuk/yq     - a jq wrapper (default Cygwin distribution)

*https://github.com/mikefarah/yq   - Go implementation (default Ubuntu 20.04 distribution)

Search for: yq_edit, yq_diff, yq_patch functions
Update 2:
There is another discussion with some more reliable workarounds:
yq write strips completely blank lines from the output : https://github.com/mikefarah/yq/issues/515
Bash scripts (new implementation):
Implementation: https://github.com/andry81-devops/gh-workflow/blob/master/bash/github/init-yq-workflow.sh
Example of usage: https://github.com/andry81-devops/gh-workflow/blob/master/bash/cache/accum-content.sh
# Usage example:
#
>yq_edit "<prefix-name>" "<suffix-name>" "<input-yaml>" "$TEMP_DIR/<output-yaml-edited>" \
  <list-of-yq-eval-strings> && \
  yq_diff "$TEMP_DIR/<output-yaml-edited>" "<input-yaml>" "$TEMP_DIR/<output-diff-edited>" && \
  yq_restore_edited_uniform_diff "$TEMP_DIR/<output-diff-edited>" "$TEMP_DIR/<output-diff-edited-restored>" && \
  yq_patch "$TEMP_DIR/<output-yaml-edited>" "$TEMP_DIR/<output-diff-edited-restored>" "$TEMP_DIR/<output-yaml-edited-restored>" "<output-yaml>"
#
# , where:
#
#   <prefix-name> - prefix name part for files in the temporary directory
#   <suffix-name> - suffix name part for files in the temporary directory
#
#   <input-yaml>  - input yaml file path
#   <output-yaml> - output yaml file path
#
#   <output-yaml-edited>          - output file name of edited yaml
#   <output-diff-edited>          - output file name of difference file generated from edited yaml
#   <output-diff-edited-restored> - output file name of restored difference file generated from original difference file
#   <output-yaml-edited-restored> - output file name of restored yaml file stored as intermediate temporary file

Example with test.yml from above:
export GH_WORKFLOW_ROOT='<path-to-gh-workflow-root>' # https://github.com/andry81-devops/gh-workflow

source "$GH_WORKFLOW_ROOT/bash/github/init-yq-workflow.sh"

[[ -d "./temp" ]] || mkdir "./temp"

export TEMP_DIR="./temp"

yq_edit 'content-index' 'edit' "test.yml" "$TEMP_DIR/test-edited.yml" \
  ".\"content-index\".timestamp=\"2022-01-01T00:00:00Z\"" && \
  yq_diff "$TEMP_DIR/test-edited.yml" "test.yml" "$TEMP_DIR/test-edited.diff" && \
  yq_restore_edited_uniform_diff "$TEMP_DIR/test-edited.diff" "$TEMP_DIR/test-edited-restored.diff" && \
  yq_patch "$TEMP_DIR/test-edited.yml" "$TEMP_DIR/test-edited-restored.diff" "$TEMP_DIR/test.yml" "test-patched.yml" || exit $?

PROs:

*

*Can restore blank lines together with standalone comment lines:  # ...

*Can restore line end comments:   key: value # ...

*Can detect a line remove/change/add altogether.

CONs:

*

*Because of has having a guess logic, may leave artefacts or invalid corrections.

*Does not restore line end comments, where the yaml data is changed.


text: Q: CentOS Server How to Keep PHP Socket Server running? I have tried the nohup php socket.php & and the server does start and remain started after the ssh window is closed. But when I got back a while later, its not running again. How can I keep this running?


text:
Q: Wakanda: trying to connect to an remote MySQL database I'm trying to connect to an remote MySQL database. When I created new mySql datastore model, Data classes were shown in designer (read-only).
When i started the app following errors were displayed:
Wakanda Enterprise Server Errors
With Built-in DB everything was fine.
What could be the problem?

A: In order to use remote database, you need an enterprise version of wakanda and therefor a license as the first line of your error states.

License not found. Server running in community mode.

You can get a license on wakanda.io.


text:
Q: Trying to do a loop on worksheets while pasting a value from an array on the same row/column of each sheet I am trying to figure out how to loop through worksheets, then paste for example value 1 from an array on sheet 1 in A2, value 2 from array on sheet 2 in A2 and so on.
Does anyone have an idea of how I can do this in VBA?


text:
Q: Git re-do the last add and commit Currently I am implementing some git hooks that clears my notebook cells when committing. Unfortunately, after committing the script fails (because the files are cleaned and interpreted as new files, which makes sense). Thus, I need to re-do the add & commit command for the exact same files.
Is there any way to automate this? Or at least how can I re-do the same add and commit of the same files again.


text:
Q: HoloViews Chord Diagram Edge Colour Gradient I am visualizing a Network with undirected links via Holoviews' Chord Diagram. Unfortunately, I can't find any option to choose a colour gradient for edges/links (to visualize that connections don't have directionality). Is there a solution or workaround for this?
Reference:


text:
Q: Group an image with text in an un-word-wrappable group in HTML5 In HTML, is it possible to have a group of an image and text that cannot be broken by word wrapping? i.e. would either be rendered together on one line, or wrap together to the next?
This can be done with words, by using   but I want to add a small, letter sized icon to this group.
Example:

  Some some normal, wrappable text
  &nsbp;Product Name

NB. for brevity I have removed the attributes from the  tags.
Currently, it is possible for the "logo.png" image to appear on one line, and "Product Name" on the next.
This code is part of a resizable element, sometimes it will be capable of being rendered on 1 line, others it will need to, so I don't want to force a
 for the times it is not needed.

A: Extending from comment:
As you want to combine logo and product name as a whole "un-wrappable" part, you can use white-space:nowrap:
fiddle
.unbreakable
{
  white-space:nowrap;
}


text:
Q: Reporting Services 2008 - Long subreports cause page break Similar to this question, but I have one "master" report which contains many subreports. Everything works great until one of the subreports, when rendered (to PDF, for example), will take up > the space left on a page.  In this case, the page breaks so that the subreport starts on a new page.  Sometimes this looks incredibly awkward when the one report only takes up a little bit of room on one page, then it breaks to the next page because the following subreport is too long.  Any suggestions?  It is not a width/margin problem, because when all of the subreports are short, it looks fine.  Also, I am using HTML placeholders, and I do not have any margins set on the subreports, nor do I have any of these checked:

*

*Add a page break before

*Add a page break after

*Keep contents on a single page, if possible

A: Check the MS article KB938943, I was unable to fix this...

A: In Reporting Services 2008, there is a new property on the Subreport called KeepTogether. This was always True in 2005 with no way to change it. We've had great success in getting rid of blank space and blank pages in 2008 (with exception to dynamic height property on charts, but thats another ticket).
Also check for KeepTogether on your grids, rectangles, etc.. and turn them all to False when you don't want them to stay together.

A: Do you have any groupings in the subreports that specify page breaks? If so, this may cause the page break. regardless of the settings in the 'master' report.


text:
Q: Problems when viewing a DWG file translated to an SVF file with Autodesk Forge Viewer API I'm trying to visualize a DWG file with the Forge Viewer.The translation into SVF format is all clear and smooth.
If it's not clear, graphically the SVF looks exactly the same as the DWG file when visualized with Autodesk Electrical, it's just that some of the "line" components are considered as fragmented into more and unrelated "line" components.
For example if I had one line in the DWG file, on the SVF visualized on the Viewer this line is fragmented into more lines that don't even have an attribute that relates them to each other.
I tried checking the metadata of the SVF file and there is no "parental" relation with this group of lines.
As a solution I was thinking to add an attribute to the lines in Autodesk Electrical, which would be the same for each "subline" that is part of a "line", though I was wondering if this could be a problem I could fix through the translation process in Forge.

A: Is it actual straight line segments that are being split into multiple lines? Note that the SVF format can handle line segments, circular arcs, and elliptical arcs, but more general curves have to be tessellated into line segments.
As for attaching data to these drawing elements, you could potentially store the data separately from the SVF/F2D file, and link them to the drawing elements through their ACad handles or the SVF "dbIDs".


text:
Q: Input into form, output into iframe URL I am trying to get a map search where the user inputs the location they want and it appears in an iframe below, so user looks for London and the URL would bring back google.com/maps&location=london. I cannot get the output part to work so far;
I feel I am so close just can't work out how to move the location to the iFrame

            <form class="lookup-form">
                <input type="text" class="postcode" placeholder="Location" >
                <input type="submit" class="go-btn" value="Search"/>
                Search

            </form>

A: So you just need to be able to pass the location to the src?
Use $('#selector').attr('src', value);
Also, your var declaration used the wrong selector to get the value.
}else if(error === false)  {
     jQuery('.form-error').hide();
     jQuery('.postcode-wrapper .go').click(function(){
          jQuery(".search-results").slideDown("slow");
     });

     var location = encodeURIComponent(jQuery('.postcode').val());  // Fix your selector
     console.log(location);
     $('iframe').attr('src', 'https://google.com/maps&location=' + location); // Add this
     jQuery('.postcode-wrapper .go').click();
}

And one last thing, I believe the url is wrong and it should be
https://www.google.com/maps/place/locationvariable.


text:
Q: How to format special characters inserted into a Jinja2 template? I want to insert a bullet into an HTML file generated by a Jinja2 template. The Python code sends the string
'●'

but when in the HTML code it's generated as
●

so the reader sees the code for the special character, no the special character itself?

A: I think you have to use the safe filter to prevent Jinja from auto-escaping.


text:
Q: Bind previous value to input field while using common form for update and add I am using common form for add and update data.
When I am click on edit form and change input field value,but then I close the form.
Then the previous value should be display in table not the updated as I have not clicked on update form.
Can someone provide the solution for this. thanx in advance.
Here is html
 <form [formGroup]="addEducationForm">

                GPA
                <input type="number" formControlName="gpa" class="form-control" [readonly]="educationObjectAccess.gpa === 'read'" [(ngModel)]="educationData.gpa"
                    [ngClass]="{ 'is-invalid': submitted && education.gpa.errors && educationObjectAccess.gpa !== 'none'}" />

GPA is required

 </form>

A: Don't bind the value to ngModel as this updates the model with each change which is not what you want.
I would suggest keeping a separate myFormValues object which you update only when the user explicitly presses your update button.

onUpdate(): void{

  this.myFormValues = Object.assign( ...this.myFormValues, ...this.addEducationForm.value )

}

A: I solved the problem by self.
<form [formGroup]="addEducationForm">

                GPA
                <input type="number" formControlName="gpa" class="form-control" [readonly]="educationObjectAccess.gpa === 'read'" [(ngModel)]="educationData.gpa"
                    [ngClass]="{ 'is-invalid': submitted && education.gpa.errors && educationObjectAccess.gpa !== 'none'}" />

GPA is required

 </form>

replace round brackets in ngModel as it acts as both input/output.
instead of [(ngModel)] write [ngModel].


text:
Q: Java Fibonocci sequence BigInteger I am trying to run a program which find the nth sequence in the Fibonacci series; however, the issue is, I want to implement BigInteger in it so it can run values of 1000 or even more.
Is there any way to efficiently add it in?
import java.util.*;
import java.math.*;
public class fib {
//Arkham
    /*public static BigInteger fibonacci2(int n) {
    if (n == 0 || n == 1) {
        return BigInteger.ONE;
    }
    return fibonacci2(n - 2).add(fibonacci2(n-1));
}*/

    public static int Fibonacci(int n) {

        int num = Math.abs(n);
        if (num == 0) {
            return 0;
        }
        else if (num <= 2) {
            return 1;
        }

        int[][] number = { { 1, 1 }, { 1, 0 } };
        int[][] result = { { 1, 1 }, { 1, 0 } };

        while (num > 0) {
            if (num%2 == 1) result = MultiplyMatrix(result, number);
            number = MultiplyMatrix(number, number);
            num/= 2;
        }
        return result[1][1]*((n < 0) ? -1:1);
    }

    public static int[][] MultiplyMatrix(int[][] mat1, int[][] mat2) {
        return new int[][] {
                { mat1[0][0]*mat2[0][0] + mat1[0][1]*mat2[1][0],
                  mat1[0][0]*mat2[0][1] + mat1[0][1]*mat2[1][1] },
                { mat1[1][0]*mat2[0][0] + mat1[1][1]*mat2[1][0],
                  mat1[1][0]*mat2[0][1] + mat1[1][1]*mat2[1][1] }
        };
    }

    public static void main(String[] args) {

        Scanner reader = new Scanner(System.in);  // Reading from System.in
        System.out.println("Enter a number: ");
        int n = reader.nextInt();

        System.out.println("\n" + Fibonacci(n));
    }
}

A: when you replace int by BigIntegeryou should do some changes, however, I changed your code and came up with a something like this :
   public static BigInteger FibonacciB(int n) {
    final BigInteger one = BigInteger.ONE;
    final BigInteger zero = BigInteger.ZERO;
    final BigInteger two = new BigInteger(String.valueOf(2));
    final BigInteger minusOne = one.negate();

    BigInteger num = new BigInteger(String.valueOf(n));

    if (num.equals(zero)) {
        return zero;
    } else if (num.compareTo(two) <= 0) {
        return one;
    }

    BigInteger[][] number = {{one, one}, {one, zero}};
    BigInteger[][] result = {{one, one}, {one, zero}};

    while (num.compareTo(zero) > 0) {
        if (num.mod(two).equals(one)) result = MultiplyMatrixB(result, number);
        number = MultiplyMatrixB(number, number);
        num = num.divide(two);
    }

    if (num.compareTo(zero) < 0)
        return result[1][1].multiply(minusOne);
    return result[1][1];

}

// the matrix mutltiplier method :
  public static BigInteger[][] MultiplyMatrixB(BigInteger[][] mat1, BigInteger[][] mat2) {

    return new BigInteger[][]{
            {(mat1[0][0].multiply(mat2[0][0])).add((mat1[0][1].multiply(mat2[1][0]))),
                    (mat1[0][0].multiply(mat2[0][1])).add((mat1[0][1].multiply(mat2[1][1])))
            },
            {
                    (mat1[1][0].multiply(mat2[0][0])).add((mat1[1][1].multiply(mat2[1][0]))),
                    (mat1[1][0].multiply(mat2[0][1])).add((mat1[1][1].multiply(mat2[1][1])))
            }
    };
}

I hope this would help you

A: Is java the correct tool for this? Perhaps Kotlin would work better:
  tailrec fun fibonacci(i:BigInteger, current:BigInteger=zero, next:BigInteger=one):BigInteger {
    return if (i == zero) current else iterate(i - one, next, current + next)
  }

(taken from https://github.com/russel/Fibonacci/blob/master/Kotlin/src/main/kotlin/uk/org/winder/maths/fibonacci/fibonacci.kt)


text:
Q: Replace one occurrence with regexp I want to replace a only one instance with a regex rather than all of them. How would I do this with Go's regexp library?
input: foobar1xfoobar2x
regex: bar(.)x
replacement: baz$1
ReplaceAllString output: foobaz1foobaz2
ReplaceOneString output: foobaz1foobar2x

A: In general, if you use lazy match and use anchors for beginning and end, you can have the replace first behavior:
replace `^(.*?)bar(.*)$` with `$1baz$2`.

Example:
package main

import (
    "fmt"
    "regexp"
)

func main() {
    src := "foobar1xfoobar2x"
    pat := regexp.MustCompile("^(.*?)bar(.*)$")
        repl := "${1}baz$2"
    output := pat.ReplaceAllString(src, repl)
    fmt.Println(output)
}

Output
foobaz1xfoobar2x

A: I had the same problem. The most clean solution I've come up with:
package main

import (
    "fmt"
    "regexp"
    "strings"
)

func main() {
    re, _ := regexp.Compile("[a-z]{3}")
    s := "aaa bbb ccc"

    // Replace all strings
    fmt.Println(re.ReplaceAllString(s, "000"))

    // Replace one string
    found := re.FindString(s)
    if found != "" {
        fmt.Println(strings.Replace(s, found, "000", 1))
    }
}

Running:
$ go run test.go
000 000 000
000 bbb ccc

A: I cound't use accepted solution because my pattern was very complicated.
I ended up with using ReplaceAllStringFunc :
https://play.golang.org/p/ihtuIU-WEYG
package main

import (
    "fmt"
    "regexp"
)

var pat = regexp.MustCompile("bar(.)(x)")

func main() {
    src := "foobar1xfoobar2x"
    flag := false
    output := pat.ReplaceAllStringFunc(src, func(a string) string {
        if flag {
            return a
        }
        flag = true
        return pat.ReplaceAllString(a, "baz$1$2")
    })
    fmt.Println(output)
}


text:
Q: How to reset text on automatically created buttons android studio I am currently implementing a tic tac toe game for Android in one of my class. When a player clicks one of the "grid" buttons, the button Text is set to whichever symbol this player is (X or O). One of the requirements is to have our game buttons generated automatically on start. So none of the grid buttons have actual ids before the start of the app.
No problem here, until I have to reinitialize the game. Once a winner is declared, I need to reset the grid buttons' text so that it doesn't show X or O on any of them anymore. The thing is, the buttons don't have any ID so it's not as easy as
button.setText("");
I should also add that our professor wants us to use our own Button class (BoutonCase) that implements onClickListener and inherits from Button. Not that it matters in this case. Here's a portion of the code.
public class ticTacToeFragment extends Fragment implements View.OnClickListener {

int compteur = 0;
LinearLayout ligneColonne1;
LinearLayout ligneColonne2;
LinearLayout ligneColonne3;
boolean JOUEUR_X = true;
int[][] statutJeu = new int[3][3];
Button btnReinitialiser;

@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
                         final Bundle savedInstanceState){

    View v = inflater.inflate(R.layout.fragment_tictactoe, container, false);
    int cpt = 0;
    ligneColonne1 = (LinearLayout) v.findViewById(R.id.ligne1);
    ligneColonne2 = (LinearLayout) v.findViewById(R.id.ligne2);
    ligneColonne3 = (LinearLayout) v.findViewById(R.id.ligne3);
    btnReinitialiser = (Button) v.findViewById(R.id.btnReinit);

    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);

    btnReinitialiser.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v){
            reinitialiserJeu();
        }
    });

    for(int i = 0; i < 3; i++ ){
        final BoutonCase button = new BoutonCase(this.getContext());
        button.setId(cpt);
        final int positionCourante = i;
        button.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v){
                if(JOUEUR_X){
                    button.setText("X");
                    statutJeu[1][positionCourante] = 1;
                    JOUEUR_X = false;
                }
                else{
                    button.setText("0");
                    statutJeu[1][positionCourante] = 3;
                    JOUEUR_X = true;
                }
                button.setEnabled(false);
                verifierGagnant();
            }
        });
        ligneColonne1.addView(button, lp);
        cpt++;
    }

    for(int i = 0; i < 3; i++ ){
        final BoutonCase button = new BoutonCase(this.getContext());
        button.setId(cpt);
        final int positionCourante = i;
        button.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v){
                if(JOUEUR_X){
                    button.setText("X");
                    statutJeu[1][positionCourante] = 1;
                    JOUEUR_X = false;
                }
                else{
                    button.setText("0");
                    statutJeu[1][positionCourante] = 3;
                    JOUEUR_X = true;
                }
                button.setEnabled(false);
                verifierGagnant();
            }
        });
        ligneColonne2.addView(button, lp);
        cpt++;
    }

    for(int i = 0; i < 3; i++ ){
        final BoutonCase button = new BoutonCase(this.getContext());
        button.setId(cpt);
        final int positionCourante = i;
        button.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v){
                if(JOUEUR_X){
                    button.setText("X");
                    statutJeu[2][positionCourante] = 1;
                    JOUEUR_X = false;
                }
                else{
                    button.setText("0");
                    statutJeu[2][positionCourante] = 3;
                    JOUEUR_X = true;
                }
                button.setEnabled(false);
                verifierGagnant();
            }
        });
        ligneColonne3.addView(button, lp);
        cpt++;
    }

    final Button button = new Button(this.getContext());
    button.setId(cpt);
    button.setOnClickListener(new View.OnClickListener(){

        @Override
        public void onClick(View v){
            onCreateView(inflater,container,savedInstanceState);
        }
    });return v;
}

public void onClick(View v){
}

void verifierGagnant(){
    //Horizontal --- row
    Toast toastGagnant;
    for(int i=0; i<3; i++){
        if(statutJeu[i][0] == statutJeu[i][1] && statutJeu[i][0] == statutJeu[i][2]){
            if (statutJeu[i][0]==1){
                toastGagnant = Toast.makeText(this.getContext(),"Joueur X a gagné !", Toast.LENGTH_SHORT  );
                toastGagnant.show();
                break;
            }
            else if (statutJeu[i][0]==3) {
                toastGagnant = Toast.makeText(this.getContext(),"Joueur 0 a gagné !", Toast.LENGTH_SHORT  );
                toastGagnant.show();
                break;
            }
        }
    }

    //Vertical --- columns
    for(int i=0; i<3; i++){
        if(statutJeu[0][i] == statutJeu[1][i] && statutJeu[0][i] == statutJeu[2][i]){
            if (statutJeu[0][i]==1){
                toastGagnant = Toast.makeText(this.getContext(),"Joueur X a gagné !", Toast.LENGTH_SHORT  );
                toastGagnant.show();
                break;
            }
            else if (statutJeu[0][i]==3) {
                toastGagnant = Toast.makeText(this.getContext(),"Joueur 0 a gagné !", Toast.LENGTH_SHORT  );
                toastGagnant.show();
                break;
            }
        }
    }

    //First diagonal
    if(statutJeu[0][0] == statutJeu[1][1] && statutJeu[0][0] == statutJeu[2][2]){
        if (statutJeu[0][0]==1){
            toastGagnant = Toast.makeText(this.getContext(),"Joueur X a gagné !", Toast.LENGTH_SHORT  );
            toastGagnant.show();
        }
        else if (statutJeu[0][0]==3) {
            toastGagnant = Toast.makeText(this.getContext(),"Joueur 0 a gagné !", Toast.LENGTH_SHORT  );
            toastGagnant.show();
        }
    }

    //Second diagonal
    if(statutJeu[0][2] == statutJeu[1][1] && statutJeu[0][2] == statutJeu[2][0]){
        if (statutJeu[0][2]==1){
            toastGagnant = Toast.makeText(this.getContext(),"Joueur X a gagné !", Toast.LENGTH_SHORT  );
            toastGagnant.show();
        }
        else if (statutJeu[0][2]==3) {
            toastGagnant = Toast.makeText(this.getContext(),"Joueur 0 a gagné !", Toast.LENGTH_SHORT  );
            toastGagnant.show();
        }
    }
    compteur++;
    if(compteur == 9){
        toastGagnant = Toast.makeText(this.getContext(),"Partie Null !", Toast.LENGTH_SHORT);
        toastGagnant.show();
    }
}

 void reinitialiserJeu (){
        for(int i = 0; i < 2; i++ ){
            for(int j = 0; j < 2; i++ ){
                statutJeu[i][j] = 0;
            }
        }
         compteur = 0;
    }

A: You could save all your buttons in a ArrayList<BoutonCase> buttons;
Then add your buttons:
final BoutonCase button = new BoutonCase(this.getContext());
buttons.add(button);

and when you want to reset the game you loop all of them and set their text.
for (BoutonCase button : buttons) {
        button.setText("");
    }


text:
Q: printf() after popen(): strange behaviour I don't understand the behaviour of using printf() after popen(). I have a folder with these 3 files:

*

*middle.txt

*test.app

*test.c

test.c is the source code of test.app:
test.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char **argv)
{
    FILE *fpipe;
    char *command = "ls";
    char c = 0;
    char output[1000];

    fpipe = popen(command, "r");

    if (fpipe == 0)
    {
        perror("popen() error");
        exit(1);
    }

    while (fread(&c, sizeof c, 1, fpipe))
    {
        strncat(output, &c, 1);
    }

    pclose(fpipe);

    char *position;
    char result[9];

    position = strstr(output, "test.app");

    if (position != NULL)
    {
        memcpy(result, position + 8, sizeof(result));
        fflush(stdout);
        printf("Output string: %s", result);
        fflush(stdout);
    }

    return 0;
}

When I run test.app I obtain this ouput:
Output string: test.app test.c

Why not this?
Output string:
test.app

EDIT
Using suggestions from the comments I modified 3 lines (position + 8 is a mistake from my original source code) with these:
char output[1000] = {0};
char result[9] = {0};
memcpy(result, position, sizeof(result));

but now this is the output:
Output string: test.app
middle.txt
test.app
test.c

A: I modified 3 lines (by opening post) with these:
char output[1000] = {0};
char result[9] = {0};
memcpy(result, position, sizeof(result) - 1);

and now this is the output:
Output string: test.app

1 Byte presents in output was responsible of this strange behaviour. We have to pay attention with the copied size, printed buffer must be a null-terminated string


text:
Q: Validation of input does not output correctly I am on my way to learning Javascript. I created a form which looks like this:
    <form method="post" action="#">
       <input type="text" name="name" placeholder="Bitte verrate uns Deinen Namen."  id="anfrage-name"/>
       <input type="email" name="email" placeholder="Und nun Deine E-Mail-Adresse..." id="anfrage-email"/>
       <textarea name="message" placeholder="...gefolgt von Deiner Nachricht an uns." rows="6" id="anfrage-kaufen"></textarea>
       <input type="submit" class="send-button" value="Anfragen" id="anfrage-abschicken"/>

    </form>

In JQuery I am going to validate the Email:
$(document).ready(function(e) {
    $('#anfrage-abschicken').click(function() {
        var sEmail = $('#anfragen-email').val();
        if ($.trim(sEmail).length == 0) {
            //no email
            $('#error-message').text('Du musst dieses Feld ausfüllen.');
            e.preventDefault();
        }
        if (validateEmail(sEmail)) {
            // email format right
            return true;
        }
        else {
            // wrong email format
            $('#error-message').text('Dein E-Mail-Format stimmt nicht.');
            e.preventDefault();
        }
    });
});

function validateEmail(sEmail) {
    var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
    if (filter.test(sEmail)) {
        return true;
    }
    else {
        return false;
    }
}

Unfortunately, it is not working. How can I get this to work? Here is my JSFIDDLE

A: When you submit a form use onsubmit event. It's a wrong approach to listen button onclick event. onsubmit event automatically responds to Enter key form submission:
$('form').submit(function (e) {
    var sEmail = $('#anfrage-email').val();

    if ($.trim(sEmail).length == 0) {
        //no email
        $('#error-message').text('Du musst dieses Feld ausfüllen.');
        e.preventDefault();
        return false;    // <-- stop further validation
    }

    if (!validateEmail(sEmail)) {
        // wrong email format
        $('#error-message').text('Dein E-Mail-Format stimmt nicht.');
        e.preventDefault();
    }
});

Also you passed event object e to the wrong function. So this:
$(document).ready(function(e)

should be
$(document).ready(function(e) {
    $('form').submit(function (e) {
    ...

Another mistake: your jQuery selector should be $('#anfrage-email').val(); not #anfragen-email.
Demo: http://jsfiddle.net/gW377/5/

A: Note that you are requesting for $('#anfragen-email') and your element is called anfrage-email
After that, you can replace e.preventDefault(); with return false to achieve the same goal (and this way it will work).
The remaining code seems to be right:
http://jsfiddle.net/gW377/3/

A: Your button is also the submit button for the form.  I'd suggest starting by binding to the submit event for the form rather than the button click.  More generally, try the jQuery Validatory plugin which will do much of this for you.

A: You had a couple of errors on you selectors
 var sEmail = $('#anfragen-email').val();

Should be:
 var sEmail = $('#anfrage-email').val();

Since you don't have an element with that id in you DOM
And you need to pass the event object e in the click event.
 $('#anfrage-abschicken').click(function(e) {

Fiddle


text:
Q: javascript return data after success function I want to submit a form using ajax function to mysql, but my attempt gives me the NULL results in mysql table.
Here's my javascript :

function pesan()
    {
        email = $("#email").val();
        from_nama = $("#from_nama").val();
        from_phone = $("#from_phone").val();

        $.ajax
        ({
            url : "<?php echo site_url('kirim/undangan')?>/",
            type: "POST",
            dataType: "JSON",
            success: function(data)
            {
               $('#alert').show();
               $('#email'+data).html(data.email);
               $('#from_nama'+data).html(data.from_nama);
               $('#from_phone'+data).html(data.from_phone);
            },
            error: function (jqXHR, textStatus, errorThrown)
            {
                alert('Error upload data');
            }

        });
    }

And the form :

Data Personal

                                <input type="email" class="form-control input-lg" id="email"  name="email"  placeholder="Email" required>

                                <input type="text" class="form-control input-lg"  id="from_nama" name="from_nama" placeholder="Nama" required>

                                <input type="number" class="form-control input-lg"  id="from_phone"  name="from_phone" placeholder="Phone" required>

                               <input type="hidden" name="id" id="id" />

                                    <button id="pesan" type="button" class="btn btn-download btn-md" onclick=pesan()>

                                    Pesan
                                    </button>

Here's the controller :

function undangan()
 {
   $email          =   $this->input->post('email');
   $from_nama  =   $this->input->post('from_nama');
   $from_phone  =   $this->input->post('from_phone');

   $data_user = array(

    'email'        => $email,
    'name'            => $from_nama,
    'phone'        => $from_phone,
    'status'                => '0',
    'unique_id'            => uniqid()

       );

            $this->load->model('excel');

   $this->excel->tambahuser($data_user);

  $this->load->view('kirimundangan.php',$data);
 }

The model :

function tambahuser($data_user)
        {
            $this->db->insert('request', $data_user);
            $this->db->insert_id();

            foreach ($data_user as $key)
            {
                $data = array(

                    'from_name'          =>   $this->input->post('from_nama'),
                    'from_phone'         =>   $this->input->post('from_phone')
                );
            }

        }

I think I made mistake in writing code inside the success:function(data), any help?

A: Change peson function to
function pesan()
    {
        var email = $("#email").val(),
          from_nama = $("#from_nama").val(),
          from_phone = $("#from_phone").val();

        $.ajax
        ({
            url : "<?php echo site_url('kirim/undangan')?>/",
            type: "POST",
            dataType: "JSON",
            data:{from_nama: from_nama, email: email, from_phone: from_phone},
            success: function(data)
            {
               $('#alert').show();
               $('#email'+data).html(data.email);
               $('#from_nama'+data).html(data.from_nama);
               $('#from_phone'+data).html(data.from_phone);
            },
            error: function (jqXHR, textStatus, errorThrown)
            {
                alert('Error upload data');
            }

        });
    }

and you expecting a json response so you have to change your server side code as well and from there you have to return data with json not with a view.
I hope this will work for you


text:
Q: How to get script elemnt in BeautifulSoup4 I am trying to extract the url under the script's in beautifulsoup4 in python. Lets assume we have a js code like that
<script>
  var data = [{
      tag: "A",
      name: "shelf",
      url: "/book"
    },
    {
      tag: "A",
      name: "publisher",
      url: "/computer"
    }, {
      tag: "A",
      name: "book",
      url: "/calculator"
    }, {

</script>

how can i take the url with using bs4
for i in soup.find_all('script'):
    print(i.get('url'))

i have tried so far this code but it didnt work


text:
Q: What is the minimum disk space occupied by a neo4j node property? This article seems to imply a 41byte minimum on the disk space occupied by each property of a node, regardless of the property type.  For boolean and short node properties, this seems quite high.  Am I misunderstanding the article, or is this a correct and intended consequence of the fixed-size records in neo4j?  How can we minimize the disk space occupied by properties with small data types such as booleans or shorts?
https://neo4j.com/developer/kb/understanding-data-on-disk/


text:
Q: How to loop through the columns and create different plots? I have a dataframe "A" with samples as rows and Genes as columns with gene expression values (RPKM).
        Gene1   Gene2           Gene3        Gene4        Gene5    Gene6
Sample1 0.02   0.038798682  0.1423662   2.778587067 0.471403939 18.93687655
Sample2 0      0.059227225  0.208765213 0.818810739 0.353671882 1.379027685
Sample3 0      0.052116384  0.230437735 2.535040249 0.504061015 9.773089223
Sample4 0.06   0.199264618  0.261100548 2.516963635 0.63659138  11.01441624
Sample5 0      0.123521916  0.273330986 2.751309388 0.623572499 34.0563519
Sample6 0      0.128767634  0.263491811 2.882878373 0.359322715 13.02402045
Sample7 0      0.080097356  0.234511372 3.568192768 0.386217698 9.068928569
Sample8 0      0.017421323  0.247775683 5.109428797 0.068760572 15.7490551
Sample9 0      2.10281137   0.401582013 8.202902242 0.140596724 60.25989178

To make a scatter plot showing correlation between Gene1 vs Gene5 and Gene6 I used following code:
library(tidyr)
library(ggplot2)
pdf("Gene1.pdf")
A %>%
  gather(key = variable, value = values, Gene5:Gene6) %>%
  ggplot(aes(Gene1, values)) +
  geom_point() +
  facet_grid(. ~ variable, scales = "free_x") +
  geom_smooth(method = "lm", se = FALSE) +
  scale_y_continuous(trans = "log2", labels = NULL, breaks = NULL) +
  scale_x_continuous(trans = "log2", labels = NULL, breaks = NULL)
dev.off()

I also want to plot for
Gene2 vs Gene5 and Gene6
Gene3 vs Gene5 and Gene6
Gene4 vs Gene5 and Gene6

Ofcourse I can replace Gene1 in the code with other Gene to plot. But instead of manual replacement I would like to make a loop so that from Gene1 to Gene4 plots against Gene5 and Gene6 with different plots each saved in pdf with respective gene names.
Based on request this is an Update about dput(A):
structure(list(Gene1 = c(0.02, 0, 0, 0.06, 0, 0, 0, 0, 0), Gene2 = c(0.038798682,
0.059227225, 0.052116384, 0.199264618, 0.123521916, 0.128767634,
0.080097356, 0.017421323, 2.10281137), Gene3 = c(0.1423662, 0.208765213,
0.230437735, 0.261100548, 0.273330986, 0.263491811, 0.234511372,
0.247775683, 0.401582013), Gene4 = c(2.778587067, 0.818810739,
2.535040249, 2.516963635, 2.751309388, 2.882878373, 3.568192768,
5.109428797, 8.202902242), Gene5 = c(0.471403939, 0.353671882,
0.504061015, 0.63659138, 0.623572499, 0.359322715, 0.386217698,
0.068760572, 0.140596724), Gene6 = c(18.93687655, 1.379027685,
9.773089223, 11.01441624, 34.0563519, 13.02402045, 9.068928569,
15.7490551, 60.25989178)), class = "data.frame", row.names = c("Sample1",
"Sample2", "Sample3", "Sample4", "Sample5", "Sample6", "Sample7",
"Sample8", "Sample9"))

A: Would a loop work for you? I haven't tested (since you don't have the data as dput()), so may need some cleanup.
cols <- colnames(A)
cols <- cols[!cols %in% c("Gene5", "Gene6")]
for(i in cols){
    name <- paste(i, ".pdf", sep = "")
    id <- which(colnames(A) == i)
    # add a new column - this is the one accepting the "rotating" gene input
    A$Gene <- A[,id]

p <- A %>%
        select(Gene, Gene5, Gene6) %>%
        gather(variable, values, Gene5:Gene6) %>%
        ggplot(aes(Gene, values)) +
        geom_point() +
        facet_grid(. ~ variable, scales = "free_x") +
        geom_smooth(method = "lm", se = FALSE) +
        scale_y_continuous(trans = "log2", labels = NULL, breaks = NULL) +
        scale_x_continuous(i, trans = "log2", labels = NULL, breaks = NULL)

    pdf(name)
    print(p)

     dev.off()
        }

A: if you need an explicit for loop:
for (gene in paste0("Gene",1:4)){
 a= A %>%
    gather(key = variable, value = values, Gene5:Gene6) %>%
    ggplot(aes(get(gene), values)) +
    geom_point() +
    facet_grid(. ~ variable, scales = "free_x") +
    geom_smooth(method = "lm", se = FALSE) +
    scale_y_continuous(trans = "log2", labels = NULL, breaks = NULL) +
    scale_x_continuous(trans = "log2", labels = NULL, breaks = NULL)

    print(a)

}


text:
Q: Changing leaflet circle marker colour and size when clicked upon I am currently using GIS to plot train stations within Wales
I have currently made a custom circle marker to point to that of the stations latlng successfully adding it to the map. I am wanting the circle marker to be used to show the train stations within Wales and to change colour/style upon being clicked.
I do not wish for this to be the default marker within leaflet but to be that of the custom circle marker

However The code which I believed would change the icon throws the error

Uncaught TypeError: e.target.setStyle is not a function

Is there a way to change this point markers colour upon being clicked?
UPDATE
Changing the code to that of below has removed the error however default markers still show as well as the circle markers, I am able to click this without an error but not colour/style change happens

Current version stand at

Live version link
https://ces-web2.southwales.ac.uk/students/18018815/mitchtut/giscw2/leaflet.htm
UPDATE
Colour changes and error removed however it changes after a click and is in need of slight refining this was fixed through reversing the click/unclick styles
Final Code

A: Your code (which I adapted into a reproducible example here) is adding the dataset twice to the map, once as L.CircleMarkers...
  var trainGeo = L.geoJSON(wtsGeo, {
    pointToLayer: function (feature, latlng) {
      return L.circleMarker(latlng, tMarker);
    },
  });

...and once as default L.Markers...
  var clickLayer = L.geoJSON(wtsGeo, {
    style: clickStyle,
    onEachFeature: addHandler,
  });

... so at each datapoint there's a circle and a marker with the default icon, like
Now, using two different symbols per data point is a questionable practice, and might be the source of the confusion here. I suggest you to consider using only one symbol per data point instead.
The error itself happens because you're trying to use a method (setStyle) specific to L.CircleMarkers (inherited from L.Path's setStyle) on a L.Marker (note that, when your event handler is running, e.target is an instance of L.Marker since the event handler is attached to clickLayer which is spawning default L.Markers).
While you might want to change the style of the circle when clicking on the spatially associated (but not logically-associated) marker, I urge you to use one symbol per datapoint.

A: As @IvanSanchez wrote in his answer, problem comes from clicking on the default marker, which has no setStyle method. And there is definitely no need for two layers from the same GeoJSON source.
Solution for what you want to achieve is to use just pointToLayer method to create marker and click event.
Code could the look something like this:
var clicked;

var clickStyle =  {
  radius: 6,
  fillColor: "#ff0000",
  color: "#ff0000",
  opacity: 1,
  weight: 2,
  fillOpacity: 1,
}
var unclickStyle = {
  radius: 6,
  fillColor: "#09f9df",
  color: "#ff0000",
  weight: 1,
  opacity: 1,
  fillOpacity: 1,
}

function clickOnMarker(e){
  if (clicked) {
    clicked.setStyle(unclickStyle);
  }
  e.target.setStyle(clickStyle);
  clicked = e.target;
}

var layer = L.geoJSON(wtsGeo, {
  pointToLayer: function (feature, latlng) {
    var marker = L.circleMarker(latlng, unclickStyle);
    marker.on('click', clickOnMarker);
    return(marker);
  }
}).addTo(map);


text:
Q: ng commands throws insufficient memory error [Fatal process OOM in insufficient memory to create an Isolate] When I run any angular command (ng command), I am getting insufficient memory error. But there is enough memory (RAM & Heap) in my system. The npm version is 6.4.1.
ng version or ng create or ng build

Getting the following error as:
<--- Last few GCs --->

<--- JS stacktrace --->

#
# Fatal process OOM in insufficient memory to create an Isolate
#

A: By default the memory limit in Node.js is 512 mb.
You need to run:

set NODE_OPTIONS=--max-old-space-size=30720

(*) Refer here if you want more information.

A: As per the list of commands (which can be seen using ng help). You should use ng -v to get the version you are using for Angular.

A: Resolved the issue by re-installing nodejs.


text:
Q: Is it possible to pass a structure variable as a function argument without previously defining it? I have two structs defined as so (in color.h):
typedef struct rgb {
  uint8_t r, g, b;
} rgb;

typedef struct hsv {
  float h, s, v;
} hsv;

hsv rgb2hsv(rgb color);
rgb hsv2rgb(hsv color);

I then have the following in main.c which works:
hsv hsvCol = {i/255.0, 1, 1};
rgb col = hsv2rgb(hsvCol);

I want to be able to just create the variable hsvCol inside the parameters for hsv2rgb without having to create the variable and passing it as a parameter.
I've tried the each of the following (in place of the two lines above), sadly none of which compile :(
rgb col = hsv2rgb({i/255.0, 1, 1});
rgb col = hsv2rgb(hsv {i/255.0, 1, 1});
rgb col = hsv2rgb(hsv hsvCol {i/255.0, 1, 1})
rgb col = hsv2rgb(struct hsv {i/255.0, 1, 1});

My question is:

*

*Can I do what I was trying to do at all (but obviously in a different way)?

*If 1, how do I go about doing so?

A: You can make use of a compound literal.
Quoting C11, chapter §6.5.2.5, paragraph 3,

A postfix expression that consists of a parenthesized type name followed by a brace enclosed
  list of initializers is a compound literal. It provides an unnamed object whose value is given by the initializer list.

and, paragraph 5,

The value of the compound literal is that of an unnamed object initialized by the
  initializer list. [...]

So, in your case, the code like
hsv hsvCol = {i/255.0, 1, 1};
rgb col = hsv2rgb(hsvCol);

can be re-written as
rgb col = hsv2rgb( ( hsv ) {i/255.0, 1, 1} );
                    ^^^^    ^^^^^^^^^^^^^
                    |             |
                    |              -- brace enclosed list of initializers
                    -- parenthesized type name


text:
Q: division function random integer need quotient and remainder printed out HI i wrote this code to have program , while using random integer less than 100 => divide the function , return qoutient and remainder and print them in output, but seems i do not work can you please help which part is wrong.
    #include <cstdlib>
#include <iostream>
#include <ctime>
using namespace std;

using namespace std;
 int division(int& remainder,int qoutient)
{
int dividant;
int divisor;
    int quotient=dividant/divisor;
   int remainder=dividant%divisor;
}

int main()
{
    int dividant =(rand()%99);
    int divisor =(rand()%99);
    int qoutient;
    int remainder_result;
    srand(time(NULL));
    do{qoutient=division(dividant,divisor);
    cout<<"this is q:"<<qoutient<<endl;
    cout<<"remainder"<<remainder_result<<endl;}
    while(dividant>divisor);

    }

A: *

*your division function makes use of variables divident and divisor declared in main, which is out of bounds for the function and will result in an error. in order to use these variables you need to pass these into the function using parameters.

*you also declare your division function as void, returning nothing, yet use it an a statement in your do while loop. In order to have the function return a value you need to replace void with the type you want to return, in this can an int, and return a value at the end of the function.

*srand(time(NULL)) is placed after the initial rand functions, meaning the rand functions will return the same value as rand isnt seeded yet, THEN seed rand afterwards. You need to place srand(time(NULL)) before your rand() calls

I suggest you read up more on c++ concepts, you don't have much right in this program along with some pretty messy coding techniques.

A: You have compilation errors.  Your division function references variables that were not declared.  You will need to either parametize those variables, or change your division function; whatever the case, the function cannot access the variables declared in main's scope.
Here's a compilation error/warning list from IDEOne:
prog.cpp: In function 'void division(int&, int)':
prog.cpp:11: error: 'dividant' was not declared in this scope
prog.cpp:11: error: 'divisor' was not declared in this scope
prog.cpp:11: warning: unused variable 'quotient'
prog.cpp: In function 'int main()':
prog.cpp:23: error: void value not ignored as it ought to be
prog.cpp:25: error: 'remainder' was not declared in this scope
prog.cpp:28: error: expected `;' before '}' token
prog.cpp:20: warning: unused variable 'remainder_result'

Once you fix those errors, please let us know how it goes.  I also recommend you heed the warnings as they likely indicate other problems in the code.

A: There were quite a few problems with the code, so I may have misunderstood what you were trying to do.  Here's the fixed code based on my understanding.  I took the liberty of changing your output so it shows the data for the full operation, so you can check the results:
#include <cstdlib>
#include <iostream>
#include <ctime>
using namespace std;

void division(int dividend, int divisor, int& quotient, int& remainder)
{
    quotient = dividend / divisor;
    remainder = dividend % divisor;
}

int main()
{
    srand(time(NULL));
    int dividend = rand() % 99;
    int divisor = rand() % 99;
    int quotient, remainder;
    division(dividend, divisor, quotient, remainder);
    cout << dividend << "/" << divisor << " = " << quotient << " remainder: " << remainder << endl;
    return 0;
}


text:
Q: Chrome not showing Saved Passwords My saved passwords are not being populated on sites I visit anymore. I recently downloaded Ubuntu 16 and I seem to have lost my Passwords on my newly installed Google chrome. I checked the following.

*

*I have password sync settings turned on in chrome for all my devices (Macbook Air, Samsung Phone, Windows PC).

*I verified that the google account is the correct one which I have always used to save and sync passwords and other chrome settings.

*I checked passwords.google.com, making sure it is the correct account and all the saved passwords are gone! I had about 200+ saved passwords previously. So they don't show up on the devices and on my google cloud account anymore!

*I should also add that along with passwords, the saved addresses are also gone from Chrome settings. The payment methods however still seem to be there.

Of course, I never explicitly deleted or ask to delete passwords from any of my devices.
How should I recover them all in Ubuntu Google Chrome?

A: I just resolved this issue using "Remove Person"
Step 1
Go to the "Other Person Setting" by clicking your photo on the Google-chrome web browser in the rightmost corner.
step 2
Remove person
step 3
Login again with your Gmail account which has Saved Password details.
step 4
Turn on Sync
This should sync all the Google Chrome settings as well as your Saved Passwords.

A: In my case, it's because of the disk access control of Chrome.
Chrome saving password requires access to the disk. Some versions of Mac OS like Big Sur & Mojave will block chrome from saving passwords if the user not given chrome disk asscess.
system preference > security & privacy > privacy tab > Fill Disk Access > Unlock Settings and Add Chrome to the access list

A: Same issue on my Chrome on latest Linux Plasma/KDE
Fixed with:

*

*goto chrome://flags/

*enable #clean-undecryptable-passwords

*restart chrome

Source:  https://bugs.chromium.org/p/chromium/issues/detail?id=1251355#c20

A: It is still happening in Chrome 104.0.5112.79. As Augusto correctly noted, it's due to corruption of local Chrome's passwords database (see https://bugs.chromium.org/p/chromium/issues/detail?id=1251355#c20 for more details), and chrome://flags/#clean-undecryptable-passwords was removed in recent versions (!?). Basically you're left with 3 options:

*

*as mentioned in the bug discussion, close Chrome, backup (just in case), then remove Login Data db from your problematic profile:

cd [PATH_TO_CHROME_PROFILES]/Default
rm "Login Data"
rm "Login Data-journal"

Then upon re-opening the browser, passwords should populate.

*

*Another option is viable if you have a backup of your profile dir, specifically of Login Data files. This was my case (experience some crazy data corruption with APFS), and while the backup was 2 weeks old (and I did not want to lose any tabs or history over that period), I recovered only these files from the backup and it helped to re-populate all (including recently saved) passwords from my Google Account.

*Last option is to use the following tool in attempt to salvage your password data: https://github.com/mramendi/chrome_password_grabber/tree/google-fix
Hope Google can fix it soon upstream.

A: Easiest solution
They have not been deleted just google try to keep your passwords safe.

*

*Make sure you are login and not paused in chrome

*Go to https://passwords.google.com/


text:
Q: Compare DateTime in a generic list I'm trying to query a generic list using code below.
    ArticleStartDate = Convert.ToDateTime("2013-05-07 09:00:00.450");
    var queryable = context.GetQueryable<FeaturedArticleResultItem>()
    queryable = queryable.Where(t => t.StartDisplay > ArticleStartDate).OrderBy(t => t.StartDisplay);

I'd like to get results which has a 'StartDisplay' date time later then 9:00am 7th of May, and my query returns list of items later then the day (7th, which is good), however, I've also got the items in the list like 8:30am 7th of May. It looks like it compares the date ok, but not the time...
Hope the above make sense.
Just a bit more info, I just found that t.StartDisplay looks like this {7/05/2013 1:31:00 a.m.}. Does it matter when comparing the time?


text:
Q: rounding a decimal in C# based on user input I'm trying to round decimals based on the user input instead of predefined values.
e.g. User inputs 1.2345, then they input the amount of decimals they need it rounded to like say 3. It would then round it and output 1.236
However, I can't for the life of me figure out how to round decimals based on input, only predefined values.
What would be the best way to do something like this?

A: Try Math.Round
var input = 3;
var value = 1.2345;

var result = Math.Round(value, input, MidpointRounding.AwayFromZero);


text:
Q: Calculate the weighted mean for a variable, which has two types with R I have the following dataset with the number of times ("n") the variable "V0220" appears in the data by the "id_municipio", but this variable has two types: 1 and 2. Moreover, I have the weight ("peso_amostral") of each observation.
id_municipio peso_amostral v0220     n
     1100015          2.04     2     1
     1100015          2.68     1     1
     1100015          3.45     2     1
     1100015          4.51     1     1
     1100015          4.62     2     1
     1100015          4.75     1     1

What I would like to do is the following:
id_municipio  2     1
   1100015    X     Y

Therefore, I want to calculate the weighted mean for each variable "V0220" for the type (2 or 1) of this variable by id_municipio. Note that "X" and "Y" are the weighted mean values for "V0220", by type 2 and 1, respectively. I want to do it using R.

A: You can try this using dcast from data.table. You can change fun.aggregate for the function that you need.
library(data.table)

dcast(data,
      id_municipio ~ v0220,
      fun.aggregate = mean,
      value.var     = "peso_amostral")

OUTPUT:
  id_municipio    1    2
1      1100015 3.98 3.37


text:
Q: Building kernel uImage using LOADADDR While building the kernel I am giving LOADADDR as "0x80008000":
make uImage LOADADDR=0x80008000

Can you please help to understand what is the use of this? Can I change the LOADADDR, is there any restriction on the length of the LOADADDR?

A: (I'm assuming that you're using ARM based on the mention of U-Boot and the value of LOADADDR.)

Can you please help to understand what is the use of this?

 LOADADDR specifies the address where the kernel image will be located by the linker. (This is true for a few architectures (e.g.  Blackfin), but not for ARM.
LOADADDR specifies the address where the kernel image will be located by U-Boot and is stored in the U-Boot header by the mkimage utility.  Typically the load address (for placement in memory) is also the start address (for execution).  Note that the uImage file is typically just the (self-extracting, compressed) zImage file with the U-Boot wrapper.

Can I change the LOADADDR,

Yes, but according to (Vincent Sanders') Booting ARM Linux that would be contrary to ARM convention:

*

*Despite the ability to place zImage anywhere within memory,
   convention has it that it is loaded at the base of physical RAM plus
   an offset of 0x8000 (32K). This leaves space for the parameter block
   usually placed at offset 0x100, zero page exception vectors and page
   tables. This convention is very common.

(The uImage mentioned in your question is probably just a zImage with the U-Boot wrapper, so the quotation does apply.)

is there any restriction on the length of the LOADADDR?

The "length"?  If you're using a 32-bit processor, then the length of this address would be 32 bits.

ADDENDUM
arch/arm/boot/Makefile only uses LOADADDR for building the uImage from the zImage.
From (Russel King's) Booting ARM Linux the constraints on this LOADADDR are:

The
  kernel should be placed in the first 128MiB of RAM.  It is recommended
  that it is loaded above 32MiB in order to avoid the need to relocate
  prior to decompression, which will make the boot process slightly
  faster.
When booting a raw (non-zImage) kernel the constraints are tighter.
  In this case the kernel must be loaded at an offset into system equal
  to TEXT_OFFSET - PAGE_OFFSET.

The expected locations for the Device Tree or ATAGs or an initramfs can add more constraints on this LOADADDR.

A: Putting this in other terms, kernel compilation can generate different images, compressed or not (i.e. needed for XIP).
LOADADDR is the entry_point of the kernel, must be correct (match with where u-boot loads it in DDR) for certain architectures that compiles with absolute long jumps, and not important at all for ARM that can execute relative jumps.


text:
Q: How to get current user id Django I am stuck with the JWT, can any one tell me how can I get user ID along with token.
My url.py :
from rest_framework_jwt.views import obtain_jwt_token
from scrumboard.views import UserDetail
from scrumboard import views

urlpatterns = [
    url(r'^api-token-auth/', obtain_jwt_token),
    url(r'^users/$', views.UserList.as_view()),
]

views.py:
class UserList(generics.ListAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer

class UserDetail(generics.RetrieveAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer

serializers.py:
class UserSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ('id', 'username', 'email', 'password')

The problem is that when i go to api-token-auth/, its only giving me the username and password and not the id.

A: You can get the token, userid and username by following these steps:
Inside your app, create a utils.py file (at the same level where  serializers.py is placed).
Content of utils.py:
from .serializers import UserSerializer #you have already created UserSerializer

def jwt_response_payload_handler(token, user=None, request=None):
    user = UserSerializer(user, context={'request': request}).data
    return {
        'token': token,
        'userid': user['id'],
        'username':user['username']
    }

In your settings.py, add
JWT_AUTH = {
    'JWT_RESPONSE_PAYLOAD_HANDLER':
    'app_name.utils.jwt_response_payload_handler', #app_name is name of the app which contains utils.py
}

Now when you hit the api (api-token-auth/) to get the token, it will respond with token, userid and username.
Example of response:
{
     'token':'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6ImdhbmVzaG5lZ2lAZ21haWwuY29tIiwiZXhwIjoxNTI0NTAyNzIzLCJ1c2VyX2lkIjoxLCJ1c2VybmFtZSI6ImdhbmVzaG5lZ2kifQ.RxnYF1gwaYywSnnWC-ngrcZaw90lpD6Rq7jcbnEoZVk',
     'userid':1,
     'username':'ganeshnegi'
}

A: According to the django-rest-framework-jwt docs this view only returns the username and password (emphasis mine).

In your urls.py add [url(r'^api-token-auth/', obtain_jwt_token)] to enable obtaining a token via a POST included the user's username and password.

I wouldn't worry about not obtaining the id, you should be able to query the User table by username.


text:
Q: How to global a Mysql connection OUT of a class to legacy code I am converting a legacy site over to Class Driven MVC style site.
I have a fully functional DAL layer instantiated by a Super Class ($Sys). I can global the DB class just fine so that legacy code can: $Sys->Db->Query("sql here") ... tastes great, less filling.
Except there are hundreds and hundreds of straight mysql calls. ie: mysql_query("sql here").
All the legacy mysql calls rely upon the credentials/connection established by a db.inc file (which I want to get rid of).
Question: Is there any way to have the object "global" the connection / credentials established by the Object/DAL so that they are natively available to the legacy mysql calls? Ergo, the native mysql calls will run without the need to execute code outside the object?

A: In one my project we use Zend Framework side-by-side with legacy code. We fetch db connection params from our DAL (Zend_Db) and set up connection for legacy code:
$db = Zend_Db_Table_Abstract::getDefaultAdapter();
$dbParms = $db->getConfig();
$db2 = mysql_connect($dbParms['host'], $dbParms['username'], $dbParms['password'])
        or die("Could not connect:" . mysql_error());
mysql_select_db($dbParms['dbname']) or die("Could not select database");


text:
Q: If we listen to the sound, why does $\sin(x^2)$ shrink and grow in intervals? $\sin(x^2)$ gives (it seems) an ever shrinking sine wave:

Its frequency gets higher, and the pitch of the sound wave should too, right? But if we pass the $\sin$ through the Play function (with a reasonable coefficient like 1500) we get

It goes up, and then down, on certain intervals. This is the pitch, i.e. the frequency, which I expected to look more like $a^x$ instead of like the screenshot above.
The sound pitch lowers and so should the sine function do? But it looks like it doesn't (according to the first screenshot)?
Where am I wrong? Is the sine frequency really getting wider at some points (I think it should not) or what else?

A: What (I think) happens is that you use a constant rate of $8000\,\text{Hz}$ on a steady increasing frequency. This leads to interesting effects when the frequency of the function gets bigger than you rate-frequency.
This fact can be explored by just using a $\sin$-Function and use a interval which is slightly larger than $\pi$ at example:
Show[Plot[Sin[x], {x, 0, 30 Pi}],
 ListLinePlot[Table[{x, Sin[x]}, {x, 0, 30 Pi, Pi + 0.1}],
  PlotStyle -> Black, Mesh -> All]]

While you used a normal $\sin$-function, you got a multiplication of two wave-functions with different frequencies just by using a too small rate-frequency.
You can visualize this. Use your function $\sin(x^2)$ but a constant interval to get the plot below:
p = Table[Sin[x^2], {x, 0, 100, 0.05}];
ListLinePlot[p, AspectRatio -> 1/10, PlotRange -> All,
 ImageSize -> 1500]

We can also analyze the frequency of this (in a little bit of cheating) by partitioning the list in equal parts and doing an FFT:
p = Table[Sin[x^2], {x, 0, 200, 0.005}];
g1 = ListLinePlot[p, AspectRatio -> 1/10, PlotRange -> All,
   ImageSize -> 1500];
pp = Partition[p, Floor[Length[p]/500]];
fp = Flatten@Table[Abs[Fourier[pp[[i]]]]^2, {i, 1, Length[pp]}];
g2 = ListLinePlot[fp, AspectRatio -> 1/10, PlotRange -> All,
   ImageSize -> 1500];
g3 = GraphicsGrid[{{g1}, {g2}}]

Which looks like your diagram there.
EDIT:
To answer your comment:
(First notice, that the first diagram of the output of Play is a diagram which shows the frequency over time)
It's like whats shown in the first picture but whats actually happens is displayed in the second picture. Your function frequency gets so high, that you Sample-Rate-Frequency goes into a kind of interference with it. So that you get an alternating frequency drift. A way to prevent this is to increase the sample rate. An example:
Play[Sin[(20*t*2 Pi)^2], {t, 0, 25}, SampleRate -> 8000]

This is what you've got essentially.
If we now increase our sample rate, we can go into higher frequencies of your function without getting this interference.
Play[Sin[(20*t*2 Pi)^2], {t, 0, 25}, SampleRate -> 80000]

Notice how this sound can play much longer before our frequency begins to drift away.


text:
Q: Initialisation order in Lua Table Constructor So, a table constructor has two components, list-like and record-like. Do list-like entries always take precedence over record-like ones? I mean, consider the following scenario:
a = {[1]=1, [2]=2, 3}
print(a[1]) -- 3
a = {1, [2]=2, [1]=3}
print(a[1]) -- 1

Is the index 1 always associated with the first list-like entry, 2 with the second, and so on? Or is there something else?

A: There are two types of tables in Lua, arrays and dictionaries, these are what you call "lists" and "records". An array, contains values in an order, this gives you a few advantages, like faster iteration or inserting/removing values. Dictionaries work like a giant lookup table, it has no order, it's advantages are how you can use any value as a key, and you are not as restricted.
When you construct a table, you have 2 syntaxes, you can seperate the values with commas, e.g. {2,4,6,8} thereby creating an array with keys 1 through n, or you can define key-value pairs, e.g. {[1]=2,[58]=4,[368]=6,[48983]=8} creating a dictionary, you can often mix these syntaxes and you won't run into any problems, but this is not the case in your scenario.
What you are doing is defining the same key twice during the table's initial construction. This is most generally impractical and as such hasn't really had any serious thought put into it during the language's development. This means that what happens is essentially unspecified behaviour. It is not completely understood what effect this will have, and may be inconsistent across different platforms or implementations.
As such, you should not use this in any commercial projects, or any code you'll be sharing with other people. When in doubt, construct an empty table and define the key-value pairs afterward.


text:
Q: C# CAML query to sharepoint returns all items in the list (instead of only ones that mach query value) I have the following code in my app to pull details from a sharepoint list.
            string siteUrl = "http://SHAREPOINTURL";

        ClientContext clientContext = new ClientContext(siteUrl);
        clientContext.Credentials = new NetworkCredential("UN", "PW", "DOMAIN");
        SP.List oList = clientContext.Web.Lists.GetByTitle("Licences");

        CamlQuery camlQuery = new CamlQuery();
        camlQuery.ViewXml = "<Where><Eq><FieldRef Name='Account' /><Value Type='Text'>123456</Value></Eq></Where>";

        ListItemCollection collListItem = oList.GetItems(camlQuery);
        clientContext.Load(collListItem);
        clientContext.ExecuteQuery();

        Console.WriteLine("Filtered List: " + collListItem.Count.ToString() + "\n");
        foreach (ListItem oListItem in collListItem)
        {
            Console.WriteLine("Account: {0} \nLicence: {1} \nMAC: {2}\n", oListItem["Account"], oListItem["Licence"], oListItem["MAC"]);
        }

In the sharepoint list I have created multiple test items but every time I run the above code all items in the list are returned regardless of what I use for the camlQuery.
Can anyone let me know where I'm going wrong with this pretty new to C# and never touched sharepoint before this.
Edit1: updated with advice from below.
Edit2: simplified the code but still getting the same problem.

A: If you want to return the filtered items, in your case is returning all the items, correct? if yes, this problem is in CAMLQuery ...
I have read a small documentation(link below):
Microsoft MSDN
And I noticed the formatting ViewXml:
camlQuery.ViewXml = "<Where><Eq><FieldRef Name='Account' /><Value Type='Text'>123456</Value></Eq></Where>"

try with this code:
camlQuery.ViewXml = "<View><Query><Where><Eq><FieldRef Name='Account' /><Value Type='Text'>123456</Value></Eq></Where></Query></View>"

I have working using with caml.
some syntax to reflect:
camlquery.query = "<query> ..... </query>";
camlquery.ViewXml = "<view> ..... </view>";

SORRY MY BAD ENGLISH :S

A: The issue is your last line of code:
textBoxReadShow.Text = Licence + "\t\t" + MAC + "\n";

You're truncating the text in the textbox each iteration of the loop.
You appear to want to be appending the text to the end of the textbox:
textBoxReadShow.Text += Licence + "\t\t" + MAC + "\n";

A: Remove<Query> and </Query>  from the CAML query.


text:
Q: How to access protected variable in child class I have class A:
class A:
    _useful: dict
...

and class B which inherits from A:
class B(A):
    def foo(self, key, value):
        super()._useful.update({key: value})
...

However I get an error:
AttributeError: 'super' object has no attribute '_useful'

A: You forgot to initialize the dictionary, try this
class A:
    _useful: dict = dict()


text:
Q: Evenly spaced image grid I've been all over this site, but haven't found decent solution yet.
I'm making a photography site that has a fixed menubar div on the left and the content div flowing on the right. In the photo gallery page there should be a grid of image thumbnails with fluid margins so that the thumbnails are always evenly spaced across the right (content) div.
Here's the structure:

...

^There is a vignette roll over animation in each thumbnail.
And the CSS:
html {
height: 100%;
padding:0;
margin:0;
}

body {
    height: 100%;
    padding: 0;
    margin: 0;
}

#wrapper {
    float: left;
    height: 100%;
    width:100%;
    padding:0;
    margin:0;
}

#left_column {
    position: fixed;
    top: 0;
    bottom: 0;
    left: 0;
    z-index:100;
    width: 240px;
    height: 100%;
    overflow: hidden;
    background-color:#ff0000;
}

#right_column {
background-color:#cccccc;
width:auto;
height:100%;
    margin-left: 240px;
    position: absolute;
}

#thumb_container {
    position: relative;
    max-width:50%;
    min-width:240px;
    height:auto;
    border-color:#000000;
    display: inline-block;
    margin: 2%;
}

#thumb_fx {
    opacity: 1;
    filter: alpha(opacity=100);
    -webkit-transition: opacity 0.5s linear;
    transition: 0.5s;
    -moz-transition: 0.5s; /* Firefox 4 */

    z-index: 100;
    position: absolute;
    top: 0;
    left: 0;
    height: 100%;
    width: 100%;
    background: transparent;
    box-shadow:inset 0px 0px 85px rgba(0,0,0,1);
    -webkit-box-shadow:inset 0px 0px 85px rgba(0,0,0,1);
    -moz-box-shadow:inset 0px 0px 85px rgba(0,0,0,1);
}

#thumb_fx:hover {
    opacity: 0;
    filter: alpha(opacity=0);
    -webkit-transition: opacity 0.5s linear;
    transition: 0.5s;
    -moz-transition: 0.5s; /* Firefox 4 */
}

.grayscale img{
    max-width:100%;
    min-width:50%;
    height:auto;
    position: relative;
    border:none;
    z-index: -1;
    position: relative;
}

The best solution so far is this: http://jsfiddle.net/VLr45/1/ but the margins go way too tight before the div is dropped to the next row. And I don't understand how to adjust them.
Any help?

A: When you calculate the number of boxes that will fit, add the minimum margin you would like:
Margin as pixels
var boxMinMargin = 10; // 10px

var columns = Math.floor(parent / (box + boxMinMargin));

http://jsfiddle.net/VLr45/14/

Margin as %
var boxMinMargin = box * 0.1; // 10% of box

var columns = Math.floor(parent / (box + boxMinMargin));

http://jsfiddle.net/VLr45/24/

If you prefer to set the margin with css, you can set the width in you box class
.box {
    margin: 2%;

    /*

    or

    margin-top: 2%;
    margin-right: 3%;
    margin-bottom: 4%;
    margin-left: 5%;

    */
}

http://jsfiddle.net/VLr45/17/


text:
Q: Javascript Convert array to Array of Objects I have a form and I am using Ajax to submit data to the API. The form contains a repeater which aids the user to enter any number of data repeatedly. The user submits the form after a few steps. When I try to bind the value to the Object is not binding. The API is built using Spring Boot, and by default, Jackson is used for conversion of JSON to Objects.
Here is the full code,
f.submit(function(e){
            e.preventDefault();
            var ignoreFields = ["_csrf"];
            var unindexed_array = $(this).serializeArray().filter(val => ignoreFields.indexOf(val.name) === -1);
            var indexed_array = {};
            $.map(unindexed_array, function(n, i){
                indexed_array[n['name']] = n['value'];
            });
            $.ajax({
                  type: $(this).attr('method'),
                  contentType: 'application/json',
                  url: $(this).attr('action'),
                  data: JSON.stringify(indexed_array),
                  dataType: 'json', cache: false, timeout: 600000,
                  success: function (d) {
                  }, error: function (e) {
                  }
              });
        })

before JSON.stringify()
   {
    act1[0].quantity: "4",
    act1[0].name: "abc",
    act1[0].status: "Working",
    act2[0].quantity: "5",
    act2[0].id: "1",
    act3[0].quantity: "4",
    act3[0].id: "2",
    act3[0].unit: "mm",
    activity: "zdzdsd zsdsad",
    endTime: "23:02",
    location: "sdasd",
    note: "sdfsdfsd sdfsdfsd",
    startTime: "03:03"
  }

if I convert the above code to the following format I expect this to work, since I am using a list and Jackson Library will be able to identify this format
    {
    endTime: "23:02",
    location: "sdasd",
    note: "sdfsdfsd sdfsdfsd",
    startTime: "03:03",
    act1:[{
       quantity: "4",
       name: "abc",
       status: "Working"
    }],
    act2:[{
       quantity: "5"
       id: "1"
    }],
    act3:[{
       quantity: "4"
       id: "2",
       unit: "mm"
    }]
}

I tried many ways in Javascript to convert into this format, How can we achieve the above format?

A: Keeping a personal library of helpful functions can often make this sort of transformation easier.  I have used functions like the included assocPath, and hydrate many times, including in a recent SO answer (which has more details about what they do.)
Put together my solution involves a number of fairly small functions.  I do have to make an assumption about your input structure not entirely clear from the question, namely that what's displayed is some kind of shorthand for a real JS format.  If not, most of the code will probably still work; it just might take some additional effort to convert to something usable.
This is what it looks like:

// utility functions
const assoc = (prop, val, obj) =>
  Number .isInteger (prop) && Array .isArray (obj)
    ? [... obj .slice (0, prop), val, ...obj .slice (prop + 1)]
    : {...obj, [prop]: val}

const assocPath = ([p = undefined, ...ps], val, obj) =>
  p == undefined
    ? obj
    : ps.length == 0
      ? assoc(p, val, obj)
      : assoc(p, assocPath(ps, val, obj[p] || (obj[p] = Number .isInteger (ps[0]) ? [] : {})), obj)

const hydrate = (pvEntries) =>
  pvEntries .reduce ((a, [k, v]) => assocPath (k, v, a), {})

// helper functions
const extractIndices = s =>
  s .split (/[\[\]]/)
    .map (s => /^\d+$/ .test (s) ? Number(s) : s)
    .filter(n => n !== '')

const makePath = (s) =>
  s .split ('.') .flatMap (extractIndices)

// main function
const transform = (input) =>
  hydrate (
    Object .entries (input)
      .map (([k, v]) => [makePath (k), v])
  )

// test data
const input = {"act1[0].quantity": "4", "act1[0].name": "abc", "act1[0].status": "Working", "act2[0].quantity": "5", "act2[0].id": "1", "act3[0].quantity": "4", "act3[0].id": "2", "act3[0].unit": "mm", "activity": "zdzdsd zsdsad", "endTime": "23:02", "location": "sdasd", "note": "sdfsdfsd sdfsdfsd", "startTime": "03:03"}

// demo
console .log (transform (input))
.as-console-wrapper {max-height: 100% !important; top: 0}

Using the helpers I already had, the only trick I needed in order to build this is to write some code to transform this style input: "act1[0].quantity" into the style I prefer to use, ["act1", 0, "quantity"].  That code is makePath, which depends on extractIndices.  While they could easily be combined here, extractIndices looks as though it might be useful on its own.
Using that, we can transform your input above into this:
[
  [["act1", 0, "quantity"], "4"],
  [["act1", 0, "name"], "abc"],
  [["act1", 0, "status"], "Working"],
  [["act2", 0, "quantity"], "5"],
  [["act2", 0, "id"], "1"],
  [["act3", 0, "quantity"], "4"],
  [["act3", 0, "id"], "2"],
  [["act3", 0, "unit"], "mm"],
  [["activity"], "zdzdsd zsdsad"],
  [["endTime"], "23:02"],
  [["location"], "sdasd"],
  [["note"], "sdfsdfsd sdfsdfsd"],
  [["startTime"], "03:03"]
]

and then simply call hydrate on that result.


text:
Q: Batch file redirection I have a batch file which invokes my IDE, so I just want to know if we could extract the contents present in my IDE(whole contents) to some text files.
My batch file is written below
D:\WindRiver\wrenv.exe -p vxworks653-2.2.3 run
PAUSE

Is there any more code needed to be added to my existing batch file??

A: I am not sure what do you think by "extract the contents present in my IDE" but generally, that kind of problem is solved using automation tools. Such tools can grab anything in Windows environment from window names, button captions, text content... everything you may need to get from 3thd party application (even pictures of gui elements)
I suggest you take a look at AutoHotKey, ~200KB scripting language for windows automation.
You cant do this in batch, generally.
Taking a content of a window in AutoHotKey can be as simple as:
 WinGetText, text, "name of the window"
 FileAppend, %text%, c:\out.txt

It can get a bit more complicated then that, but nothing you may want doesn't involve more then 10 lines of AHK scripting.
This is the best approach becuase it doesn't depend on features of the given program, tso once you learn AHK, you can obtain any information from the system in uniform manner.
Keep in mind that some applications are using non standard windows components and that they may not be automatable (this is rare however).
On the community forum there are lots of usefull functions and libraries for basically anything you may need in order to get info - redirection of stdin/out to your file, COM Accesibilty module (system way to automate things in windows), even some ocr wrappers to scan information pictured on images.

A: I asked a similar question which may be of use. That sort of approach is only likely to work if your IDE outputs information to stdout/stderr etc.
I've had some (limited) success with hooking into processes that are already running to try and intercept data that they're outputting.
Specifically, what is it you're trying to capture? The output from one of it's windows? Error messages if it fails to start?
[Edit] I'm still not sure exactly what you're trying to capture, but it sounds like you could launch a Python script from your batch file. The script launches your IDE and captures stdout and stderr which will give you both normal output and any errors.

A: Sorry for the late reply.This is the actual IDE(D:\WindRiver\wrenv.exe -p vxworks653-2.2.3)when i place this one in the command prompt my IDE gets invoked.Plz get back to me for any more clarifiaction
Thanks
stefen

A: >>> hi,i jst tried with AutoHotKey....
No, its not correct.
The correct code can only be made if I have installation of WindRiver which I don't have.
Ok, let me explain this shortly.
First Ill assume that title of the IDE starts with "WindRiver" word.
WindRiver must hold the text in some standard window control somehwere in its control hierrachy. The type of the control that is in question directs the way how can u grab the text from it. If it is ListView or ListBox for instance, you have to use
ControlGet, outputVar, List,, SysListView321, WindRiver

The above code means, "get me text of first SysListView32 control (hence 1 at the end) from application which title starts with 'WindRiver', and put it in ouputVar variable"
If it keeps in Edit box, you can simply do:
ControlGetText, OutputVar, Edit1, WindRiver

This means "get me content of first Edit control inside application with title WindRiver"
In order to get the type and number of control in question, simply open Window Spy (right click AHK tray icon) and hover over control with mouse to see its details.
The entire scripts will look like:
Run, d:\WIndriver ....
WinWaitActive, WindRiver
ControlGetText, OutputVar, Edit1, WindRiver
MsgBox %OtputVar%

If title of window is changing constantly you will have to use window class instad title to identify window. For instance you can target notepad as
ControlGetText, o, Edit1, Untitled

or
COntrolGetText, o, Edit1, ahk_class Notepad

First method uses window title, second one uses Window API class of the application which is better as title can change.
All in all, to get a bit fluent with AHK check out start up examples. I can ashure you that after several days of practice you will find yourself adjusting any application out there to your needs.
To see how powerfull AHK is and what amazing things can be done in it, check out Dock module.
There is no way you can do this in batch and using std redirection, so you better get used to AHK or some similar atuomation language (AutoIt, Phantom, WinRunner....). BTW, this kind of quetsion is usualy answered in a matter of hours on AHK community Ask For Help forum.


text:
Q: Element not found on phantomjs But working fine on chrome I am using phantomjs version 1.1.0 and  phantomjs-2.1.1.exe for windows.
CONTINUE ACTIVATED
This is the HTML code

CONTINUE

I have tried to locate the element using

*

*relative xpath for both the classes : .//*[@class='t-next-pd continue-to-query button-text'], .//*[@class='right-align']

*by text

*by partial text

*by link

*by cssSelector

*relative xpath with text

*By absolute xpath (Last priority)

*By ClassName

*javascript executor

*Implicit wait and Explicit wait

NOTHING SEEMS TO WORK
The CONTINUE button only gets activated when I enter name and age.
This is the code when CONTINUE button is not activated.

CONTINUE

CONTINUE DEACTIVATED

A: After filling in the details wait for a second. PhantomJS immediately searches for the activated continue button. It's most likely a timing issue. The continue button might take 500ms to 1 second to become active.
So when PhantomJS starts searching for the activated button it cannot find it because if doesn't exist in the DOM yet.
If you're using Python use time.sleep(2). It pauses for 2 second. This gives the DOM time to change the inactivated code to the activated code.
I used this a.t-next-pd.continue-to-query.button-text to find the activated button. This is a CSS Selector and it worked fine in my test case :)
Convert this to the language you're using. I'm using Python:-
# code
# to
# fill the form
time.sleep(2)
driver.find_element_by_css_selector('a.t-next-pd.continue-to-query.button-text')