How to fix the exception, when I call new Microsoft.Office.Interop.Word.Application()

Question: When I call new Microsoft.Office.Interop.Word.Application() to initialize, an error occurred. The message is as follows:

Unable to cast COM object of type 'Microsoft.Office.Interop.Word.ApplicationClass' to interface type 'Microsoft.Office.Interop.Word._Application'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{00020970-0000-0000-C000-000000000046}' failed due to the following error: Library not registered. (Exception from HRESULT: 0x8002801D (TYPE_E_LIBNOTREGISTERED)).

Some help was obtained after searching in MSDN(this page).
But when I checked HKEY_CLASSES_ROOT\Wow6432Node\Interface{00020970-0000-0000-C000-000000000046}\TypeLib, I found my "Version" is 3.0 instead of 8.6, "(Default)" is {00020905-0000-4B30-A977-D214852036FF} instead of {00020905-0000-0000-C000-000000000046}. And in HKEY_CLASSES_ROOT\Wow6432Node\TypeLib{00020905-0000-0000-C000-000000000046}, there should only be 1 subkey named 8.7 instead of 8.6.
I have tried to change the Version in HKEY_CLASSES_ROOT\Wow6432Node\Interface{00020970-0000-0000-c000-000000000046}\TypeLib to 8.7 and (Default) to {00020905-0000-0000-0000-c000-000000000046}, but it still doesn't work.
I also, according to this page instructions try to "Quick Repair" and completely reinstall Office. How do I modify the registry keys to be successful?
My Word version is Professional 2019(Click-to-run).
In addition, I'm sure my code is correct. Because I wrote the code on another computer where it executed perfectly.
Here's a little bit of my code:
<code>    Microsoft.Office.Interop.Word.Application wordApp;
    Microsoft.Office.Interop.Word.Document wordDoc;
    wordApp = new Microsoft.Office.Interop.Word.Application();
    wordApp.Visible = visible;
    Object Nothing = Missing.Value;
    wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
</code>
Comment: Having such a gross version mismatch is no doubt the problem.   Microsoft was able to keep the interop compatible for a very long time but that's been running out of gas.  Version number are hard to track, I *think* that Word 2016 was version 2.8 so 3.0 sounds right for 2019.  A major version number change must always be considered breaking.  Very important to have 2019 installed on your dev machine so you can build your program with the correct type library.  And to **not** use the olden PIA as a reference in your project.  https://stackoverflow.com/a/21018418/17034
Comment: You could use a tool such as Process Monitor from sysinternals to check what registry keys are really used (filter on your process name to avoid millions of traces...).
Comment: A proper re-install could suffice?
Comment: In your place, trying to troubleshoot this, I'd start in Excel VBA and see if `New Word.Application` works there. If it doesn't, then you might get a more informative message and you can be fairly sure the problem is in the Registry. If it does work, then it narrows down the problem to the .NET "interop".
Answer: I had a very similar issue where an application runs fine on a bunch of machines, but was giving this error on another one. Turns out installed version of Office was 64-bit and was causing the problem.
After installing the 32-bit version, everything works fine.
Answer:
Reinstall word (keep the latest version if you have more than 1)

If you have word library object reference in your project, then make sure your client pc has it so open regedit and search for :

Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Classes\TypeLib{00020905-0000-0000-C000-000000000046}\x.x

where x.x is the word library version
If you have more than one x.x, delete the one thats empty, that should solve it!
Comment: Please do format the text in answer.
Answer:
Reinstall word (keep the latest version if you have more than 1)

If you have word library object reference in your project, then make
sure your client pc has it so open regedit and search for :
Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Classes\TypeLib{
00020905-0000-0000-C000-000000000046}\x.x
where x.x is the word library version

If you have more than one x.x, delete the one thats empty, that should solve it!


How to add values to url on python request

Question: I wanna get data from an api and I use this: requests.get("https://www.metaweather.com/api/location/woeid/2013/4/i/"). I want woeid to be a variable and i be an integer.
Answer: You can use Python's f-string syntax to substitute variable names for values in a string.
woeid = "2487956"
i = 12
url = f"https://www.metaweather.com/api/location/{woeid}/2013/4/{i}/"
print(url)
response = requests.get(url)

The url becomes:
https://www.metaweather.com/api/location/2487956/2013/4/12/
Answer: The longer and more time consuming version of CodeMonkey's answer would be
woeid = "2487956"
i = 12
url = "https://www.metaweather.com/api/location/" + woeid + "/2013/4" + i "/"
print(url)
response = requests.get(url)

Reason why I added this is because, string interpolation isnt supported by all languages.


How can I merge 2 spotfire tables by a regex match?

Question: I am working on a spotfire tool, and I am using a calculated column in my main data table to group data rows into 'families' through a regex match. For example, one row might have a 'name' of ABC1234xyz, so it would be part of the ABC family because it contains the string 'ABC'. Another rows could be something like AQRST31x2af, and belong to the QRST family. The main point is that the 'family' is decided by matching a substring in the the name, but that substring could be any length, and isn't necessarily the beginning of the name string.
Right now I am doing this by a large nested If statement with a calculated column. However, this is tedious for adding new families, and maintaining the current list of families. What I would like to do is create a table with 2 columns, the string match and the family name. Then, I would like to match from this table to determine family instead of the nested if. So, it might look like the below tables:
Match Table:

id_string | family
----------------------
ABC       | ABC
QRST      | QRST
SUP       | Super

Main Data Table:

name        | data        | family
---------------------------------------
ABC1234     | 1.02342     | ABC
ABC1215     | 1.23749     | ABC
AQRST31x2af | 1.04231     | QRST
BQRST32x2ac | 1.12312     | QRST
1903xSUP    | 1.51231     | Super
1204xSUP    | 1.68123     | Super

If you have any suggestions, I would appreciate it.
Thanks.
Answer: @wcase6- As far as I know, you cannot add columns from one table to another based on expression. When you add columns, the value in one matching column should exactly match with the other one.
Instead, you can try the below solution on your 'Main Data Table'.
Note: This solution is based on the scenarios posted. If there are more/different scenarios, you might have to tweak the custom expressions provided.
Step 1: Add a calculated column 'ID_string' which ignores lower case letters and digits.
Trim(RXReplace([Name],"[a-z0-9]","","g"))

Step 2: Add a calculated column 'family'.
If([ID_string]="SUP","Super",If(Len([ID_string])>3,right([ID_string],4),[ID_string]))

Final Output:

Hope this helps!
Comment: Hmmm, thanks for the suggestion. Unfortunately, my example didn't cover every case, so this won't work. Some of my required families include digits, which would break this, among other things. The issue is that I don't control the naming conventions for items in the Name field, but for the purpose of analysis I need to break them into categories. I am going to try to do something using IronPython to accomplish this, then.
Answer: As @ksp585 mentioned, it doesn't seem like Spotfire can do exactly what I want, so I have come up with a solution using IronPython. Essentially, here is what I have done:

Created a table called FAMILIES, with the columns IDString and Family, which looks like this (using the same example strings above):
IDString  | Family
------------------------
ABC       | ABC
SUP       | Super
QRST      | QRST

Created a table called NAMES, as a pivot off of my main data table, with the only column being NAME. This just creates a list of unique names (since the data table has many rows for each name):
NAME
------------------------
ABC1234
ABC1215
AQRST31x2af
BQRST32x2ac
...

Created a Text Area with a button labeled Match Families, which calls an IronPython script. That script reads the NAMES table, and the FAMILIES table, compares each name to the IDString column with a regex, and associates each name with a family from the results. Any names that don't match a single IDString get the family name 'Other'. Then, it generates a new table called NAME_FAMILY_MAP, with the columns NAME and FAMILY.
With this new table, I can then add a column back to the original data table using a left outer join from NAME_FAMILY_MAP, matching on NAME. Because NAME_FAMILY_MAP is not directly linked to the NAMES table (generated by a button press), it does not create a circular dependency.

I can then add families to the FAMILIES table using another script, or by just replacing the FAMILIES table with an updated list. It's slightly more tedious than what I was hoping, but it works, so I'm happy.


How to test async XMLHttpRequest callbacks in Jest?

Question: I have the following Jest test which includes calling a mock server using ajax with XMLHttpRequest:
import mock from "xhr-mock";

describe("ajax callbacks", function() {
  beforeEach(function() {
    mock.setup();
  });

  afterAll(function() {
    mock.teardown();
  });

  it("gets called when done", function(done) {
    mock.get("/get-url", {
      status: 200,
      body: '{ "key": "value" }'
    });

    const doneCallback = jest.fn();

    const xhr = new XMLHttpRequest();
    xhr.open("GET", "/get-url");
    xhr.onreadystatechange = function() {
      if (xhr.readyState === XMLHttpRequest.DONE) {
        doneCallback();
        done();
      }
    }
    xhr.send();

    expect(doneCallback).toHaveBeenCalled();
  });
});

which will obviously fail because the AJAX call is handled asynchronously and the expectation is made before the callback is called.
Is there any way where Jest can wait till the callback is called before making the expectation?
Please note that I cannot turn the request into a synchronous one because of the domain requirements. And neither can I turn it into a Promise based API just to be able to test it. This is just a simplified version of the test which is being written so that the folks here can grasp it easily. The actual code is different and it has abstractions to what is written here.
Comment: Why don't you put the expectation statement within `onreadystatechange` handler, before calling the `done()` function?
Comment: @slideshowp2 But it logically doesn't make sense. Cause if `onreadystatechange` handler does get run, then it automatically means that the `doneCallback` will run, so adding the expectations there would not have much value.
Answer: You can use Sinon to mock XMLHttpRequests.
import { createFakeServer } from 'sinon';

describe('Example', () => {

    let xhr;

    beforeEach(() => xhr = createFakeServer());

    afterEach(() => xhr.restore());

    test('example calls callback', () => {
        jest.spyOn(exampleObject, 'exampleCallback');

        xhr.respondWith('POST', '/expected/url', [200, { }, JSON.stringify({ foo: 'response' })]);

        exampleObject.funcToDoRequest();

        xhr.respond();

        expect(exampleObject.exampleCallback).toBeCalledWith({ foo: 'response' });
    });

});

See more information from https://sinonjs.org/releases/v9.2.0/fake-xhr-and-server/
Another way would be to use setTimeout if xhr-mock is used. Wrap callback assertion to setTimeout and call done() callback for the Jest test. Feels kind of a hack, but works.
rest of your code
...

setTimeout(() => {
  expect(doneCallback).toHaveBeenCalled();
  done();
});

Answer: I solved it by basically using the async/await support that Jest provides. The solution is to wrap the asynchronous request into a Promise and resolve the Promise when the onreadystatechange callback gets called. As such:
import mock from "xhr-mock";

describe("ajax callbacks", function() {
  beforeEach(function() {
    mock.setup();
  });

  afterAll(function() {
    mock.teardown();
  });

  it("gets called when done", async function() {
    mock.get("/get-url", {
      status: 200,
      body: '{ "key": "value" }'
    });

    const doneCallback = jest.fn();

    const xhr = new XMLHttpRequest();
    xhr.open("GET", "/get-url");

    await new Promise(function(resolve) {
      xhr.onreadystatechange = function() {
        if (xhr.readyState === XMLHttpRequest.DONE) {
          doneCallback();
          resolve();
        }
      }
      xhr.send();
    });

    expect(doneCallback).toHaveBeenCalled();
  });
});

Using await will make the test pause till the Promise gets resolved. I know this feels a bit hacky. But that's all we have for now. I tried looking into other solutions but couldn't find any.
To know more about using async/await with Jest, refer here.
Comment: This works, but Jest provides a simpler way to promisification, the [`done` parameter](https://jestjs.io/docs/en/asynchronous.html#callbacks), so you don't need to use `new Promise` or `async`/`await`.
Comment: @ggorlen I've given the reason [here](https://stackoverflow.com/questions/64195652/how-to-test-async-xmlhttprequest-callbacks-in-jest#comment113538381_64195652).
Comment: I see, but the `doneCallback` feels redundant. I'm not sure what that accomplishes over calling `done` directly which implicitly asserts that the request succeeded. Are you trying to assert that the request didn't fail? If so, this seems like it'd timeout if it fails. I see you explain the actual code has other abstractions, but what's shown here seems like an antipattern in and of itself.


scrollIntoView affect my Listener

Question: is there a way to prevent
 scrollIntoView()

from affecting my scroll Listener i have tried
 evt.data.stopPropagation();

and
 elementos.scrollIntoView().stopPropagation();

it dosen't work
Answer: It should be
evt.stopPropagation();

and
element.scrollIntoView();

elementos.scrollIntoView().stopPropagation() does not make any sense
Comment: im working with Ckeditor ,
     evt.data.stopPropagation();
works fine but i need to exclude the event fired by my other functions

scrollIntoView affect my Listener


Count how often second element is second element

Question: I have a dataframe with a column CCC that contains three-letter items. I want to count how often does each letter/element happen as first, second or third element. For example, if I have strings "spr" and "str" I have "s" two times as first letter, "p" one time as second letter, "t" one time as second letter and "r" two times as third letter. In the end I need three dictionaries
Right now I struggle to extract the second letter/element.
elements = ["p","b","t","d","k","g","f","v","s","<","z","S","Z","x","G","_","*","m","n","N","r","l","j","h","c"]
counts_C1 = {}
for element in elements:
    counts_C1[element] = df.CCC.str.startswith(element).sum()

counts_C2 = {}
for element in elements:
    counts_C2[element] =

counts_C3 = {}
for element in elements:
    counts_C3[element] = df.CCC.str.endswith(element).sum()

Comment: something like this?  `df.CCC.str[1].eq(element).sum()`
Answer: You would use .str[position]
So Below is the solution:
df = pd.DataFrame()
df['CCC'] = ['spr','str']

elements = ["p","b","t","d","k","g","f","v","s","<","z","S","Z","x","G","_","*","m","n","N","r","l","j","h","c"]
counts_C1 = {}
for element in elements:
    counts_C1[element] = df.CCC.str.startswith(element).sum()

counts_C2 = {}
for element in elements:
    counts_C2[element] = (df.CCC.str[1] == element).sum()

counts_C3 = {}
for element in elements:
    counts_C3[element] = df.CCC.str.endswith(element).sum()


Which features are unlocked when playing the Little Big Planet 2 story mode?

Question: I realized that I needed to finish the first pack of missions in Little Big Planet 2 story mode to play the community levels. Now I would like to know what else I get if I finish the other missions, and the whole game.
Answer: You get a pin and trophy for completing the main path levels in each world (i.e. challenge levels don't count).  When you complete all the main path levels in the game, you get another pin and trophy.  That's it.
Of course, along the way, you collect a lot of prize bubbles, both in the game and for completing each level.  These help when creating your own levels.


Norm-Euclidean Domains Division Algorithm

Question: A norm-Euclidean domain is an Euclidean domain with respect to the norm function or the absolute value of the norm function. This implies that, for all $a,b \in R, b \neq 0$ where $R$ is a norm-Euclidean ring, we can find $q,r \in R$ such that $a=bq +r$ and either $r=0$ or $Norm(r)<Norm(b)$. I understand that Euclideanity of a domain implies the existence of such a $q,r$, however is there an analogue of the division function in the regular integers for general norm-Euclidean domains that can deterministically find $(q,r)$?
E.g. For norm-Euclidean imaginary quadratic rings, the problem is simple, as the algebraic norm coincides with the square of the Euclidean distance on a 2d graph, so finding $q$ corresponds to finding the closest lattice point on a 2d graph.
Comment: $q$ and $r$ may not be effectively computable in general. For *computable Euclidean domains* see [here](http://www.math.uchicago.edu/~kach/mathematics/slides9oct2012.pdf).
Comment: @DietrichBurde Thanks - I'll give it a read
Answer: For complex quadratic fields, what you do, as you wrote, is
set $q = NI(a/b)$, where $NI(\alpha)$ is the algebraic integer whose coefficients (with respect to the standard integral basis) are
the nearest integers to the coefficients of $\alpha = a/b$.
The proof that a given number field is norm-Euclidean is in general constructive, so all you have to do is follow the proof.
If the number field was shown to be norm-Euclidean with the help of a computer, this will not be helpful. What you can do is consider all
algebraic integers $q$ that differ not too much from $NI(a/b)$.
As the discriminants get larger, this is less and less likely to work. What you try then is check whether one of the quotients
$q = NI(\epsilon \cdot a/b)$ for lots of units $\epsilon$ leads to a small remainder, because when it does then so will
$r = a - b \cdot q \epsilon^{-1}$. But none of this is deterministic
in general, except for number fields in which you have proved that this will work for specific units and specific choices of NI.
Thus there is a deterministic algorithm for each specific norm-Euclidean number field, but not for all norm-Euclidean fields.
Comment: Look at the articles by Cerri, e.g. http://www.ams.org/journals/mcom/2007-76-259/S0025-5718-07-01932-1/ , or at https://arxiv.org/pdf/1202.6019.pdf
Comment: In the past I constructed an algorithm that checked the orbit action of $\epsilon a/b -NI(\epsilon a/b)$ for real quadratic fields and it seemed to be quite a good algorithm but failed for certain cases, particularly when $d$ was large. Do you know of any papers that describe constructive methods to prove the Euclideanity of (particularly quadratic) number fields for high $d$? I've been tearing my hair out looking all over for such proofs but have yet to come across any.
Comment: Woops - $d$ refers to the value for the quadratic extension $\mathbb{Q}(\sqrt(d))$.


Area Effect Clouds: RadiusOnUse/DurationOnUse

Question: In my testing the radius and duration of Area Effect Clouds can be altered when entities come into contact with them, but only if the Cloud has a potion effect to apply to the entity and the effect is of a certain group of effects. For some reason Clouds with effects like Thick and Mundane can be summoned even though those effects cannot be applied to a player.
I want to alter the duration or the radius (either or, doesn't matter) of an Area Effect Cloud when it touches an entity without applying an effect to that entity, is this possible?
Answer: There are two main way to do this: The "forwards" way and the "backwards" way.
The "forwards" way would be to not use the properties of the AEC at all and instead emulate it with commands by doing calculations based on the radius of the cloud and then modifying the cloud's radius based on a player being inside it or not. That's pretty complicated.
The "backwards" way is to give the AEC an effect that doesn't normally happen (like "luck") and then to simply remove that effect from every player whenever they have it. So just this in a repeating command block or ticking function:
/effect clear @a luck

If you want to get really fancy, you can put that command into a function that is called by a hidden advancement with a corresponding effects_changed (archive) trigger, that should be the solution with the best performance.
Comment: Hmmm... all stuff I already tried. Oh well, thank you!
Comment: Aaand…? Does it work or not? You sound like it doesn't, but you didn't say why, how or what else you want.
Comment: It doesn't work how I want it to and it seems like there isn't a perfect solution as of now. Thank you for your help.
Comment: You need to give more details, otherwise I can't help you.
Comment: Basically I just wanted to execute from an AEC when a mob came into contact with it but I didn't want to actually apply any effects to the mob.
Comment: That's what my answer is about, yes. Your solution is right here!


Is it possible to trigger during an SQL row update using Logic Apps?

Question: How to trigger email upon SQL table row update ?
I want to trigger email as soon as user updates the table.
"When an item is modified (V2)" step is not working when I update the table row.
Answer: Yes it is Possible, Please make sure that based on the MICROSOFT DOCUMENTATION
You have A ROWVERSION or an IDENTITY column  .
e.g:- make sure that you have a column with data type as timestamp .
For more information please refer this Microsoft Blog: Poweruser


How do you use the new ^ system?

Question: How is this system different than the old one? Also, what new capabilities does it bring?
Answer: Introduced in 1.13, the caret notation ^ denotes the direction relative to the player's head rotation. Like the tilde notation ~, it can be used in any command that supports relative coordinates.
The general syntax is ^<left> ^<up> ^<forward>. Use negative values to specify the opposite direction. Using /tp as an example, to teleport a player 5 blocks to his/her right hand side, execute the command /tp ^-5 ^ ^.
Refer to Minecraft wiki.

How do you use the new ^ system?


Querying a table based on another table's value

Question: So this is the general flow of my app:
Main Menu -> Account Manager -> Account Details -> Payment Schedule
The data from the user's selection in Account Manager is passed to Account Details through a Serialized Object. Then from Account Details the same Serialized Object is then passed to Payment Schedule for calculation purposes and all the results are thrown into my database specifically into PayTable.
Each account can have multiple payments so to make sure I can associate the proper payment entries to the proper account I have a GroupID in my PayTable. So now entries into PayTable are assigned a GroupID which is based on the AccountID in AccountsTable passed to Payment Schedule.
So if AccountID = 1 then GroupID = 1.
Using this I can filter out the proper payments for the proper account and then  display them in my GridView in Payments Schedule.
EDIT ( Removed most of the old post that didn't matter anymore but left the gist of my situation up top for reference )
Summary
I had two tables Account and Payment. Account had colID and Payment had GroupID. GroupID was dependent on the colID of the account selected. So if colID was say 3 all payment entries during that instance would also be assigned a GroupID of 3 so I could pair the proper payments to the right account.
Problem being I needed to compare the two fields (GroupID == colID ) and get all the entries that would match the condition. So this meant a cross comparison of two fields from two tables.
Solution

Used INNER JOIN and created a view for easier GridView reference:
db.execSQL("CREATE VIEW " + viewPayments +
                " AS SELECT " + payTable + "." + colPayID + " AS _id," +
                " " + accountsTable + "." + colID + "," +
                " " + payTable + "." + colGroupID + "," +
                " " + payTable + "." + colPayBal + "," +
                " " + payTable + "." + colInterest + "," +
                " " + payTable + "." + colPayDue + "," +
                " " + payTable + "." + colDateDue + "," +
                " " + payTable + "." + colPaid + "" +
                " FROM " + payTable +
                " JOIN " + accountsTable + " ON " + payTable + "." + colGroupID + " = " + accountsTable + "." + colID );

Fixed my query
Cursor filterpay(String Payment) {
    SQLiteDatabase db = this.getWritableDatabase();
    String[] columns = new String[]{"_id", colGroupID, colPayBal, colInterest, colPayDue, colDateDue, colPaid};
    Cursor c = db.query(viewPayments, columns, colGroupID + "=?", new String[]{Payment}, null, null, null);
    return c;

Last but not least, adjust my code for posting on my GridView.
TextView txt;
txt = (TextView)findViewById(R.id.putithere);
txt.setVisibility(View.GONE);

public void Paygrid(){

dbHelper = new DatabaseHelper(this);
String Payment = String.valueOf(txt.getText());
Cursor a = dbHelper.filterpay(Payment);
startManagingCursor(a);

String[] from = new String[]{DatabaseHelper.colPayBal, DatabaseHelper.colInterest, DatabaseHelper.colPayDue, DatabaseHelper.colDateDue, DatabaseHelper.colPaid};
int[] to = new int[]{R.id.Amount,R.id.Interest, R.id.Total, R.id.DateDue, R.id.Paid};

SimpleCursorAdapter saa = new SimpleCursorAdapter(this, R.layout.paygrid, a, from, to);
intgrid.setAdapter(saa);

}

The txt stuff was just me being lazy to find a cleaner way to get the colID of the Account and reference it in my 'PayGrid' so I probably won't recommend following me in that regard.
Also since I'm new here so I don't know how to mark this question as answered when I answer my own question so if someone could point that out that would nice. That aside I hope this helps someone in the future. Cheers.
On a side note, thanks for the downvote random person! Your help is much appreciated.
Comment: first where: `" WHERE (" + colGroupID + "=? OR 1=?)"` next params: for all: `new String[]{"0", "1"}` for specific groupid `new String[]{GroupId, "0"}`
Comment: I'm not seeing where you're passing the GroupID or AccountID to your query.
Comment: Why is this `new String[]{}` **empty**? You aren't passing your parameter...
Comment: Sorry about that, I must've overwritten that part when I was copy-pasting codes. I edited and marked it as a NOTE now. Again, sorry.
Answer: I just saw the "Answer your question" button at the bottom of the page RIGHT AFTER I edited and posted my own solution.... yes, I did facepalm when I did.
Solution

Used INNER JOIN and created a view for easier GridView reference:
db.execSQL("CREATE VIEW " + viewPayments +
                " AS SELECT " + payTable + "." + colPayID + " AS _id," +
                " " + accountsTable + "." + colID + "," +
                " " + payTable + "." + colGroupID + "," +
                " " + payTable + "." + colPayBal + "," +
                " " + payTable + "." + colInterest + "," +
                " " + payTable + "." + colPayDue + "," +
                " " + payTable + "." + colDateDue + "," +
                " " + payTable + "." + colPaid + "" +
                " FROM " + payTable +
                " JOIN " + accountsTable + " ON " + payTable + "." + colGroupID + " = " + accountsTable + "." + colID );

Fixed my query
Cursor filterpay(String Payment) {
    SQLiteDatabase db = this.getWritableDatabase();
    String[] columns = new String[]{"_id", colGroupID, colPayBal, colInterest, colPayDue, colDateDue, colPaid};
    Cursor c = db.query(viewPayments, columns, colGroupID + "=?", new String[]{Payment}, null, null, null);
    return c;

Last but not least, adjust my code for posting on my GridView.
TextView txt;
txt = (TextView)findViewById(R.id.putithere);
txt.setVisibility(View.GONE);

public void Paygrid(){

dbHelper = new DatabaseHelper(this);
String Payment = String.valueOf(txt.getText());
Cursor a = dbHelper.filterpay(Payment);
startManagingCursor(a);

String[] from = new String[]{DatabaseHelper.colPayBal, DatabaseHelper.colInterest, DatabaseHelper.colPayDue, DatabaseHelper.colDateDue, DatabaseHelper.colPaid};
int[] to = new int[]{R.id.Amount,R.id.Interest, R.id.Total, R.id.DateDue, R.id.Paid};

SimpleCursorAdapter saa = new SimpleCursorAdapter(this, R.layout.paygrid, a, from, to);
intgrid.setAdapter(saa);

}

The txt stuff was just me being lazy to find a cleaner way to get the colID of the Account and reference it in my PayGrid so I probably won't recommend following me in that regard.


What software should I use to visualize a major renovation?

Question: We are going to make major changes in our new apartment (remove walls, construct new walls, new windows, new doors, new kitchen, new bathrooms, paint, fake ceiling, new furniture  etc.). Where do I find a good software to visualize the changes, preferable in 3D with possibility to add light. We have the plan in drawing.
I had a look at Google sketchup but seems beyond my capabilities - a possibility would be to find someone to create the 3D work and send me the sketchup file. Where do I find someone and what should I expect it to cost.
I also looked at floorplanner.com but does not give me a real sense of how changes will look.
Comment: possible duplicate of [DIY Design Software](http://diy.stackexchange.com/questions/949/diy-design-software) also [Affordable 2D drafting software for amateurs?](http://diy.stackexchange.com/q/820/22)
Answer: Sketchup might seem a little intimidating at first, but it is very easy to learn and use. There are a lot of great tutorial videos online. Also there are tons of free models available for furniture, fixtures etc.
I have tried a few specialized 3D home modeling programs. They all have a learning curve much steeper then sketchup and at the same time often produce inferior results.
Comment: I was actually talking about various home design programs you would find in Staples or OfficeDepot. They cost $30-$50 and suck compared to sketchup.
Comment: Something like Blender *can* produce superior results, but I'd agree that it is a little harder to learn Blender, Maya, etc.  Blender is to SketchUp what C++ is to Visual Basic.  People that are new to programming will find VB to be more powerful because it's easier to learn and use, but in the hands of an expert, C++ is more powerful.
Answer: SketchUp is good, but Blender is also a possibility.
As far as getting someone to do it for you, I wouldn't know the best place for that.  In terms of cost, it depends on how good the person is and how much detail you want.  A rough visualization would take only a little bit of time, but more detailed stuff would take quite a while.  A little warning, however.  A render -- especially if it is mediocre --probably isn't going to give you a feel for the volume of the space.
I haven't done 3d work in quite a while, but I suppose I could do it if you don't have any luck elsewhere.  I haven't worked with Blender before, but really the only thing I might have problems with is figuring out the render settings.
Comment: I love Blender for its power, but trying to learn to use it is like learning to sing underwater...
Answer: I tried using Punch Home Design for my renovation. It was ok, but really slow by the time you chucked in a lot of details.
My neighbour, who is in the building industry and managing all aspects of her renovation, used Sketchup. Having seen the quality of her drawings I'd definitely go the Sketchup route.
As for Blender - not unless you already know it well.
Answer: I've had good luck with SweetHome 3D. I like it above Sketchup for this kind of thing because it's much easier to adjust things, say move a wall 2". It's also fast and fairly customizable.
Answer: I'd probably try Sketchup, but several years ago, I used 3-D Home Architect. I bought an older simpler version at the time and it worked fine to draw my basement when I was finishing it.
Answer: Try Blophome. I've been using it for years. It's very simple and you can add lights and regulate the ambient light of the project. It has a large amount of furniture.
Answer: If you find the various software intimidating/hard to get started with/has a steep learning curve there is always graph paper (or a scale ruler), cardboard and hot glue to make a physical model (and possibly a camera, if that helps you "see" better than looking at the model directly - people vary.)


Remove class from single div of a sequence that was rendered through map

Question: I am rendering a sequence of divs with some content and a button. All divs have a certain class on them and they also have a button. When I click on that button, I want to remove the class of the div that it belongs to. My render code looks like this:
render () {
  return (

      {
        arr.map(x => {
          return (

              <button onClick={() => this.handleClick()}> Remove class <button>

          )
        })
      }

  )
}

For the button click, I am simply setting the displayClass to false and I successfully remove the div:
handleClick () {
  this.setState({ displayClass: false })
}

The problem here obviously is that the way I'm doing it, it will remove all classes from all divs. So my question is how can I make each button click to only remove the class from it's own div?
Comment: The react way is to make the class a part of the state using an array, or to turn the `` inside the loop into a stateful component.
Comment: What the best way to fix this is depends on whether the app has to know about the class state of an individual div.
Answer: Just extract each div into separate component with his own state:
class ClassManagableDiv extends PureComponent {
  state = {
    displayClass: true
  };

  handleClick = () => {
    this.setState({ displayClass: false })
  }

  render() {
    return

      <button onClick={this.handleClick}> Remove class </button>

  }
}

And next apply it to your array:
render () {
  return (

      {
        arr.map(x => <ClassManagableDiv />)
      }

  )
}

Answer: You can create a stateful component for the individual div that will contain that state. Then when you click on the button, it will only update the state of that component, not of all.
Answer: render () {
  return (

      {
        arr.map(x => {
          return (

              <button onClick={(ev) => this.handleClick(ev,"someClass")}> Remove class <button>

          )
        })
      }

  )

}
and
handleClick (ev,classN) {
    ev.currentTarget.parentNode.classList.remove(classN)
}

what it does ? you sen de event "ev" when calling handleClick plus add the className to be removed, then in handleClick you get that target el that fired the event, then look for its parent / which is the one that holds the class / and remove it
Comment: return (

 this.handleClick(ev,"someClass")}> Remove class

          )


Steam download issue

Question: Normally I let my games on Steam download at night. Recently I bought a game that because of its size I'd have to let download over night. I got the game like 3 days ago and every morning Steam has stopped downloading that game and started to download another instead. Anyone know why it's doing this?
Comment: How many games do you have queued up to download...? At some point you should only have the one game to download right?
Comment: what game you trying to download?
Answer: I'm not sure why Steam is doing that, but a solution would be to set the game download to high priority.
Right-click the game in your steam library, then go to properties --> updates, and set "automatic updates" to "high priority"

Another option would be to go to your downloads tab (view --> downloads) and pause all other updates.
Answer: Not all Steam games are hosted on the same server.
If you have multiple games going, and you pause one to try to download another, you may see different download speeds. This means that you're not making the same connection to get the game enough though it is still on Steam.
This means that if one server is particularly overloaded with a popular game, it may occasionally pause. If you have multiple games downloading, it'll simply move on to the next game.
Remove/pause your other games and let Steam download only this one game.

Steam download issue


Right margin lost when minimizing window

Question: I can provide more specific code if necessary but this basic code should demonstrate my issue.  Essentially my page looks great when the window is maximized (min-width + left + right margin).  But when you minimize the window the right margin disappears.
The idea is to have a body that always maintains a specific page margin around the content.  Then to have the content always centered.
Code below.  I've simplified my implementation to highlight my issue.

    ....my content

Comment: I ended up solving my issue in another way.  Below is the solution I ended up using.
Answer: You need to use 'display:inline-block;'
http://jsfiddle.net/CunsN/

  ....my content

Comment: This seems to be working.  Thanks!  I still need to check a few other things though.
Answer: try position fixed and forget about inline style

    ....my content

Comment: Thanks but setting a fixed position would require me changing some of the positions and styles of the rest of the elements.  Although I will give this a try just to see how it works in production.  Thanks.
Answer: Here is the solution that I ended up using.

       ....my content

Thank you for all your suggestions.


Icons color Accessibility testing - Tools and process

Question: We have a repository of old icons which are flat,gradient,simple,compound icons for win32 and win64 applications(basically legacy software icons). Currently we are trying to do color accessibility for this,so these icons are accessible for visually impaired people.(luminosity and Color blindness)
How can we take this process? What tools we can use to analyze this? How to do the testing of the icon?
I tried Contrast color analyzer tool for luminosity and color blindness, most of icons I tested failed in the process,since the tool asking only for background and foreground color(Ex:Close icon in a red gradient circle,in this case foreground will be reddish orange and red,and background will be white, Most of the results are failing). How do we perform this testing and conclude and suggest icon color accessibility?
Please suggest us.
Attaching icon:
Thanks,
Nithin
Comment: If the icon of your example is failing in all the gradient (from red to orange) lighten up all the gradient, if only one of the extremes then lighten up that one, is this what you are doing right now?
Comment: Are we talking about contrast between the icon and its background or contrast within the icon itself?
Comment: @Alvaro: Yes i tried doing that, however if its orange its showing its failing, if i change the rgb value its only right until i make it pure red. How do i handle gradient icons ?
Comment: @MattObee I need both, if its a flat icon its easy for me to check the color contrast between icon and background. However if i have gradient icon i am facing this problem.
Comment: And guys, Is this the right approach to test the icon color accessibility?
Answer: My suggestion is go for flat icons and use color with purpose. From a user experience perspective, in my opinion, color should be used in certain elements to give attention rather than to represent physical aspects of the element (or other kind of connotations).
If you use icons that have gradients and colors my suggestion to check visually if things have enough contrast or not, is to convert everything to black and white.

To test in a contrast tool, then a possibility, which I am not sure how accurate it is, is to apply an average blur filter to the color to obtain the mid color. Then use that color in the contrast tool and see if it needs more lightness or not.


Matrix with a certain pattern

Question: Consider the following matrix:
$$\left[\begin{array}{cccc} 1+x_1y_1 & 1+x_1y_2 & \ldots & 1+x_1y_n  \\
1+x_2y_1 & 1+x_2y_2 & \ldots & 1+x_2y_n \\
1+x_3y_1 & 1+x_3y_2 & \ldots & 1+x_3 y_n \\
\vdots & & & \\
1+x_ny_1 & 1+x_ny_2 & \ldots & 1+x_n y_n \\
\end{array}  \right]$$
with $x_k, y_k$ being real numbers. I suppose that there must be some neat way of computing the determinant of this matrix. Those ones are annoying to me.
Comment: @costrom this heavily depends on your choice of the $x_k$ and $y_k$ respectively
Comment: This appears to be singular, after doing several matrices out by hand and doing some symbolic calcs in Octave
Answer: The matrix can be expressed as the sum of two rank $1$ matrices, each of which is the outer product of vectors
$$M=\mathbf{11}^T+\mathbf{xy}^T$$
where $\mathbf{1}=[1,1,1,\cdots,1]^T\in\mathbb{R}^{n\times 1}$, $\mathbf{x}=[x_1,x_2,\cdots,x_n]^T\in\mathbb{R}^{n\times 1}$ and $\mathbf{y}=[y_1,y_2,\cdots,y_n]^T\in\mathbb{R}^{n\times 1}$.
Using the subadditive property of the rank, where $\text{rank}(A+B)\leq\text{rank}(A)+\text{rank}(B)$, we have
$$\text{rank}(M)\leq\text{rank}(\mathbf{11}^T)+\text{rank}(\mathbf{xy}^T)\Rightarrow \text{rank}(M)\leq 2$$
Thus, only when $n=2$ the matrix can be full rank, and so potentially have a non-zero determinant, which is easily evaluated as $(1+x_1y_1)(1+x_2y_2)-(1+x_2y_1)(1+x_1y_2)$. However for $n\geq3$, the matrix will be rank deficient, in which case the determinant will be $0$.
Comment: This is impressively simple. Well done! (+1)
Answer: Here are two approaches.
1) By inspecting the pattern of this matrix, one sees that it is of the form $A+x y^T$ where $A$ is the matrix of ones and $x,y$ are appropriate column vectors. The matrix determinant lemma then gives $\det(A+x y^T)=\det(A)+y^T \text{adj}(A)x$ where $\text{adj}(A)$ is the adjugate matrix of $A$. But the determinant of $A$ vanishes; moreover, if $n\geq 3$ then then so too does the the adjugate, so the determinant is equal to zero for $n\geq 3$.
2) If we imagine trying to compute this determinant by cofactors, we see that should be some degree polynomial of degree $2n$ in the variables $x_k,y_k$. Furthermore, said polynomial must be antisymmetric with respect to swaps of $x$- or $y$- variables. This suggests an answer of the form $\displaystyle A\prod_{i<j}(x_i-x_j)(y_i-y_j)$ where $A$ is some overall constant. To normalize this, we take $x_k=y_k=\omega^k$ where $\omega=e^{2\pi i/k}$. Then the matrix is circulant and for $n\geq 3$ has a zero eigenvalue, but the above polynomial doesn't vanish. Consequently both $A$ and the determinant itself must vanish if $n\geq 3$.
Answer: If the matrix is $M$, then
$M=J+XY$
where $J$ is the vector of all ones. $X$ is an $n*n$ matrix that has $x_1,x_2,...,x_n$ on the diagonal and zeros elsewhere. $Y$ is an $n*n$ matrix that has $y_1,y_2,...,y_n$, with the same order, on every row.
$rank(J)=1, rank(Y)=1,rank(X)= n$
$rank(XY)\leqslant min(rank(X),rank(Y))=min(1,n)=1$
Therefore
$rank(XY)=1$
$rank(J+XY)\leqslant rank(J)+rank(XY)=2$
If $2<n$, then we can conclude
$rank(J+XY)\leqslant 2 < n$
So, the rank of $M=J+XY$ is less that $n$ and consequently, its determinant is zero. But the correctness depends on the assumption that $2<n$

Matrix with a certain pattern


Run multiple projects in debug mode from the command line in Visual Studio

Question: Our program has multiple parts (Frontend npm, Backend and multiple executables in one solution). It's tedious to always open all these and run them manually so I'm trying to make a bat script to run them all for me. This includes building and running the backend and the executables in debug mode. The executables reside in a single solution but it's made up of multiple projects that need to run simultaneously. It is configured in to start all the needed projects when running the  solution
I also want to start the three solutions concurrently so the script is not waiting for each of them to start up but starts them at the same time.
I've looked up how to use Visual Studio from the command line.

I've tried using the /run switch at first but this only builds and runs the program without debugging which is not the desired outcome for me.
I've tried seeing if /? has more info than the online documentation but it also didn't list an option that would be good for me.
I wanted to use /build option then use /debugexe but then I would have to run it for all my executables and I want all projects to run from one debugging session.

I've also found various stackoverflow questions about running visual studio from the command line but none of them seemed to ask for what I need in this scenario.
This is my .bat so far
<code>@echo off

set "VS_PATH=C:\Program Files\Microsoft Visual Studio\2022\Enterprise\Common7\IDE\devenv.exe"

set "PROGRAM_FOLDER=C:\Dev\Repos\Program"
set "PROGRAM_SOLUTION=Program.sln"

set "BACKEND_FOLDER=C:\Dev\Repos\web-backend"
set "BACKEND_SOLUTION=Web-Backend.sln"

set "FRONTEND_FOLDER=C:\Dev\Repos\web-frontend"

@REM EXECUTION ///////////////////////////////////////////////////////////////////
@REM Programs
echo Opening Programs solution folder
cd /d "%PROGRAM_FOLDER%"

echo Build and run solution
"%VS_PATH%" /run "%PROGRAM_SOLUTION%"

@REM Backend
echo Opening Backend solution folder
cd /d "%BACKEND_FOLDER%"

echo Build and run solution
"%VS_PATH%" /run "%BACKEND_SOLUTION%"

@REM Frontend
echo Opening Frontend folder
cd /d "%FRONTEND_FOLDER%"

echo Starting frontend
npm start
</code>
Comment: You say that everything is all in one Solution? In which case, is there a reason you can't use the normal Visual Studio functionality for multiple startup projects? See https://learn.microsoft.com/en-us/visualstudio/ide/how-to-set-multiple-startup-projects?view=vs-2022
Comment: We typically `start` executables and `call` batch files. `start` is to launch them outside of the `cmd` console. So each would start after each other and not have to wait for them to complete before starting the next process. Also. `Start "" "path\program.exe"` .... with the empty comment double quotes after start
Comment: Yep this is the way it's set up right now. When I use the /run switch it works fine, the problem is I also want to debug.
Answer: If you need that debugger to be called while starting the processes, I suggest a different approach over the batch script. You probably want to have only a single debugging session for all processes instead of individual sessions for each one. In that case, you might be better off creating a simple launcher application that spawns child processes. It would do the same job as the batch script, but it will be a lot easier to attach a debugger to it. (EDIT: ...since it can track the PID of those processes.)
Looks like you already have working a solution to run your applications without debugger... There is an extension that will allow you to debug to multiple processes: https://github.com/karpach/debug-attach-manager


sorting vector of vector of strings in C++

Question: I am having trouble to figure out, how to sort a vector of vector of strings, here is the testing code.

#include &ltiostream>
#include &ltvector>
#include &ltboost/algorithm/string.hpp>

int main(int argc, char** argv) {
  std::vector &ltstd::vector &ltstd::string> > data_var;
  std::vector &ltstd::string> temp;

  std::string str1 = "1,hello3,temp2";
  std::string str2 = "2,hello2,temp1";
  std::string str3 = "3,hello1,temp3";

  boost::split(temp, str1, boost::is_any_of(","));
  data_var.push_back(temp);
  boost::split(temp, str2, boost::is_any_of(","));
  data_var.push_back(temp);
  boost::split(temp, str3, boost::is_any_of(","));
  data_var.push_back(temp);

  // sorting code here...
}

Thanks in advance...
Comment: How do you know if one `vector` should come before or after another?
Comment: a vector> can be thought of as a two dimensional array of strings, or 3d array of chars.  How would you like this sorted?
Comment: So... is your sorting code that you commented out broken?  Or do you just want us to implement the sorting code for you?
Comment: @SB: I am not able to figure out how to sort it...
Comment: @Bill: changed the strings...
Answer: Alright: new -simpler- answer, having learned that vectors are comparable:
//sorting code here...
std::sort(data_var.begin(), data_var.end(), std::greater<std::vector<std::string>>());

Comment: You're missing parenthesis after `std::greater>` to actually construct the functor.
Comment: This will sort by the first column, then second, then third, etc.  If you want a specific column, use Bill's answer, or if you want a specific order, customize my first answer or Bill's answer.
Comment: how do I specify sort on which column?
Answer: If you only want to sort based on the second column, then you just need to provide a custom comparison operator.  Once way to do that is:
struct StringListCompare
{
  bool operator()(const vector<string>& lhs, const vector<string>& rhs)
  {
    // what do we do if lhs or rhs don't have two elements?
    if (lhs.size() < 2 || rhs.size() < 2)
    {
      // ?
    }
    else
    {
      return lhs[1] < rhs[1];
    }
  }
} StringListComparer;

int main()
{
  // ...
  sort(data_var.begin(), data_var.end(), StringListComparer);
}

Edit: If you won't know until runtime which column you'll be sorting on, you can encode that in the sorting object:
class StringListCompare
{
public:
  explicit StringListCompare(int column) : m_column(column) {}
  bool operator()(const vector<string>& lhs, const vector<string>& rhs)
  {
    // what do we do if lhs or rhs don't have (m_column + 1) elements?
    return lhs[m_column] < rhs[m_column];
  }
private:
  int m_column;
};

Notice how we've added a constructor that takes which column it'll act on.  You can use it like this:
  // We set it up so the columns are 0-based:
  StringListCompare compare_column_0(0), compare_column_1(1), compare_column_2(2);

  cout << "Original:\n" << data_var << endl;
  sort(data_var.begin(), data_var.end(), compare_column_2);
  cout << "Sorted on column 2:\n" << data_var << endl;
  sort(data_var.begin(), data_var.end(), compare_column_1);
  cout << "Sorted on column 1:\n" << data_var << endl;
  sort(data_var.begin(), data_var.end(), compare_column_0);
  cout << "Sorted on column 0:\n" << data_var << endl;

You don't even need to make the local variable if you don't want to:
  sort(data_var.begin(), data_var.end(), StringListCompare(2));
  cout << "Sorted on 2, no local sort variable:\n" << data_var << endl;

[Code at ideone]
Comment: is there anyway I can pass the column as a parameter to the StringListComparer?
Comment: @Ringo: It makes the class more complicated, but yes.  I'll add a sample.
Comment: @Ringo: I've added code so the comparison object knows which column it'll be comparing against.  Does that make sense?
Answer: I'm going to assume each vector represents an record of some type, and compare the internal strings from left to right.  Obviously the sorter() code is easily replaceable.  You should to add a sorter() function somewhere to your code, and pass it to the std::sort algorithm.
bool sorter(const std::vector<std::string>& left, const std::vector<std::string>& right)
{
    //go through each column
    for(int i=0; i<left.size() && i<right.size()) {
        // if left is "more" return that we go higher
        if( left[i] > right[i])
            return true;
        // if left is "less" return that we go lower
        else if (left[i] < right[i])
            return false;
    }
    // if left is longer, it goes higher
    if (left.size() > right.size())
        return true;
    else //otherwise, left go lower
        return false;
 }

 int main() {
     std::vector <std::vector <std::string> > data_var;
     //...

     //sorting code here...
     std::sort(data_var.begin(), data_var.end(), sorter);

     //...
 }

Comment: You're right, I wasn't reading the signs right.  But in fact, operator< *is* overloaded for vector, as is operator>, so you could use std::greater, or std::less(which would be the default)
Comment: Your 'sorter' comparator is equivalent to the default one.
Comment: @Benjamin Lindley: I'm pretty sure the default comparer is std::less, which defaults to T::operator<(const T&), which is not overloaded for std::vector.  Also, we're going for decreasing order (std::more, if it worked on vectors)
Comment: @Mooing Duck: thanks, but I don't understand 1 thing, you are sending the parameters to std::sort as const right? then how does it modify data_var?
Comment: @Benjamin: well look at that!  I never knew it was!  http://msdn.microsoft.com/en-us/library/572x098y(v=VS.71).aspx
Comment: std::sort does the modifications.  It uses a helper named "sorter" to tell it the order, but "sorter" doesn't actually need to change anything.
Comment: i c... Can you point me some link which explains std::sort function?
and not http://www.cplusplus.com/reference/algorithm/sort/
Comment: Since the "fix" is so dramatic, I posted it as a second answer.  @Ringo, check out the one-line answer, since Benjamin showed me an easier way.
Comment: I was going to say the code in `sorter` could be replaced with `std::lexicographical_compare` but I checked the MSVC++ headers and the `operator<` overload already calls `std::lexicographical_compare`. I did not know that before.
Answer: Check out the sort function from algorithm:
template <class RandomAccessIterator> void sort ( RandomAccessIterator first, RandomAccessIterator last );

template <class RandomAccessIterator, class Compare> void sort ( RandomAccessIterator first, RandomAccessIterator last, Compare comp );

Click here for an example + docs


Using auto-fill or auto-fit in grid-template-rows: repeat(auto-fill, 200px) only sets the height for the first row - why is this?

Question: I wanted to set the row height for each row in a grid using grid-template-rows: repeat(auto-fill, 200px) but realised it only applies to the first row of the grid. Turns out grid-auto-rows: 200px was better suited for my needs, but I'd still like to know why using auto-fill in grid-template-rows: repeat(auto-fill, 200px) only sets the height for the first rows instead of all rows. Note: if I use an integer instead of auto-fill it correctly sets the height for the number of specified rows.
Image examples:

grid-template-rows: repeat(auto-fill, 200px)
grid-template-rows: repeat(3, 200px)
Answer: From the specfication:

When auto-fill is given as the repetition number, if the grid container has a definite size or max size in the relevant axis, then the number of repetitions is the largest possible positive integer that does not cause the grid to overflow its grid container (treating each track as its max track sizing function if that is definite or as its minimum track sizing function otherwise, and taking gap into account); if any number of repetitions would overflow, then 1 repetition. Otherwise, if the grid container has a definite min size in the relevant axis, the number of repetitions is the smallest possible positive integer that fulfills that minimum requirement. Otherwise, the specified track list repeats only once.

It's a bit tricky but auto-fill is suitable for column definition because we have a max size since by default the element will be full width but it's not the case when dealing with row and height.
Unless you define an explicit height, you will most probably fall into the case of only one repetition like you are facing:

.container {
  display:grid;
  grid-template-rows:repeat(auto-fill,200px);
  grid-gap:5px;
}

.container div {
   height:50px;
   background:red;
}

body {
  border:5px solid blue;
}

The same will happen in a column definition when using inline-grid

.container {
  display:inline-grid;
  grid-template-columns:repeat(auto-fill,200px);
  grid-gap:5px;
}

.container div {
   height:50px;
   background:red;
}

As you already noticed, the correct way is to use grid-auto-rows: 200px
Comment: @tfu yes exactly, auto-fill will be converted to the *best* number that will avoid you any overflow. It's suitable for column layout to have a dynamic layout on resize but we rarely use it with rows. Probably there is a use case for rows but I don't have anyone in mind actually
Comment: Thanks - that makes sense now.

So given a container height of 500px and no spacing, `repeat(auto-fill, 100px)` and `repeat(5, 100px)` would have the same outcome because auto-fill would calculate that only 5 100px items will fit in a 500px container.
Answer: So upon my inspection, I realized that this occur because the height of the parent is not sufficient for every row to be at least 200px.
Make sure element have sufficient height and use auto-fit it worked for me.


Mean of wc -l in grep command

Question: Is the wc -l showing how many times the search string is found in the binary file?
-l, --lines
print the newline counts (I think a newline is an empty line?)
 grep --binary-files=text 'postal_code77586' formhistory.sqlite | wc -l

andy@7 ~/Downloads> grep --binary-files=text 'postal_code77586' formhistory.sqlite | wc -l
1

Answer: The program wc:
wc - print newline, word, and byte counts for each file

is very useful. In your example it is printing how many lines have the text postal_code77586, via the -l options. You had one line with that text.
The grep / wc pair of commands used this way is better suited to text files. If your file is truly binary, then the newline character will be merely be as hit is the binary stream and wouldn't really mean "lines" at all.
Note that regardless, if there are multiple occurrences of postal_code77586 between newline characters, the count would still be 1.
Comment: Geany would not open the file, so I am sure it is a binary file. I used Ghex. @Doug Smythies
Answer: Yes. -l counts lines (in this case from the output of grep command), -w counts words (strings) and -b counts characters (bytes).
I personally would use the grep parameter -c to get the same result. In this example:
grep -c --binary-files=text 'postal_code77586' formhistory.sqlite

No pipe to wc needed.

Mean of wc -l in grep command


NInject, NHIbernate and ISession in request scope

Question: I'm basically using an example which I've seen in many places but I'm not convinced it's working properly.
So, I have the following:
public class NHibernateHelper
{
    private readonly string _connectionString;
    private ISessionFactory _sessionFactory;

    public ISessionFactory SessionFactory
    {
        get { return _sessionFactory ?? (_sessionFactory = CreateSessionFactory()); }
    }

    public NHibernateHelper(string connectionString)
    {
        _connectionString = connectionString;
    }

    private ISessionFactory CreateSessionFactory()
    {
        return Fluently.Configure()
                .Database(FluentNHibernate.Cfg.Db.MySQLConfiguration.Standard
                    .Dialect("NHibernate.Spatial.Dialect.MySQLSpatialDialect,NHibernate.Spatial.MySQL")
                    .ConnectionString(_connectionString))
                    .Mappings(m => m.FluentMappings.AddFromAssemblyOf<EventListing>())
                    .ExposeConfiguration(x =>
                    {
                        x.SetProperty(NHibernate.Cfg.Environment.CurrentSessionContextClass, ConfigurationManager.AppSettings["current_session_context_class"]);
                    })
                .BuildSessionFactory();
    }
}

and in my Ninject startup I have
private static void RegisterServices(IKernel kernel)
    {
        NHibernateHelper helper = new NHibernateHelper(WebConfigurationManager.ConnectionStrings["eventlisting"].ConnectionString);
        kernel.Bind<ISessionFactory>().ToConstant(helper.SessionFactory).InSingletonScope();
        kernel.Bind<ISession>().ToProvider(new SessionProvider()).InRequestScope();
        kernel.Bind(typeof(IReadOnlyRepository<>)).To(typeof(ReadOnlyRepository<>)).InRequestScope();
        kernel.Bind(typeof(IRepository<>)).To(typeof(Repository<>)).InRequestScope();
}

and my session provider class looks like
public class SessionProvider : Provider<ISession>
{
    protected override ISession CreateInstance(IContext context)
    {
        ISession session = DependencyResolver.Current.GetService<ISessionFactory>().OpenSession();
        session.FlushMode = FlushMode.Auto;
        return session;
    }
}

What is confusing me is that despite stating that ISession should be created in request scope, it seems to hit the CreateInstance method multiple times per request and looks to be spawning multiple sessions.
e.g. if I have a controller with this constructor:
public SomeController(
        IRepository<SomeClass> someClassRepository,
        IRepository<SomeOtherClass> someOtherClassRepository)
    {
        _someClassRepository = someClassRepository;
        _someOtherRepository = someOtherClassRepository;
    }

then the CreateInstance method gets called twice (I should add the constructor for the repositories takes an ISession parameter):
public Repository(ISession session)
    {
        this.Session = session;
    }

I thought having it as InRequestScope would mean it is only called once. Is it me misunderstanding or am I missing some code out somewhere.
Answer: I made a quick test to verify that ninject's "basic" Scoping and Provider functionality is working correctly:
public class StringProvider : Provider<string>
{
    protected override string CreateInstance(IContext context)
    {
        return context.ToString();
    }
}

var kernel = new StandardKernel();

kernel.Bind<string>().ToProvider(new StringProvider()).InSingletonScope();

kernel.Get<string>();
kernel.Get<string>();
kernel.Get<string>();

In this case, StringProvider.CreateInstance(..) is - correctly - only called once.

I believe your issue is with the correct configuration of the ninject extension which provides .InRequestScope(). The sad truth is, that when it is not configured correctly, it's not going to yell at you / throw an exception, no it's going to keep quiet. You'll only find it out once the unexpected behavior bites you in the ass ;-)
See here: ASP.NET MVC + Ninject: InRequestScope
This is an instance of such an issue which i answered just yesterday.


Existence of an element that satisfies specific order

Question: Consider a group $G$ such that $|G| = 12 = 12 \times 1 = 4 \times 3 = 6 \times 2$.
We know that the order of any subgroup must divide the order of the group by Lagrange's Theorem.
Since

$12 \mid 12$
$1 \mid 12$
$4 \mid 12$
$3 \mid 12$
$6 \mid 12$
$2 \mid 12$

It is natural to ask if we can find an element $g_d \in G$ such that $ord(g_d) = d$ where $d$ is any divisor of $12$.
It is clear that there's an element $g_1$ with order $1$, namely the identity of $G$. From Cauchy's theorem we can also get $g_2$ and $g_3$. Moreover, $12 = 2^2\times3$ so there's an element $g_4$ of order $4$ from Sylow's Theorems.
We're left to find a non-trivial element of order $12$ and another of order $6$. I wonder if there are any theorems that guarantee the existence of such elements.
Thanks.
Comment: @AnneBauval That sentence does not make sense! You need the word "neither" to go with "nor": "$A_4$ has elements of order neither $4$ nor  $6$" or better: "$A_4$ has neither elements of order $4$ nor of order $6$".
Comment: I neither believe s.o. won't understand nor will misunderstand my sentence.
Comment: Sylows theorem does not guarantee element orders, just subgroup orders. (E.g. $A_4$ of order 12 has no element of order 4.) Basicaly, unless your group is cyclic, the only thing you can guarantee from the group order are prime order elements.
Comment: $g_{12}$ does not exist in general, except for $G\cong C_{12}$. For the other four groups of order $12$ there is no element of order $12$ - see [here](https://groupprops.subwiki.org/wiki/Groups_of_order_12).
Comment: $A_4$ neither has elements of order $4$ nor $6.$
Comment: @ahulpke So, in this case we can only guarantee the existence of elements $g_2$ and $g_3$ from Cauchy's. And we don't know anything about the existence of the following elements: $g_4$,$g_6$ and $g_{12}$?
Answer: By Cauchy's theorem, you can guarantee elements of orders $2$ and $3.$ Every group has an identity, so it has an element of order $1.$ The group $A_4$ only has elements of orders $1, 2,$ and $3.$


If the squares of two integers are congruent $\bmod n$, the integers need not be

Question: How do you prove

$a^2 ≡ b^2 \pmod{n}$ does not imply $a ≡ b \pmod{n}$
Answer: By checking the simplest case:
$$
1^2\equiv2^2\pmod{3}
$$
but $1\not\equiv2\pmod{3}$.
It shouldn't be surprising, as $a^2=(-a)^2$.
Supplementary exercise: prove that

"for all integers $a,b$, $a^2\equiv b^2\pmod{n}$ implies $a\equiv b\pmod{n}$" is equivalent to $n=2$.
Comment: @Kandace This *is* a proof.
Comment: You have to change the first sentence with the word proof, preferably followed by a colon.
Comment: @Kandace A formal proof that something does not imply something else is by exhibiting a counterexample.
Comment: But how do I put that in proof form?
Comment: but I have to prove that a^2 ≡ b^2(modn) DOES NOT imply a≡b(modn) with a formal proof. I might just not be understanding this.
Comment: Oh okay I was trying to do something else, that makes sense now.
Comment: $2^2\equiv 4^2\pmod{4}$ is another simple counterexample but not of the form $a^2=(-a)^2$
Comment: @Henry Nice example, thanks!
Answer: $a^2\equiv (-a)^2$ and $a\not\equiv -a$ unless $a=\frac{n}{2}$


How to autosize/resize the columns of a table in Lotus using VBA?

Question: I am coding up a VBA script to create & email a table of data.  And while it does work, it's also ugly.  One thing I'd like to do is resize these columns so they don't take up the entire width of the page.
The "autosize column" option would be nice, except I don't see anywhere in the API.  Alternatively, I'm open to manually setting the widths of each column.  Can someone tell me what code I need to add?
Dim rtNav As NotesRichTextNavigator
Dim rtTbl As NotesRichTextTable
Dim TblHeader_FontStyle As NotesRichTextStyle
Dim TblBody_BackgroundStyle As NotesRichTextStyle
Dim TblHeader_BackgroundStyle As NotesColorObject
Dim TblBody_FontStyle As NotesColorObject

Sub AppendTable()
'Define styles
    Set TblHeader_BackgroundStyle = NtSession.CreateColorObject
        TblHeader_BackgroundStyle.NotesColor = COLOR_DARK_BLUE
    Set TblHeader_FontStyle = NtSession.CreateRichTextStyle
        TblHeader_FontStyle.NotesColor = COLOR_WHITE
        TblHeader_FontStyle.FontSize = 8

    Set TblBody_FontStyle = NtSession.CreateColorObject
        TblBody_FontStyle.NotesColor = COLOR_WHITE
    Set TblBody_BackgroundStyle = NtSession.CreateRichTextStyle
        TblBody_BackgroundStyle.NotesColor = COLOR_BLACK
        TblBody_BackgroundStyle.FontSize = 10
'-----------------------------------------------------
'Make table structure
    NtBod.AppendTable lRowCount:=1, lColumnCount:=5
    Set rtNav = NtBod.CreateNavigator
    Set rtTbl = rtNav.GetFirstElement(RTELEM_TYPE_TABLE)
    rtTbl.Style = TABLESTYLE_TOP
    Call NtBod.AppendStyle(TblHeader_FontStyle)
    Call rtTbl.SetColor(TblHeader_BackgroundStyle)
    rtNav.FindFirstElement (RTELEM_TYPE_TABLECELL)
'The rest of the procedure to navigate the table and insert the data goes here

Answer: There is a parameter in the AppendTable method that lets you specify the style for each column, including the width.
From the AppendTable method documentation:

Call
  notesRichTextItem.AppendTable(rows%,
  columns% [, labels]  [,leftMargin&]
  [, rtpsStyleArray] )
Parameters:
rows%     Integer. Number of rows in the table.
columns%      Integer. Number of columns in the table.
labels     Array of type String. Optional. Text of labels for a tabbed
  table. The number of array elements
  must equal the number of rows.
  Omitting this parameter appends a
  basic table. Including this parameter
  appends a tabbed table.
leftMargin&     Long.  Optional. Left margin of the table in twips.
  Defaults to 1440. The following
  constants are available:

RULER_ONE_CENTIMETER (567)
RULER_ONE_INCH (1440)

rtpsStyleArray     Array of type NotesRichTextParagraphStyle. Optional.
  Creates a table with fixed-width
  columns and style attributes as
  specified. Omitting this parameter
  creates an auto-width  table. The
  array must contain one element for
  each column in the table in sequence.
  Explicitly set the first line left
  margin and left margin, which control
  the start of text  relative to the
  start of the column, and the right
  margin, which controls column width.
Comment: That's what I was looking for.  I haven't worked on this code in awhile, so I'm a little rusty.


Python JoinableQueue and Queue Thread Not Completing

Question: I am using the following code to complete a task using multithreading with Queue and Joinable Queue. Sometimes the script executes perfectly other times it stalls at the end of the task without ending the worker and will not continue on to the next portion of the script. I am new to working with Queue and JoinableQueue and I need to find out why this stalling happens.
Before this part in the code I run another Queue, JoinableQueue worker to download some data and it works perfectly fine everytime. Do I need to close() any thing from the first Queue/JoinableQueue?  Is there a way to check if it stalls and if so continue on?
Here is my code:
import multiprocessing
from multiprocessing import Queue
from multiprocessing import JoinableQueue
from threading import Thread

def run_this_definition(hr):
    #do things here
    return()

def worker():
while True:
    item = jq.get()
    run_this_definition(item)
   jq.task_done()
return()

q = Queue()
jq = JoinableQueue()

number_of_threads = 8

for i in range(number_of_threads):
    t = Thread(target=worker)
    t.daemon = True
    t.start()

input_list = [0,1,2,3,4]
for item in input_list:
    jq.put(item)
jq.join()
print "finished"

The script never prints "finished" when it stalls, but seems to finish all the tasks and stalls at the end of the 'run_this_definition' on the very last item in the Queue.
Comment: Possible duplicate of [Python threads and queue example](https://stackoverflow.com/questions/15173975/python-threads-and-queue-example)
Answer: My guess is you are using the multiprocessing.JoinableQueue()!? Use the Queue.Queue() instead for threading. It has a .join() and a .task_done() method as well. Furthermore you should pass your queue as an argument to your threads: See the following example:
import threading
from threading import Thread
from Queue import Queue

def worker(jq):
    while True:
        item = jq.get()
        # Do whatever you have to do.
        print '{}: {}'.format(threading.currentThread().name, item)
        jq.task_done()
    return()

number_of_threads = 4
input_list = [1,2,3,4,5]
jq = Queue()
for i in range(number_of_threads):
    t = Thread(target=worker, args=(jq,))
    t.daemon = True
    t.start()
for item in input_list:
    jq.put(item)
jq.join()

print "finished"

The print output form multiple threads might look messy, but as an example it should be fine.
For the future: Please provide a comprehensive example of your code. Neither your imports, nor number_of_threads, run_this_definition or input_list were defined in your example.
Comment: Great I will try this and add the appropriate portion of my code above.  Thank you.
Comment: Doing this gives me the error worker takes 0 arguments 1 given - should I remove the args=(jq,) portion?
Comment: @AshleyA. whoops. no you should allow your worker to take an argument:) I fixed the code.
Comment: No problem - thank you! I tried this and is still is stalling again after completing the last item in the input list. Could it be that one of the threads is stalling somewhere along the way? Would there be a way to check to see what threads are currently running?
Comment: @AshleyA hmm then its getting hard to help, without knowing more about your code. You can use `threading.enumerate()` to get a list of threads that are alive. General advise: try to isolate your problem. Use my example (I guess it is working for you?!) and add your code step by step until it starts stalling. Furthermore use `print` or even better the logging module to debug.


Seek for advice. Fizz buzz coding challenge (conditional statements)

Question: I am a newbie to JS and I am working on a FizzBuzz challenge. Below is what I have tried Essentially when the function takes a value then it would iterate from 1 up to the value and an array would result.
I am hoping  to seek advice on adding conditional checking such as: 1) if the value n is less than 4, it will return the string: "Please insert a value greater than or equal to 4" and 2) if the function is passed no value, it should return an empty array. I am not sure where to add and should I be using if...else or simply if for each conditional checking. Much obliged.
var fizzBuzz = function(n, arr = []) {
  for (let i = 1; i < n; i++) {
  if (n === 1) {
    arr.push('1');
    return arr.reverse();
  } else {
    if (n % 4 === 0 && n % 5 === 0) {
      arr.push('FIZZBUZZ');
    } else if (n % 5 === 0) {
      arr.push('Buzz');
    } else if (n % 4 === 0) {
      arr.push('Fizz');
    } else {
      arr.push('' + n);
    }
    return fizzBuzz(n - 1, arr);
  }
  }
}

Comment: Is your code working? If it is, then you should post to codereview.stackexchange for advice on improving it. If it is not working, do add the expected and actual output
Comment: One piece of advice. Always return the same type. Don't return a string sometimes and an array others. This makes it tricky for the caller to deal with,
Comment: Perhaps an alternative to returning a string is to throw an exception?
Comment: Thanks Paul, however it seems that I would have to use 'try' , 'catch' which I am not supposed to use at this stage of the course since they have not been covered.
Answer: You may be overthinking this

The number one job of code is to make sense to programmers.
Deeply-nested conditionals are hard to make sense of and hard to maintain. So: keep all conditional paths as short as possible, and never put the happy-path inside an if.

Here are your requirements:

if the value n is less than 4, it will return the string: "Please insert a value greater than or equal to 4"
if the function is passed no value, it should return an empty array

Rule #1 suggests we'll express the conditions exactly as you described them.
Rule #2 suggests that we'll handle those special cases first, in short, terminal branches, with the remainder of the function handling the default scenario. This will keep the function nice and flat (i.e. few levels of indentation, which helps control cyclomatic complexity), and make it easier for future devs to skim the implementation.
function fizzBuzz( n ) {
  // if the function is passed no value, it should return an empty array
  // I put this case first to avoid having to figure out whether `undefined < 4`
  if( n === undefined ) {
    // this is a short, terminal branch
    return []
  }

  // if the value n is less than 4, it will return a specific string
  if( n < 4 ) {
    // this is a short, terminal branch
    return 'Please insert a value greater than or equal to 4'
  }

  // this is the trunk: it will be as long as the happy path requires
  let out = []
  for( let i = 1; i < n; i++ ) out.push(i)

  return out
}

If you're new to JS and looking for some general tips, you could do worse than my own Javascript guidelines.


What is the maximum cardinality of $C$?

Question: Let $A$ be a set with $n$ elements. Let $C$ be a collection of distinct subsets of $A$ such that for any two subsets $S_1$ and $S_2$ in $C$, either $S_1 ⊂ S_2$ or $S_2⊂ S_1$. What is the maximum cardinality of $C$?

$n$
$n+1$
$2^{n-1}+1$
$n!$

AFAIK : Set $A$ with $n$ elements has total number of subsets is $2^n$ including $\phi$ set. The given condition will be satisfy be all $2^n$ elements, but somewhere answer is given $n+1$ .

Can you explain in formal way please? what I'm missing here?
Comment: It is not true that if $S_1$ and $S_2$ are _arbitrary_ subsets of $A$ then either $S_1\subset S_2$ or $S_2\subset S_1$. For a counterexample take $A=\{1,2\}$, $S_1=\{1\}$ and $S_2=\{2\}$.
Comment: You are right,that was missing.
Answer: If $A = \{1, 2, 3\}$ then we might have $C = \{\varnothing, \{1\}, \{1, 2\}, \{1, 2, 3\}\}$ which would be $3+1$ elements. We absolutely cannot have $$C = \{\varnothing, \{1\}, \{2\}, \{3\}, \{1, 2\}, \{1, 3\},\{2, 3\}, \{1, 2, 3\}\}$$because in that case, for instance, $\{1\} \in C$ and $\{2\} \in C$, but we have neither $\{1\}\subseteq \{2\}$ nor $\{2\}\subseteq \{1\}$.
For this reason $C$ has to be a strict subset of the powerset of $A$ (unless $A$ has only $0$ or $1$ element), which means it cannot have $2^n$ elements.
As for why it's exactly $n+1$, note that if $A = \{x_1,\ldots,x_n\}$, then $C = \{S_0, S_1, \ldots,S_n\}$ with $S_0 = \varnothing$ and otherwise $S_i = \{x_1, \ldots,x_i\}$ does have the property we want, so the answer is at least $n+1$.
There also cannot be more than $n+1$ elements in $C$, because if there were, then there would be $S_i, S_j \in C$ with $S_i \neq S_j$ such that $|S_i| = |S_j|$, by the pidgeonhole principle (there are only $n+1$ different cardinalities available). In that case we cannot have neither $S_i \subseteq S_j$ nor $S_j \subseteq S_i$.
Comment: This holds if $n$ is finite. On the other hand, if $n$ is an infinite cardinal $\aleph_\alpha$ (in which case I grant $n$ would be an unusual letter to use for it), the answer _will_ be $2^n$.
Comment: @HenningMakholm True. For instance on $\Bbb N$, or rather $\Bbb Q$, you can just let $C$ be the set of Dedekind cuts, for instance.
Comment: Hmm, the argument I had in mind for $2^n$ for all infinite $n$ doesn't quite seem to work unless I assume something like GCH.
Comment: @Arthur: Generalizing Dedekind cuts was what I had in mind, but the dense set we get has cardinality $\sup\limits_{\lambda<|A|} 2^\lambda$. This works well as long as $2^\lambda\le|A|$ for all $\lambda<|A|$ -- which is the the case for $|A|=\omega$ and infinitely many larger cardinals (e.g. $|A|=\beth_\alpha$ for any limit ordinal $\alpha$) -- but there may be ones it does not hold for.
Comment: @HenningMakholm You would also need to be careful what order you choose, since the standard ordering of $\Bbb R$, for instance, just gives you $2^{\aleph_0}$ back. You need an ordering where only a few bounded subsets have $\sup$-s, whatever way that is best put into words.
Comment: @Arthur: Yes, one would start by well-ordering $A$, such that a lexicographical order on $2^A$ can be defined.

What is the maximum cardinality of $C$?


How to release a locked file

Question: We have a file server running ubuntu server. Sometime, when one of the users is using a file and closing it, the server still shows that the file is locked for editing.
How can I release that lock? Is there a fix for this problem?
The ubuntu server is 10.xx.
Comment: What file type is it? A document? A picture? Which program is used to open the file?
Comment: This might be related with hidden `.~lock` files which still exist
Comment: And what protocol do you use to access the files? Samba/SMB/CIFS or NFS, or ...
Comment: Just a general hint: Ubuntu 10.04 is not longer supported - so it could make sense to consider upgrading this machine in the near future. I am aware that this is not a solution - but you should keep it in mind.
Comment: @dufte How would the EOL state of the release cause lock files to be made for files?
Comment: @thomas it doesn't
Comment: @dufte It's unclear then in your comments that's what your intention was going for.  Which is why I asked :)
Comment: @ThomasWard - i mentioned it - as running unsupported versions is afaik often commented as 'not supported by community either'. To split this from my main pointer regarding .lock files i used 2 comments in a row ;)
Answer: To unlock a folder using your terminal, just press Ctrl+Alt+T on your keyboard to open Terminal. When it opens,  navigate to the locked folder, or file, and run the command(s) below:
sudo chown -R username:enter_username folder_name

Or
sudo chown -R username:enter_username file_name.ext

Comment: dont know if the api changed but I needed to omit "username:" what I used was "sudo chown -R username folder_name"

How to release a locked file


How to count the frequency of numbers given in a text file

Question: How to count the frequency of numbers given in a text file. The text file is as follows.
     0
     2
     0
     1
     0
     1
     55
     100
     100

I want the output as follows
     0   3
     1   2
     2   1
     55  1
     100 2

I tried this without success
     def histogram( A, flAsList=False ):
         """Return histogram of values in array A."""
         H = {}
         for val in A:
             H[val] = H.get(val,0) + 1
         if flAsList:
             return H.items()
         return H

Any better way. Thanks in advance!
Comment: possible duplicate of [Counting (and writing) word frequencies for each line within text file](http://stackoverflow.com/questions/5595574/counting-and-writing-word-frequencies-for-each-line-within-text-file)
Answer: Use Counter. It's the best way for this type of problems
from collections import Counter
with open('file.txt', 'r') as fd:
    lines = fd.read().split()
    counter = Counter(lines)
    # sorts items
    items = sorted(counter.items(), key=lambda x: int(x[0]))
    # prints desired output
    for k, repetitions in items:
        print k,'\t', repetitions

The output:
0   3
1   2
2   1
55  1
100 2

Answer: Use a Counter object for this:
from collections import Counter
c = Counter(A)

Now the c variable will hold a frequency map of each of the values. For instance:
Counter(['a', 'b', 'c', 'a', 'c', 'a'])
=> Counter({'a': 3, 'c': 2, 'b': 1})

Answer: Please consider using update:
def histogram( A, flAsList=False ):
 """Return histogram of values in array A."""
 H = {}
 for val in A:
     # H[val] = H.get(val,0) + 1
     if H.has_key(val):
        H[val] = H[val] + 1
     else:
        H.update({val : 1})
 if flAsList:
     return H.items()
 return H

Answer: Simple approach using a dictionary:
histogram = {}

with open("file","r") as f:
    for line in f:
        try:
            histogram[line.strip()] +=1
        except KeyError:
            histogram[line.strip()] = 1

for key in sorted(histogram.keys(),key=int):
    print key,"\t",histogram[key]

Output:
0       3
1       2
2       1
55      1
100     2

Edit:
To select a specific column you'd want to split the line using split(). For example the sixth field by splitting on a single space:
try:
    histogram[line.strip().split(' ')[5]] +=1
except KeyError:
    histogram[line.strip().split(' ')[5]] = 1

Comment: Thanks sudo_O, good one because results are in increasing order. What if I need this result for a specific column in a file? Suppose numbers given in column six?


Show that invertible matrix is in symplectic group via linear isomorphism

Question: For $V = \mathbb{R}^{2n}$, with $e^i$ the standard basis, I'm trying to show that $B \in \text{GL}(2n, \mathbb{R})$ is contained in $Sp(n, \mathbb{R})$ if and only if the linear isomorphism $f:V \to V$ defined by $f^*_B(e^j) = B^i_je^j$ satisfies $f^*_B(\beta) = \beta$ where
$$ \beta = e^1\wedge e^{n+1} + e^2\wedge e^{n+2} + ... + e^n\wedge e^{2n} $$
I'm not sure how to evaluate $B^i_j(e^1 \wedge e^{n+1})$, though this might be a misunderstanding of how the wedge product functions, and I'm not sure how this shows that $B \in Sp(n, \mathbb{R})$.
Comment: How do you define $\operatorname{Sp}(n,\mathbb{R})$? I'm asking because often the definition of $\operatorname{Sp}(n,\mathbb{R})$ is that it consists of linear isomorphisms satisfying $f^{*}(\beta) = \beta$.
Comment: The matrix definition - matrices $B \in M_{2n,2n}(\mathbb{R})$ satisfying $B \begin{bmatrix}
     O_n & I_n \\
     -I_n & O_n\\
     \end{bmatrix} B^T = \begin{bmatrix}
     O_n & I_n \\
     -I_n & O_n\\
     \end{bmatrix}$
Comment: I'd expect that the two definitions are equivalent, since I think that $f^*$ corresponds in some way to the multiplication of $B$, just trying to figure out how to show that given the problem.
Answer: First, note that $(e_i)_{i=1}^{2n}$ is the standard basis of $V$ while $(e^i)_{i=1}^{2n}$ is the associated dual basis and so it is a basis of $V^{*}$. Set
$$ \Omega = \begin{pmatrix} 0_n & I_n \\ -I_n & O_n. \end{pmatrix} $$
and verify that $\Omega$ is the matrix which represents the bilinear form $\beta$ with respect to the standard basis (that is, $\beta(e_i, e_j) = e_i^T \Omega e_j$).
Now, let
$$B = \begin{pmatrix} B_{1}^{1} & \dots & B_{n}^1 \\ \vdots & \ddots & \vdots \\ B^n_1 & \dots & B^n_n \end{pmatrix} \in M(2n,\mathbb{R}) $$
and let $f_B \colon V \rightarrow V$ be the linear map given by $f_B(v) = Bv$ (so that $f$ is represented by $B$ with respect to the standard basis). Note that we have $f_B(e_i) = B_i^j e_j$ and $f_B^{*} \colon V^{*} \rightarrow V^{*}$ is the dual map of $f_B$ which satisfies $f_B(e^i) = B^i_j e^j$.
Finally, let us tackle the question. A matrix $B \in M(2n,\mathbb{R})$ belongs to $\operatorname{Sp}(n,\mathbb{R})$ if and only if $B^T \Omega B = \Omega$. Multiplying on the left by $e_i^T$ and on the right by $e_j$, we see that
$$ \beta(e_i, e_j) = e_i^T \Omega e_j = e_i^T B^T \Omega B e_j = (B e_i)^T \Omega (B e_j) = \beta(B e_i, B e_j) = \beta(f_B(e_i), f_B(e_j)) $$
which shows that $B \in \operatorname{Sp}(n,\mathbb{R})$ if and only if $\beta(e_i,e_j) = \beta(f_B(e_i), f_B(e_j))$ for all $i,j$ (make sure you understand why!) and this is equivalent to $f_B^{*}(\beta) = \beta$.


a Very simple example

Question: When talking of functions that are Riemann integrable but not Lebesgue integrable  we always give the example of $f(x)=\frac{\sin(x)}{x}$ on $]0,\infty [$ but my question is : is it the same with $f(x)=x$ on $]-\infty,\infty [$ and if so why never use this as an example??
Comment: $f(x) = x$ is neither Riemann integrable nor Lebesgue integrable on $[-\infty,\infty)$. The associated limits both diverge
Comment: You're confusing an improper integral with its Cauchy principal value.
Answer: $f(x)=x$ is not Riemann integrable, in improper sense, or Lebesgue integrable.

a Very simple example


How to call an AJAX function after setting a session variable?

Question: /**********************
    User clicks on an album
**********************/
var $curr;
$(document).on('click', 'div#albumlist>a', function(ev) {
    ev.preventDefault();

    $.get('albums.php?aid='+$albumid).done(showThumbs());  // Set the session album ID and refresh thumbnails
});

/**********************
    AJAX Thumbnails
**********************/
function showThumbs() {
    $.ajax({
        url: 'thumbs.php',
        type: 'post',
        success: function(output) {
            document.getElementById("content").innerHTML="
album name

"+output;
        },
        error: function (xhr, ajaxOptions, thrownError) {
            document.getElementById("content").innerHTML="
album name

" +
                "ERROR " + xhr.status + ": " + thrownError;
        }
    });
}

I'm trying to create a site where the user clicks on an album, a session variable "aid" is updated, and then showThumbs() is called to display the photos in the selected album within a container.
I originally had:
$.get('albums.php?aid='+$albumid);
showThumbs();

But that yielded the same results.
After viewing the network traffic, it seems that showThumbs() is called before the session variable is set. This happens on an intermittent basis. Is there a way to force the AJAX call to wait until the $.get is done before showThumbs() executes?
Thanks. :)
Answer: You pass a function reference to .done() like this (without the parens after the function name):
$.get('albums.php?aid='+$albumid).done(showThumbs);

When you put the () like showThumbs() that executes it immediately rather than just passing a function reference that can be called later.
Answer: When you pass your callback, don't invoke, just pass the implementation. Change to:
$.get('albums.php?aid='+$albumid).done(showThumbs);

or
$.get('albums.php?aid='+$albumid).done(function () {showThumbs()});

But the second one seems silly.
Comment: So these two statements are equivalent in javascript.  var functionName = function () { stuff }; and function functionName() { stuff };  -- If that makes sense, then think about what the first example looks like. In the first example you're storing the implementation to a variable and you can pass that variable around like any other variable or you can execute it by placing () at the end. That's how callbacks work in general.
Comment: Thank you! That works like a charm. I'm new-ish to jQuery and JavaScript in general. What's the difference between invoking and passing the implementation?
Comment: Also, check this out: http://recurial.com/programming/understanding-callback-functions-in-javascript/


How do I control an object in processing via Arduino sketch?

Question: I have managed to connect the Arduino sketch to a Processing sketch, but I am stuck on how I get the Arduino to control an object in the processing.
Using a tilt sensor, the aim is that when the tilt sensor is tilted one way it will move the object in processing that way, and then when it is tilted the other way it will move the object the other way.
Can anyone help?
This is my code for Arduino:
void setup()
{
  // put your setup code here, to run once:
Serial.begin(9600);
}

void loop()
{
  // put your main code here, to run repeatedly:
Serial.println("Hello, World!");

delay(100);

}

This is my code for Processing:
import processing.serial.*;
Serial myPort;
String val;
PShape bike;

void setup()
{
String portName = Serial.list()[0];
myPort = new Serial(this, portName, 9600);

size(800, 600);
bike = createShape(RECT, 0, 0, 200, 200);
bike.setFill(color(102, 204, 0));
bike.setStroke(false);

}

void draw()
{
  if ( myPort.available() > 0)
  {  // If data is available,
  val = myPort.readStringUntil('\n');         // read it and store it in val
  }
println(val); //print it out in the console

shape(bike, 0, 0);

}

Answer: Break your problem down into smaller pieces.
Write a simple example sketch (in other words a [mcve]) that only does one thing: it simply reads in values from the Arduino and prints them to the console. It doesn't even really need to draw anything to the screen.
Write another [mcve] that just does one thing: it simply moves an object on screen. Notice that this should not involve your Arduino code at all. Try to make it as standalone as possible.
When you get both of these working completely separately, then you can think about combining them into one sketch. And if you get stuck, you can post that [mcve] along with a specific technical question.
Here's a sketch that moves an object based on the mouse position, just go get you started:
float objectX = 0;

void setup() {
  size(500, 100);
}

void draw() {

  if (mouseX > objectX) {
    objectX ++;
  }

  background(0);
  ellipse(objectX, height/2, 25, 25);
}

Answer: your arduino code looks that´s only hello world.
What I do to use arduino libs (sensors, actuators) using processing, is to split the tasks for 2 arduinos: one that uses the libs and send/recive data from the other arduino. This second arduino is loaded with the standard firmdata (firmware), that allows to comunicate easily and directly from processing sketch: http://playground.arduino.cc/Interfacing/Processing