Q:

How do I attach checkboxes to a submit

I have unknown amount of checkbox inputs on a page created based on rows in an sql database.
The checkboxes look like:
<input type="checkbox" class="deletefunc" value="<? echo $mid; ?>">

The checkboxes are intended, when checked and submitted, to delete a row from the database based on the value of $mid
The checkboxes could be either loose (not contained in any forms), or each could be contained in its own form (without a submit button). There is no way however to contain all the checkboxes in one form.
The reason is it's displayed in a loop with output like this:

<input type="checkbox" class="deletefunc" value="<? echo $mid; ?>">
<input type="checkbox" class="star" value="1">

<form name....><input type="submit" value="something"></form>

So what I need help understanding is, how to gather all the checkboxes based on classname, and attach them to a submit button....
And further, how would I write the loop function so it knows how many deletes to perform? What I mean is, how would I write a loop that would get the values from an unknown amount of inputs. Normally I know how many inputs there are and what the names are so its a matter of assigning a variable for each input.... I've never done this with an unknown amount of inputs.

A:

I would do it like this:
HTML:
<input type="checkbox" class="deletefunc" value="<? echo $mid; ?>">
<button id="delete-them">Delete Them</button>

JS:
$(function() {
    $('#delete-them').on('click', function() {
        var data = $('.deletefunc').attr('name', 'delete[]').serialize();
        $.ajax('delete-them.php', {
            method: 'POST',
            data: data,
            success: function() {
                alert('deleted!');
            }
         });
     });
});

PHP:
<?php
    $ids = $_POST['delete'];
    $params = array_fill(0, count($ids), "?");
    $sql = "DELETE FROM some_table WHERE id IN (" . implode(",", $params) . ")";
    //DELETE FROM some_table WHERE id IN(?,?,?,?);
    $pdo = new PDO('mysql:host=localhost;dbname=mydb', 'user', 'pass');
    $stmt = $pdo->prepare($sql);
    $stmt->execute($ids);
?>

So we basically listen for a click on our button, when it happens, we set the name (with [] at the end so it becomes an array) for all of the items with the class we care about, so that when we serialize those items we know how to reference it in our PHP.
We then POST that data over to the server, where we read the array we just sent, see how many there are, and then create a query to delete those items.


Q:

Java 8 Comparator keyExtractor

In Java 8 Comparator, we can create a comparator as follows.
Comparator.comparing(keyExtractor);

Currently I have a class as follows
class Employee {
    String name;
    Department dept;
}

class Department {
    String departmentName;
}

Now, if I want to create a comparator for Employee class which sorts the records based on the department name, how can I write my key extractor?
Tried the below code, but did not work.
Comparator.comparing(Employee::getDept::getDepartmentName);

A:

The trick here is method references are not objects and don't have members to access. So you can't do this:
Employee::getDept.getDepartmentName

Moreover, method references are not classes, so you can't get another method reference from them. So this also fails.
Employee::getDept::getDepartmentName

Finally, the only option that is left with us is this.
e -> e.getDept().getDepartmentName()

Try this out,
Employee empOne = new Employee("Mark", new Department("Accounts"));
Employee empTwo = new Employee("Melissa", new Department("Sales"));
List<Employee> employees = Arrays.asList(empOne, empTwo);
employees.sort(Comparator.comparing(e -> e.getDept().getDepartmentName()));
employees.forEach(System.out::println);

A:

You can use function that extracts a sort key
I.e.
Comparator.comparing(Employee::getDept,Comparator.comparing(Department::departmentName));


Q:

How to get the type of an expression as a string?

I'm having a small problem here. I have a clang::Expr object. I want to get the type of that expression as a string. According to the documentation, clang::Expr returns a QualType. clang::QualType has a method called getAsString() which returns a string describing that type.
// Get the expressions to the left and right of the binary operator.
const Expr *lhs = binop->getLHS()->IgnoreParenCasts();
string typeLhs = lhs->getType()->getAsString();

When I type make, it reports an error:
remove_memcpy.cpp:110:46: error: no member named 'getAsString' in 'clang::Type'
            string typeLhs = lhs->getType()->getAsString();
                             ~~~~~~~~~~~~~~  ^

Apparently Expr::getType() returns a clang::Type, not a clang::QualType as expected.
It's weird, in the documentation it days that Expr::getType() returns a clang::QualType. Perhaps it is because the latest version of the documentation is Clang 9.0.0, but I'm using Clang 6.0.1. Maybe they changed it.
If I have a clang::Expr, whose underlying type is int or something, how can I get the int as a string, std::string("int");?

A:

getAsString does provide a functionality that you're looking for.
The problem with your code is that Expr::getType does return clang::QualType not clang::QualType *. It has an overloaded operators * and -> that return clang::Type & and that's why you get this compiler error.
Long story short: change it to lhs->getType().getAsString()


Q:

Python- trying to understand plural vs singular in code. For example: for i, square in enumerate(squares):

I'm trying to clarify my understanding regarding situations in the code in which the singular seems to extract from the plural.  I'm not sure if this is standard among different languages, or, unique to specific situations in python.  Regardless, in the example below I refer to square within the squares list:
squares=['white', 'black', 'red', 'blue', 'green']

for i, square in enumerate(squares):
    print(i, square)

0 white
1 black
2 red
3 blue
4 green

Is python intuitive enough to know I am referring to the singular square from the "squares" list?  Is it unique to just this type of coding request or is it more broad and standard?  etc.

A:

The variables square and squares are completely unrelated. In this case, the use of the variable square (singular) is an arbitrary decision by the coder. I.e.
squares=['white', 'black', 'red', 'blue', 'green']
for i, square in enumerate(squares): print(i, square)

...would work identically had the coder chosen ...
wombats=['white', 'black', 'red', 'blue', 'green']
for oodles, noodles in enumerate(wombats): print(oodles, noodles)

The enumerate method is a generator which iterates through a list, and yields each item in the list's index, and value in that order. By convention only, coders often choose i to stand for index and will frequently give the list a plural name, and the variable intended to hold the value the singular of that plural.
But it is entirely arbitrary and up to the coder's preferences what the variable's names are.


Q:

Finding real coefficients of equation given that $a+ib$ is a root

Below is the question present in a past examination paper. I'll be giving my attempts and how I thought it through. Do feel free to point out any mistakes I make throughout my working even if unrelated to the question itself.

(a) Find $a+ ib$ such that $\frac{2+3i}{1-i} = a+ib$. If $a+ib$ is a root of the equation $px^2+qx+r=0$ where $p$ and $q$ are real numbers, find $p$,$q$ and $r$.

Before getting down to the technical side of the problem, I analyzed the question (somewhat). If the complex number $a+ib$ is a root of the given equation, then its conjugate $a-ib$ is also a root of the equation. However, since this is a quadratic equation, does the number of roots exceed the highest degree (in this case, 2)? If not, then are $a+ib$ and $a-ib$ the only roots of the equation?

Attempt to find $a+ib$
$$\frac{2+3i}{1-i} = a + ib$$
$$\frac{2+3i}{1-i} * \frac{1+i}{1+i} = a+ib$$
$$\frac{(2+3i)(1+i)}{2} = \frac{-1+5i}{2} = a+ib$$
$\therefore \frac{-1+5i}{2}$ is the first root and $\frac{-1-5i}{2}$ is the second root.
With these two roots, how would I proceed to obtain the coefficients of the above equation? I know it seems as though I haven't attempted this, I have however I cannot find any resources online that relate to this particular problem (somewhat identically atleast).
Method of solving (results matched with answersheet)
Since I got both roots $\frac{-1+5i}{2} = \alpha$ and $\frac{-1-5i}{2} = \beta$. I was able to structure my quadratic as $(x-\alpha)(x-\beta)$.
From there on all I did was subsitute, expand, simplify.
$$(x-(\frac{-1+5i}{2})(x-(-\frac{-1-5i}{2})$$
$$(x+\frac{1}{2} - \frac{5i}{2})(x+\frac{1}{2}+\frac{5i}{2})$$
$$x^2+x+\frac{13}{2}$$
$$2x^2+2x+13$$
$p=2,q=2, r=13$

A:

I will first note that $(2+3i)(1+i) = -1+5i$, so your value of $a+bi$ needs to be adjusted.
If you have a quadratic and you know its two roots $\alpha, \beta$, it must be equivalent (up to constant scaling) to $(x-\alpha)(x-\beta)$.
Thus, your polynomial is (a scaled multiple of)
$$
(x-a+bi)(x-a-bi) = x^2 - 2ax +a^2+b^2
$$


Q:

How can we solve the "freshest questions get looked at only" problem?

There is an observable usage pattern with StackOverflow that people monitor the newest questions and answer only them. So after the initial flurry there is very little activity on a question. Generally that is fine, but some types of questions have answers that change over time (what framework is available for X, for example), or might have better answers if got the attention of the newer members of the community who weren't around when it was first asked.
The problem with asking a new question is that it very quickly gets closed as a duplicate. So perhaps there should be a way to resurrect old questions. The most obvious way would be to have a question closed as a duplicate cause the duplicate to become new again (with perhaps some exceptions based on number of votes on answers, or the number of answers).
Another might to allow someone with sufficient reputation to resurrect a question.
Any other suggestions?

A:

The obvious solution to this problem is to get rid of the Newest Questions view. Now I'm saying we should do that but it's clear to me that's what most people look at. New questions get the most vote activity. Far fewer people look at the home page (but they do).
Or perhaps make Newest Questions a higher-rep privilege?


Q:

Resize uploaded image - PHP

I am using the basic upload code from the w3schools website but I would like to add the ability to resize the image on upload to 200px wide. Is this something that can be simply added to this code or do I need a different approach to achieve this?
Here's the code:
    <?php
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 200000))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "
";
    }
  else
    {
    echo "Big Upload: " . $_FILES["file"]["name"] . "
";
    echo "
";
    echo "Type: " . $_FILES["file"]["type"] . "
";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb
";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "
";

    if (file_exists("upload/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
      }
    }
  }
else
  {
  echo "Invalid file";
  }
?>

A:

You need to check which image library you have available first, using phpinfo() - you likely have GD and/or ImageMagick. There are tons of tutorials on how to write the resizing code out there - here's one: http://www.9lessons.info/2009/03/upload-and-resize-image-with-php.html


Q:

Prism 7 Register Multiple DialogWindow

I want to have 2 types of dialog windows that hosts the view for example one with WindowStyle=ToolWindow and another WindowStyle=None and a way to indicate which to resolve I thought of doing like this in the UserControl that i want to host:
      this.Loaded += delegate
        {
            var window = Window.GetWindow(this);
            window.WindowStyle = WindowStyle.ToolWindow;

        }

but i also want to set things like AllowsTransparency which can only be set before initialized

A:

To solve your problem you don't need to use containerRegistry.RegisterDialogWindow at all.
Just look into release notes https://github.com/PrismLibrary/Prism/releases/tag/v7.2.0.1367 and find out an example with title "Style the DailogWindow".
You should configure windows-style for each UserControl dialog inside your View using Dialog.WindowStyle attached property:
<prism:Dialog.WindowStyle>
    <Style TargetType="Window">
        <Setter Property="WindowStyle" Value="ToolWindow" />
        <Setter Property="AllowsTransparency" Value="False" />
    </Style>
</prism:Dialog.WindowStyle>


Q:

Checkbox edit is not working in jqgrid

{
    name: 'hidden',
    editable: true,
    formatter: "checkbox",
    editoptions: {
        value: 'True: False'
    },
    edittype: "checkbox",
    index: 'hidden',
    width: 40,
    sortable: true,
    sorttype: 'int',
    align: "center"
},

This code is working in jqgrid, is some time editable in chrome but not editable in firefox and safari, etc.
Plz help me thanks

A:

{name: 'hidden', editable: true, formatter: "checkbox",  edittype: "checkbox", index: 'hidden', width: 40, sortable: true, sorttype: 'int', align: "center",formatoptions:{disabled:false}},

formatoptions:{disabled:false}  is missing


Q:

How do you output a query from a .cfm page using jQuery AJAX in JSON format?

I am trying to output a query from a .cfm page using jquery with json format. Can someone tell me what I am dong wrong?
Edit: Answer here
Edit: Just posted my cfc code
Edit: I currently am getting an error.
SyntaxError: JSON.parse: unexpected character.

test.cfm output looks like
{"COLUMNS":["TEAM"],"DATA":[["Dallas Cowboys"],["NY Giants"],["Philadelphia Eagles"],["Washington Redskins"]]}

In my .html page I have

    <input type="button" id="runQuery" value="Show Teams" />
    <input type="text" name="name">

In my test.cfm calling page I have
   <cfinvoke
   component="learncf_jquery"
   method="getAllTeams"
   returnVariable="getItems">
   </cfinvoke>

  <cfoutput>#SerializeJSON(getItems)#</cfoutput>

learncf_jquery.cfc
<cfcomponent name="jQueryExample" output="false">

<cffunction name="getAllPlayers" output="false" access="private" returntype="query">
    <cfset var qAllPlayers = queryNew('playerName, team') />

    <cfset queryAddRow(qAllPlayers, 40) />

    <cfset querySetCell(qAllPlayers, 'playerName', 'Alford, Jay', 1) />
    <cfset querySetCell(qAllPlayers, 'team', 'NY Giants', 1) />
    <cfset querySetCell(qAllPlayers, 'playerName', 'Barden, Ramses', 2) />
    <cfset querySetCell(qAllPlayers, 'team', 'NY Giants', 2) />
    <cfset querySetCell(qAllPlayers, 'playerName', 'Beckum, Travis', 3) />
    <cfset querySetCell(qAllPlayers, 'team', 'NY Giants', 3) />
    <cfset querySetCell(qAllPlayers, 'playerName', 'Bernard, Rocky', 4) />
    <cfset querySetCell(qAllPlayers, 'team', 'NY Giants', 4) />
    <cfset querySetCell(qAllPlayers, 'playerName', 'Blackburn, Chase', 5) />
    <cfset querySetCell(qAllPlayers, 'team', 'NY Giants', 5) />
    <cfset querySetCell(qAllPlayers, 'playerName', 'Boss, Kevin', 6) />
    <cfset querySetCell(qAllPlayers, 'team', 'NY Giants', 6) />
    <cfset querySetCell(qAllPlayers, 'playerName', 'Bradshaw, Ahmad', 7) />
    <cfset querySetCell(qAllPlayers, 'team', 'NY Giants', 7) />
    <cfset querySetCell(qAllPlayers, 'playerName', 'Canty, Chris', 8) />
    <cfset querySetCell(qAllPlayers, 'team', 'NY Giants', 8) />
    <cfset querySetCell(qAllPlayers, 'playerName', 'Diehl, David', 9) />
    <cfset querySetCell(qAllPlayers, 'team', 'NY Giants', 9) />
    <cfset querySetCell(qAllPlayers, 'playerName', 'Feagles, Jeff', 10) />
    <cfset querySetCell(qAllPlayers, 'team', 'NY Giants', 10) />

    <cfset querySetCell(qAllPlayers, 'playerName', 'Adams, Flozell', 11) />
    <cfset querySetCell(qAllPlayers, 'team', 'Dallas Cowboys', 11) />
    <cfset querySetCell(qAllPlayers, 'playerName', 'Austin, Miles', 12) />
    <cfset querySetCell(qAllPlayers, 'team', 'Dallas Cowboys', 12) />
    <cfset querySetCell(qAllPlayers, 'playerName', 'Brown, Courtney', 13) />
    <cfset querySetCell(qAllPlayers, 'team', 'Dallas Cowboys', 13) />
    <cfset querySetCell(qAllPlayers, 'playerName', 'Choice, Tashard', 14) />
    <cfset querySetCell(qAllPlayers, 'team', 'Dallas Cowboys', 14) />
    <cfset querySetCell(qAllPlayers, 'playerName', 'Colombo, Marc', 15) />
    <cfset querySetCell(qAllPlayers, 'team', 'Dallas Cowboys', 15) />
    <cfset querySetCell(qAllPlayers, 'playerName', 'Davis, Leonard', 16) />
    <cfset querySetCell(qAllPlayers, 'team', 'Dallas Cowboys', 16) />
    <cfset querySetCell(qAllPlayers, 'playerName', 'Jones, Felix', 17) />
    <cfset querySetCell(qAllPlayers, 'team', 'Dallas Cowboys', 17) />
    <cfset querySetCell(qAllPlayers, 'playerName', 'Kitna, Jon', 18) />
    <cfset querySetCell(qAllPlayers, 'team', 'Dallas Cowboys', 18) />
    <cfset querySetCell(qAllPlayers, 'playerName', 'Procter, Corey', 19) />
    <cfset querySetCell(qAllPlayers, 'team', 'Dallas Cowboys', 19) />
    <cfset querySetCell(qAllPlayers, 'playerName', 'Romo, Tony', 20) />
    <cfset querySetCell(qAllPlayers, 'team', 'Dallas Cowboys', 20) />

    <cfset querySetCell(qAllPlayers, 'playerName', 'Akers, David', 21) />
    <cfset querySetCell(qAllPlayers, 'team', 'Philadelphia Eagles', 21) />
    <cfset querySetCell(qAllPlayers, 'playerName', 'Baskett, Hank', 22) />
    <cfset querySetCell(qAllPlayers, 'team', 'Philadelphia Eagles', 22) />
    <cfset querySetCell(qAllPlayers, 'playerName', 'Booker, Lorenzo', 23) />
    <cfset querySetCell(qAllPlayers, 'team', 'Philadelphia Eagles', 23) />
    <cfset querySetCell(qAllPlayers, 'playerName', 'Clemons, Chris', 24) />
    <cfset querySetCell(qAllPlayers, 'team', 'Philadelphia Eagles', 24) />
    <cfset querySetCell(qAllPlayers, 'playerName', 'Demps, Quintin', 25) />
    <cfset querySetCell(qAllPlayers, 'team', 'Philadelphia Eagles', 25) />
    <cfset querySetCell(qAllPlayers, 'playerName', 'Feeley, A.J.', 26) />
    <cfset querySetCell(qAllPlayers, 'team', 'Philadelphia Eagles', 26) />

    <cfset querySetCell(qAllPlayers, 'playerName', 'Hobbs, Ellis', 27) />
    <cfset querySetCell(qAllPlayers, 'team', 'Philadelphia Eagles', 27) />
    <cfset querySetCell(qAllPlayers, 'playerName', 'Jackson, DeSean', 28) />
    <cfset querySetCell(qAllPlayers, 'team', 'Philadelphia Eagles', 28) />
    <cfset querySetCell(qAllPlayers, 'playerName', 'Klecko, Dan', 29) />
    <cfset querySetCell(qAllPlayers, 'team', 'Philadelphia Eagles', 29) />
    <cfset querySetCell(qAllPlayers, 'playerName', 'McNabb, Donovan', 30) />
    <cfset querySetCell(qAllPlayers, 'team', 'Philadelphia Eagles', 30) />

    <cfset querySetCell(qAllPlayers, 'playerName', 'Alexander, Lorenzo', 31) />
    <cfset querySetCell(qAllPlayers, 'team', 'Washington Redskins', 31) />
    <cfset querySetCell(qAllPlayers, 'playerName', 'Campbell, Jason', 32) />
    <cfset querySetCell(qAllPlayers, 'team', 'Washington Redskins', 32) />
    <cfset querySetCell(qAllPlayers, 'playerName', 'Clark, Devin', 33) />
    <cfset querySetCell(qAllPlayers, 'team', 'Washington Redskins', 33) />
    <cfset querySetCell(qAllPlayers, 'playerName', 'Cooley, Chris', 34) />
    <cfset querySetCell(qAllPlayers, 'team', 'Washington Redskins', 34) />
    <cfset querySetCell(qAllPlayers, 'playerName', 'Dixon, Antonio', 35) />
    <cfset querySetCell(qAllPlayers, 'team', 'Washington Redskins', 35) />
    <cfset querySetCell(qAllPlayers, 'playerName', 'Fletcher, London', 36) />
    <cfset querySetCell(qAllPlayers, 'team', 'Washington Redskins', 36) />
    <cfset querySetCell(qAllPlayers, 'playerName', 'Hackett, D.J.', 37) />
    <cfset querySetCell(qAllPlayers, 'team', 'Washington Redskins', 37) />
    <cfset querySetCell(qAllPlayers, 'playerName', 'Randle El, Antwaan', 38) />
    <cfset querySetCell(qAllPlayers, 'team', 'Washington Redskins', 38) />
    <cfset querySetCell(qAllPlayers, 'playerName', 'Smoot, Fred', 39) />
    <cfset querySetCell(qAllPlayers, 'team', 'Washington Redskins', 39) />
    <cfset querySetCell(qAllPlayers, 'playerName', 'Suisham, Shaun', 40) />
    <cfset querySetCell(qAllPlayers, 'team', 'Washington Redskins', 40) />

    <cfreturn qAllPlayers />
</cffunction>

<cffunction name="getAllTeams" access="remote" output="false" returntype="query">
    <cfset var allPlayers   = getAllPlayers() />
    <cfset var qGetAllTeams = "" />

    <cfquery name="qGetAllTeams" dbtype="query">
        SELECT DISTINCT team FROM allPlayers ORDER BY team
    </cfquery>

    <cfreturn qGetAllTeams />
</cffunction>

A:

./test.cfm:
   <cfinvoke
   component="learncf_jquery"
   method="getAllTeams"
   returnVariable="getItems">
   </cfinvoke>
   <cfoutput>#SerializeJSON(getItems)#</cfoutput>

Here's some of my code that I've modified to match your example:
My HTML:

And my javascript, which puts the query result into the table:
    $("#runQuery").click(function () {

        $.ajax({

            type: "GET",
            url: "./test.cfm",
            dataType: "json",
            success: function (resp, textStatus, jqXHR) {
                buildResultsTable(resp);
            },
            error: function (jqXHR, textStatus, errorThrown)
            {
                alert(errorThrown);
            }
        });

    });

    function buildResultsTable(resp)
    {
        var tmp_html = $("
");
        var j = 0;

            $("#results").html("");

            for (var i = 0; i < resp["COLUMNS"].length; i++)
            {
                var tmp_th = $("");
                tmp_th.text(resp["COLUMNS"][i]);
                tmp_html.append(tmp_th);
            }
            $("#results").append(tmp_html);

            for (j = 0; j < resp["DATA"].length; j++)
            {
                tmp_html = $("
");

                for (var i = 0; i < resp["DATA"][j].length; i++)
                {
                    var tmp_td = $("");
                    tmp_td.text(resp["DATA"][j][i]);
                    tmp_html.append(tmp_td);
                }
                $("#results").append(tmp_html);
            }

    }


Q:

when going from excel to R, dropping a 0 from the beginning of a number. How do i keep this from happening?

I have a series of zip codes that are stored in excel (not my choice), that I need to import into R, but to retain the ability to used a matching function i need the "0" that starts off the majority of these zipcodes. How do I keep them R from dropping the 0 when reading the csv?

A:

These data are saved as a .csv file, but if you want to reproduce it, you will have to run these first lines:
    ZIP<-structure(list(V1 = c("08979", "67689", "06978", "54823")), class = "data.frame", row.names = c(NA,
-4L))

write.csv(ZIP, "Zips.csv")

If you read in without any options
ZIP<-read.csv("Zips.csv",header=F)
head(ZIP)
     V1
1  8979
2 67689
3  6978
4 54823

You are missing zeros in front, because R is assuming the class is integer or numeric, so a zero in the front is meaningless. However if you set colClasses = "character", you can avoid this:
ZIP<-read.csv("Zips.csv",header=F, colClasses="character")

head(ZIP)
 V1
1 08979
2 67689
3 06978
4 54823

It also works as factor:
ZIP<-read.csv("Zips.csv",header=F, colClasses="factor")
head(ZIP)
     V1
1 08979
2 67689
3 06978
4 54823


Q:

is it possible to modify json objects in CLI?

I have thousands of files containing a JSON objects
such as
{ "mykey" :"myvalue"}

and I have to add a key-value into each files
eg.
{ "mykey" :"myvalue", "newkey": "newvalue"}

I know I can easily come up Python script to do it.  Is there a easier way to do that in CLI? Something like
   addjson "newkey" "newvalue" myfile*.json

A:

You can use the json node.js module.
After getting node.js you can install it with sudo npm install -g json
Usage json -I -f myfile.json -e 'this.newkey="newvalue"'
Only one file at the same time but as you said, you can use python
or an example with a for loop in bash: for i in $(ls myfile*.json); do json -I -f $i -e 'this.newkey="newvalue"'; done
Documentation: http://trentm.com/json/


Q:

Updating UI thread (textbox) via C#

Business Intelligence guy here with enough C# under my belt to be dangerous.
I’ve built a homebrew winforms application that essentially executes a command-line tool in a loop to “do stuff”.  Said stuff may complete in seconds or minutes. Normally I will need to execute the tool once for each row sitting in a DataTable.
I need to redirect the output of the command-line tool and display it in “my” app.  I’m attempting to do so via a text box.  I’m running into issues around updating the UI thread that I can’t get straightened out on my own.
To execute my command-line tool, I’ve borrowed code from here: How to parse command line output from c#?
Here is my equivalent:
        private void btnImport_Click(object sender, EventArgs e)
        {
           txtOutput.Clear();
            ImportWorkbooks(dtable);

        }

        public void ImportWorkbooks(DataTable dt)
        {

            ProcessStartInfo cmdStartInfo = new ProcessStartInfo();
            cmdStartInfo.FileName = @"C:\Windows\System32\cmd.exe";
            cmdStartInfo.RedirectStandardOutput = true;
            cmdStartInfo.RedirectStandardError = true;
            cmdStartInfo.RedirectStandardInput = true;
            cmdStartInfo.UseShellExecute = false;
            cmdStartInfo.CreateNoWindow = false;

            Process cmdProcess = new Process();
            cmdProcess.StartInfo = cmdStartInfo;
            cmdProcess.ErrorDataReceived += cmd_Error;
            cmdProcess.OutputDataReceived += cmd_DataReceived;
            cmdProcess.EnableRaisingEvents = true;
            cmdProcess.Start();
            cmdProcess.BeginOutputReadLine();
            cmdProcess.BeginErrorReadLine();

            //Login
            cmdProcess.StandardInput.WriteLine(BuildLoginString(txtTabCmd.Text, txtImportUserName.Text, txtImportPassword.Text, txtImportToServer.Text));

            foreach (DataRow dr in dt.Rows)
            {
                   cmdProcess.StandardInput.WriteLine(CreateServerProjectsString(dr["Project"].ToString(), txtTabCmd.Text));

                //Import Workbook

                cmdProcess.StandardInput.WriteLine(BuildPublishString(txtTabCmd.Text, dr["Name"].ToString(), dr["UID"].ToString(),dr["Password"].ToString(), dr["Project"].ToString()));
            }
            cmdProcess.StandardInput.WriteLine("exit");   //Execute exit.
            cmdProcess.EnableRaisingEvents = false;
            cmdProcess.WaitForExit();
        }

private void cmd_DataReceived(object sender, DataReceivedEventArgs e)
        {
            //MessageBox.Show("Output from other process");
            try
            {
        // I want to update my textbox here, and then position the cursor
        // at the bottom ala:

                StringBuilder sb = new StringBuilder(txtOutput.Text);
                sb.AppendLine(e.Data.ToString());
                txtOutput.Text = sb.ToString();
                this.txtOutput.SelectionStart = txtOutput.Text.Length;
                this.txtOutput.ScrollToCaret();

            }
            catch (Exception ex)
            {
                 Console.WriteLine("{0} Exception caught.", ex);

            }

        }

Referencing txtOuput.text when I instantiate my StringBuilder in cmd_DataReceived () neatly causes the app to hang: I’m guessing some sort of cross-thread issue.
If I remove the reference to txtOuput.text in StringBuilder and continue debugging, I get a cross-thread violation here:
txtOutput.Text = sb.ToString();

Cross-thread operation not valid: Control 'txtOutput' accessed from a thread other than the thread it was created on.

OK, not surprised. I assumed cmd_DataReceived is running on another thread since I’m hitting it as the result of doing stuff after a Process.Start() …and if I remove ALL references to txtOuput.Text in cmd_DataReceived() and simply dump the command-line text output to the console via Console.Write(), everything works fine.
So, next I’m going to try standard techniques for updating my TextBox on the UI thread using the information in http://msdn.microsoft.com/en-us/library/ms171728.aspx
I add a delegate and thread to my class:
delegate void SetTextCallback(string text);
// This thread is used to demonstrate both thread-safe and
// unsafe ways to call a Windows Forms control.
private Thread demoThread = null;

I add a procedure to update the text box:
 private void SetText(string text)
    {
        // InvokeRequired required compares the thread ID of the
        // calling thread to the thread ID of the creating thread.
        // If these threads are different, it returns true.
        if (this.txtOutput.InvokeRequired)
        {
            SetTextCallback d = new SetTextCallback(SetText);
            this.Invoke(d, new object[] { text });
        }
        else
        {
            this.txtOutput.Text = text;
        }
    }

I add another proc which calls the thread-safe one:
 private void ThreadProcSafe()
    {
       // this.SetText(sb3.ToString());
        this.SetText("foo");

    }

...and finally I call this mess within cmd_DataReceived like this:
private void cmd_DataReceived(object sender, DataReceivedEventArgs e)
{
    //MessageBox.Show("Output from other process");
    try
    {

        sb3.AppendLine(e.Data.ToString());

        //this.backgroundWorker2.RunWorkerAsync();
        this.demoThread = new Thread(new ThreadStart(this.ThreadProcSafe));
        this.demoThread.Start();
        Console.WriteLine(e.Data.ToString());

    }
    catch (Exception ex)
    {
         Console.WriteLine("{0} Exception caught.", ex);

    }

}

…When I run this text, the textbox sits there dead as a doornail, not getting updated. My console window continues to update. As you can see, I tried simplifying things a bit just by getting the textbox to display "foo" vs. the real output from the tool - but no joy. My UI is dead.
So what gives? Can't figure out what I'm doing wrong. I'm not at all married to displaying results in a textbox, btw - I just need to be able to see what's going in inside the application and I'd prefer not to pop up another window to do so.
Many thanks.

A:

I think the issue is in this line:
cmdProcess.WaitForExit();

It's in the method ImportWorkbooks which is called from the Click event method of btnImport. So your UI thread is blocked until the background process is completed.

A:

You're calling ImportWorkbooks from the UI thread. Then, in this method, you're calling "cmdProcess.WaitForExit()". So basically you're blocking the UI thread until the process has finished executing. Execute ImportWorkbooks from a thread and it should work, or remove the WaitForExit and use the process' "Exited" event instead.

A:

one of the reasons you text box doesn't update is because you don't pass the string to your SetText  method.
You don't need to create a thread.
Your implementation will of SetText will handle passing the call to from the worker thread (where cmd_DataReceived is called) to the UI thread.
Here is what I suggest you do:
private void cmd_DataReceived(object sender, DataReceivedEventArgs e)
{
    //MessageBox.Show("Output from other process");
    try
    {

        string str = e.Data.ToString();
        sb3.AppendLine(str);
        SetText(str); //or use sb3.ToString if you need the entire thing

        Console.WriteLine(str);

    }
    catch (Exception ex)
    {
         Console.WriteLine("{0} Exception caught.", ex);

    }

}

Also, you are blocking the UI thread as @Fischermaen mentioned when you call WaitForExit, you don't need it.
I would also suggest that you run ImportWorkbooks on a worker thread like so:
(if you do this you can leave the call to WaitForExit)
private void btnImport_Click(object sender, EventArgs e)
{
     txtOutput.Clear();
     ThreadPool.QueueUserWorkItem(ImportBooksHelper, dtTable);
}

private ImportBooksHelper(object obj)
{
    DataTable dt = (DataTable)obj;
    ImportWorkbooks(dtable);
}


Q:

Link to get all users that ever had access to a SharePoint site

I want to obtain all users that ever had access to a SharePoint site.
Is it correct that I have to use this?
http://sharepointsite/_layouts/15/people.aspx?MembershipGroupId=0
Can I get the XML of that page as well?
What's the difference between the link above and this one:
/_api/web/siteusers

A:

Yes, you could use the url http://sharepointsite/_layouts/15/people.aspx?MembershipGroupId=0, this is user infomation list. In SharePoint, we have the User Information List in SharePoint, which stores information about users. Some examples are Picture, Email, DisplayName, LoginName, and more.
When we grant any user permissions to a user, they are added automatically to the hidden User Information list a new item will be created in the User Information List storing some information about the user.
Below article would help you know more about user infomation list:
https://gallery.technet.microsoft.com/office/User-Information-List-in-8b420e8c
This one /_api/web/siteusers is SharePoint rest Service. SharePoint rest Service is for developers mostly. Developers can interact remotely with SharePoint data by using any technology that supports REST web requests. This means that developers can perform Create, Read, Update, and Delete (CRUD) operations from their SharePoint Add-ins, solutions, and client applications, using REST web technologies and standard Open Data Protocol (OData) syntax.
Please read this article for more about sharepoint rest service:
https://docs.microsoft.com/en-us/sharepoint/dev/sp-add-ins/get-to-know-the-sharepoint-rest-service?tabs=csom


Q:

What kind of hardware does Microsoft use to build Azure?

I'm curious about Azure virtual machines and Web/Worker role hardware. What kind of hardware (CPU, Disk, network cards, chipsets, etc..) does Microsoft use to run Azure on? Is there public information available?

A:

I can answer this, and the answer is....a variety. They buy Intel based kit from at least HP, IBM and Dell and buy their matching disks/memory etc. from those manufactures. Ultimately so long as they keep to their own Hyper-V HCL they can buy what they want but that's what they do, the don't do that Google 'roll-your-own' trick.


Q:

SQL UNION Query on the same table, same field

I'm trying to build a SQL Union Query which would return two columns (one per select) with the result from the same field, sorted with the WHERE clause.
Here is what I trying :
SELECT scg.grade AS course_1
FROM cp_StudentCourseGrade AS scg
JOIN cp_CourseSecSem AS css ON
css.courseSecSem_id = scg.courseSecSem_id
JOIN cp_Course AS c1 ON
c1.course_id = css.course_id
UNION
SELECT scg.grade AS course_2
FROM cp_StudentCourseGrade AS scg
JOIN cp_CourseSecSem AS css ON
css.courseSecSem_id = scg.courseSecSem_id
JOIN cp_Course AS c2 ON
c2.course_id = css.course_id**
WHERE c1.course_id = c2.course_id AND c1.course_id=1 AND c2.course_id=2;

and this should return me something like that :
    course_1 | course_2
    -------------------
    4.0      | 6.0
    4.5      | 6.0
    6.0      | 5.5
    2.5      | 5.0
    1.0      | 4.0
    5.5      | 4.5

But I am having an error that says :

unknown column c1.course_id

Does anyone have an idea how I should do it?

A:

This is what you need:
SELECT scg1.grade AS course_1, scg2.grade AS course_2
FROM cp_StudentCourseGrade AS scg1
JOIN cp_CourseSecSem AS css1 ON
css1.courseSecSem_id = scg1.courseSecSem_id
JOIN cp_Course AS c1 ON
c1.course_id = css1.course_id AND c1.course_id=1
JOIN cp_StudentCourseGrade AS scg2
JOIN cp_CourseSecSem AS css2 ON
css2.courseSecSem_id = scg2.courseSecSem_id
JOIN cp_Course AS c2 ON
c2.course_id = css2.course_id AND c2.course_id=2;


Q:

How I can uninstall without trace files from console? even with the program folder eg gimp uninstall

How I can uninstall without trace files from console? even with the program folder eg gimp uninstall
i use
sudo apt-get –purge remove gimp
sudo apt-get clean gimp

and nothig the folder still appear in my personal folder

A:

The package manager never removed files from your personal folder (If this should be the case, but then the package maintainer has worked poorly.). These files or folders you always have to remove yourself.
In your case, E.G.
rm -r ~/.gimp-2.8

2.8 depends on your Gimp version.


Q:

Links to election nomination pages from notifications don't have the right #anchor

I recently received a notification that someone posted a comment on my election nomination post. That notification linked me to this URL: https://anime.stackexchange.com/election/1#post-34503
However, the anchor #post-34503 doesn't link you anywhere in particular. It just leaves you at the top of the page. The actual anchor for my post is #post-23961.
"34503" appears to be the ID of the comment in question - https://anime.stackexchange.com/election/1#comment-34503 does take me to the right place.

A:

This will be fixed as of build 2862. I'm using the comment anchor rather than the nomination post anchor.


Q:

Why do comments affect the logic of my file?

EDIT:
In here, it shows this as being a comment.  In my IDE, it shows this as being code.  So weird (Code set #2):
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="bootstrap-3.3.2-dist/js/bootstrap.min.js"></script>

I have two files.  One has comments and one does not.  The first set of code functions perfectly.  The second set of code tells me Uncaught ReferenceError: $ is not defined in the JavaScript console, and the alert is not called.  Why are the comments affecting my script?
Code Set #1
<!DOCTYPE html>
<html lang="en">
<head>
    <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script src="bootstrap-3.3.2-dist/js/bootstrap.min.js"></script>
</head>
<body>
<script>
    $(function () {
        alert("JQUERY!");
    });
</script>
</body>
</html>

Code Set #2
<!DOCTYPE html>
<html lang="en">
<head>
    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script src="bootstrap-3.3.2-dist/js/bootstrap.min.js"></script>
    <![endif]-->
</head>
<body>
<script>
    $(function () {
        alert("JQUERY!");
    });
</script>
</body>
</html>

A:

These are no ordinary comments, but conditional comments.
See: http://www.quirksmode.org/css/condcom.html
The comment above comments all javascript includes, thus they are not loaded, except in Internet Explorer lower than Version 9.
You get the error message because jquery is not loaded (it is inside the HTML comments). If you Use e.g. IE8 there won't be an error.


Q:

Bash script doesn't catch SIGINT while in read loop

I have several scripts with while read line loops that don't execute my cleanup function when I press Ctrl C. For example:
#!/bin/bash

cleanup() {
  stty echo
  exit 0
}

trap cleanup SIGINT SIGHUP SIGTERM

stty -echo
while read -r line; do
  echo "$line"
done < /foo/bar

cleanup

When I press Ctrl-C, my terminal is screwed up because the stty -echo setting is still in effect. I have many other scripts where my cleanup function works flawlessly. The only time I seem to have a problem is when I press Ctrl-C while the script is in a read loop. Is there a way to ensure that the cleanup function will get called when Ctrl-C is pressed while the script is inside a read loop? Or am I just missing something obvious here?
Update: There is something else going on in my scripts. I ran the exact script above, and I can't get it to fail the way my other scripts do. I will have to try to distill the broken scripts down to something that I can get to fail, at which point I will update the question.
Update 2: Okay, I figured it out. I was getting an error from stty (which I wasn't seeing because my real cleanup function was also clearing the screen). The error was: stty: standard input: Inappropriate ioctl for device. I looked this up an apparently it was due to calling stty while stdin was redirected from the file /foo/bar. So I changed my trap call to trap "break" SIGINT SIGHUP SIGTERM and it worked.

A:

It turns out the problem was due to the fact that my cleanup function was calling stty, and stty evidently doesn't like to be called while stdin is being redirected from a file. Thus, when I pressed Ctrl-C while the script was executing the read loop, the cleanup function got called as if I had called it from within the loop:
while read -r line; do
  ...
  cleanup
  ...
done < "$filename"

This, in turn, meant that stty was executed with a redirected stdin, and it died with the error stty: standard input: Inappropriate ioctl for device.
I was able to fix this by changing my trap line:
trap "break" SIGINT SIGHUP SIGTERM

So instead of having it effectively insert a call to cleanup into my loop when I press Ctrl-C, it instead just (effectively) inserts a break into the loop, thus breaking out of the loop and subsequently calling the cleanup function via the line after the loop.


Q:

Concerns about use of MAC in my specification

Here is the pseudocode for a routine I am designing:
encrypt(password, string):
  nonce1 := generate_random_nonce()
  nonce2 := generate_random_nonce()
  key := derive_key(nonce1, password)
  encrypted := cipher(nonce2, key, string)
  return (nonce1 || nonce2 || encrypted || mac(key, encrypted))

I realized that an attacker with the encrypted text might be able to brute force the key, since a mac is not slow to compute (like key derivation).
I thought about using a third nonce for the mac key instead of the ciphertext key, but the mac key should be secret so this isn't an option.

How should I correctly use a MAC to authenticate the ciphertext (and thus plaintext) in this situation?

A:

The pseudocode has a serious issue: changing the value of nonce2 in an otherwise valid cryptogram is not detected, and results in invalid deciphered plaintext. That would be fixed by
encrypt(password, string):
  nonce1 := generate_random_nonce()
  nonce2 := generate_random_nonce()
  key := derive_key(nonce1, password)
  encrypted := nonce2 || cipher(nonce2, key, string)
  return (nonce1 || encrypted || mac(key, encrypted))

but leaves two lesser issues:

The same key is used for cipher and mac; when not done properly, that can be a bad thing, and is a known recipe for disaster, e.g. if both cipher and mac used the key as an AES key for CBC encryption and CBC MAC, rather than using a carefully thought authenticated encryption mode like AES-GCM-SIV. With cipher chacha, and mac blake2b which is based on the chacha core, we should at least worry (even though I see no attack right now), and perhaps use something like proposed by Maarten Bodewes in that other answer.
We are told that derive_key is pkcs5_pbkdf2; this does key stretching, which is indispensable for any password; but PBKDF2 does not leverage the RAM and possibly multiple CPUs available at no cost to legitimate users, hence is orders of magnitude less safe against serious adversaries (using ASICs or FPGAs for password searching) than something state-of-the-art like scrypt.

A:

I would propose a rather different scheme.
encrypt(password, string):
  nonce := generate_random_nonce()
  secret := pbkdf(nonce, password)
  mackey := kbkdf(secret, 'mackey')
  enckey := kbkdf(secret, 'enckey')
  iv := kbkdf(secret, 'iv')
  encrypted := cipher(iv, enckey, string)
  return (nonce || encrypted || mac(mackey, encrypted))

Note that I've split the derive_key into pbkdf, a password based key derivation function and kbkdf, a key based key derivation function. For the PBKDF you can use PBKDF2 with a high enough iteration count. For the KBKDF you can go for HKDF-extract or maybe just for KDF1 (which is basically a secure hash - say SHA-256 - over the secret and additional data).
As long as the nonce is truly random this scheme should be secure, and you can use related primitives for the cipher and mac without any problems. This is because the KBKDF cannot be reversed. This is also why you don't need to MAC the IV; mackey, enckey and iv will all be different for each call to encrypt.
This scheme also removes the nonce2 from the output making it smaller.


Q:

How to find solutions of linear Diophantine ax + by = c?

I want to find a set of integer solutions of Diophantine equation: $ax + by = c$, and apparently $\gcd(a,b)|c$. Then by what formula can I use to find $x$ and $y$ ?
I tried to play around with it:
$x = (c - by)/a$, hence $a|(c - by)$.
$a$, $c$ and $b$ are known. So to obtain integer solution for $a$, then $c - by = ak$, and I lost from here, because $y = (c - ak)/b$. I kept repeating this routine and could not find a way to get rid of it? Any hint?
Thanks,
Chan

A:

The diophantine equation $ax+by = c$ has solutions if and only if $\gcd(a,b)|c$. If so, it has infinitely many solutions, and any one solution can be used to generate all the other ones.
To see this, note that the greatest common divisor of $a$ and $b$ divides both $ax$ and $by$, hence divides $c$ if there is a solution. This gives the necessity of the condition (which you have backwards). (fixed in edits)
The converse is actually a constructive proof, that you can find in pretty much every elementary number theory course or book, and which is essentially the same as yunone's answer above (but without dividing through first).
From the Extended Euclidean Algorithm, given any integers $a$ and $b$ you can find integers $s$ and $t$ such that $as+bt = \gcd(a,b)$; the numbers $s$ and $t$ are not unique, but you only need one pair. Once you find $s$ and $t$, since we are assuming that $\gcd(a,b)$ divides $c$, there exists an integer $k$ such that $\gcd(a,b)k = c$. Multiplying $as+bt=\gcd(a,b)$ through by $k$ you get
$$a(sk) + b(tk) = \gcd(a,b)k = c.$$
So this gives one solution, with $x=sk$ and $y=tk$.
Now suppose that $ax_1 + by_1 = c$ is a solution, and $ax+by=c$ is some other solution. Taking the difference between the two, we get
$$a(x_1-x) + b(y_1-y) = 0.$$
Therefore, $a(x_1-x) = b(y-y_1)$. That means that $a$ divides $b(y-y_1)$, and therefore $\frac{a}{\gcd(a,b)}$ divides $y-y_1$. Therefore, $y = y_1 + r\frac{a}{\gcd(a,b)}$ for some integer $r$. Substituting into the equation $a(x_1-x) = b(y-y_1)$ gives
$$a(x_1 - x) = rb\left(\frac{a}{\gcd(a,b)}\right)$$
which yields
$$\gcd(a,b)a(x_1-x) = rba$$
or $x = x_1 - r\frac{b}{\gcd(a,b)}$.
Thus, if $ax_1+by_1 = c$ is any solution, then all solutions are of the form
$$x = x_1 - r\frac{b}{\gcd(a,b)},\qquad y = y_1 + r\frac{a}{\gcd(a,b)}$$
exactly as yunone said.

To give you an example of this in action, suppose we want to find all integer solutions to $$258x + 147y = 369.$$
First, we use the Euclidean Algorithm to find $\gcd(147,258)$; the parenthetical equation on the far right is how we will use this equality after we are done with the computation.
\begin{align*}
258 &= 147(1) + 111 &\quad&\mbox{(equivalently, $111=258 - 147$)}\\
147 &= 111(1) + 36&&\mbox{(equivalently, $36 = 147 - 111$)}\\
111 &= 36(3) + 3&&\mbox{(equivalently, $3 = 111-3(36)$)}\\
36 &= 3(12).
\end{align*}
So $\gcd(147,258)=3$. Since $3|369$, the equation has integral solutions.
Then we find a way of writing $3$ as a linear combination of $147$ and $258$, using the Euclidean algorithm computation above, and the equalities on the far right. We have:
\begin{align*}
3 &= 111 - 3(36)\\
&= 111 - 3(147 - 111) = 4(111) - 3(147)\\
&= 4(258 - 147) - 3(147)\\
&= 4(258) -7(147).
\end{align*}
Then, we take $258(4) + 147(-7)=3$, and multiply through by $123$; why $123$? Because $3\times 123 = 369$. We get:
$$258(492) + 147(-861) = 369.$$
So one solution is $x=492$ and $y=-861$. All other solutions will have the form
\begin{align*}
x &= 492 - \frac{147r}{3} = 492 - 49r,\\
y &= -861 + \frac{258r}{3} =86r - 861, &\qquad&r\in\mathbb{Z}.
\end{align*}
You can reduce those constants by making a simple change of variable. For example, if we let $r=t+10$, then
\begin{align*}
x &= 492 - 49(t+10) = 2 - 49t,\\
y &= 86(t+10) - 861 = 86t - 1,&\qquad&t\in\mathbb{Z}.
\end{align*}

A:

As others have mentioned one may employ the extended Euclidean algorithm. It deserves to be better known that this is most easily performed via row-reduction on an augmented matrix - analogous to methods used in linear algebra. See this excerpt from one of my old sci.math posts:
For example, to solve  mx + ny = gcd(x,y) one begins with
two rows  [m   1    0], [n   0    1], representing the two
equations  m = 1m + 0n,  n = 0m + 1n. Then one executes
the Euclidean algorithm on the numbers in the first column,
doing the same operations in parallel on the other columns,

Here is an example:  d =  x(80) + y(62)  proceeds as:

                      in equation form   | in row form
                    ---------------------+------------
                    80 =   1(80) + 0(62) | 80   1   0
                    62 =   0(80) + 1(62) | 62   0   1
 row1 -   row2  ->  18 =   1(80) - 1(62) | 18   1  -1
 row2 - 3 row3  ->   8 =  -3(80) + 4(62) |  8  -3   4
 row3 - 2 row4  ->   2 =   7(80) - 9(62) |  2   7  -9
 row4 - 4 row5  ->   0 = -31(80) -40(62) |  0 -31  40

Above the row operations are those resulting from applying
    the Euclidean algorithm to the numbers in the first column,
        row1 row2 row3 row4 row5
namely:  80,  62,  18,   8,   2  = Euclidean remainder sequence
               |    |
for example   62-3(18) = 8, the 2nd step in Euclidean algorithm

becomes:   row2 -3 row3 = row4  on the identity-augmented matrix.

In effect we have row-reduced the first two rows to the last two.
The matrix effecting the reduction is in the bottom right corner.
It starts as the identity, and is multiplied by each elementary
row operation matrix, hence it accumulates the product of all
the row operations, namely:

       [  7 -9] [ 80  1  0]  =  [2   7  -9]
       [-31 40] [ 62  0  1]     [0 -31  40]

The 1st row is the particular  solution: 2 =   7(80) -  9(62)
The 2nd row is the homogeneous solution: 0 = -31(80) + 40(62),
so the general solution is any linear combination of the two:

       n row1 + m row2  ->  2n = (7n-31m) 80 + (40m-9n) 62

The same row/column reduction techniques tackle arbitrary
systems of linear Diophantine equations. Such techniques
generalize easily to similar coefficient rings possessing a
Euclidean algorithm, e.g. polynomial rings F[x] over a field,
Gaussian integers Z[i]. There are many analogous interesting
methods, e.g. search on keywords: Hermite / Smith normal form,
invariant factors, lattice basis reduction, continued fractions,
Farey fractions / mediants, Stern-Brocot tree / diatomic sequence.

A:

Do you mean $\gcd(a,b)$ divides $c$? If so, you can divide both sides of the equation to get
$$
\frac{a}{g}x+\frac{b}{g}y=\frac{c}{g}
$$
where $g=\gcd(a,b)$.
But since $\gcd(a/g,b/g)=1$, you can use the extended Euclidean algorithm to find a solution $(x_0,y_0)$ to the equation
$$
\frac{a}{g}x+\frac{b}{g}y=1.
$$
Once you have that, the solution $(X,Y)=(\frac{c}{g}\cdot x_0,\frac{c}{g}\cdot y_0)$ is a solution to your original equation. Furthermore, the values
$$
x=X + \frac{b}{g} t\quad y=Y - \frac{a}{g} t
$$
give all solutions when $t$ ranges over $\mathbb{Z}$, I believe.


Q:

Jquery animation on mouseover and stop on mouseout

i have six buttons with this code :
$('img#b1').on('mouseenter', function() {
    var height = $('div#b1').css('height');
    if(height == '50px'){
        $('div#b1').animate({
        'width' : '1100'
    }, 200);
    }
});
$('img#b1').on('mouseout', function() {
    var height = $('div#b1').css('height');
    if(height == '50px'){
        $('div#b1').animate({
        'width' : '990'
    }, 200);
    }
});

it works but if you quickly move mouse over and out for few times then take mouse out, it will resume the animation for times mouse went over it.
i dont want to resume animation if mouse is not over it.
how can i fix that?

A:

Here is perfect example of this.
$('img#b1')
  .hover(function() {
    $(this).stop().animate({ width: 1100 }, 'fast');
  }, function() {
    $(this).stop().animate({ width: 990 }, 'fast');
  });

http://css-tricks.com/full-jquery-animations/

A:

You should code like the following:
$('img#b1').on({
    mouseenter: function() {
        var height = $('div#b1').css('height');
        if(height === '50px'){
            $('div#b1').stop().animate({
                width: 1100
            }, 200);
        }
    },
    mouseout: function() {
        var height = $('div#b1').css('height');
        if(height === '50px'){
            $('div#b1').stop().animate({
                width: 990
            }, 200);
        }
    }
});

It makes your code more clearly.


Q:

Chosen - Binding to change event after Chosen is applied to select

I am currently using the jQuery Chosen plugin, and it is working well. Currently, I can bind to Chosen's change event like so:
$('#the_selector').chosen().change( ... );

And this works fine. I have encountered a case, however, where I need to bind to the change event after Chosen has already been applied to the select. Is there a way to do this?

A:

I was able to bind to the event using:
$('#the_selector').on('change', function(){
    Do stuff
});


Q:

login check in php

i have created a login form with userid and password input and login button and it is linked to a table called login in mysql with fields userid, password, category and department. the department field is used to specify departemtnt of staff. if the department field is empty, then the user is an admin. so when when i click my login button i want it to check if $department=="" and if that is true i should be redirected to admin page else my staff page. this is my checklogin.php file:
$sql="SELECT * FROM login WHERE userid='$myid' and password='$mypassword'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count==1)
{
$_SESSION['myid'];
$_SESSION['mypassword'];
$get=mysql_query("SELECT department FROM login");
$mydept = mysql_fetch_assoc($get);
if($mydept=="")
{
header("location:admain.php");
}
else
{
header("location:stmain.php");
}
}
else
{
header("location:main_err.php");
}

now no matter what login id and password i give i am redirected to admain.php page can anyone help me on this??

A:

There are so many bugs
You are starting session later while accessing them earlier, Also you are selecting department in the query and accessing
$result3['category'];

I dont know your table structure, bug start the session at the top Replace
 $sql1="SELECT department FROM login WHERE id='$myid' and password='$mypassword'";

With
 $sql1="SELECT category FROM login WHERE id='$myid' and password='$mypassword'";

EDIT
Use this
$sql="SELECT * FROM login WHERE userid='$myid' and password='$mypassword'";
$result = mysqli_query($con,$sql)or die(mysqli_error());
$count=mysqli_num_rows($result);
if($count==1)
{
  $row = mysqli_fetch_array($result);
  $mydept=$row['department'];
  if($mydept=="")
  {
    header("location:admain.php");
  }
  else
  {
    header("location:stmain.php");
  }
}
else
{
  header("location:main_err.php");
}


Q:

How to handle long axis labels with seaborn?

I have a few graphs I made with seaborn. I plot boxplots and other things by certain groups. I'll give you an example to illustrate:

As you can see, the x-lables are too long. I rotated them by 90 degrees just to make them readable. I could go and change the category names manually. However, I need to perform this task weekly - and the categories change over time. Do you have any good idea how to solve this issue?
For good measure, I'll give you what I have done so far. Given a figitive dataset, this is basically what I do with my pandas dataframe df:
    rank  sentiment category
0     1   0.657413        super_long_string
1     2   0.895769        super_long_string
2     3  -0.435457        super_long_string
3     4  -0.717959        other_super_long_string
4     5   0.869688        other_super_long_string

ax =sns.boxplot(x='category', y=sentiment, data=df);
ax.set_xticklabels(ax.get_xticklabels(),rotation=90)
plt.figure()

Is there a way to strip a way the long x-axis lables without losing the info? My idea is to keep the labels in a legend. Maybe similar to this example? Is that possible with seaborn, and if so how?

Any ideas? Thank you very much in advance!

A:

well of course you could try to make the boxplots horizontally by flipping the x and y
ax =sns.boxplot(y='category', x=sentiment, data=df);

you could also generate a custom legend in which you set a patch with the color of each of your boxplots
import pandas as pd
import seaborn.apionly as sns
import scipy as sp
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt

labels = ['this is some really really long label text, so long that it is much better read horizontally',
          'and another really long label, this could probably be very much reduced',
          'a short label for a change',
          'lorem ipsum',
          'and another really long and very descriptive label, including some abbreviations a.n.g']

Df = pd.DataFrame(sp.randn(len(labels),10))
Df['labels'] = labels

fig, ax = plt.subplots()
ax = sns.boxplot(data=Df.melt(id_vars='labels'),x='labels',y='value',ax=ax)
ax.set_xticklabels('')

leg_handles = []
for label,artist in zip(labels,ax.artists):
    handle = mpatches.Patch(facecolor=artist.get_facecolor(),label=label)
    leg_handles.append(handle)

ax.legend(handles=leg_handles,bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=1, mode="expand", borderaxespad=0.)
fig.subplots_adjust(top=0.75)


Q:

Jquery ajax and my php ajax sheet?

I am using alot of jquery ajax requests for my website, and my php sheet with which the ajax in jquery points to is getting rather long!
I would like to know how many if, elseif, else statements are considered too many?
If I have hundreds will it slow down my site or ajax requests? How many is considered too many, and if they are too many how do I deal with it?
Thanks

A:

My dear there is no limit of too many. As for as your concern about slow performance it always depends upon your quality of code. If you are writing quality code then there is no problem.
For Example you have sent an ajax request to a file which will return you the records from the table. Now the performance will depend how you write query, how you send back the result, how you display your result. So concentrate on writing quality of code.


Q:

Optimize SQL query in OrientDB with two sub-queries

Assume having the following SQL query:
select count(name)
from asset
where bucket in (
  select @RID
  from bucket
  where repository_name = 'some-release'
) and blob_updated < sysdate() - 17280000000

+----+-----+
|#   |count|
+----+-----+
|0   |90717|
+----+-----+

I find out how many files in repository some-release are older than 200 days. It takes me 17.588 seconds. However the following query, which I want to utilize to convert 200 days to milliseconds, gives me the same output but takes 83.93 seconds:
select count(name)
from asset
let $days = (
  select eval ( "200 * 24 * 60 * 60 * 1000" )
)
where bucket in (
  select @RID
  from bucket
  where repository_name = 'some-release'
) and blob_updated < sysdate() - first($days.eval)

Why does it take so long and how to optimize it?
Repository some-release contains 255196 files.

A:

Have you tried running your query through the EXPLAIN? More on that in OrientDB
 documentation.
The LET block is evaluated per each record, so if you've got plenty of assets in your some-release repositories (or have had in the past) this will substantially fine your query evaluation time. To avoid this you can evaluate it directly in your WHERE clause, i.e.:
select count(name)
from asset
where bucket in (
  select @RID
  from bucket
  where repository_name = 'some-release'
) and blob_updated < sysdate() - eval('200 * 24 * 60 * 60 * 1000')

May I ask what are you trying to achieve? By any chance, are you trying to get rid of some old assets? you can set up a Cleanup Policy for this purpose.
You may want to compact your blob store, to reduce the number of assets that you might not need anymore. Please make sure you understand what will happen before you run the Admin - Compact blob store task.


Q:

Recursive prefix parser factorial Java

I recently started learning java in uni and a task we had to do is to understand recursion and add factorial function to this Polish notation code. I have tried various methods, and this is the latest one:
public class PolishNotation {

    public static void main(String[] args) {
        try (Scanner scanner = new Scanner(System.in)) {
            System.out.println("Please enter the operators");
            System.out.println("for operators +, -, *, and !");
            System.out.println("Leave spaces between all operators and digits");
            System.out.print("expression: ");
            System.out.println("value = " + evaluateEXP(scanner));
        }
    }

    //input contains the expression user has entered
    public static int evaluateEXP(Scanner scanner) {
        //checks if there is another digit after current one
        //allows expression to be looked at from right to left
        if (scanner.hasNextInt())
            return scanner.nextInt();

        //if there is another digit after current one then
        //operands and operators are established
        char operator = scanner.next().charAt(0);
        int operand1 = evaluateEXP(scanner);
        int operand2 = evaluateEXP(scanner);
        return evaluateOP(operator, operand1, operand2);
    }

    //operator has to be one of +, - , * or ! otherwise error is given
    private static int evaluateOP(char operator, int operand1, int operand2) {
        if (operator == '+')
            return operand1 + operand2;
        if (operator == '-')
            return operand1 - operand2;
        if (operator == '*')
            return operand1 * operand2;
        if (operator == '/')
            return operand1 / operand2;
        if (operator == '!')
            //if ! used then uses factorial method
            return factorial(operand1);
        //RunTimeException allows to return an error string in a int "type" method
        throw new RuntimeException("operator not allowed for this language");
    }

    private static int factorial(int n) {
        return n == 1 ? 1 : factorial(n - 1) * n;
    }

}

There are no errors, but a result does not come out so I am guessing that it's stuck on an infinite loop. The idea of this code is that if I did ! + 3 2 it should do !5 so return 120 and I cannot use while or for loops. The rest of the operands work, it's just the factorial that doesn't.

A:

The problem is that in evaluateEXP your code always expects 2 operands. However ! only takes one operand, so if you enter something like ! 5 it will wait for more input.
The solution is to check if the operator is unary or binary, and only accept one operand if it is unary. Here are a few ways to refactor your code to achieve this:
1) Check the operator in the evaluateEXP method and only get the second operand if it's binary (in your case not !):
//input contains the expression user has entered
public static int evaluateEXP(Scanner scanner) {
    //checks if there is another digit after current one
    //allows expression to be looked at from right to left
    if (scanner.hasNextInt())
        return scanner.nextInt();

    //if there is another digit after current one then
    //operands and operators are established
    char operator = scanner.next().charAt(0);
    int operand1 = evaluateEXP(scanner);
    int operand2 = 0;
    //only take second operand if operator is not unary
    if (operator != '!') {
        operand2 = evaluateEXP(scanner);
    }
    return evaluateOP(operator, operand1, operand2);
}

2) Pass the scanner to evaluateOP and let it take the operands directly:
//input contains the expression user has entered
public static int evaluateEXP(Scanner scanner) {
    //checks if there is another digit after current one
    //allows expression to be looked at from right to left
    if (scanner.hasNextInt())
        return scanner.nextInt();

    //if there is another digit after current one then
    //operands and operators are established
    char operator = scanner.next().charAt(0);
    return evaluateOP(operator, scanner);
}

//operator has to be one of +, - , * or ! otherwise error is given
private static int evaluateOP(char operator, Scanner scanner) {
    if (operator == '+')
        return evaluateEXP(scanner) + evaluateEXP(scanner);
    if (operator == '-')
        return evaluateEXP(scanner) - evaluateEXP(scanner);
    if (operator == '*')
        return evaluateEXP(scanner) * evaluateEXP(scanner);
    if (operator == '/')
        return evaluateEXP(scanner) / evaluateEXP(scanner);
    if (operator == '!')
        //if ! used then uses factorial method
        return factorial(evaluateEXP(scanner));
    //RunTimeException allows to return an error string in a int "type" method
    throw new RuntimeException("operator not allowed for this language");
}

3) Building up on the 2nd solution you could also merge the 2 methods as they are so closely linked anyways:
//input contains the expression user has entered
public static int evaluateEXP(Scanner scanner) {
    //checks if there is another digit after current one
    //allows expression to be looked at from right to left
    if (scanner.hasNextInt())
        return scanner.nextInt();

    //if there is another digit after current one then
    //operands and operators are established
    char operator = scanner.next().charAt(0);

    if (operator == '+')
        return evaluateEXP(scanner) + evaluateEXP(scanner);
    if (operator == '-')
        return evaluateEXP(scanner) - evaluateEXP(scanner);
    if (operator == '*')
        return evaluateEXP(scanner) * evaluateEXP(scanner);
    if (operator == '/')
        return evaluateEXP(scanner) / evaluateEXP(scanner);
    if (operator == '!')
        //if ! used then uses factorial method
        return factorial(evaluateEXP(scanner));
    //RunTimeException allows to return an error string in a int "type" method
    throw new RuntimeException("operator not allowed for this language");
}


Q:

Rails: periodically_call_remote then redirect

I need to check some database values with a periodically_call_remote function.
I want to redirect if some values have already a certain state.
How to do this? redirect_to in the function does not seem to work.

A:

Do you need to do a refresh on the entire page?  You could use javascript to update your content.
The following javascript may work as well.
window.location = "http://www.address.com/"


Q:

Limited function calls in nodejs on same operation?

I am currently working on some scientific calculations for which my base calculation loops are executed over and over again with recursive calls as long as at least one parameter is false.
Currently my nodejs server stops at around 905 - 915th recursive function call.
The weird thing is, that it doesn't crash, nor output any error. It just stops doing anything -> no more logs etc.
Is this some protection behaviour from node to avoid overflow?
I am struggling with this for a few weeks now whilst trying to limit the "loops" with an as intelligent as possible software.
Thank you for your help & advice.
Greetings Noa.
As requested I provide some abstraction of my actual code
I hope this helps. I cannot put my original code on here because it consists of more than 1.5k lines - theres a lot to check.
But the below example covers the base logic behind the recursive call.
// Contains objects which contain an array
// which represents the amount of the ex_obj terms
var amount = {
  a:[10,10],
  b:[7.5,7.5],
  c:[2.5,2.5,2.5,2.5]
}

// Contains objects, which contain an array of other objects
// that represent some selection
// Each object in an array consists of different values per attribute per 1 amount
var ex_obj = {
  a: [
    {aa: 1.41, ab: 0.143, ac: 0.5},
    {aa: 1.30, ab: 1.43, ac: 0.42}
  ],
  b: [
    {aa: 0.32, ab: 5.54, ac: 1.3},
    {aa: 0.33, ab: 4.49, ac: 2.5}
  ],
  c: [
    {aa: 0.54, ab: 1.4, ac: 3.5},
    {aa: 0.39, ab: 1.434, ac: 3.91},
    {aa: 0.231, ab: 1.44324, ac: 2.91},
    {aa: 0.659, ab: 1.554, ac: 3.9124},
  ]
}

// Here we have an object that represents
// the "to be" state which should be achieved
var should_be ={
  aa: 14.534,
  ab: 3.43,
  ac: 5.534
}

function calculate(){
  // Now we want to mulitply the amount object values with
  // the ex_obj values

  for(let prop in ex_obj){
    for(let i = 0, i < ex_obj[prop].length, i++){
      for(let propa in ex_obj[prop][i]){
        // here every aa,ab,ac gets mulitplied with the
        // contains of the amount obj for the matching
        // propertyname
      }
    }
  }

  // the next step is to check if the sum of all ex_obj property
  // child values per aa, ab and ac match the should_be propertie values

  // if everything is above the should_be and not too high then the
  // programm can stop here and print out the amount obj.

  // if the sum of the ex_obj properties is too little
  // compared to the should_be obj
  // we need to check which property is too little
  // e.g. aa is too little
  // then we check where aa in the ex_obj per 1 value is
  // the highest
  // then we increment the matching amount property child
  // and start calculate() again

  // same procedure for - if something is too much
}

A:

Since your code isn't complete it's hard to say exactly what's going wrong. If you exceed node's call stack limit you will get an exception, although 1000 recursions isn't normally a problem.
It might be that you're choking the Node.js event-loop. Instead of directly calling the recursive function, you can try to call
process.nextTick(function(){calculate()})


Q:

How can I load a sprite sheet in Flash correctly?

As common users of flash you know that you can export images to a moveclip, doing frame per frame, but thats not very "optimized" way to do it, in C++ my friend who I can't talk with right now, have read a spritesheet and made the movements and everything by it, and since AS2 is basicly C++, that would happen to a similar code to it, but I didn't managed to find it.
The thing I want is to import same sized images from a sprite sheet like this one:
http://j.imagehost.org/0829/WoodyGX_0.jpg
They are all same sized images put together that form the sprite sheet, so there is this "algorithm" to read each one and like label it to a action use, but since I don't know that I am asking someone who could tell me the likely algorithm or a way to read that sheet, image per image into my movieclip.
Thanks for now.

A:

I couldn't resist the urge to quote you:

AS2 is basicly C++

Just because I like it.
Anyway. Yes, you  could do it, sort of, but AS2 has a rather limited toolset, so it's going to be difficult. First of all, you would need to use BitmapData.draw() method to create a bitmapdata object containing all pixels of the spritesheet you loaded.
Next, you can choose to either do BitmapData.copyPixels() or BimtapData.draw() (again, you can draw from another bitmapdata, using only a portion of it - you will need to look at the parameter where you are to pass a rectangle and a matrix, to tell it what part exactly to copy.
Lastly, to draw it, you would use MovieClip.beginBitmapFill(bitmapdata), and draw the boundaries to fill with the bitmapdata you already have.


Q:

set custom filename with JSZIP

I've coded out a zip-download, but the problem that i'm facing is that i can't manage to give the .zip a custom filename It keeps giving me some random name like these "ff22f3dc-24dc-41cb-b83d-06acef1694d0.zip". Is there an option or something similar to set it?
The way I init my download is by using this piece of code. I'm not working with an 'a' tag btw.
jszip.generateAsync({type:"blob"})
                .then(function(content)
                {
                    window.location = URL.createObjectURL(content);
                });
        }

I'm thankful for every advice.
EDIT: this zip contains Excel files (working with JSZIP Utils)

A:

According to this page in the documentation, it's possible to use the FileSaver polyfill to give your download a custom filename. It only works on modern browsers though, you will need to use feature detection to fall back to the default behaviour.
See if this works:
try {
    var isFileSaverSupported = !!new Blob;
} catch (e) {}

jszip.generateAsync({ type: "blob" })
    .then(function(content) {
        if(isFileSaverSupported) {
            saveAs(content, "custom_filename.zip");
        } else {
            window.location = URL.createObjectURL(content);
        }
    });


Q:

I want to post array param in HttpURLConnection android

I am a fresher in developing Android apps, in my app I want to post params in the format below:
user_id=12&task_id=100&user_ids=["91","92"]

I am not able to send the user_ids in array format. I am receiving the user_ids as string in my Rails API.
I am using HttpURLConnection, and in my writer.write() I am passing my post params as
writer.write("user_id="+id+"&task_id="+tid+"&user_ids="+["91","92"]+");

Please help.

A:

If any one facing the same problem, I found a work around.
You need to add the array in a string
1. Step 1
Create a final ArrayList<String> SelectedTagIds = new ArrayList<String>();

and add the array items using
SelectedTagIds.add("One");
SelectedTagIds.add("Two");
...

2. Step 2
Convert
SelectedTagIds.toString();

3. Step 3
Format the String by replacing the string to
SelectedTagIds.replace("[","").replace("]","").replaceAll("\\s","").trim();

4 Step 4
Finally post the String to the server (I used HttpURLConnection to post my data to the server), and in the server code, convert the received SelectedTagIds to Array and loop accordingly to achieve you'r desired result.


Q:

Extend of size of a list in python

I have function that appends the substrings of a string to a list. When the input string is large a
MemoryError exception
is thrown. Is there any length limit for the 1 dimensional list?.If yes how can I extend it?

A:

Yes. Available memory. Make more memory available to the process, either by adding more swap, adding more RAM, or moving to an architecture with a larger memory limit.

A:

Besides making more memory, you have several other options.

Try to change your algorithm so it is less memory-intensive. For example, if you don't need all these substrings at once, you could create and use them successively using a generator function or a generator expression.
If you need them, try to just hold the "big string" in memory, and work with buffer().
If the big string comes from a file, you could mmap() this file (or a part of it) into your address space.


Q:

use only one wireless card to connect to wifi network and share internet through wifi at same time

Is it possible to use only one wireless card to connect to other wifi network to access internet and share the internet to other devices via same wireless card at same time ?
No! I didn't mean hotspot since it means only sharing internet of other network card's (example, eth0) via wifi
I am doing two things at same time:

connect to other wifi using wireless card wlan0
share internet via same wireless card wlan0

A:

Yes it is possible to share internet through same wireless card through which you are connect to some WIFI.
You have to check whether your wireless card supports this feature or not. Following links will help you to do so:

Connectify for Linux with Single wireless interface
How do I create a WiFi hotspot sharing wireless internet connection (single adapter)


Q:

php dynamic table from muldimentional array

can you give me idea how to implement this idea for "dynamic" html table.
I have an array
$arr = array(
  array(
       'label' => 'First name',
       'data' => array(
           array('fname' => 'John'),
           array('fname' => 'Ralph'),
       ),
  ),
  array(
       'label' => 'Last name',
       'data' => array(
           array('lname' => 'Doe'),
           array('lname' => 'Loren'),
       ),
  ),
  array(
       'label' => 'Description',
       'data' => array(
           array('description' => 'Something bout John'),
           array('description' => 'Something about Ralph'),
       ),
  ),
);

Now from the keys 'label' im creating the table columns
---------------------------------------
|First Name | Last Name | Description |
---------------------------------------

The problem is how to put 'fname' keys in the first column, 'lname' in the second and 'description' in the third.
With this part of code im trying to put the data in all columns
    private function tableBody()
{
    $data = $this->data;
    $table = '
';

    foreach($data as $key => $value){
        foreach($value['data'] as $k => $v){
            $table .= '
';
            foreach($v as $col => $name){
                $table .= '' . $name . '	';
            }
            $table .= '
';
        }
    }

    $table .= '
';

    return $table;
}

Also my idea is not to hard code array keys for multiple usage(except label and data).

A:

First I would remap the data to process it in loops.
$labels = [];
$rows = [];
foreach($arr as $column) {
    $label = $column['label'];
    $labels[] = $label;
    foreach($column['data'] as $key => $value) {
        $rows[$label][] = $value;
    }
}

Now print out the labels with the headline.
echo "
\n";
echo "
";
foreach($labels as $label) echo "{$label}	";
echo "
\n";

Iterate through the rows and create the HTML.
$labelCount = count($labels);
$rowCount = count($rows[$labels[0]]);

while($rowCount) {
    echo "
";
    for ($i = 0; $i < $labelCount; $i++) {
        $current = array_shift($rows[$labels[$i]]);
        $value = reset($current);
        echo "{$value}	";
    }
    echo "
\n";
    $rowCount--;
}
echo "
\n";

This gives a table like below

First name	Last name	Description

John	Doe	Something bout John

Ralph	Loren	Something about Ralph


Q:

Using "top" in Linux as semi-permanent instrumentation

I'm trying to find the best way to use 'top' as semi-permanent instrumentation in the development of a box running embedded Linux. (The instrumentation will be removed from the final-test and production releases.)
My first pass is to simply add this to init.d:
top -b -d 15 >/tmp/toploop.out &

This runs top in "batch" mode every 15 seconds. Let's assume that /tmp has plenty of space…
Questions:

Is 15 seconds a good value to choose for general-purpose monitoring?
Other than disk space, how seriously is this perturbing the state of the system?
What other (perhaps better) tools could be used like this?

A:

Look at collectd. It's a very light weight system monitoring framework coded for performance.


Q:

Loop through collision detection with multiple processes

I'm using python to write an ideal gas simulator, and right now the collision detection is the most intensive part of the program.  At the moment though, I'm only using one of my 8 cores. (I'm using an i7 3770 @ 3.4GHz)
After minimal googling I found the multiprocessing module for python (2.7.4).  And I've tried it.  With a bit of thought I've realised the only thing I can really run in parallel is here, where I loop through all the particles to detect collisions:
for ball in self.Objects:
        if not foo == ball:
            foo.CollideBall(ball, self.InternalTimestep)

Here foo is the particle that I'm testing against all the others.
So I tried doing this:
for ball in self.Objects:
        if not foo == ball:
            p = multiprocessing.Process(target=foo.CollideBall, args=(ball, self.InternalTimestep))
            p.start()

Although the program does run a little faster, it's still only using 1.5 cores to their fullest extent, the rest are just in idle and it's not detecting any collisions either!  I've read that if you create too many processes at once (more than the number of cores) then you get a backlog (this is a loop of 196 particles), so this might explain the lower speed than I was expecting, but it doesn't explain the fact I'm still not using all my cores!
Either way it's too slow!!!  So is there a way I can create 8 processes, and only create a new one when there are less than 8 processes running already?  Will that even solve my problem?  And how do I use all of my cores/why is this code not already?
I only found out about multiprocessing in python yesterday, so I'm afraid any answers will have to be spelt out to me.
Thanks for any help though!
---EDIT---
In response to Carson, I tried adding p.join directly after p.start and this slowed the programme right down.  Instead of taking o.2 seconds per cycle it's taking 24 seconds per cycle!

A:

As far as I understand, you test one particle against all others and then perform that operation on each particle in turn. Based on this, I'd say your problem is that you try to optimize your code to work on all cores without trying to optimize your code itself.
Instead you could partitionate your particles so that you only check those that are close to each other. One possible mean to do so is a quad tree: See http://en.wikipedia.org/wiki/Quadtree.
In a second step you can parallelize everything. For quad trees you resolve the upmost level by hand and create a new process for each sub tree. By this, the processes are independent from each other and don't block. I'd expect a quadratic speed up (think of square root of your current run time) by the quad tree and the enabling of a further linear speed up (divide by number of processes) through parallelization.
Sorry, I can't spell it out in Python.


Q:

Why was Hosea acceptable to the people if he took his adulterous wife back?

Hosea is described by Rabbi Yochanan in Pesachim 87a as the greatest of the four major prophets.  At G-d's command (Hosea 1:2), he married a prostitute, Gomer, and fathered children, although there was some doubt as to whether they were all his.  His wife continues her harlotry even after they are married, but Hosea refuses to divorce her.  This is turned into a beautiful metaphor for G-d's refusal to divorce Israel, although it, too, had strayed.  I understand it to be black-letter halacha that a husband must at least divorce his wife if she admitting to having sex with another man.  (Of course, in Temple times, she and her lovers would have been subject to a criminal trial if two witnesses could testify they saw her commit adultery.)
My question is: how could Hosea's prophecy be accepted if he refused to follow one commandment?  Also, couldn't his prophecy that G-d told him to take Gomer back (Hosea 3:1; Pesachim 87b) be considered self-serving?  Rabbi Barry Fruendel suggested to me that Hosea got a "pass" because he was a prophet.  What is the basis for that?  I assume he had to be recognized as a prophet before he violated the law, right?

A:

Radak says that this was all in a Maraih Nevua (dream). This can possibly explain why Hosea was accepted as a prophet. Sinning in a dream is not the same as sinning in actuality. See Rav Pealim that it is used as a way for Hashem to let one know that they have to do Teshuva on something they did inappropriate, which in the case of Hosea he inappropriately maligned the Jews.
Dreaming of doing a sin


Q:

Hide div after redirecting to new HTML page

I have two html pages index.html and register.html
From index.html I need to go to register.html and show Login page after skipping select region. below is the code I am trying.
$("#lgnToProfile").on("click", function(){
window.location.href = "register.html";
$("#slctRgn").hide();
$("#lgnPage").show();
});

Can anyone check and suggest me how to resolve this and what I am doing wrong?
I referred the solutions provide at Show DIV or Section after redirecting to html page But no success.

A:

Once you navigate to a new page, none of the Javascript that ran on the previous page has any effect anymore.
What you would need to do, is somehow inform register.html that it needs to hide the select region div and then hide the div from a script running in register.html.
For example, from index.html you could add a query string parameter to notify register.html.
$("#lgnToProfile").on("click", function() {
    window.location.href = "register.html?hideSlctRgn=1";
}

Then, from register.html, on document ready, check if the parameter is set and hide the div accordingly.
$(function() {
    if ( window.location.search.indexOf('hideSlctRgn=1') != -1 ) {
        $("#slctRgn").hide();
        $("#lgnPage").show();
    }
})

There are other (better) ways to test for the existence of a query string parameter, but the above is a simple way. Instead of a query string parameter you could set a cookie, or perhaps use local storage.


Q:

How do I make Rails 4 associations automatically save to both tables using has_many / belongs_to?

My associations are about 50% working..
I have three tables - Users, Bands, and Bandmemberships
I can pull info from the database in my view from two tables and it works fine..

@user.bands.each

And when I run commands in the console it saves to the bands database and the bandmemberships database

user = User.first
user.bands.create(:name => "sample")

However if I run the "preferred" command in the console, it fails:

user = User.first
user.create_band(:name => "sample")
NoMethodError: undefined method `create_band' for # User:0x007ff0b9182728

But, if I use the bands/new.html.erb form only the band is saved in the database, but nothing in the association table (bandmemberships).  Not sure where to look really but I feel like I'm just missing one line of code somewhere to make it all work

Main View
views/users/show.html.erb
<% provide(:title, "My Dashboard") %>

      <%= render @user %>

You are in <%= @user.bands.count %> bands:

        <% if @user.bands.any? %>
            <% @user.bands.each do |band| %>

<%= render band %>

            <% end %>
        <% else %>

You are not in any bands.

Click here to join a band

        <% end %>

Bands Controller
controllers/bands_controller.rb
class BandsController < ApplicationController

  def create
    @band = Band.new(strong_params)
    if @band.save
      redirect_to @band
    else
      render 'new'
    end
  end

  def new
    @band = Band.new

  end

  def show
    @band = Band.find(params[:id])

  end

  private

  def strong_params
    params.require(:band).permit(:name)
  end

end

Users Controller
controllers/users_controller.rb
class UsersController < ApplicationController

  def create
    @user = User.new(strong_params)
    if @user.save
      sign_in @user
      flash[:success] = "You are now signed in"
      redirect_to @user
    else
      render 'new'
    end
  end

  def show
    @user = User.find(params[:id])
  end

  def new
    @user = User.new
    @user.bands.build
  end

  private

    def strong_params
      params.require(:user).permit(:firstname, :lastname, :email, :password, :password_confirmation)
    end

end

Users Model
models/user.rb
class User < ActiveRecord::Base

  has_many :bandmemberships
  has_many :bands, through: :bandmemberships
  has_many :tours, through: :bands

  accepts_nested_attributes_for :bands, :tours

  before_save {self.email = email.downcase }
  before_create :create_remember_token

  validates :firstname,
            presence: true,
            length: { maximum: 50}

  validates :lastname,
            presence: true,
            length: { maximum: 50}

  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i

  validates :email,
            presence: true,
            format: { with: VALID_EMAIL_REGEX },
            uniqueness: { case_sensitive: false}

  has_secure_password
  validates :password,
            length: { minimum: 6 }

  def User.new_remember_token
    SecureRandom.urlsafe_base64
  end

  def User.encrypt(token)
    Digest::SHA1.hexdigest(token.to_s)
  end

  private

    def create_remember_token
      self.remember_token = User.encrypt(User.new_remember_token)
    end

end

Band Model
models/band.rb
class Band < ActiveRecord::Base

  has_many :bandmemberships
  has_many :users, through: :bandmemberships

  has_many :bandtourmemberships
  has_many :tours, through: :bandtourmemberships

  accepts_nested_attributes_for :tours
  accepts_nested_attributes_for :users

end

Band/User association Model
models/bandmembership.rb
class Bandmembership < ActiveRecord::Base

  belongs_to :user
  belongs_to :band

end

A:

With has_many, you can't use create_object as that method doesn't exist.
You'll want to use user.bands.create(attributes_hash) in order to create a band associated to a user.
Check out the AR association docs for has_many for more details on this.


Q:

new list from specific index of multidimension list?

I'm basically trying to extract some data from multidimension list into a new list. While this code does what I want, but I'm wondering if there are better ways to get this result without looping through original list?
aa = [
    ["a", "aa", "aaa"],
    ["b", "bb", "bbb"],
    ["c", "cc", "ccc"],
]
b = []
for a in aa:
    b.append(a[1])
b
>> Result: ['aaa', 'bbb', 'ccc']

A:

>>> aa = [["a", "aa", "aaa"],
          ["b", "bb", "bbb"],
          ["c", "cc", "ccc"]]
>>> b = zip(*aa)[2]
>>> print b
['aaa', 'bbb', 'ccc']

I'm pretty sure zip still iterates through the list, but this is a much more succint way of getting the desired result.
Note that in Python 3, zip returns an iterator, so you need to convert to a list first
list(zip(*aa))[2]

or use a list comprehension
[i[2] for i in aa]


Q:

How to set background image for div

I have 3 horizontally aligned images. I set a background image (background image) for the aligned images as below. When I run my code, the background image flows over the images. I want the 3 aligned images to appear on top of the background image. I tried to use box-shadow which couldn't work. I don't want the background image to cross over any of the 3 aligned images. How do I do this please?
HTML

CSS
//how I align my 3 images horizontally.
.column-img {
    float: left;
    width: 33.33%;
    padding: 5px;
}

A:

Hm, so you want the background.png to appear behind the other images? If you insist on having it within the DOM, you'd need to remove it from the document flow. Something like this:

.column-img {
  float: left;
  width: 33.33%;
  padding: 5px;
}

.background {
  position: absolute;
  top: 0;
  left: 0;
  z-index: -1;
}

.background-anchor {
  position: relative;
}


Q:

Is it possible to force Play Framework to compile all js files in only one via RequireJS?

Using Play-Framework 2.1(rc4) and the "built-in" RequireJS, everything works great, and Play successfully compress (uglify) all my JS files in PROD, but I'd like it to join all of them in one JS file.
Is this possible? If yes, how to do so ? Is there a build.js to make with these directives ?

A:

Yes it is possible.
You have to add the requireJsShim in the Build.scala file. Often, the value of requireJsShim is the same as the requireJs property.
Once you've done that, everything will be compiled in one file!
There is an example project for Play 2.1.0: https://github.com/schleichardt/play-2.1-features/tree/stackoverflow-question-14704169 (it is not in the master but in the stackoverflow-question-14704169 branch)
play dist
(! means in JAR or ZIP)
And dist/play-2-1-features-1.0-SNAPSHOT.zip!play-2-1-features-1.0-SNAPSHOT/lib/play-2-1-features_2.10-1.0-SNAPSHOT.jar!public/javascripts-min/main.js contains all JavaScript/CoffeeScript code.


Q:

setting guifont in GVIM for windows xp ineffective

Multiple part question on running gvim on windows xp.

I have a _vimrc file that does not want to take either one of my guifont settings below:
set guifont=Monospace:h8
set gfn=Monospace:h8
I do not have a _gvimrc file, as it seems to take all the other settings I have told it to take. Do I really need a _gvimrc configuration file?
When I do a split-screen, why does my syntax highlighting disappear on the new screen(s)? My first file will highlight fine.
Is there a comprehensive blog on how to configure gvim for windows xp? I have found a few 'how-tos' but they haven't really been all that helpful.

Thanks.

A:

Nevermind, I was using the wrong font. There are a certain number of fonts gvim does not take on Windows. I am using this setting:
set gfn=courier_new:h9

Thanks.


Q:

Updating entity property values through reflection

I have entity class structure like this as below, having json columns that are related to classes and i am in the process of updating entity with some of the values.
[System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "CA2227:Collection properties should be read only", Justification = "ORM", Scope = "module")]
public class DesignProject : PatchEntityProperties
{
    [Key, GraphQLNonNullType]
    public string ProjectNumber { get; set; }
    public string Name { get; set; }
    [Column(TypeName = "jsonb")]
    public ProjectSectionStatus SectionStatuses { get; set; } = new ProjectSectionStatus();
}

and then the ProjectSectionStatus class looks like as below
public class ProjectSectionStatus
{
    public Guid Id { get; set; } = Guid.NewGuid();
    [JsonConverter(typeof(JsonStringEnumConverter))]
    public ProjectSectionStage ExecutiveSummarySectionStatus { get; set; } = ProjectSectionStage.NOT_STARTED;
    [JsonConverter(typeof(JsonStringEnumConverter))]
    public ProjectSectionStage CodesAndGuidelinesSectionStatus { get; set; } = ProjectSectionStage.NOT_STARTED;
    public string CodesAndGuidelinesSectionNotesHTML { get; set; } = "";
    [JsonConverter(typeof(JsonStringEnumConverter))]
    public ProjectSectionStage AirSystemsSectionStatus { get; set; } = ProjectSectionStage.NOT_STARTED;
    public string AirSystemsSectionNotesHTML { get; set; } = "";
    [JsonConverter(typeof(JsonStringEnumConverter))]
    public ProjectSectionStage ExhaustEquipmentSectionStatus { get; set; } = ProjectSectionStage.NOT_STARTED;
    public string ExhaustEquipmentSectionNotesHTML { get; set; } = "";
    ....
    .....
    .....
}

below is where i am updating some of the properties in section statuses for targetdesignproject
 var targetDesignProject = this._dbContext.DesignProjects.Where(a => a.ProjectNumber == targetProjectNumber).SingleOrDefault();
 targetDesignProject.SectionStatuses.AirSystemsSectionStatus = Entities.Enums.ProjectSectionStage.INCOMPLETE;
 targetDesignProject.SectionStatuses.CodesAndGuidelinesSectionStatus = Entities.Enums.ProjectSectionStage.INCOMPLETE;
 targetDesignProject.SectionStatuses.ExecutiveSummarySectionStatus = Entities.Enums.ProjectSectionStage.INCOMPLETE;
 targetDesignProject.SectionStatuses.ExhaustEquipmentSectionStatus = Entities.Enums.ProjectSectionStage.INCOMPLETE;
 targetDesignProject.SectionStatuses.InfiltrationSectionStatus = Entities.Enums.ProjectSectionStage.INCOMPLETE;
        ......
        ......

there are  10 or more similar status properties that i need to update one by one with INCOMPLETE enum status so i have tried below approach using reflection method to update all at once but stuck at setting the value
 PropertyInfo[] properties = targetDesignProject.SectionStatuses.GetType().GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

 foreach (PropertyInfo property in properties)
 {
    var propValue = property.GetValue(targetDesignProject.SectionStatuses);

    if (propValue is ProjectSectionStage)
    {
       property.SetValue() // not sure how to update here
    }
 }

Is there any way to update these statuses using reflection with Incomplete enum status. Could any one please let us know  idea in suggestions how to update these using reflection that would be very grateful to me.
thanks in advance
Update :
foreach (PropertyInfo property in properties)
{
     var propValue = property.GetValue(targetDesignProject.SectionStatuses);

     if (propValue is ProjectSectionStage)
     {
           property.SetValue(targetDesignProject, ProjectSectionStage.INCOMPLETE, null);
           // getting an error - Object does not match target type
      }
 }

A:

I have solved this problem using below code
foreach (PropertyInfo property in properties)
{
     var propValue = property.GetValue(targetDesignProject.SectionStatuses);

     if (propValue is ProjectSectionStage)
     {
           property.SetValue(targetDesignProject.SectionStatuses, ProjectSectionStage.INCOMPLETE, null);
           // getting an error - Object does not match target type
      }
 }