Debugging the result property in a ViewExecutable

Question: I need to debug the $result property of the ViewExecutable object passed to hook_views_post_execute but for what ever reason, Drupal can't handle it. $view->result is an array of type ResultRow, and because it's an array, I'm attempting to log it like so:
\Drupal::logger('foo')->notice('
' . print_r($view->result, TRUE) . '
');

When I do this and then load the view I'm attempting to mess with, it loads the page without css and then the recent log messages just shows up blank, no errors or anything that would actually be helpful.
I've tried a number of different ways but this is always the result. Why can't this logger print a simple array?
I've even tried looping through the array and printing just the value:
foreach($view->result as $key => $value) {
  \Drupal::logger('bar')->notice(print_r($value, true));
}

And that will render the view without css and then the logger doesn't print anything at all. I double checked and printed a regular string and that worked, but when I attempt to print the value it just breaks and doesn't do anything.
Comment: *In fact, if you don't have debug logs that express your frustrations at the platform, are you really a developer?* In fact, it means you don't know how to use a debugger. I'd strongly suggest using an IDE like PHPStorm or Visual Studio Code with Xdebug. e.g. https://www.jetbrains.com/help/phpstorm/configuring-xdebug.html#updatingPhpIni Live is much less frustrating with a real debugger.
Comment: Install the Devel module. It gives you a handful debugging helpers like `dpm($view->result)` or when you also have Kint installed `ksm($view->result)` to pretty-print variables into the Status Messages block.
Comment: @leymannx I have that and was trying, but 1/2 the time when I'm printing those my site breaks and it takes me to the install page and the logs say SQL connection broke 2006...
Answer: Your code works fine for me so perhaps your view has no results?
Anyways, the Drupal log is not really meant to be used for printing variables for debugging purposes. Use an appropriate tool like Devel which has/comes with another module called Kint, enable Kint.
use Drupal\views\ViewExecutable;

/**
 * Implements hook_views_post_execute()
 */
function mymodule_views_post_execute(ViewExecutable $view) {
  kint($view->result);
}

Flush cache and you'll see this

For more info on how to use Kint, see Welcome to Kint 101
Comment: @TheSnowboardingDev you'll need to [lower Kint's recursion](https://drupal.stackexchange.com/a/250540/27710)
Comment: @TheSnowboardingDev I'd recommend using XDebug for debugging. It saved my life.
Comment: Thanks, it appears to work with `$value` now, however, it doesn't work with some of the objects that exist inside of $value.. I keep getting an SQL disconnect error. Specifically, when I try to print out a entity reference that exists inside of $value.


Getting average of survey results when I only have the count for each response?

Question: So I have the results from a survey, but they're aggregated by year and response number. I for the devil of me cannot figure out how to get average survey response by the scale. Like for instance, for 2010, I have:
\begin{array}{|c|cccccc|}\hline\text{Value}&0 &  1 &  2 & 3 & 4 & 5\\\hline
\text{Frequency}&1 & 0 & 4 & 21 & 37 & 17\\\hline\end{array}
And the average of the bottom row is $13.33$, but that doesn't tell me what I want. That tells me the average number of responses, but I want the average response on the scale. I have no idea aside from making a dataset with 17 5s etc and then doing an average on that?
Answer: Multiply values with frequency (%) and sum.
Answer: Consider a basic example first: \begin{array}{|c|ccc|}\hline\text{Value}&1&2&3\\
\hline
\text{Frequency}&2&3&5\\\hline\end{array}
This is equal to the following dataset: $1,1,2,2,2,3,3,3,3,3$
We would calculate the average value by computing
\begin{align}\frac{\text{sum of items}}{\text{number of items}}&=\frac{1+1+2+2+2+3+3+3+3+3}{10}\\
&=\frac{23}{10}\\
&= 2.3\end{align}
This is equal to $$\frac{1\times 2+2\times 3+3\times 5}{2+3+5}=\frac{2+6+15}{10}=\frac{23}{10}=2.3$$
i.e we multiply each value by its frequency, add them together, and then divide by the sum of the frequencies

Therefore, we would compute \begin{align}\frac{0\times 1+1\times0+2\times 4+3\times 21+4\times 37+5\times 17}{1+0+4+21+37+17} &= \frac{0+0+8+63+148+85}{80}\\
&= \frac{304}{80}\\
&=3.8\end{align}
Comment: Thank you! This logic also helped me properly calculate the standard deviation for my frequencies.
Comment: No worries, this was how my Maths teacher back at school taught me to think about it and I think it really helps
Answer: The survey received a total of $1 + 4 + 21 + 37 + 17 = 80$ responses, of which $1$ response was $0,$
$4$ responses were $2,$ and so forth.
If you had a list of all the responses, you would add up the $80$ numbers in the list and divide by $80$ to get the mean.
But in fact you do have a list of the responses, just not in the same order in which they were recorded. And since addition is commutative, the order does not matter.
The responses were
$$
0, 2, 2, 2, 2, \overbrace{3, \ldots, 3}^{\text{$21$ responses}},
\overbrace{4, \ldots, 4}^{\text{$37$ responses}},
\overbrace{5, \ldots, 5}^{\text{$17$ responses}}.
$$
The easiest way to add them up is by using multiplication to add up the repeated values:
$$
S = 0 + 4\times 2 + 21\times 3 + 37\times 4 + 17\times 5,
$$
and then $\frac{S}{80}$ is the mean value.


nginx: make internal redirect to a different `location` block

Question: try_files' signature is try_files file ... uri;, so one usually uses it to perform tasks like serve file1 if it exists otherwise serve file2 if it exists otherwise pass the decision to a different location block (the one for the mentioned uri).
Can I somehow use the last part only? That means, do not try to serve any files, just pass the request to a different location block. The simple idea of not mentioning any files fails with nginx: [emerg] invalid number of arguments in "try_files" directive.
A workaround is to write try_files /does/not/exist.html /some/uri; but it looks ugly and possibly incurs a penalty for checking the existence of the nonexistent file.
For context, why do I need this?
I have a config like
location /path/ {
    try_files $uri $uri/index.html =404;
    alias /some/dir/;
    expires 604800;
}

This unfortunately doesn't match /path (no trailing /). One could simply write location /path, but it is said to cause path traversals.
My idea is to add one more handler like
location = /path {
  <do the same as for /path/>
}

I could of course copy the alias and try_files there, but that way I would also have to copy the expires directive and possible others and keep them synced.
Comment: You could use `rewrite ^ /path/ last;`
Answer: Yes, rewrite is good here, just add a block location /path and use rewrite to redirect the request to the /path/ block, like this
location = /path {
    rewrite ^ /path/ last;
}

location /path/ {
    try_files $uri $uri/index.html =404;
    alias /some/dir/;
    expires 604800;
}


Node JS Route Behavior makes no sense

Question: I'm trying to make a simple authentication page using Node with Express framework.
At this moment, I'm not particularly worried about the weak protection.
However, my route file is displaying weird behavior.
Here is the code:
var express = require('express');
var router = express.Router();
var admin = require("../controllers/admin");

router.get('/', function(req, res) {
  console.log('Entered top route.');
  if(req.body.isAuthenticated) {
    res.redirect('admin/index');
  } else {
    res.redirect('admin/login');
  }
});

router.post('/authenticate', function(req,res) {
    if(req.body.pword == "key") {
        console.log("Resetting body.isAuth'ed");
        req.body.isAuthenticated = true;
        console.log("New val: " + req.body.isAuthenticated);
        res.redirect('admin/index');
    } else {
        console.log("Failed login attempt: " + req.body.pword);
        res.redirect('admin/login');
    }
});

router.get('/login', admin.login);
router.get('/index', admin.index);

module.exports = router;

The idea is that the route is entered, upon which we hit the top route (properly logged by console). This redirects based on whether a req variable is set. This all works properly, and the login (I'm using jade templating) is properly rendered. The login file has a form which calls back to this routing file with 'admin/authenticate'. This also works properly; I'm able to properly retrieve the input (confirmed via console logs). However, the actions I take in the /authenticate/ function, even though they are the exact same thing I do in the '/' route right above, fail. I get 404's and Express Not Found printouts which are entirely useless.
My console properly logs 'Failed login attempt' or 'Resetting body...New val: true", but then doing the exact same res.redirect that is initially done in the router.get('/') method above fails, whereas the res.redirects in that function properly redirect and render the correct values.
Any ideas what could be wrong? I could post the admin.login/admin.index methods in the controllers/admin file. However, they're very simple and I think this error stems from a basic misunderstanding of the difference between get and post methods or something (this is my first time using Node).
Thanks!
Answer: I think the issue is because of the relative path.
Doing res.redirect('admin/index') from path / and path /authenticate is not same.
res.redirect('admin/index') from /authenticate will redirect user to /authenticate/admin/index, may be thats why it is giving 404.
Try to change res.rediret('admin/index') to res.redirect('/admin/index') in authenticate callback.
Comment: Yup; that fixed it. Stupid of me, I thought everything in the same file started from the same 'route'.

Node JS Route Behavior makes no sense


Openldap with ppolicy

Question: We have working installation of OpenLDAP version 2.4 which is using shadowAccount attributes. I want to enable  ppolicy overlays.
I have gone through the steps provided at OpenLDAP and ppolicy howto. I have made the changes to slapd.conf and imported the password policy.
On restart OpenLDAP is working fine and I can see the password policy when I do a ldapsearch.
The user object looks like given below.
# extended LDIF
#
# LDAPv3
# base <dc=xxxxx,dc=in> with scope subtree
# filter: uid=testuser
# requesting: ALL
#

# testuser, People, xxxxxx.in
dn: uid=testuser,ou=People,dc=xxxxx,dc=in
uid: testuser
cn: testuser
objectClass: account
objectClass: posixAccount
objectClass: top
objectClass: shadowAccount
shadowMax: 90
shadowWarning: 7
loginShell: /bin/bash
uidNumber: 569
gidNumber: 1005
homeDirectory: /data/testuser
userPassword:: xxxxxxxxxxxxx
shadowLastChange: 15079

The password policy is given below.
# default, policies, xxxxxx.in
dn: cn=default,ou=policies,dc=xxxxxx,dc=in
objectClass: top
objectClass: device
objectClass: pwdPolicy
cn: default
pwdAttribute: userPassword
pwdMaxAge: 7776002
pwdExpireWarning: 432000
pwdInHistory: 0
pwdCheckQuality: 1
pwdMinLength: 8
pwdMaxFailure: 5
pwdLockout: TRUE
pwdLockoutDuration: 900
pwdGraceAuthNLimit: 0
pwdFailureCountInterval: 0
pwdMustChange: TRUE
pwdAllowUserChange: TRUE
pwdSafeModify: FALSE

I do not what should be  done after this. How can the shadowAccount attributes be replaced with the password policy.
Answer: shadowAccount attributes have nothing to do with the password policies. Password policies (which themselves are based on a draft RFC and could change tomorrow or die completely) are managed the server. The shadow stuff is managed by LDAP clients. For example, the password policies allow the server to enforce password history and quality on the server side, but clients must handle the shadowAccount stuff.

Openldap with ppolicy


Primefaces - Custom Pagination/ Sorting load() issue

Question: We are using Primefaces 3.0.RC2 in our application with seam faces and CDI. We have followed the lazy loaded data table implementation on the component showcase. Since we have a large dataset, we have overridden the load() method to fetch only pagewise results. (vs loading all records in memory at once).
The pagination works as expected, however the sorting does not. The records get sorted correctly the first time the column header is clicked. For all subsequent clicks, the load() method is called twice, sending different values for the sorting order as a result of which, the sort order remains the same on the table. It seems like both the load() calls are being made in the APPLY_REQUEST_VALUES phase.
Can anyone provide any inputs as to why this is happening and how it can be avoided. Any pointers would be highly appreciated.
Some additional info:
As stated earlier, we have overriden the load() method and have it actually query the DB to fetch sorted results pagewise (by specifying max results and order by in the query) and it works fine.
@Override
public List<ABC> load(int first, int pageSize, String sortField, SortOrder
sortOrder, Map<String, String> filters)
{
    // Fetch data pagewise from the database
    datasource = dao.findPagewiseSortedResults(sortField,
            SortOrder.ASCENDING == sortOrder ? true : false, first, pageSize);

    // Set the row count
    this.setRowCount((int) dao.findTotalCount());

    return datasource;
}

However, on clicking the column on the datamodel for sorting, 2 post requests are made.
Find below the xhtml code:

            <f:facet name="header">
                <h:outputText value="User Name" />
            </f:facet>
            <h:outputText value="#{record.username}" />

.........

        </dataTable>

We have even upgraded to the latest Primefaces version (3.0.1) but it hasn't helped. Are we missing anything? Any pointers would be very helpful.
Thanks.
Comment: I use 3.0 Final with Lazy Loading, filtering and sorting, but cannot see this behaviour. Even if it were present such bug (but is not), you could always read the sortOrder field and act consequently. Maybe it's better if you post some code
Comment: @perissf,Thanks for you reply. I have added some code to the original question. Please let me know if you need any more information/
Answer: Since you are providing the sorting by use of the load() method, you don't have to use dataTable's native sorting tool. You need to remove the sortBy attribute from p:dataTable tag.
The component should be defined this way:

EDIT
This way, you'll have your column sortable exactly in the order specified by the client: you will read the SortOrder specified, with the Java code you have posted, and you will use that SortOrder consequently in your implementation of dao#findPagewiseSortedResults()
Comment: Thanks again perissf. But wouldn't this mean that the records will always be sorted in the order i specify in my database query. How will i provide the user with the option of sorting them in asc/desc order. I mean to keep the columns sortable and depending on the sort order specified, the order by clause in the query is applied. Is there a way to do that?
Comment: I have updated my answer. Not sure to understand what you are asking
Comment: I thought u asked to delete sortBy attributes from the columns too. Sorry about the confusion. I deleted the sortBy attribute from datatable. The results are sorted & fetched from DB in asc order correctly. However, on clicking a column to reverse sorting order, it reverses the order correctly once and thereafter always remains sorted in desc order (no matter how many times i click). I see that it sends an asc sortorder to the backend (first load() call) but that is followed & overriden immediately by desc sort order(second load() call) and it seems like no sorting happened. Any leads?
Comment: I just don't understand why the load() method should be called twice.
Comment: Print the sortOrder each time load() is invoked, to check if the method is effectively invoked twice, or if your dao#findPagewiseSortedResults() is not behaving like desired
Comment: The load() is definitely called twice (confirmed in the logs and i see 2 post requests in firebug). I also the printed the query in the dao and that is perfectly fine. Basically, the sort will work if the second load() call is not made.


Cohomology of Stiefel manifolds

Question: Define the complex Stiefel space $W_{n,k}$ as $U(n)/U(k)$. What is its (co)homology? (Either singular or de Rham).
I've searched through a bunch of classical references but can't seem to find this information anywhere. I'd be over the moon with either a reference, or even just a sketch proof.
Edit: Quite a few papers seem to refer to specific facts without giving any reference. For instance, I have seen statements such as $H_{2k+1}(W_{n,k};\mathbb{Z})\cong\mathbb{Z}$, but with no real explanation as to why this is true. This leads me to believe that the (co)homology of these complex Stiefel spaces is classically well-known, but I can't seem to find where.
Comment: Viewing $W$ as the set of tuples $(v_1,\dots,v_k)$ of orthonormal vectors, there is a projection onto the last componnt. That is a fibration with fiber a sphere and fiber a smaller Stieffel manifold. Have you tried to obtain a recursive decription of the cohomology using this?
Comment: @MarianoSuárez-Álvarez I haven't, no. I'm just about to update the question with some extra information actually.
Comment: I don't have it in front of me, but I'm pretty sure this is in Fuchs' Topology II.  Also, almost any paper of Bob Stong's would contain this calculation.  Maybe try his Notes on Cobordism Theory.
Comment: @Randall Yes! It's Theorem III.3.2.A, p. 218. Thank you. Do you want to post this as an answer so that I can accept it? Save anybody else from searching in all the wrong places.
Comment: Ha, sure.  Glad I could help.
Comment: Can add the precise reference in my answer.  Did you find it in Fuchs or Stong?
Answer: See pages 301-302 of Hatcher's Algebraic Topology for some partial results.
Comment: This is great thanks. I didn't realise that this was in Hatcher, and it seems quite clear, so if it comes down to it then I will try using this as a way of calculating the homology myself!
Answer: Per OP's request:
I don't have it in front of me, but I'm pretty sure this is in Fuchs' Topology II. Also, almost any paper of Bob Stong's would contain this calculation. Maybe try his Notes on Cobordism Theory.
Found in:  Fuchs and Viro's Topology II, Theorem III.3.2.A, page 218 (Springer).
Comment: It is, and it's Theorem III.3.2.A, p. 218

Cohomology of Stiefel manifolds


Passing Class as parameter for use with typeof()

Question: I have a delegate function:
myDelegate md = cls => String.Format("blahblah: {0}", typeof(cls).FullName));

I want to pass a Class there as parameter cls, which will be used in typeof().
Example use:
md(System.String); // => blahblah: System.string

What type to define for input parameter cls, to be able passing any Class into my function?
Comment: If you're willing to shift to passing the *type*, this is quite straightforward - but the `typeof` will have to be used at the call site rather than within the method. Otherwise, I think you're stuck.
Comment: `typeof(cls)` could be replaced by `cls.GetType()` which would make your code compile and print the the type of `cls` as you seem to want. I don't really understand what exactly you are trying to achieve though, so not sure if that fits your usecase.
Comment: YOu can pass `Type cls`
Answer: The type you are looking for is Type.
Use it like this:
myDelegate md = cls => String.Format("blahblah: {0}", cls.FullName));
md(typeof(System.String));

You can also use generics to get similar results
public static string TypePrinter<T>()
{
    return String.Format("blahblah: {0}", typeof(T).FullName));
}
TypePrinter<System.String>();

Comment: Both version works now. Damn these strongly typed languages, Sometimes it demands very complicated construct to achieve relatively simple task. At least I've learned something new. Thank you.
Comment: First solution works, but the seconds complaints something like `cannot use type in context`
Comment: My bad, I wrote it without compiling and made a mistake. Updated the answer and converted to C# 5.
Comment: Yeah, but having a compiler tell you "shit won't work" is worth a lot in bigger projects. ;)
Answer: Are you looking for something similar to this-
Func<Type,string> fn = t => string.Format("blah from - {0}",t.FullName);
Console.WriteLine(fn(typeof(Int32))); //blah from - System.Int32

Comment: [`Func Delegate`](https://msdn.microsoft.com/en-us/library/bb549151(v=vs.110).aspx) is exactly what I was looking for. I'm just unable to pass `Class` directly, I have to pass `Type` as a result of `typeof()` call, which is less DRY, but affordable.


A property of Stirling Numbers of the Second kind (Combinatorics related)

Question: I have this question regarding the Stirling Numbers of the Second Kind, $S(n,r).$ the question is
"Prove that $\binom{n}{k-1}\leq S(n, k)\leq \binom{n-1}{k-1}k^{n-k}.$
For the upper bound, I used induction and the recursive formula $S(n+1,k)=S(n,k-1)+kS(n,k)$. The inductive step gives
$$
S(n+1,k)=S(n,k-1)+kS(n,k)\leq \binom{n-1}{k-2}(k-1)^{n-k+1}+\binom{n-1}{k-1}k^{n-k+1}
$$
and then used the equality $\binom{n-1}{k-2}+\binom{n-1}{k-1}=\binom{n}{k-1}$ to get the desired $S(n+1,k)\leq \binom{n}{k-1}k^{n+1-k}$.
However, I can't get the same to work for the lower bound... Maybe I'm just not seeing it right.
So my questions are...
a) Can the lower bound be proven this way?
b) Is there another way to prove both bounds? Is there some combinatorial argument I am not seeing?
c) Also. Why is combinatorics so hard. Why can't it behave nicely like other mathematics...
Answer: How about
$$S(n+1,k)=S(n,k-1)+kS(n,k)\ge S(n,k-1)+S(n,k)\ge\binom{n}{k-2}
+\binom{n}{k-1}=\binom{n+1}{k-1}?$$
Comment: You've proven me dumb, but thank you nonetheless... Do you know of another argument I could use to prove both bounds?


Is it considered the bug of both GCC and Clang for the sequence of copy-initialization of the result of a call?

Question: Please see this example
#include <iostream>
struct A{
    A(){
        std::cout<<"A constructed\n";
    }
    ~A(){
        std::cout<<"A destroyed\n";
    }
};
struct B{
    B(int){
        std::cout<<"B constructed\n";
    }
    ~B(){
        std::cout<<"B destroyed\n";
    }
};
struct C{
    C(){
       std::cout<<"C constructed\n";
    }
    ~C(){
        std::cout<<"C destroyed\n";
    }
    bool operator==(B const&){
        return true;
    }
};
struct D{
    D(bool){
        std::cout<<"D constructed\n";
    }
};
bool fun(){
    A a;
    C c;
    return c==0;
}
int main(){
    D d = fun();
}

The outputs of the above example are identity in both GCC and Clang, they are that
A constructed
C constructed
B constructed
B destroyed
C destroyed
A destroyed
D constructed

That means the copy-initialization of the result of the call is sequenced after all the destruction of the local or temporary variable of that function. It contradicts with the following rule, which is
[stmt.return#3]

The copy-initialization of the result of the call is sequenced before the destruction of temporaries at the end of the full-expression established by the operand of the return statement, which, in turn, is sequenced before the destruction of local variables ([stmt.jump]) of the block enclosing the return statement.

According to the rule, the output should be that
A constructed
C constructed
B constructed
D constructed
B destroyed
C destroyed
A destroyed

Is it a bug of GCC and Clang?
Comment: Define your own class MyBool and use it as a return type for `fun()`. The class needs to be constructible from `bool` and convertible (castable) to `bool`. Then see whether the returned object creation gets sequenced before or after the params' destruction.
Comment: @CiaPan Thanks. You reminded me that the result object of the call is just the parameter of the constructor of `D`. The standard only guarantees the sequence of that parameter rather than the complete initialization of object `d`. https://godbolt.org/z/r3jdd9aTn
Comment: That's right. The `d` variable is irrelevant and it needn't even be explicitly declared. One may use the returned object to directly initialize a param to another function, like `gun(fun())` or use it immediately as some action performer and abandon it: `fun().doSomething();`. The rule you quoted applies anyway in all those cases.
Answer: The return value from the function in question is a bool. This is what gets returned.
Your logged output shows no evidence of when the copy-initialization of the bool return value was sequenced, before or after anything else.
It also happens to be true that once the bool value is returned, the caller uses it to construct a new instance of D. But this is something completely unrelated to the copy-initialization semantics of the returned bool value from the function call.
Comment: Correct, and the temporary `bool` expression in `main()` was initialized accordingly to what you've quoted. And after that happened that `bool` result of the expression gets used to construct a new instance of `D`. The constructor of `D` cannot be called until its `bool` parameter is evaluated. Therefore, it will require violating a few fundamental rules of physics of our shared universe in order to reverse the flow of time and be able to construct an object before its constructor's parameter is evaluated.
Comment: I'm just wrong in the above comment. D::D(bool) will be called for copy-initialization of `d`. I see what the temporary object of type bool you said here, it's just the parameter of `D::D(bool)`, the rule only guarantees the sequence of the copy-initialization of the parameter.
Comment: the function call expression is a prvalue, hence the result object(`d`) is copy-initialized from the operand of the return statement, as per "the return statement initializes the glvalue result or prvalue result object of the (explicit or implicit) function call by copy-initialization from the operand."
Comment: I don't understand your meaning. In my mind, it looks like `d.operator==(c==0)`. Anyhow, there's no temporary object of type bool in this example. Why do you say there is a medium object?
Comment: The value returned from `fun()` is `bool`. It is not `D`. There is no existing `D` object, and there is no `d.operator==` that's getting invoked. A `D` object does not get created until ***after*** `fun()` returns. Which part of that is unclear to you?
Comment: Correct, only the copy-initialization of the parameter is sequenced like that. And you can't call the constructor until its parameter is initialized. Therefore it is logically impossible for `D` to be constructed until after `fun()`'s return value is copy-initialized.
Comment: I see. you may mention which object is it in this example that its sequence of the copy-initialization is guaranteed by the standard if you would like.


Need to Check if a particular location is within the boundaries of the map

Question: i use osmdroid MapView.
I need to find if user Location in within the boundaries of the map (depends the zoom level).
I try to user MapView.getBoundingBox().contain(location).. But it seems that the getBoundingBox() returns the Visible boundaries.
is there a way to get the original Map boundaries (depends the zoom level)?
Thanks
Answer: You can find out the latitude and longitude of the northwest and southeast corners
of your mapview with code like:
<code>GeoPoint topLeftGpt     = (GeoPoint) mapView.getProjection().fromPixels(0, 0);
GeoPoint bottomRightGpt = (GeoPoint) mapView.getProjection().fromPixels(
            mapView.getWidth(), mapView.getHeight());
</code>
You can then find out if the point of interest falls within these bounds.
Answer: For v2:
<code>    LatLng northwest  = (LatLng) mMap.getProjection().fromScreenLocation(new Point(0, 0));
    LatLng southeast = (LatLng) mGoogleMap.getProjection().fromScreenLocation(
        new Point(mMapView.getWidth(), mMapView.getHeight()));
</code>


Finding members of a ring

Question: From Coding Theory: A first Course, by Ling and Xing
In example 3.2.8, it gives
$\mathbb Z_{2}[x]/(1+x^2)=\{0,1,x,1+x\}$, and $\mathbb Z_{2}[x]/(1+x+x^2)=\{0,1,x,1+x\}$
How did they find the elements of the set?  How would the method be extended beyond $\mathbb Z_{2}$?  The field $\mathbb Z_{2}$ seems to be making things appear simpler than they really are.  Based on this, I am supposed to find the set for $\mathbb Z_{16}[x]/(1+x+x^4)$, but I don't see how.
Answer: These are residue classes in the ring of polynomials. So
$$f(x) \equiv g(x)$$ in $Z_k[x]/(m(x))$
if and only if their remainders upon division by $m(x)$ are the same.
Clearly then the equivalence classes of these polynomials can be represented by the polynomials in $Z_k[x]$ of degree up to $\deg(m(x))-1.$
Answer: Hint: Use the Division Algorithm. By definition, the elements of $\mathbb F_2[x] / (x^2 + 1)$ are the possible remainders $r(x)$ when $x^2 + 1$ is divided by another polynomial in $\mathbb F_2[x].$ What can those be?
Generally, if $R$ is a finite ring with $n$ elements and $f(x)$ is a monic polynomial with coefficients in $R,$ then the quotient ring $R[x] / (f(x))$ is finite. (Remember that the elements of $R[x] / (f(x))$ are the possible remainders when the Division Algorithm is run with $f(x).$ Each remainder is a polynomial of degree less than $f(x),$ and there are only finitely many choices for each coefficient.) Consequently, it is just a matter of writing down all of the possible remainders. For the field $R = \mathbb F_2,$ this is simple because there are only two choices for each coefficient. How many choices are there in $\mathbb Z / 16 \mathbb Z?$ What is the maximum degree of a polynomial in $(\mathbb Z / 16 \mathbb Z)[x] / (x^4 + x + 1)?$

Finding members of a ring


Access Query: Return all records that occur on a certain day, ignoring the time

Question: I have an Invoices table with a Date/Time field.  I want to write a query that returns all invoices for a certain day.
The problem I'm having is that when I filter the query by a particular date (such as 04/30/2011), no records are being returned.  My suspicion is that Access is trying to return records that are an EXACT MATCH of 04/30/2011.
What I want is a query that returns all invoices that occur ON 04/30/2011 regardless of what time they occur.  Basically, I want Access to care about the day but not the time.
Is there any documentation on how to do this?  I sure can't find any.  I'm using Access 2010.  Thanks!
Comment: Why are you storing a time part of other than 0 in an Invoice Date field? An Invoice Date is a date, it should have 0 as the time component. My guess is that you're populating the field with Now() instead of with Date(), a common mistake that is urged on Access users by a lot of the examples in the sample databases and help files.
Answer: Without seeing your attempt, it's hard to say what you're doing wrong. I imagine you're trying to check for equality, which basically will mean that it must have happened exactly at midnight.
SELECT * FROM table WHERE date >= #04/30/2011# AND date < #05/01/2011#
Comment: Worth noting that you can dynamically "roll" this check based on the given day. `SELECT * FROM table WHERE date >= #04/30/2011# AND date < DateAdd("d",1,#2011-04-30#)`. This is basically Thomas' example, with the very important exception that the right, dynamic check is exclusive and not inclusive.
Answer: It is about the datatype, I assume your date is stored in a datetime field. This will store the time as well and if no time is specified will default to midnight. I ususally use the BETWEEN function to do this:
SELECT *
FROM table
WHERE datefield BETWEEN '2011-04-30' AND '2011-05-01'

Because both dates will be at midnight, you will get the results from April 30.
Comment: I'd suggest datefield >= '2011-04-30' AND datefield < '2011-05-01', just in case someone creates an invoice at midnight on 1st May.  :)
Comment: Lane - To expand on Will A's comment, `DateCol Between A and B` translates to `Col >= A And Col <= B`. `Col >= A And Col < B` would be better.
Comment: Or to further muddy the waters how about "WHERE datefield BETWEEN #4/30/2011# AND #4/30/2011# + #23:59:59#"? I use this approach when the date value for the criteria is referenced from a text box on a form.
Answer: You are correct about what Access is doing; when you supply a datetime value with no time, it assumes midnight. So "2011-04-30" means "2011-04-30 00:00:00".
There is a Datediff function in Access that's used like this:
Datediff("d", "2011-04-30", [FieldName]) = 0

Answer: You could try something like:
DateAdd("d", DateDiff("d", 0, MyDate), 0 )

Another choice:
CDate(Format(MyDate,"yyyy-mm-dd"))

Another variant of solutions mentioned by others that allows you to plug in a single date:
DateCol >= #2011-04-30# And DateCol <= DateAdd("d",1,#2011-04-30#)


Desserializando json complexo

Question: Sou novo por aqui e gostaria da ajuda voçês, preciso desserializar um json,
para usar numa aplicação xamarin forms e estou com dificuldades, como proceder no c#? segue o json abaixo

{
  "RECORDS": [{
      "Codigo": "33338",
      "Descricao": "MOLA WIL 50-1 - TRAS RURAL - 57\/64",
      "PrecoVenda": 74.75,
      "Referencia": "WIL 50-1",
      "Grupo": "002",
      "GrupoDesc": "MAM WILLYS",
      "Categoria": 3,
      "CategoriaDesc": "Material Acabado - Molas",
      "Classe": "001",
      "ClasseDesc": "MOLAS",
      "NCM": "7320.10.00"
    },
    {
      "Codigo": "33339",
      "Descricao": "MOLA WIL 50-2 - TRAS RURAL - 57\/64",
      "PrecoVenda": 69,
      "Referencia": "WIL 50-2",
      "Grupo": "002",
      "GrupoDesc": "MAM WILLYS",
      "Categoria": 3,
      "CategoriaDesc": "Material Acabado - Molas",
      "Classe": "001",
      "ClasseDesc": "MOLAS",
      "NCM": "7320.10.00"
    }
  ]
}

Preciso desserializar e jogar dentro de um a lista pra fazer Binding nas propriedades, método que estou utilizando, segue
public async void Ler()
    {
       var json = await LerArquivo.CarregarArquivo("Catalogo.json");
       var Catalogos = JsonConvert.DeserializeObject<List<Catalogo>>(json);
    }

Ao executar meu código tenho isto de retorno
Comment: Troque a imagem por texto, isso facilitara alguém a te ajudar. Sempre que possível, evite imagens
Comment: Exemplo: https://pt.stackoverflow.com/questions/168348/serializando-e-desserializando-objetos-json-com-c
Comment: Exemplo: https://pt.stackoverflow.com/questions/219560/deserialize-json-com-restsharp-e-com-javascriptserializer/219627#219627
Answer: Crie duas classes com o seguinte código:
public class Rootobject
{
    public RECORD[] RECORDS { get; set; }
}

public class RECORD
{
    public string Codigo { get; set; }
    public string Descricao { get; set; }
    public string PrecoVenda { get; set; }
    public string Referencia { get; set; }
    public string Grupo { get; set; }
    public string GrupoDesc { get; set; }
    public string Categoria { get; set; }
    public string CategoriaDesc { get; set; }
    public string Classe { get; set; }
    public string ClasseDesc { get; set; }
    public string NCM { get; set; }
}

agora instale o pacote Newtonsoft.Json - (Json.NET) e com essa instalação execute o seguinte código:
var result = Newtonsoft
            .Json
            .JsonConvert
            .DeserializeObject<Rootobject>(File.ReadAllText("./data.json"));

nesse caso a variável result vai conter a lista de que precisa. Pode também fazer um ajuste no campo PrecoVenda mudando o seu tipo para decimal.
Outros exemplos:

Serializando e Desserializando objetos Json com C#
Deserialize JSON com Restsharp e com JavaScriptSerializer
Comment: o problema com o código acima é que recebo uma exceção do tipo, Unhandled Exception:
Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[EstrelaApp.Model.Catalogo]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
Comment: @FlávioJune eu fiz de acordo com a pergunta acho que faltou passar algo. Coloque na pergunta o exemplo completo
Comment: @FlávioJune é algum campo no json com problema. Observe isso
Comment: Boa noite @Virgilio Novic, fiz de acordo com seu exemplo ainda não deu certo na variavel "json" tenho os dados porem não consigo desserializa-lo, a variavel "Catalogos é null"
Comment: Passa o json completo @FlávioJune
Comment: O json é esse mesmo o que muda é somente a quantidade de objetos contido nele, mas a estrutura é essa
Comment: @FlávioJune A SUA CLASSE Catalogo POR FAVOR
Comment: @FlávioJune você continua fazendo errado pelo visto.
Comment: @FlávioJune você fez uma classe diferente da minha resposta?

Desserializando json complexo


How can I search through xml using linq

Question: I want to search through my xml file. The structure looks like this:
<AForetag xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <Place ID="1006">
        <Foretag>
            <Epost>email@example.com</Epost>
            <Namn>Abe</Namn>
            <Ort>Abc123</Ort>
            <Adress>Abc123</Adress>
            <Postnummer>Abc123</Postnummer>
            <Landskap>Abc123</Landskap>
            <Telefon>Abc123</Telefon>
            <Medlemskap>Abc123</Medlemskap>
        </Foretag>
        <Foretag>
            <Epost>def456</Epost>
            <Namn>def456</Namn>
            <Ort>def456</Ort>
            <Adress>def456</Adress>
            <Postnummer>def456</Postnummer>
            <Landskap>def456</Landskap>
            <Telefon>def456</Telefon>
            <Medlemskap>def456</Medlemskap>
        </Foretag>
    </Place>
</Aforetag>

And I want to search for the Element <Landskap>. And if I get and match I should pick all the other elements, Epost, Namn, Ort, Adress, Postnummer, Landskap, Telefon and Medlemskap. The info I want to put in an array.
I have tried this:
var aforetag = from foretag in doc.Descendants("Place")
                       where foretag.Attribute("ID").Value == "1006"
                       select foretag;

var landskap = aforetag.Elements("Foretag")
                       .Descendants()
                       .Where(x => x.Element("Landskap")
                       .Value
                       .Contains(s)
                       .Descendants()
                       .Select(c => (string)c)
                       .ToArray();

Comment: You tried that. And, what happened?
Comment: So, you also don't know what an exception is. Almost all cases of `NullReferenceException` are the same. Please see "[What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)" for some hints.
Comment: Ill get this Warning: NullReferenceException was unhandled.
Objectreferens has not been given an instance of an object. (Sorry for bad translate)

And its stops to work.
Comment: Got it to work. Thanks, its my XML schema thats was messed up. Had some bad values in it like '--'.
Comment: @faceplant your query is not good, I doubt it doesn't work as you expected unless you have had some modification to make it work
Answer: var landskap = aforetag.Elements("Foretag")
                       .Where(e=>e.Element("Landskap").Value.Contains(s))
                       .Select(e=>e.Elements().Select(x=>x.Value).ToArray());
//the result is an IEnumerable<string[]> for the matched keyword s

Answer: Your code is not well formed. Copy this into VS and there are a few errors, fix one and more errors!...
And most importantly, your XML is not XML as the start and end tag don't even match! Plus, there are other issues.
Fix all these and I'm sure it will help.
Comment: It did help, sorry for wasting your guys time.
Comment: @faceplant No worries!

How can I search through xml using linq


How to convert Humdrum files to Lilypond format?

Question: I have some Humdrum krn score files and want to make Lilypond files out of it for further processing and output generation.
What ist the best way to do this?
I tried the user interface Frescobaldi but there is no import option.
Has anybody experiences in converting this way?

from .krn to music-xml using Humdrum's hum2xml export and then
from .xml to .ly using Lilypond's musicxml2ly import
Comment: I don't have any experience with lilypond and humdrum but If you have experience with Linux maybe you check [this](https://github.com/craigsapp/hum2ly) one :
Answer: Found a review paper of music notation conversions including humdrum to Lilypond: "The Effects of Translation Between Symbolic Music Formats: A Case Study with Humdrum, Lilypond, MEI, and MusicXML" presented at the 2019 Music Encoding Conference in Vienna.
It should be possible. However, the conversions tested in the paper give results that are not very good


Configuring Jenkins for running with BitBucket

Question: I'm trying to setup Jenkins on my mac mini in order to pull my iOS project source code from BitBucket and build it automatically. I've already gone through the major well know problems generating the ssh keys,uploading them in BitBucket,performing an ssh connection by console for adding the host to the well know list (you can find all my adventure here and here). Now,there are 3 user in my system: A,B and Shared. When I installed Jenkins it automatically placed itself in Shared, but I generated the ssh keys with the user A. So just to be clear In the A home directory there is an .ssh directory with public and private keys.
When I try to run by Jenkins job I get this error message:
Started by user anonymous
Building in workspace /Users/Shared/Jenkins/Home/jobs/myprojectAdHocBuild/workspace
Checkout:workspace / /Users/Shared/Jenkins/Home/jobs/myprojectAdHocBuild/workspace - hudson.remoting.LocalChannel@625cb0bb
Using strategy: Default
Cloning the remote Git repository
Cloning repository email@example.com:myuser/myproject.git
git --version
git version 1.8.0
ERROR: Error cloning remote repo 'origin' : Could not clone firstname.lastname@example.com:myuser/myproject.git
hudson.plugins.git.GitException: Could not clone email@example.com:myuser/myproject.git
    at hudson.plugins.git.GitAPI.clone(GitAPI.java:271)
    at hudson.plugins.git.GitSCM$2.invoke(GitSCM.java:1036)
    at hudson.plugins.git.GitSCM$2.invoke(GitSCM.java:978)
    at hudson.FilePath.act(FilePath.java:851)
    at hudson.FilePath.act(FilePath.java:824)
    at hudson.plugins.git.GitSCM.determineRevisionToBuild(GitSCM.java:978)
    at hudson.plugins.git.GitSCM.checkout(GitSCM.java:1134)
    at hudson.model.AbstractProject.checkout(AbstractProject.java:1325)
    at hudson.model.AbstractBuild$AbstractBuildExecution.defaultCheckout(AbstractBuild.java:676)
    at jenkins.scm.SCMCheckoutStrategy.checkout(SCMCheckoutStrategy.java:88)
    at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:581)
    at hudson.model.Run.execute(Run.java:1516)
    at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:46)
    at hudson.model.ResourceController.execute(ResourceController.java:88)
    at hudson.model.Executor.run(Executor.java:236)
Caused by: hudson.plugins.git.GitException: Command "/usr/local/git/bin/git clone --progress -o origin email@example.com:myuser/myproject.git /Users/Shared/Jenkins/Home/jobs/myprojectAdHocBuild/workspace" returned status code 128:
stdout: Cloning into '/Users/Shared/Jenkins/Home/jobs/myprojectAdHocBuild/workspace'...

stderr: Host key verification failed.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

    at hudson.plugins.git.GitAPI.launchCommandIn(GitAPI.java:885)
    at hudson.plugins.git.GitAPI.access$000(GitAPI.java:40)
    at hudson.plugins.git.GitAPI$1.invoke(GitAPI.java:267)
    at hudson.plugins.git.GitAPI$1.invoke(GitAPI.java:246)
    at hudson.FilePath.act(FilePath.java:851)
    at hudson.FilePath.act(FilePath.java:824)
    at hudson.plugins.git.GitAPI.clone(GitAPI.java:246)
    ... 14 more
Trying next repository
ERROR: Could not clone repository
FATAL: Could not clone
hudson.plugins.git.GitException: Could not clone
    at hudson.plugins.git.GitSCM$2.invoke(GitSCM.java:1048)
    at hudson.plugins.git.GitSCM$2.invoke(GitSCM.java:978)
    at hudson.FilePath.act(FilePath.java:851)
    at hudson.FilePath.act(FilePath.java:824)
    at hudson.plugins.git.GitSCM.determineRevisionToBuild(GitSCM.java:978)
    at hudson.plugins.git.GitSCM.checkout(GitSCM.java:1134)
    at hudson.model.AbstractProject.checkout(AbstractProject.java:1325)
    at hudson.model.AbstractBuild$AbstractBuildExecution.defaultCheckout(AbstractBuild.java:676)
    at jenkins.scm.SCMCheckoutStrategy.checkout(SCMCheckoutStrategy.java:88)
    at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:581)
    at hudson.model.Run.execute(Run.java:1516)
    at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:46)
    at hudson.model.ResourceController.execute(ResourceController.java:88)
    at hudson.model.Executor.run(Executor.java:236)

As you can see it fails when Hudson try to run the GIT command. The odd things is that if I try to run
/usr/local/git/bin/git clone --progress -o origin email@example.com:myuser/myproject.git /Users/Shared/Jenkins/Home/jobs/myprojectAdHocBuild/workspace

In my console, it works fine (after fixing a small problem relative the folder write permission with chmod)
I found a post reporting a similar error which names a number of possible options but I'm not sure how to perform correctly these operations on my console. It looks like Jenkins is trying to run a command with a user which doesn't have permission to retrieve the appropriate keys from my .ssh directory.Not really sure.Maybe this output can help:
MacMini:~ myuser$ ps axu | grep "/jenkins"
myuser      11660   0.0  4.6  2918124  97096   ??  S     6:59pm   1:05.63 /usr/bin/java -jar /Users/myuser/Library/Caches/org.jenkins-ci.jenkins/jenkins.war
jenkins         9896   0.0  9.0  2939824 188552   ??  Ss    4:06pm  17:55.91 /usr/bin/java -jar /Applications/Jenkins/jenkins.war
myuser      11930   0.0  0.0  2432768    588 s000  S+   10:28am   0:00.00 grep /jenkins
MacMini:~ myuser$ ps axu | grep tomcat
myuser      11932   0.0  0.0  2432768    588 s000  S+   10:28am   0:00.00 grep tomcat
MacMini:~ myuser$

I really hope to fix this problem, because I would like to write a very detailed tutorial with all the information I found disseminated around the web.
Answer: Ok maybe I found the solution here: http://colonelpanic.net/2011/06/jenkins-on-mac-os-x-git-w-ssh-public-key/
Comment: can anybody confirm it?


How to edit a webform block (not the webform itself)

Question: I have one webform block I would like to edit. I know I can use hook_form_alter, the problem is that any changes I make using it are affecting the actual webform plus the block.
How can change stuff just on the webform block? It's just a captcha component I want to disable, thanks.
Comment: If you're wanting to disable the captcha, that part is in the form, so you need to modify the form. You do want to modify the webform but only when it appears in a block. Have you tried using hook_form_alter to see if there is any data attached to either the $form or $form_state array which you can test to see if this webform is currently being output by a block as opposed to the page view?
Comment: I have tried but there doesn't seem to be anything that gives a hint that it's a block and not a node.
Answer: probably the easiest way is to create a separate form for that block (a copy of what you have now, but dedicated to that block), and disable Captcha for that form name
Comment: I like this suggestion, let me give it a try but as last option. Would be great to catch everything that happens on one form for a certain purpose in one place but thanks, it's a great workaround.
Comment: I know what you mean... I think otherwise you would need to customise Captcha to allow for an exception on that particular block, or create a custom module to handle it. One way to think about it though is that the block version could be a mini version of the full form... semantics I realise, but these things help me sleep at night sometimes :)


In one column calculate the product of two columns

Question: I'm trying to create a formula in Google Sheets where in one column the product of two columns is calculated. I could simply type in each cell as an example in Column F:
<code>=if(and(A1>0,C1>0),A1*C1,"")
</code>
but it would get tedious if there are 100 rows in those columns. I have tried:
<code>=arrayformula(if(and(A1:A100>0,C1:C100>0),A1:A100*C1:C100,""
</code>
Comment: Possible duplicate of [ArrayFormula and "AND" Formula in Google Sheets](https://stackoverflow.com/questions/43710792/arrayformula-and-and-formula-in-google-sheets)
Comment: Try this `=arrayformula(if(A1:A100>0,if(C1:C100>0,A1:A100*C1:C100,"")))` or `=array_constrain(arrayformula(if(A1:A>0,if(C1:C>0,A1:A*C1:C,""))),100,1)`. But you should read [ArrayFormula and "AND" Formula in Google Sheets](https://stackoverflow.com/questions/43710792/arrayformula-and-and-formula-in-google-sheets) to learn about the use of `AND` in an arrayformula. In fact, your question is a possible duplicate of that question.
Answer: Try:
<code>=arrayformula(if((A1:A100>0)*(C1:C100>0),A1:A100*C1:C100,""))
</code>


Double field module theming

Question: Could anyone please help with the Double field module in Drupal 8 and Twig? I am trying to produce the following with no luck so far as I cannot figure out the proper Twig variables to use.

{{ first }}

{{ second }}

I would like to have the raw values in the html above.
-- I'm adding some more info here because my goal is to understand the mechanics of twig in this case and how I can get the field values of the two subitems
I have overriden (as suggested by drupal's theme debug system) the field--fieldname.html.twig template in which I have the following

{% for item in items %}

      {{ item.first }}

      {{ item.second }}

{% endfor %}

which is not printing anything in the value areas and apart from that does not iterate through all the items either.
Answer: If you are using default (Unformatted list) formatter override double-field-item.html.twig template with the following markup:

{{ item.first }}

{{ item.second }}

Note that Double field ships with HTML list formatter which may render definition list so you might not need to override anything.
Comment: Thanks a lot @ya.teck, but I still cannot quite grasp the solution. I am not very proficient with drupal excuse my possible ignorance, but are you suggesting I override the double-field-item.html.twig in general? Can I do that by just adding a file with the same name in my theme's templates folder? I have actually already used the {{ item.first/second }} markup on the drupal suggested field template iterating through items but I get no output at all.
Comment: You need to clear caches for the changes to take effect. Also consider using the second approach with HTML list formatter. Seems it covers your case perfectly.
Comment: Thanks again for your suggestion @ya.teck I had a look at the definition list provided and in fact it is working but I'm having a little inconsistency with what the actual html of my theme is so I would really like to understand why isn't the code I added to my original question not working, as it is important all customisations are kept within the actual theme's files and not base anything on core or module alterations.
Comment: The code you used in `field--fieldname.html.twig` is wrong. You should not use `item.first` and `item.second` there.
Comment: "a little inconsistency with what the actual html of my theme is"
Note the you can override a template (`double-field-definition-list.html.twig`) for the definition list as well.

Double field module theming


Retrieving all the columns of a table through Java

Question: I have this below code in which a request goes from browser through rest web service to the controller and then database connection get established through jdbc , my query is that i want to change my below code in such a way so that it can retrieve all the columns of the table , please advise how can i achieve the same
<code>@GET
    @Produces(MediaType.TEXT_HTML)

    public String retriveData(@QueryParam("tablename") String tablename) throws SQLException
    {
        Connection con=null;
        PreparedStatement ps=null;
        String statement="";
        String retString="";

        try {
            //Class.forName("com.mysql.jdbc.Driver");
            //put sql jdbc jar in tomcat lib
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

            System.out.println(" ******Driver Loaded *******");

            con=DriverManager.getConnection("jdbc:sqlserver://sv53720.hk.sunlife:1433; databaseName=pin_uat", "pinread","pinread123");
            con.setAutoCommit(false);

            System.out.println(" ******Connected To MSSql ******");

            System.out.println("FROM TABLE NAME : "+tablename);
            statement="SELECT * FROM "+tablename+";";

            System.out.println("STATEMENT : "+statement);
            ps=con.prepareStatement(statement);
            // Turn use of the cursor on.
            //ps.setFetchSize(50);
            ps.setMaxRows(10);
            ResultSet rs=ps.executeQuery();
            ResultSetMetaData rsmd=rs.getMetaData();
            String name=rsmd.getColumnName(1);
            while(rs.next())
            {

                retString=retString+name+" : "+rs.getString(name)+"<br>";
                System.out.println(retString);

            }

            System.out.println("Table FOUND!!!");
            ps.close();
            rs.close();
            con.close();
            return retString;

        }catch(Exception e) {
            e.printStackTrace();

        }
        finally {
            if(con!=null)
                con.close();
        }

        return "Unable To Read Table :(";

    }
</code>
Comment: You had a good start with `rsmd.getColumnName` but you can also know how many columns there is to get all the columns that way. Check [this answer](https://stackoverflow.com/a/3818712/4391450) from the duplicate.
Comment: you need to query the information schema
Comment: Possible duplicate of [Retrieve column names from java.sql.ResultSet](https://stackoverflow.com/questions/696782/retrieve-column-names-from-java-sql-resultset)
Answer: Try this
<code>   statement="SELECT * FROM "+tablename+";";
        ps=obj.getConnection().prepareStatement(statement);
        ps.setMaxRows(10);

        ResultSet rs=ps.executeQuery();
        ResultSetMetaData rsmd=rs.getMetaData();
        int columnCount = rsmd.getColumnCount();

     // The column count starts from 1
     for (int i = 1; i <= columnCount; i++ ) {
       String name = rsmd.getColumnName(i);
       retString=retString+i+"- coloum name="+name+",";

     }
     System.out.println(retString);
</code>
Comment: it did not give string value


$A\in M_3(\mathbb R)$ orthogonal matrix with $\det (A)=1$.  Prove that $(\mathrm{tr} A)^2- \mathrm{tr}(A^2) = 2 \mathrm{tr} (A)$

Question: $A\in M_3(\mathbb R)$ orthogonal matrix with $\det (A)=1$.
I need to prove that $(\mathrm{tr} A)^2-\mathrm{tr}(A^2) = 2 \mathrm{tr} (A)$ ; $\mathrm{tr}$=trace.
I know that if $A$ is orthogonal than $A^tA=I$ and that $A$ is diagonalizable and similar to $D=\begin{pmatrix}
\lambda_1 &  & \\
 & \lambda_2 & \\
 &  & \lambda_3
\end{pmatrix}$. We know as well that $\mathrm{tr} A=\mathrm{tr} D= \lambda_1+ \lambda_2+\lambda_3$  that  $\mathrm{tr} A^2=\mathrm{tr} D^2= \lambda_1^2+ \lambda_2^2+\lambda_3^2$ and that
$\lambda_1 \lambda_2 \lambda_3=1$. It's not enough for solving the question.
What more should I know or use in order to solve it?
Thanks
Answer: $\begin{align*}\mathrm{Tr}(A)^2-\mathrm{Tr}(A^2)&= (\lambda_1+\lambda_2+\lambda_3)^2-(\lambda_1^2+\lambda_2^2+\lambda_3^2)\\&=2(\lambda_1\lambda_2+\lambda_2\lambda_3+\lambda_3\lambda_1)\\&=2\lambda_1\lambda_2\lambda_3\left(\frac{1}{\lambda_1}+\frac{1}{\lambda_2}+\frac{1}{\lambda_3}\right)\\&=2\det(A)\mathrm{Tr}(A^{-1})\\&=2\mathrm{Tr}(A).
\end{align*}$
(Edit: In the last step, we use the facts that $A^{-1}=A^T$ when $A$ is orthogonal and $\mathrm{Tr}(A^T)=\mathrm{Tr}(A)$ for any matrix $A$.)
Comment: Does this claim on $tr(A^{-1})$ is always true?
Comment: @anon: You could add that your last step holds because $A^{-1}=A^t$ and $\text{tr}(A^t)=\text{tr}(A)$.
Comment: Yeah, I know this I mean that for every $A$ such that $trA= x+y+z+w$, $trA^{-1}=1/x+1/y+1/z+1/w$?
Comment: Jozef: The eigenvalues of $A^n$ are the $n$-th powers of the eigenvalues of $A$, so $\mathrm{Tr}(A^n)=\sum \lambda_i^n$ holds.
Comment: +1: This is the most elegant use of the orthogonality of $A$ (out of the solutions presented here at this point in time). Nice!
Answer: In $\mathbb Z[X,X^{-1}]$ we have
$$(1+X+X^{-1})^2-(1+X^2+X^{-2})=2+2X+2X^{-1}.$$
In other words, your equality holds over any commutative ring, for any matrix similar to a diagonal matrix with diagonal entries $1,a,a^{-1}$, where $a$ is a unit.
Answer: An old-fashioned argument
The matrix $A$ is the matrix of a rotation through some angle $\theta$.  It is a standard result that the trace of such a rotation is $1+2\cos\theta$.  The matrix $A^2$ is a rotation through $2\theta$ about the same axis.
So we want to show that
$$(1+2\cos\theta)^2-(1+2\cos 2\theta)=2(1+2\cos\theta).$$
With a little manipulation this reduces to the familiar $\cos 2\theta=2\cos^2\theta -1$.
Answer: A rotation is diagonalisable over the complex numbers, but generally not over the reals. However, there always is an orthonormal basis $\mathcal{B}$ and a real number $\theta$ such that $$\mathrm{Mat}_{\mathcal{B}}(A)=\left(\begin{array}{ccc} \cos(\theta) & -\sin(\theta) & 0 \\ \sin(\theta) & \cos(\theta) & 0 \\ 0&0&1\end{array}\right)$$
and you'll have $$\mathrm{Mat}_{\mathcal{B}}(A^2)=\left(\begin{array}{ccc} \cos(2\theta) & -\sin(2\theta) & 0 \\ \sin(2\theta) & \cos(2\theta) & 0 \\ 0&0&1\end{array}\right)$$
Thus $\mathrm{Tr}(A)=1+2\cos(\theta)$ and $\mathrm{Tr}(A^2)=1+2\cos(2\theta)$. The rest follows from trigonometry.
Answer: Hint:
$$\det(I-A)=\det(A^tA-A)=\det(A^t-I)\det(A)=\det(A-I)\cdot1=(-1)^3\det(I-A),$$
so $\det(I-A)=0$. IOW one of the eigenvalues is equal to $1$. Does that help?
Comment: Hi Jyrki! Isn't it enough to note that the eigenvalues are $1,z,1/z$ with $|z|=1$? (It's a Laurent polynomial identity, i.e. an identity in the ring $\mathbb Z[z,z^{-1}]$.)
Comment: @Pierre-Yves: Of course it is enough! Undoubtedly you know this, but for the record I will state that geometrically $A$ is a rotation of the 3-dimensional space. Hence (by the above argument) it has an axis (corresponding to eigenvalue 1), and an angle of rotation $\theta$ (meaning that the other two eigenvalues are $\lambda_{1,2}=\cos\theta\pm i\sin\theta.$)


Quotient, Tensor Quasicoherent Sheaves on Affine Open Subsets

Question: Quotient and tensor sheaves are defined by sheafification which is somehow implicit. Is there any easy way to handle these constructions?
Could we ignore the sheafification when we are working in affine open subsets?
For example, let $X$ be a scheme and $\mathcal F$ and $\mathcal G$ be quasicoherent sheaves. Let $U\subseteq X$ be an affine open. Is it true that  $(\mathcal F/\mathcal G)(U) = \mathcal F(U)/\mathcal G(U)$ and $\mathcal F\otimes_{\mathcal O_X}\mathcal G(U) = \mathcal F(U)\otimes_{\mathcal O_X(U)}\mathcal G(U)$?
How about other constructions involving sheafification? (for example, image, cokernel, ann, nil and so on)
Thank you in advance.
Comment: Great question about something that I still find confusing to this day.
Comment: I tend to just pretend it is what I hope it is, and then pray I can work locally on the stalks where it *is* what I hope it is.
Comment: That is a general phenomenon that : constructions involving
quasicoherent sheaves that involve sheafification for general sheaves don't require
sheafification when considered on the distinguished affine base. This lies in the fact that many operation commute with localization, therefore the presheaf is already a sheaf on the distinguished open base.
Answer: The key statement to verify is whether the thing you're looking at commutes with localization. If it does, then it commutes with sections on affine opens: start by defining the presheaf which takes the naive value on every open set, and then note that on principal affine opens $D(f)$ you get exactly the value you would expect from the quasi-coherent sheaf associated to the operation on the module of global sections. As the principal affine opens form a basis for the topology on an affine scheme and a sheaf can be specified by its values on a basis, the result follows.
In particular, this means that kernels, cokernels, images, and any other "homological" constructions commute with the associate sheaf functor on an affine scheme because localization is exact. Tensor products and nilradicals commute with localization, so they commute with the associated sheaf functor, too. Annihilators don't always commute with localization, so you need to be more careful with them.

Let me just mention one alternate neat proof that tensor products commute with sheafification, which I originally saw at the Stacks Project: consider the morphism of ringed spaces $\pi:(\operatorname{Spec} R,\mathcal{O}_{\operatorname{Spec} R})\to (\{pt\},R)$. Then the associated sheaf functor is $\pi^*$, which means it commutes with tensor products by the standard proof.
Comment: They might not be the same, but sheafification won't alter the sections on the principal affine opens: any section of the quotient sheaf on a principal affine open is glued from sections on an open cover, which by refinement we may take to be by smaller principal affine opens, and that already satisfies the sheaf condition. The proof that locality is satisfied is the same.
Comment: Ohhhh!  I think I got your idea. Do you mean the following statement? Let $\mathcal F$ be a sheaf and $\mathcal G$ be a presheaf and $\mathcal B$ be a topological basis of $X$. If $\mathcal F(U) = \mathcal G(U)$ for all $U\in \mathcal B$, then $\mathcal F = \mathcal G^\dagger$.
Comment: Well, take quotients for example: if $R$ is a ring, $S\subset R$ is a multiplicative subset,  and $A$ is an $R$-submodule of an $R$-module $B$, then $S^{-1}(B/A)\cong (S^{-1}B)/(S^{-1}A)$ naturally. "Commutes with localization" means the localization of whatever thing you're doing is the same as doing whatever you're doing to the localization. Secondly, if $\mathcal{F}$ is a quasicoherent sheaf on an affine scheme $X$, then $\mathcal{F}(D(f))=\mathcal{F}(X)_f$, then one applies the fact that you're doing something that commutes with localization.
Comment: Say $U=\operatorname{Spec} A$. Then $\mathcal{F}(U)_f/\mathcal{G}(U)_f=(\mathcal{F}(U)/\mathcal{G}(U))_f$, which is exactly the value on $D(f)$ of the sheaf associated to the $A$-module $\mathcal{F}(U)/\mathcal{G}(U)$.
Comment: Take the sheaf on $U$ associated to that $A$-module $\mathcal{F}(U)/\mathcal{G}(U)$. The sections of this on $U$ are $\mathcal{F}(U)/\mathcal{G}(U)$, and the sections on $D(f)$ are $[\mathcal{F}(U)/\mathcal{G}(U)]_f$, which is exactly the sections of the quotient presheaf $\mathcal{F}/\mathcal{G}$. As principal affine opens form a basis and this specifies a sheaf on that basis, we're done.
Comment: Alternately, look at the canonical exact sequence $0\to\mathcal{F}\to\mathcal{G}\to\mathcal{F}/\mathcal{G}\to 0$: as sections over $U$ is an exact equivalence between quasicoherent sheaves on $U$ and $A$-modules, this corresponds to the exact sequence $0\to \mathcal{F}(U)\to\mathcal{G}(U)\to [\mathcal{F}/\mathcal{G}](U)\to 0$, which is isomorphic to $0\to\mathcal{F}(U)\to\mathcal{G}(U)\to \mathcal{F}(U)/\mathcal{G}(U)\to 0$, so taking associated sheaves we see that the third item is both $\mathcal{F}/\mathcal{G}$ and the sheaf associated to $\mathcal{F}(U)/\mathcal{G}(U)$.
Comment: Yes, that's correct.
Comment: What does that mean by 'commutes with localization'? And why on $D(f)$ we get exactly the expected value?
Comment: Maybe I do not understand it well. Take quotient as an example. Let $U$ be an affine open set. I think your idea is to show $\mathcal F(D(f))/\mathcal G(D(f)) = (\mathcal F/\mathcal G)(U)_f$ and then use the gluing uniqueness. But from 'commutes with localization', we only know $\mathcal F(D(f))/\mathcal G(D(f)) = \mathcal F(U)_f/\mathcal G(U)_f$. How to show $\mathcal F(U)_f/\mathcal G(U)_f = (\mathcal F/\mathcal G)(U)_f$?
Comment: Sorry, but I'm still confused. I think we should show $(\mathcal F/\mathcal G)(U)_f = [\mathcal F(U)/\mathcal G(U)]_f$. But 'commutes with localization' only tells us $[\mathcal F(U)/\mathcal G(U)]_f = \mathcal F(U)_f/\mathcal G(U)_f$.
Comment: Okay. Now I understand that, as presheaves, $[\mathcal F(U)/\mathcal G(U)]^\sim(D(f)) = (\mathcal F/\mathcal G)^{pre}(D(f))$. But how to conclude they are actually equal as sheaves?


Is there an example of a convex combination that is not conic?

Question: I am curious to know if all convex combinations are conic combinations?
A convex combination is: $$C=\{x|x=\alpha_1x_1+...+\alpha_kx_k, \alpha_1+...+\alpha_k=1,\alpha_i\geq0\}$$
A conic combination is:$$C=\{x|x=\alpha_1x_1+...+\alpha_kx_k, \alpha_i\geq0\}$$
Answer: There's hardly anything to be curious about when convex combination litterally has an additional condition compared to conic combination.


Ajax reload div content on click button

Question: The idea is: i have a main DIV with content mini divs of cars info divided two per row, that i'm getting with a query from DB, i want when pressing that button to make reload of that main content with new content from the DB, is that possible to do ? please advise.
code looks like this:

INFO

INFO

INFO

INFO

        ......

Load more

Comment: That is possible. What have you tried so far? Also, what back-end technology and database are you using.
Comment: @Kenneth it's WP custom with PHP MySQL, i don't have quite experience with this, so didn't try much really...
Comment: Well, you need to show some effort at least. SO is not a programmer-for-free website. There are plenty of examples out there on the web. I suggest you try something and when you get really stuck, you can come back and ask a specific question
Comment: @Kenneth As you can see it's not the actual code, so i'm not trying to solve my personal problem, i'm trying to get the best solution for this Ajax reloading for others too
Answer:     function reload(url){
       $.get(url, function(data){      // $.get will get the content of the page defined in url and will return it in **data** variable
            $('#row').append(data);
       }
    }

$('#more_link').click(function(e){
        e.preventDefault();
        var url = 'http://example.com/somepage.html';
        reload(url);  // this calls the reload function
});

Comment: Thanks for your answer; can you please write some description to it?
Comment: and don't forget that ajax only works if the url is in the same domain  (and subdomain). it will not work for urls from other sites
Answer: You haven't shown the exact code you're using to generate your AJAX request, however the general pattern will be something like this, where the update logic is extracted in to it's own function which is called both on load of the page, and click of the #reload_cars button.
function getData() {
    $.ajax({
        url: 'yoururl.foo',
        success: function(data) {
            $('#row .car_section').remove();
            $('#row').append(data);
        }
    });
}
$('#reload_cars').on('click', getData);
getData();

Comment: Thanks for your answer, i forgot to mention that the URL is not static, that page is loaded from a search so will be like: `URL/New-york` and `URL/Las-Vegas` ... etc, how can i add the `url` in your code for this situation of mine?
Comment: @Jimmy, I think you should really update your OP with much more detail. You can append the URL with the value required: `url: 'URL/' + location`, assuming `location` is the variable holding the value
Comment: I tried with a specific URL and tested that page, but the code is not quite working, nothing happens, just goes to first of the page and changes URL to `URL/#'
Comment: Again, please update your question with details of your code. I can't debug something I can't see ;)
Comment: Thanks Rory! yes i update it the HTML with more details, the data from the inside the main div comes from a query without limitation so it's like 30 40 results, i want limited it to 10 and want to load the next 10 and remove the first ten, something like that
Answer: just use

    function refreshDiv(){
       var container = document.getElementById("divId");
       var content = container.innerHTML;
       container.innerHTML= content;
    }

Comment: Thanks for your answer! `document.getElementById("divId");` but where is the `divId` in your code?
Comment: "divId" is the id of div that you want reload

Ajax reload div content on click button


Result order of a select

Question: I have an interesting question:
I have a function that get a comma separated string of integers.
Here are 2 executions:
select ID from dbo.udf_NumList2table ('124,126,132,180,176')
select RP.ID, My.ID
from dbo.udf_NumList2table ('124,126,132,180,176') RP join MyTable My
        on RP.ID=My.ID

In the first execution the order of the results is like the order of the numbers in the string.
In the second execution the order of the results is ascending (176 before 180).
Why? I guess that the PK on column ID in MyTable is the reason - the SQL prefer to run on the key.
Do I right?
Answer: Select guarantees no ordering of the results, so your results are not even guaranteed to be the same each time you run, although in your case as the data is so small they will be the same. The order will be the most convienient to the optimizer so your guesses might well be correct here.
On higher volumes of data the query can be split across different threads of execution and so give a more confused order and depending on workload on the server could differ between runs.
To get a consistent order you have to use an ORDER BY clause.

Result order of a select


Vector in JSP page

Question: How I can iterate a vector in a JSP page?
I have done it:
<%
 Vector value = (Vector) request.getAttribute("status");
 for (Enumeration e = value.elements(); e.hasMoreElements(); )
 {
        StatusItem myStatus = (StatusItem) e.nextElement();

 }
%>

Is there any way to do it with jsp tags?
Thx
Comment: `Vector` is a legacy Java class. It was over a decade ago succeeded by the improved `ArrayList`. I'd suggest to keep your code up to date and ignore tutorials which are over 10 years old.
Comment: that i know it, but I'm working with a system that only supports JDK1.1
Comment: Then it shouldn't support JSPs.. ?
Answer: Print out the contents of the vector like this:
<c:foreach var="myStatus" items="${status}" >

  <c:out value="${myStatus.value}"/>
</c:foreach>

Answer: You can iterate collections by <c:forEach> jstl tag:
<c:forEach var="s" items="${status}">
    item is: ${s}
</c:forEach>

Vector in JSP page


Pandas groupby and then sort based on groups

Question: I have a dataset of news articles and their associated concepts and sentiment (NLP detected) which I want to group by 2 fields: the Concept and the Source. A simplification is following:
>>> df = pandas.DataFrame({'concept_label': [1,1,2,2,3,1,1,1],
                      'source_uri': ['A','B','A','A','A','C','C','C'],
                      'sentiment_article': [0.05,0.15,-0.3,-0.2,-0.5,-0.6,-0.3,-0.4]})

    concept_label  source_uri   sentiment_article
    1              A            0.05
    1              B            0.15
    2              A            -0.3
    2              A            -0.2
    3              A            -0.5
    1              C            -0.6
    1              C            -0.3
    1              C            -0.4

So I basically would want to know for the concept "Coronavirus" how often each news outlet writes about the topic and what the mean sentiment of the article is. The above df would then look like this:
                               mean     count
concept_label    source_uri
3                A             -0.50    1
2                A             -0.25    2
1                A             0.050    1
1                B             0.150    1
1                C             -0.43    3

I am able to do the grouping with the following code (df is the pandas dataframe I'm using, concept_label is the concept, and source_uri is the news outlet):
df_grouped = df.groupby(['concept_label','source_uri'])
df_grouped['sentiment_article'].agg(['mean', 'count'])

This works just fine and gives me the values I need, however I want the groups with the highest aggregate number of "count" to be at the top. The way I tried to do that is by changing it to the following:
df_grouped = df.groupby(['concept_label','source_uri'])
df_grouped['sentiment_article'].agg(['mean', 'count']).sort_values(by=['count'], ascending=False)

However even though this sorts by the count, it breaks up the groups again. My result currently looks like this:
                               mean     count
concept_label    source_uri
3                A             -0.50    1
1                A             0.050    1
1                B             0.150    1
2                A             -0.25    2
1                C             -0.43    3

Comment: Do you mind to provide a [mcve](/help/mcve) in particular a sampla of your data?
Comment: I added a sample to explain the problem. If it's not sufficient please let me know.
Comment: What do you mean by `it breaks up the groups again`?
Comment: The grouping by concept_label is lost. As you can see in the final example, the number 1 is not grouped anymore. The sorting on count is done on row level, not on group level.
Comment: Can you include your desired result?
Comment: The desired result is the second data example in the description. Where it says "The above df would then look like this:"
Answer: I don't believe this is the nicest answer, but I found a way to do it.
I grouped the total list first and saved the total count per concept_label as a variable that I then merged with the existing dataframe. This way I can just sort on that column and secondary on the actual count.
#adding count column to existing table
df_grouped = df.groupby(['concept_label'])['concept_label'].agg(['count']).sort_values(by=['count'])
df_grouped.rename(columns={'count':'concept_count'}, inplace=True)
df_count = pd.merge(df, df_grouped, left_on='concept_label', right_on='concept_label')

#sorting
df_sentiment = df_count.groupby(['concept_label','source_uri','concept_count'])['sentiment_article'].agg(['mean', 'count']).sort_values(by=['concept_count','count'], ascending=False)


Radio streaming nokia sdk 1.1 using http

Question: I am working on a fm radio streaming project and i am implementing radio streaming for nokia sdk1.1 but i am not successful, i have followed many alternatives like
J2ME/StreamingMedia.htm">http://www.java2s.com/Tutorial/Java/0430_J2ME/StreamingMedia.htm
player = Manager.createPlayer("http://someurl:someport"); // this is not working and showing invalid url while same url works in media player i have checked and it is valid.

please give me some suggestions.
Thanks
Answer: i suggest you look into rtsp, real time streaming protocol for j2me.
Answer: I use input stream to create radio player.
InputStream is = Connector.openInputStream("http://someurl:someport");
Player player = Manager.createPlayer(is, "audio/mpeg");
player.start();


Stack-relative vs stack deferred addressing

Question: What are the practical diffences between s and sf in the two code samples below?
I understand that stack relative look like Mem[SP + OprndSpec] and deffered look like Mem[Mem[SP + OprndSpec]].  However what I don't understand is how this is accomplished.
Stack deffered
<code>         BR      main
a:       .BLOCK  2          ;global variable #2d
b:       .BLOCK  2          ;global variable #2d
;
;******* void swap (int& r, int& s)
r:       .EQUATE 6          ;formal parameter #2h
s:       .EQUATE 4          ;formal parameter #2h
temp:    .EQUATE 0          ;local variable #2d
swap:    SUBSP   2,i        ;allocate #temp
         LDA     r,sf       ;temp = r
         STA     temp,s
         LDA     s,sf       ;r = s
         STA     r,sf
         LDA     temp,s     ;s = temp
         STA     s,sf
         RET2               ;deallocate #temp, pop retAddr
;
;******* void order (int& x, int& y)
x:       .EQUATE 4          ;formal parameter #2h
y:       .EQUATE 2          ;formal parameter #2h
order:   LDA     x,sf       ;if (x > y)
         CPA     y,sf
         BRLE    endIf
         LDA     x,s        ;   push x
         STA     -2,s
         LDA     y,s        ;   push y
         STA     -4,s
         SUBSP   4,i        ;   push #r #s
         CALL    swap       ;   swap (x, y)
         ADDSP   4,i        ;   pop #s #r
endIf:   RET0               ;pop retAddr

;
;******* main ()
main:    STRO    msg1,d     ;cout << "Enter an integer: "
         DECI    a,d        ;cin >> a
         STRO    msg1,d     ;cout << "Enter an integer: "
         DECI    b,d        ;cin >> b
         LDA     a,i        ;push the address of a
         STA     -2,s
         LDA     b,i        ;push the address of b
         STA     -4,s
         SUBSP   4,i        ;push #x #y
         CALL    order      ;order (a, b)
ra1:     ADDSP   4,i        ;pop #y #x
         STRO    msg2,d     ;cout << "Ordered they are: "
         DECO    a,d        ;     << a
         STRO    msg3,d     ;     << ", "
         DECO    b,d        ;     << b
         CHARO   '\n',i     ;     << endl
         STOP
msg1:    .ASCII  "Enter an integer: \x00"
msg2:    .ASCII  "Ordered they are: \x00"
msg3:    .ASCII  ", \x00"
         .END
</code>
Stack relative
<code>         BR      main
;
;******* int binomCoeff (int n, int k)
retVal:  .EQUATE 10          ;returned value #2d
n:       .EQUATE 8           ;formal parameter #2d
k:       .EQUATE 6           ;formal parameter #2d
y1:      .EQUATE 2           ;local variable #2d
y2:      .EQUATE 0           ;local variable #2d
binCoeff:SUBSP   4,i         ;allocate #y1 #y2
if:      LDA     k,s         ;if ((k == 0)
         BREQ    then
         LDA     n,s         ;|| (n == k))
         CPA     k,s
         BRNE    else
then:    LDA     1,i         ;return 1
         STA     retVal,s
         RET4                ;deallocate #y2 #y1, pop retAddr
else:    LDA     n,s         ;push n - 1
         SUBA    1,i
         STA     -4,s
         LDA     k,s         ;push k
         STA     -6,s
         SUBSP   6,i         ;push #retVal #n #k
         CALL    binCoeff
ra2:     ADDSP   6,i         ;pop #k #n #retVal
         LDA     -2,s        ;y1 = binomCoeff (n - 1, k)
         STA     y1,s
         LDA     n,s         ;push n - 1
         SUBA    1,i
         STA     -4,s
         LDA     k,s         ;push k - 1
         SUBA    1,i
         STA     -6,s
         SUBSP   6,i         ;push #retVal #n #k
         CALL    binCoeff
ra3:     ADDSP   6,i         ;pop #k #n #retVal
         LDA     -2,s        ;y2 = binomCoeff (n - 1, k - 1)
         STA     y2,s
         LDA     y1,s        ;return y1 + y2
         ADDA    y2,s
         STA     retVal,s
endIf:   RET4                ;deallocate #y2 #y1, pop retAddr
;
;******* main ()
main:    STRO    msg,d       ;cout << "binCoeff (3, 1) = "
         LDA     3,i         ;push 3
         STA     -4,s
         LDA     1,i         ;push 1
         STA     -6,s
         SUBSP   6,i         ;push #retVal #n #k
         CALL    binCoeff
ra1:     ADDSP   6,i         ;pop #k #n #retVal
         DECO    -2,s        ;<< binCoeff (3, 1)
         CHARO   '\n',i      ;cout << endl
         STOP
msg:     .ASCII  "binCoeff (3, 1) = \x00"
         .END
</code>
Comment: Your code formatting is pretty lousy which makes people not want to read your question.
Comment: Sorry about that, I cleaned it up.
Answer: Your question seems simple and has little to do with code other than they presumably contain examples.
(I'm not familiar with this instruction set, but have been coding a long time in assembly.)
According to the definition you provided, "stack relative" means taking an item from memory at a location determined by the stack pointer, plus a constant offset presumably embedded in an instruction.  This is called indexed addressing by most folk, with the special note that it is stack-pointer indexed.
"Deferred" (an old term) usually means "indirect through a memory location" and your definition of that is consistent with this idea: find the "stack relative" location, read that, and use that value as the memory location to fetch.


The maximum number of some elements in the finite field.

Question: Consider the finite field $\mathbb{F}_{p^q}$ for some $p$ and $q$ where $p$ is a prime number. Suppose that $r$ in $\mathbb{F}_{p^q}$ has multiplicative order $n$. Consider the set ${\bf L}=\{0,1,r,r^2,\cdots ,r^{n-1}\}$.
Let the elements of ${\bf R}=\{a_1,a_2,,\cdots ,a_t\}$ in $\mathbb{F}_{p^q}$ for some $t$, satisfy the following condition:

For any $1\leq i,j\leq t$, $i \neq j$, we have $a_i\, a_j^{-1}$ is not an element of the set $\bf L$ and also $a_i's\not \in {\bf L}$.

Example: Suppose that  $\mathbb{F}_{2^4}$ is constructed from the primitive polynomial ${\bf f}=x^4+x+1$ over $\mathbb{F}_{2}$. Let $\alpha$ be a root of  $\bf f$. It is easy to check that $\alpha^5$ has multiplicative order $3$. Now consider the set ${\bf L}=\{0,1,{\alpha}^{5},{\alpha}^{10}\}$. Suppose that we want get four elements $a_i$ with $1\leq i \leq 4$ such that for any $1\leq i,j\leq 4$ we get $a_i\, a_j^{-1}$ is not an element of the set $\{0,1,{\alpha}^{5},{\alpha}^{10}\}$. By search we get:
${\bf R}=\{{\alpha}^{11},{\alpha}^{4},{\alpha}^{7},{\alpha}^{8}\}$. It can be verified that the elements of $\bf R$ satisfy the mentioned condition.
My Question: What is the maximum value for $t$ when $p$,$q$ and $r$ are fixed?
Thanks for any suggestion.
Answer: The keys to this question are the observations that

$L^*=\{1,r,r^2,\ldots,r^{n-1}\}$ is a subgroup of the multiplicative group $\Bbb{F}_{p^q}^*$, and
the condition $a_ia_j^{-1}\notin L^*$ is equivalent to the condition
$$a_i\notin a_jL^*.$$ By elementary group theory $a_i\notin a_j L^*$ is equivalent to $a_iL^*\neq a_j L^*$. In other words, you want the elements $a_i,i=1,2,\ldots,t$, to come from distinct cosets of $L^*$.

The other condition $a_i\notin L$ rules out the coset $L^*=1\cdot L^*$, but doesn't affect anything else. Including $0$ into $L$ doesn't affect anything either because the presence of multiplicative inverses in the condition already excluded $0$ as an element of $\mathbf{R}$.
Anyway, the number of cosets of $L^*$ is
$$
N=\frac{|\Bbb{F}_{p^q}^*|}{|L^*|}=\frac{p^q-1}n.
$$

The conditions are met if and only if $\mathbf{R}$ only contains a single element from each coset of $L^*$ in $\Bbb{F}_{p^q}^*$ other than $L^*$ itself. The maximum cardinality of $\mathbf{R}$ is thus
  $$t=N-1=\frac{p^q-1-n}n.$$

It is also easy to describe explicit sets $\mathbf{R}$ of $N-1$ elements. If $g$ is any generator of the multiplicative group $\Bbb{F}_{p^q}^*$, IOW, a primitive element, then we can use
$$
\mathbf{R}=\{g,g^2,g^3,g^4,\ldots,g^{N-1}\}.
$$
Here $g^N$ is the lowest power of $g$ contained in the subgroup $L^*$.
More generally,
we can use
$$
\mathbf{R}=\{g^s\mid s\in S\},
$$
where $S$ consists representatives of cosets of the subgroup $H=N\Bbb{Z}_{p^q-1}$ in
$\Bbb{Z}_{p^q-1}$ other than $H$ itself. In the OP's case $p^q-1=15$, $g=\alpha$, $N=5$. The set of exponents
$$S=\{4,7,8,11\}$$
works because none of them is divisible by five, and they fall into distinct residue classes modulo five.
Comment: Perfect Professor Lahtonen. I wish your [finite fields note](http://users.utu.fi/lahtonen/Fq2019/moniste.pdf) was in English format. I really want to study it, word by word.


Convert string to operator

Question: I am implementing a basic interpreter function that simulates an "conditional jump".
It takes four inputs, which are

variable(Char type)
operator(<=, > ...)(String type)
integer value(int type)
line number(int type)

Function declaration
void ProgramState::conditionalJump(int var, std::string op, int immediate, int destination);
// condition: Compares var and immediate using op
// if condition is true: modify current address to destination if the
// if false: nothing happens

For example, I can write a very crude implementation that is shown below:
Example:
if ( (op == "<") && (var < immediate) ){
    cur_line = destination;
}

Is there a simple way of doing this?
I thought about overloading the operator, but I am not sure if it works.
Comment: It's not clear to me what you are asking.
Comment: Is there a way to convert string type to operator type?
Comment: Can you post the signature of the function, explain what the arguments stand for, and what the function is supposed to do?
Comment: I think what you have there is about the simplest implementation
Comment: There is no such thing as "operator type", is it? You want something like `var (op) immediate`, where `op` is evaluated as operator between arguments. There is no such thing in C++; The only thing that you can do is to write what you already have in more convoluted way, arguably cleaner/more readable but in principle functionally the same.
Answer: What you literally asked to do isn't possible, C++ provides no means to "convert" data to code.
You can (arguably) improve on a series of separate tests with something like a map from strings to functors that do the comparisons.
Setup code:
std::map<std::string, std::function<bool(int, int)> comparisons;
comparisons["<"] = std::less<int>();
comparisons[">"] = std::greater<int>();
... etc ...

Usage code (not particularly efficient but concise version):
if (comparisons.count(op) && comparisons[op](var, immediate)) {
    cur_line = destination;
}

For performance you might want to use function pointers rather than std::function as the values in the map. You have to write more setup, though. And for that matter, the code you already have might well be faster.
Comment: if OP decides to go this route, here is the link for function objects:
http://www.cplusplus.com/reference/functional/
Answer: I think that what you are asking is how to convert a std::string to a relational operator. Well, I don't know any way to achieve this with metaprogramming, but the string class has only 6 relational operators. So I would simply hard-code them into the function.
Example:
void conditionalJump(int var, std::string op, int immediate, int destination)
{
   if      ((op == "==") && (var == immediate))  cur_line = destination;
   else if ((op == "!=") && (var != immediate))  cur_line = destination;
   else if ((op == "<")  && (var < immediate))   cur_line = destination;
   else if ((op == ">")  && (var > immediate))   cur_line = destination;
   else if ((op == "<=") && (var <= immediate))  cur_line = destination;
   else if ((op == ">=") && (var >= immediate))  cur_line = destination;
}

If this wasn't what you were looking for, then my guess is that you might wanna checkout the following links:

C++ relational operators generator
Using character as relational operator in C/C++

Convert string to operator


Converting Date string to DateTime Format vb.net

Question: I have this example and it gives me exception "Conversion from string x to dateTime is invalid"
here is my method to validate Datetime.
Example Date string : "27/03/1985"
Public Function validateDateColumn(ByRef FieldName As String) As Boolean

    Try
        If IsDate(FieldName) Then
            Dim actualDate As DateTime = CDate(FieldName)
            Dim DtLicExp As DateTime = CDate(actualDate.ToString("d", Thread.CurrentThread.CurrentCulture))
            FieldName = DtLicExp.ToString("MM/dd/yyyy")
            Return True
        End If
    Catch ex As Exception
        'FieldName &= "Format must be MM/dd/yyyy"
        Return False
    End Try

End Function

any idea to validate this date string formate to datetime.
I want to convert this date "27/03/1985" to datetime.
I'm using asp.net with vb.net.
Comment: Why don't you use DateTime.TryParse : http://msdn.microsoft.com/en-us/library/9h21f14e.aspx
Comment: I wannt to convert Date like that "27/03/1985" starts with days to datetime.
Answer: Have a look at using DateTime.TryParseExact Method or DateTime.ParseExact Method
Answer: This implementation will parse dates of the format dd/MM/yyyy and update the date string to the MM/dd/yyyy as you require. DateTime.TryParseExact allows you to specify the format of the date that you need to parse.
Public Function validateDateColumn(ByRef FieldName As String) As Boolean

  validateDateColumn = False

  Dim dateValue As DateTime

  if DateTime.TryParseExact(FieldName, _
      "dd/MM/yyyy", CultureInfo.InvariantCulture, _
      DateTimeStyles.None, dateValue) Then

      validateDateColumn = True
      FieldName = dateValue.ToString("MM/dd/yyyy")
  End If

End Function

Answer: You could try the TryParse method.
Dim myDateString as String = "7/7/2010"
Dim myDate as DateTime
Dim isDate As Boolean = DateTime.TryParse(myDateString, myDate)

If isDate Then
    ' Yay I'm a real date
End If


Paying back problem with ODE. What I've done wrong?

Question:
Someone wishes to borrow \$200,000 at an interest rate of 6%. Assume that interest is compounded continuously and that payments are also made continuously. Determine the monthly payment that is required to pay off the loan in 20 years.

This is problem. and the following is my approch.
let $S(t)$ be a function that I have to pay at $t$. and let $S(0)=200,000=b$
$r=0.06$ , $p=$annual payment, $q=$monthly payment
$S'=-$(pay off)$+($interest$)$ thus $$S'=-p+rS....(*)$$ $$S'=-q+rS....(**)$$
every part is same except unit. in$(*)$, we use 'year' for unit of $t$, and 'month' for $t$ in $(**)$
solving both equation with initial value, $$S=\frac p r (1-e^{rt})+be^{rt}$$ $$S=\frac q r (1-e^{rt})+be^{rt}$$
suppose I've paid all the money exactly after 20 years. then we have $$0=\frac p r (1-e^{20r})+be^{20r}$$ $$0=\frac q r (1-e^{240r})+be^{240r}$$
simplifying in respect for p and q,
$$p=\frac{rb}{1-e^{-20r}} ≒ 17172$$ $$q=\frac{rb}{1-e^{-240r}}≒12000$$
however, $$\frac p {12} = \frac{17172}{12} ≒ 1431.01≠12000=q$$
moreover, my text book says that \$$1431.01$ per month is the right answer. this really confuses me. because my first answer was \$$12,000$ per month.
what I've done wrong? maybe $e^{-240r}$ is too small? but that's not a good reason for almost 1000% error.
Answer: You have to use $r'=\frac{r}{12}$ for the monthly interest rate. So:
$$q=\frac{r'b}{1-e^{-240r'}}=\frac{\frac{rb}{12}}{1-e^{\frac{-240r}{12}}}=1431,01=\frac{p}{12}$$


Using MFC and ATL libraries without Visual Studio

Question: My question is if I can use MFC and ATL libraries that come with PSDK Windows Server 2003 R2, without Visual Studio. I mean only at the command prompt with BCC32.exe or CL.exe?
I have found MFC and ATL libraries in the PSDK Windows Server 2003 R2 but I does not know if these libraries can be used without Visual Stuio IDE! What I need to do before using MFC and ATL at the command prompt?
Thanks!
Answer: If you have all the headers, and either the source code or compiled version of the rest, then yes it can be used without Visual Studio. Visual Studio is just an IDE that invokes the compiler etc. for you. With command line tools you do that job yourself.
Here's a minimal MFC program that you can try out:
<code>#define WINVER  0x0500      // Windows 2000 and up.
#include <afxwin.h>         // MFC core and standard components

typedef CFrameWnd   MainWindow;

class App
    : public CWinApp
{
private:
    bool createTheMainWindow()
    {
        static char const title[]   = "A general top level MFC window";
        MainWindow* const pWnd      =
            new MainWindow;
        if( !pWnd ) { return false; }   // Pre-standard 'new' in MFC...
        m_pMainWnd = pWnd;
        pWnd->Create( NULL, title );
        return true;
    }

public:
    virtual BOOL InitInstance()
    {
        CWinApp::InitInstance();

        if( !createTheMainWindow() ) { return false; }

        m_pMainWnd->ShowWindow( SW_SHOW );
        m_pMainWnd->UpdateWindow();
        return true;
    }
};

App theApp;
</code>
Cheers & hth.,
Comment: @Shahid: apparently an installation of Visual Studio Express creates a directory with some MFC headers, but lacking much including the file that you mention, as reported [over at Microsoft](http://social.msdn.microsoft.com/forums/en/vcgeneral/thread/118ca5b7-c96d-4eed-bd94-d6ac42ad0186/). Possibly it's the same with PSDK Windows Server 2003 R2. In a way it's understandable, since Microsoft wants to keep moving on to new "technologies" all the time and selling the tools for that...
Comment: Thanks Sir Alf P. Steinbach. Now it is clear to me that MFC and ATL include files and lib files can be used without Visual Studio IDE. Thanks for your great help!
Comment: One thing that I specifically want to ask that is there a good book about on MFC or ATL in which, specifically examples are compiled with bcc32.exe or cl.exe! Please suggest me if you have some knowledge about it.
Comment: The above example compiles and works fine with recent versions of Visual C++ (the [cl.exe] compiler). I'm not sure, but I *suspect* that the only generally available version of [bcc32.exe], the Borland compiler, is like 5.0 or something from the mid 1990's. If so then that compiler is probably unable to deal with recent MFC.
Comment: Ok I tried to compile your example with cl.exe. There is only error message comes out that "afxmsg_.h" include file could not be opened! Could you please suggest me where can I find "afxmsg_.h" file?
Answer: No you can't, since some functionality relies on the Visual Studio compiler specific behavior. For example the way trampolines are used to map window handles to objects.
I'm assuming that you by "can be used without Visual Stuio IDE" you actually mean "with another compiler", since you mention the Borland compiler. Of course you can write C++ in a text editor and compile those files from the command line, not using the IDE, but what you want is using another compiler, right? (the IDE and the compiler are related but not the same).


How to delete from mysql using bootstrap modal?

Question: I want to delete accounts according to the selection of a drop down list.
This is my markup for the form -
<form action="" method="post">
    <select class="form-control" size="8" id="userName" name="userName">
        <option value="9" data-userId="uid9">dilani</option>
        <option value="6" data-userId="uid6">kamala</option>
        <option value="12" data-userId="uid12">senudhi</option>
        <option value="2" data-userId="uid2">testuser</option>
        <option value="4" data-userId="uid4">tharanga</option>
    </select>

    <button type="submit" class="btn btn-primary" >Terminate</button>

</form>

In PHP, I am checking an user is submitting the form and have selected an username from dropdown before delete the account.
My PHP code is something like this -
// Check for a form submission:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Check for username is selected from dropdown list:
    if (isset($_POST['userName'])) {
        $userid = $_POST['userName'];

        //echo $userid;
        // my delete query ---

    } else {
        $error_msg .= ' You didn\' select either username or domain name to Terminate.';
    }
}

My problem is, If the form have submitted successfully then I need to display a conformation dialog box before to delete the account.
I tried it javascript onsubmit but its not working for me. As soon as I click on Terminate button the confirmation is display ignoring the selection of dropdown. That mean I don't need to select an item from username list to get this work.
This is how I checked it -
<form action="" method="post" onSubmit="return confirm('are you sure?')">

Can anybody guide me to do this using Bootstrap modal?
Thank You.
Comment: if that submit going through ajax, then you can use the beforeSend function, so in that you can call the bootstrap modal
Comment: @amtest, Since I am not good in javascript or jquery, Can you explain it with an example?
Answer: Capture the form on submit, toss out a confirm box. Return true if they click Yes, return false if they click No.
$('form').on('submit', function(){
    e.preventDefault();
    if(confirm('Are you sure you wish to delete this user?')){
        return true;
    } else{
        return false;
    }
});

Comment: Ohgodwhy, I tried it with your code. But I can not get a confire box
Answer: Either you can submit via ajax, or if you need to just confirm that you can use something like
<form id="target" action="destination.html">
  <input id="btn" type="button" value="Go"/>
</form>

$(function() {
  $("#btn").click(function(){
    if (confirm("Click OK to continue?")){
      $('form#target').submit();
    } else {
      //return false;
    }
  });
});

Comment: yes, if its true then you call the bootstrap modal, like
  $('#dialog').modal('show'); , if you get more about that modal, read this http://getbootstrap.com/2.3.2/javascript.html#modals
Comment: amtest, Can we use bootstrap modal regarding this?