text:
Q: How to call C# from C to pass array of structs having arrays as members? I have a native struct:
typedef struct
{
    char Message[STR_MAX];
    char Params[10][STR_MAX];
    int GetParamStr[10];
    int ParamCount;
} FormattedMessage_t;

and callback type:
typedef void(*FormatMsgCB_t)(FormattedMessage_t *FormatMsgs, int FormatMsgCount);

static array:
static FormattedMessage_t gFormattedMessages[10];

callback set function:
extern "C" __declspec(dllexport) void DllGuiSetFormatMsgCB(FormatMsgCB_t pCB)
{
    gFormatMsgCB = pCB;
}

call from native to managed:
void DllGuiSetFormatMessage()
{
    gFormatMsgCB(gFormattedMessages, gFormattedMsgIndex);
}

In Managed:
    [StructLayout(LayoutKind.Sequential)]
    public struct FormattedMessage_t
    {
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = MaxStrLength)]
        public string Message;

        public string[] ParamStrings;
        public int[] GetParamStrs;
        public int ParamCount;

        public const int MaxStrLength = StrMax;
    }

    public static T[] GetArray<T>(IntPtr aTblPtr, int nRows)
    {
        var entrySize = Marshal.SizeOf(typeof(T));
        IntPtr oneRowPtr = new IntPtr(aTblPtr.ToInt64());
        T[] array = new T[nRows];

        for (int i = 0; i < nRows; i++)
        {
            array[i] = (T)Marshal.PtrToStructure(oneRowPtr, typeof(T));
            oneRowPtr = new IntPtr(oneRowPtr.ToInt64() + entrySize);
        }

        return array;
    }

    private void OnSetFormatMsg(IntPtr formatMsg, int nFormatMsg)
    {
        var array = GetArray<FormattedMessage_t>(formatMsg, nFormatMsg);
        foreach (var msg in array)
        {
            var str = msg.Message;
            // and so on
        }
    }

This GetArray works for simple types as struct members. This is way beyond my P/Invoke and Native Interop skills.
This is probably wrong in many ways. Any hints how this should be done (changing both structs is no problem) would be highly appreciated.

A: You'll need to declare the C# struct like so:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct FormattedMessage_t
{
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = MaxStrLength)]
    public string Message;

    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10*MaxStrLength)]
    public byte[] ParamStrings;

    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
    public int[] GetParamStrs;

    public int ParamCount;

    public const int MaxStrLength = StrMax;
}

Then you'll need to pick out each item from ParamStrings by performing the indexing manually. The ith value runs from indices i*MaxStrLength to (i+1)*MaxStrLength-1. You'll need to pick that out, find the null terminator, and use Encoding.Default.GetString.


text:
Q: Deriving diagonal approximation of Hessian in a neural network Consider the equations relating to the diagonal approximation for the hessian matrix for a neural network in "Pattern Recognition and Machine Learning - Christopher Bishop" (on pg. 250 eq. 5.80)

*

*$\frac{\partial^2 E_{n}}{\partial w_{ji}^2} = \frac{\partial^2 E_{n}}{\partial a_{j}^2} z_{i}^2$

*$\frac{\partial^2 E_{n}}{\partial a_{j}^2} = ({h}'(a_{j}))^2 \sum_{k} \sum_{k'} w_{k'j}w_{kj}\frac{\partial^2 E_{n}}{\partial a_{k} \partial a_{k'}} + h''(a_{j})\sum_{k}w_{kj}\frac{\partial E_{n}}{\partial a_{k}}$
$a_{j}$ - input to a unit j
$h$ - activation function
$z_i = h(a_i)$ i.e output of a unit i
$w_{kj}$ - edge from j to k
I am interested in how eq. 2 follows from:
$\frac{\partial E_{n}}{\partial a_{j}} = h'(j)\sum_{k} w_{kj}\frac{\partial E_{n}}{\partial a_{k}}$
where k runs through all the units to which unit j directly sends a connection to (eq 5.56, pg 244).
In particular, I am getting a different result for the first term on the RHS of eq. 2, i.e

*$({h}'(a_{j}))^2 \sum_{k} \sum_{k'} w_{k'j}w_{kj}\frac{\partial^2 E_{n}}{\partial a_{k} \partial a_{k'}}$

So, eq. 3 should follow from:

*$h'(j)\frac{\partial }{\partial a_{j}}\sum_{k} w_{kj}\frac{\partial E_{n}}{\partial a_{k}}$

Following is the way how I tried to derive eq. 3 from eq. 4 using the chain rule of differentiation:
$h'(a_{j})\frac{\partial }{\partial a_{j}}\sum_{k} w_{kj}\frac{\partial E_{n}}{\partial a_{k}}$
$= h'(a_{j})\sum_{k}\frac{\partial a_{k}}{\partial a_{j}} \frac{\partial }{\partial a_{k}}w_{kj}\frac{\partial E_{n}}{\partial a_{k}}$
$=h'(a_{j})\sum_{k}h'(a_{j})w_{kj}\frac{\partial }{\partial a_{k}}w_{kj}\frac{\partial E_{n}}{\partial a_{k}}$
Used:
$(a_k = \sum_jh(a_j)w_{kj}) \wedge (\frac{\partial w_{kj}}{\partial a_j} = 0 )\rightarrow \frac{\partial a_{k}}{\partial a_j} = h'(j)w_{kj}$
So what remains to be shown is:

*$\sum_{k}w_{kj}\frac{\partial }{\partial a_{k}}w_{kj}\frac{\partial E_{n}}{\partial a_{k}} = \sum_{k} \sum_{k'} w_{k'j}w_{kj}\frac{\partial^2 E_{n}}{\partial a_{k} \partial a_{k'}}$

which should complete the proof.

QUESTION 1
How to establish eq. 5 ?
One may want to use:
$\frac{\partial a_k} {\partial w_{kj}} = z_j$

QUESTION 2
If
$y = f(x_1, x_2,...)$
then, is it always true that
$\frac{\partial y} {\partial x_k} = 1 / \frac{\partial x_k} {\partial y}$

redpajama_set_name: RedPajamaStackExchange


text:
Q: In a Flask application that is using SQLAlchemy, is it ok to permanently put `session.rollback` at the beginning of the app? I'm new to Flask and web development in general. I have a Flask web-application that is using SQLAlchemy, is it ok to put session.rollback at the beginning of the app in order to keep it running even after a transaction fails?
I had a problem with my website when it stopped working after I was attempting to delete records of one table. The error log showed that the deletion failed due to entries in another table still referencing these records as their foreign key. The error log suggested using session.rollback to rollback this change, so I put it at the beginning of my app just after binding my database and creating the session and my website worked. This gave me the hint to leave that line there. Is my move right, safe and ok? Can anyone tell me what is the correct thing to do if this is somewhat endangering the functionality or logic of my website by any chance?

A: You should not use the rollback at the beginning but when a database operation fails.
The error is due to an integrity condition in your database. Some rows in your table are being referenced by another table. So, you have to remove referencing rows first.

A: I'd say by that you are by definition cargo cult coding and should try to determine why you're finding these errors in the first place instead of just including a bit of code for a reason you don't understand.
The problem you're describing is the result of using foreign keys to ensure data integrity in your database. Typically SQLAlchemy will nullify all of the depending foreign keys, but since I don't know anything about your set up I can't explain why it wasn't. It is perhaps a difference between databases.
One massive problem with putting the rollback at the beginning of a route (or the entire global app) is that you might rollback data which you didn't want to. You haven't provided an MVCE so no one can really help you debug your problem.
Cargo cult coding in circumstances like this is understandable, but it's never a good practice. To solve this problem, investigate the cascades in SQLAlchemy. Also, fire up your actual SQL db interface and look at the data's structure, and set SQLALCHEMY_ECHO = 1 in your config file to see what's actually getting emitted.
Good luck!


text:
Q: Redirect to a subdirectory using htaccess I am using ProXCore in my website http://www.enkaizen.es/. I am trying to install wordpress on a subdirectory called "/soporte/"
The script came out of the box with an .htaccess like this:
<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteRule    ^$ app/webroot/    [L]
    RewriteRule    (.*) app/webroot/$1 [L]
</IfModule>

It does not allow to visit http://www.enkaizen.es/soporte/, it stays on the home page.
I added a rewrite line to the top so now the .htaccess file is like this:
<IfModule mod_rewrite.c>
   RewriteEngine on
   RewriteRule    ^soporte/?$    soporte/   [L]
   RewriteRule    ^$ app/webroot/    [L]
   RewriteRule    (.*) app/webroot/$1 [L]
</IfModule>

But it is not working. If I take out the second and third rewrite lines it does work, meaning I can visit http://www.enkaizen.es/soporte/, but then the script itself, ProXCore script, does not work at all, and I really need to have a wordpress installation on the "/soporte/" directory.
Any ideas? Please help!

A: For if someone facing this issue, I accomplished it by adding this rewrite line:
RewriteRule ^soporte/ - [L]

So the final htaccess file now is:
<IfModule mod_rewrite.c>
   RewriteRule ^soporte/ - [L]
   RewriteRule    ^$ app/webroot/    [L]
   RewriteRule    (.*) app/webroot/$1 [L]
</IfModule>

Now it is working like a charm :D


text:
Q: Pandas create column that shows absolute max value of the row, but keeps negatives I have a df that looks like this:
         a      b      c
124    -3.09  -0.38   2.34
2359    4.81   0.51  -1.53
56555  -4.34  -0.64   2.31
96786  -3.33  -3.34  -7.62

I want to calculate the absolute max value of each row in a new column that keeps negatives as negatives. The closest I've gotten is with the following:
df['new_column'] = df.abs().max(axis = 1)

new_column
3.09
4.81
4.34
7.62

But I need the new column to keep the negative signs—i.e. to look like this:
new_column
-3.09
 4.81
-4.34
-7.62

I've attempted a few things using abs().idxmax(), and am wondering if I need to find the location of the absolute max value, and then return the value in that location in the new column—just not sure how to do this. Thoughts?

A: Here's one way using two steps: First, find the absolute max. Then see if absolute max equals any values in the DataFrame using eq and use the output as the power of -1 to get the signs:
row_max = df.abs().max(axis=1)
df['new_column'] = row_max * (-1) ** df.ne(row_max, axis=0).all(axis=1)

Another option is to use mask to choose values:
df['columns'] = df.max(axis=1).mask(lambda x: x < row_max, -row_max)

Output:
          a     b     c  new_column
124   -3.09 -0.38  2.34       -3.09
2359   4.81  0.51 -1.53        4.81
56555 -4.34 -0.64  2.31       -4.34
96786 -3.33 -3.34 -7.62       -7.62

A: I like the original idea you thought of, keeping with the theme:
# setup

data = {'a': [-3.09, 4.81, -4.34, -3.33],
        'b': [-.38, .51, -.64, -3.34],
        'c': [2.34, -1.53, 2.31, -7.62]}

df = pd.DataFrame(data, index= [124, 2359,56555,96786])

instead of:
df['new_column'] = df.abs().max(axis = 1)

let's change it to return the column instead of actual value:
max_col = df.abs().idxmax(axis = 1)

from there we can just iterate over it with enumerate for the row number and set it as the new column:
df['new_column'] = [df.loc[row,col] for row, col in zip(df.index, max_col)]

results:
          a     b     c  new_column
124   -3.09 -0.38  2.34       -3.09
2359   4.81  0.51 -1.53        4.81
56555 -4.34 -0.64  2.31       -4.34
96786 -3.33 -3.34 -7.62       -7.62


text:
Q: plotnine, keep same position of geom_bar(position='dodge') when value is missing This minimal code
import pandas as pd
import plotnine as p9

df = pd.DataFrame({
    'variable': ['a', 'b', 'b'],
    'value': [1, 1, 1],
    'name': ['one', 'one', 'two']
})
(
    p9.ggplot(df, p9.aes(x='name', y='value', fill='variable'))
    + p9.geom_bar(stat='identity', position=p9.position_dodge(preserve='single'))
)

produces the following incorrect bar plot, due to a missing value.

How can I get the bar for name two and variable b to be at the correct position (at right of the two x-axis tick)?

A: Plotnine does not preserve any spaces for empty categories of a bar plot. But, you can get better positioning with position_dodge2(preserve='single') which gives centered the bars for every x position.


text:
Q: Postgres Unique JSON Array Aggregate Values I have a table that stores values like this:
| id | thing | values |
|----|-------|--------|
| 1  | a     |[1, 2]  |
| 2  | b     |[2, 3]  |
| 3  | a     |[2, 3]  |

And would like to use an aggregate function to group by thing but store only the unique values of the array such that the result would be:
| thing | values  |
|-------|---------|
| a     |[1, 2, 3]|
| b     |[2, 3]   |

Is there a simple and performant way of doing this in Postgres?

A: First you take the JSON array apart with json_array_elements() - this is a set-returning function with a JOIN LATERAL you get a row with id, thing and a JSON array element for each element.
Then you select DISTINCT records for thing and value, ordered by value.
Finally you aggregate records back together with json_agg().
In SQL that looks like:
SELECT thing, json_agg(value) AS values
FROM (
    SELECT DISTINCT thing, value
    FROM t
    JOIN LATERAL json_array_elements(t.values) AS v(value) ON true
    ORDER BY value) x
GROUP BY thing

In general you would want to use the jsonb type as that is more efficient than json. Then you'd have to use the corresponding jsonb_...() functions.


text:
Q: Css centering weird behavior I am trying to center form on the screen. I am using absolute element with left and top set on 50% and move it back to center by css transform. So far so good, but when I increase left to 90% form elements go under. I would expect that they just move outside of view port.
.center {
  padding: 30px;
  position: absolute;
  top: 50%;
  left: 90%;
  -webkit-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}

Here is the effect I don't understand
If someone can explain me why those element go under each other? Even if they are inside absolute element.
To add more wierdness, if the 'left' value will be negative, elements just go out side view port?
I know that
white-space:nowrap;

will do the trick, but WHY?
Thanks in advance

A: As pointed out in the comments, this behavior is related to inline-block level elements, but it also has to do with your position: absolute; rule, regarding your specific situation.
As you can see in the demo when inline-block level elements start reaching the outside boundaries of the viewport, the will wrap or collapse; this has to do with the nature of the display property.
There are a few ways to combat this:

*

*As you mentioned white-space: nowrap is one

*As Gaby alluded to in his comment, giving the element a width value will correct this as well - DEMO

*Changing your position to relative will also fix this - DEMO
The actual reason you are experiencing this issue is because your .center element which does have display: block, is losing it's inherit width: 100% because it has position: absolute; or alternatively put, losing it's status as a block level element.


text:
Q: How to use apache ..htaccess in lightspeed web server I did some .htaccess code to make PHP API route.
It's working in apache ( local server )
Options -MultiViews
RewriteEngine On

#What does this mean??
RewriteRule ^(.+)$ quizAPI.php?url=$1 [QSA,L]

But when I moved mine code to server it's not working because it not an apache.
I am trying to make API URL Like this :
example.com/users/get/

A:
#What does this mean??
RewriteRule ^(.+)$ quizAPI.php?url=$1 [QSA,L]

Not quite sure of the difference between Apache and LiteSpeed in this respect (perhaps a difference in how the request is mapped to the filesystem?), however, this is only working on Apache arguably by "chance". The reason being, when you request /users/get/ the above rewrites as follows:

*

*Request /user/get/

*Rewrite (1st pass) to quizAPI.php?url=user/get/

*Rewrite process then starts over (due to the L flag)

*Rewrite (2nd pass) to quizAPI.php?url=quizAPI.php&url=user/get/ (due to the QSA flag)

*Rewrite process then starts over (due to the L flag)

*Rewrite (3rd pass) to quizAPI.php?url=quizAPI.php&url=user/get/ (again)

*Rewriting process stops since the URL has passed through unchanged.

This still "works" (on Apache) since the url parameter (as read by your PHP script) is still user/get/ (the 2nd instance of the url param overwrites the first in the $_GET array). And there is no rewrite-loop. LiteSpeed, however, might be triggering another pass by the rewrite engine (causing a "loop").
However, we need to prevent that second pass by the rewrite engine (on Apache as well) and I would expect this would resolve the issue on LiteSpeed as well.
One way is to prevent the rewrite from occurring when quizAPI.php is requested. For example:
RewriteCond %{REQUEST_URI} !^/quizAPI\.php$
RewriteRule (.+) quizAPI.php?url=$1 [QSA,L]

However, this still rewrites all static assets (CSS, JS, images, etc.) to your script (which I'm assuming must "OK", since it "works" on Apache), but this might need further modification in the future.
Alternatively, if your URLs that you pass to quizAPI.php don't contain dots (that otherwise delimit file-extensions) then it would be simpler to only match URLs that don't contain dots instead (which avoids the need for the preceding condition). For example:
RewriteRule ^([^.]+)$ quizAPI.php?url=$1 [QSA,L]

And this naturally avoids rewriting requests for your static assets as well.


text:
Q: Role of CMD["bash"] in Dockerfile This is the Dockerfile of Docker Ubuntu official image:
FROM scratch
ADD ubuntu-focal-oci-amd64-root.tar.gz /
CMD ["bash"]

Can you please help me clarifying the following:

*

*What exactly CMD["bash"] does? I can see no difference by removing it (e.g. by adding in my local Dockerfile: CMD["echo", "hello"]) when starting a container.

*The equivalent shell form is CMD bash or CMD exec bash?

*If removing that completely, what is the equivalent docker exec command line?

I cannot find any reliable answer despite my thorough search...

A:

*When you create an image FROM scratch, among other things, it has an empty default command, as if you had written
ENTRYPOINT []
CMD []

*So CMD there gives some default command if you docker run ubuntu.  Most images will in fact override that CMD with something to run the program built into the derived image.

*Since that CMD uses JSON-array syntax, there isn't directly a shell-syntax equivalent of it.  The shell syntax automatically inserts a sh -c wrapper around whatever command you give it, so these two would be equivalent
CMD bash
CMD ["/bin/sh", "-c", "bash"]

*There would not be an equivalent docker exec command.  docker exec is a debugging command that's not normally part of the "build and run an image" workflow.  In particular, it does not use the ENTRYPOINT or CMD from the image at all.


text:
Q: Microsoft Graph API - @odata.count value for List messages API is not accurate and consistent I have observed an inconsistent behavior for the @odata.count property returned in response of Microsoft Graph API for Mail. I'm using the API in the following form to get the count of emails in a particular folder of a certain user within a specific time-range:
https://graph.microsoft.com/v1.0/users/<UserId>/mailFolders/<folderId>/messages/?$count=true&$filter=receivedDateTime ge 2020-01-01T00:00:00Z and receivedDateTime le 2021-02-22T23:59:59Z &$select=body, subject, receivedDateTime, sender, attachments

The response of this API is as follows:
{
"@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users('d03264a3-a4c2-4e09-a36b-72769b60c8f3')/mailFolders('AQMkADQwN2JjMTJmLTMyYjEtNDQANjQtYTZjMy1mMzgwZjZkZTc5YWUALgAAAyl9OhZlJyVNuZa50-mFdBYBACL9iHsHcJ1JjFSj-hiqIEkAAAIBEwAAAA%3D%3D')/messages(body,subject,receivedDateTime,sender,attachments)",
"@odata.count": 61,
"value": [
    {
        "@odata.etag": "W/\"CQAAABYAAAAi/Yh7B3CdSYxUo/4YqiBJAAAFmeaB\"",
        "id": "AAMkADQwN2JjMTJmLTMyYjEtNDQ2NC1hNmMzLWYzODBmNmRlNzlhZQBGAAAAAAApfToWZSclTbmWudP5hXQWBwAi-Yh7B3CdSYxUo-4YqiBJAAAAAAETAAAi-Yh7B3CdSYxUo-4YqiBJAAACqqzqAAA=",
        "receivedDateTime": "2021-02-10T15:16:04Z",
        "subject": null,
        "body": {
            "contentType": "html",
            "content": ""
        },
        "sender": {
            "emailAddress": {
                "name": "Sender"
            }
        }
    },
   .
   .
   .
   {
   }
]
"@odata.nextLink": "https://graph.microsoft.com/v1.0/users/<userId>/mailFolders('<folderId>')/messages?%24count=true&%24filter=receivedDateTime+ge+2020-01-01T00%3a00%3a00Z+and+receivedDateTime+le+2021-02-22T23%3a59%3a59Z+&%24select=body%2c+subject%2c+receivedDateTime%2c+sender%2c+attachments&%24top=10&%24skip=10"
}

Now from my experience, what I've found is that when I move an email in and out of a specific folder, the @odata.count value is not updated right away and takes some variable amount of time to get updated. This might be a expected behavior but I want to be sure about the reason.
But what's strange is that sometimes the @odata.count value is -1. Does this mean anything or there is a bug in the API?
I would like to know the exact reasons of the above two mentioned behaviors as we are using this API in a production integration app and this inconsistency is causing issues. I would be highly thankful if someone officially associated with Microsoft can explain these issues.
Thanks!


text:
Q: Do compilers take the "status quo" when optimizations produced worse results? To my knowledge, when using optimizations there is a risk to face the "maybe will be worse" case (i.e. the performance will be degraded, or the code size will be higher, or both). However do compilers able to detect such cases and return to the "status quo" (i.e. fall back to the original non-optimized code) when optimizations produced worse results? Can someone give (if possible) a particular examples of what compilers (for example, gcc, Clang (LLVM), etc.) do in this case?

A: In JIT compilers there is a thing called Deoptimization. Normally the compiler will optimize heavily assuming something, but during execution some of the assumption may fail. For example the compiler will assume the inmput of a function is always an integer and produce a highly efficient code for integer manipulation, but if, and such things happen in dynamic languages, the input is suddenly and array or a string, the code should revert. See v8 turbofan speculative optimizator for example.
For non JIT there is no way to deoptimize during runtime, but the compiler may create multiple execution paths. Your question is not fully logical because how would compiler know if it created unoptimal code? It can only use the same algorithm it used to do the optimization itself. That's probably why you are downwoted.


text:
Q: Warning: push.default is unset; its implicit value is changing in Git 2.0 I've been using Git for a while now and have recently downloaded an update only to find this warning message come up when I try to push.
warning: push.default is unset; its implicit value is changing in
Git 2.0 from 'matching' to 'simple'. To squelch this message
and maintain the current behavior after the default changes, use:

  git config --global push.default matching

To squelch this message and adopt the new behavior now, use:

  git config --global push.default simple

I can obviously set it to one of the values mentioned, but what do they mean? What's the difference between simple and matching?
If I change it on one client will I need to do anything on other clients that I share repos with?

A: If you get a message from git complaining about the value 'simple' in the configuration, check your git version.
After upgrading Xcode (on a Mac running Mountain Lion), which also upgraded git from 1.7.4.4 to 1.8.3.4, shells started before the upgrade were still running git 1.7.4.4 and complained about the value 'simple' for push.default in the global config.
The solution was to close the shells running the old version of git and use the new version.

A: It's explained in great detail in the docs, but I'll try to summarize:

*

*matching means git push will push all your local branches to the ones with the same name on the remote. This makes it easy to accidentally push a branch you didn't intend to.

*simple means git push will push only the current branch to the one that git pull would pull from, and also checks that their names match. This is a more intuitive behavior, which is why the default is getting changed to this.
This setting only affects the behavior of your local client, and can be overridden by explicitly specifying which branches you want to push on the command line. Other clients can have different settings, it only affects what happens when you don't specify which branches you want to push.

A: I was wondering why I was getting that big warning message on Ubuntu 16.04 (which comes with Git 2.7.4), but not on Arch Linux. The reason is that the warning was removed in Git 2.8 (March 2016):

Across the transition at around Git version 2.0, the user used to
  get a pretty loud warning when running "git push" without setting
  push.default configuration variable.  We no longer warn because the
  transition was completed a long time ago.

So you won't see the warning if you have Git 2.8 and later and don't need to set push.default unless you want to change the default 'simple' behavior.

A: I realize this is an old post but as I just ran into the same issue and had trouble finding the answer I thought I'd add a bit.
So @hammar's answer is correct. Using push.default simple is, in a way, like configuring tracking on your branches so you don't need to specify remotes and branches when pushing and pulling. The matching option will push all branches to their corresponding counterparts on the default remote (which is the first one that was set up unless you've configured your repo otherwise).
One thing I hope others find useful in the future is that I was running Git 1.8 on OS X Mountain Lion and never saw this error. Upgrading to Mavericks is what suddenly made it show up (running git --version will show git version 1.8.3.4 (Apple Git-47) which I'd never seen until the update to the OS.

A: Brought my answer over from other thread that may close as a duplicate...
From GIT documentation: Git Docs
Below gives the full information. In short, simple will only push the current working branch and even then only if it also has the same name on the remote. This is a very good setting for beginners and will become the default in GIT 2.0
Whereas matching will push all branches locally that have the same name on the remote. (Without regard to your current working branch ).  This means potentially many different branches will be pushed, including those that you might not even want to share.
In my personal usage, I generally use a different option: current which pushes the current working branch, (because I always branch for any changes).  But for a beginner I'd suggest simple

push.default
Defines the action git push should take if no refspec is
explicitly given. Different values are well-suited for specific
workflows; for instance, in a purely central workflow (i.e. the fetch
source is equal to the push destination), upstream is probably what
you want. Possible values are:
nothing - do not push anything (error out) unless a refspec is
explicitly given. This is primarily meant for people who want to avoid
mistakes by always being explicit.
current - push the current branch to update a branch with the same
name on the receiving end. Works in both central and non-central
workflows.
upstream - push the current branch back to the branch whose changes
are usually integrated into the current branch (which is called
@{upstream}). This mode only makes sense if you are pushing to the
same repository you would normally pull from (i.e. central workflow).
simple - in centralized workflow, work like upstream with an added
safety to refuse to push if the upstream branch's name is different
from the local one.
When pushing to a remote that is different from the remote you
normally pull from, work as current. This is the safest option and is
suited for beginners.
This mode will become the default in Git 2.0.
matching - push all branches having the same name on both ends. This
makes the repository you are pushing to remember the set of branches
that will be pushed out (e.g. if you always push maint and master
there and no other branches, the repository you push to will have
these two branches, and your local maint and master will be pushed
there).
To use this mode effectively, you have to make sure all the branches
you would push out are ready to be pushed out before running git push,
as the whole point of this mode is to allow you to push all of the
branches in one go. If you usually finish work on only one branch and
push out the result, while other branches are unfinished, this mode is
not for you. Also this mode is not suitable for pushing into a shared
central repository, as other people may add new branches there, or
update the tip of existing branches outside your control.
This is currently the default, but Git 2.0 will change the default to
simple.


text:
Q: converting CBV to FBV I am trying to change all my Function Based View to Class based view, i've been fairly successful except for this view, it's a detail view that contains paystack payment gateway. Any help will be hugely appreciated.
def car_rent_detail_view(request, pk):
    object = get_object_or_404(CarRent, id=pk)

    paystack = PaystackAccount(
        settings.PAYSTACK_EMAIL,
        settings.PAYSTACK_PUBLIC_KEY,
        object.total_cost
    )

    context = {'object': object, 'pk_public': settings.PAYSTACK_PUBLIC_KEY, 'currency': 'NGN', 'paystack': paystack,
               }
    if request.method == 'POST':
        if paystack.verify_transaction(request.POST['reference']):
            messages.success(request, "payment successfull")
            …
            car_rented.save()
            …
            rent_activation.save()
            messages.success(request, "Rent successfully updated")

    return render(request, 'app/CarRent_detail.html', context=context)

I will like to convert the CBV below to FBV so i can add payment functionality to it.
class ContestantDetail(DetailView, FormMixin):
    model = Contestant
    context_object_name = 'contestants'
    template_name = 'contest/contestant_detail.html'
    form_class = VoteForm

    def get_success_url(self):
        return reverse('contest:contestant-detail', kwargs={'pk': self.object.pk})

    def get_context_data(self, *args, **kwargs):
        context = super(ContestantDetail, self).get_context_data(*args, **kwargs)
        context['vote_contestant'] = Contestant.objects.get(pk=self.kwargs.get('pk'))
        return context

    def post(self, request, *args, **kwargs):
        form = self.get_form()
        self.object = self.get_object()

        if form.is_valid():
            return self.form_valid(form)
        else:
            return self.form_invalid(form)

    def form_valid(self, form, *args, **kwargs):
        contestant = Contestant.objects.get(pk=self.kwargs['pk'])
        ...
        contestant.save()

        messages.success(self.request, f'You have successfully casted {vote_count} vote.')
        return super().form_valid(form)

A: The Class based View above can be converted to a Function based view as demonstrated below.
def contestant_detail_view(request, pk):
    get_object_or_404(Contestant, pk=pk)
    form = VoteForm()

    context = {'contestants': get_object_or_404(Contestant, pk=pk),
               'vote_contestant': Contestant.objects.get(pk=pk),
               'form': form}

    if request.method == 'POST':
        form = VoteForm(request.POST)
        if form.is_valid():
            con = Contestant.objects.get(pk=pk)
            ...
            con.save()

    else:
        form = VoteForm()

    return render(request, 'contest/contestant_detail.html', context)


text:
Q: Get or set css class value from external SVG file using javascript(jquery) I have a svg file that contains some css classes in this format
  <style type="text/css" id="style1">
    <![CDATA[
      .fill1 {fill:#D2D3D5}
      .fill2 {fill:#A9ABAE}
      .fill3 {fill:#96989A}
    ]]>
  </style>

The svg file is displayed in an HTML file by using the following tag.
<object id="testObject" type="image/svg+xml" data="img/test.svg"></object>

Is there some way for me to get fill value of fill1,fill2 and fill3 using javascript or jquery. Also would it be possible to change these fill colors?

A: With generic Javascript, you can obtain the CSSStyleSheet object and manipulate any individual CSSStyleDeclaration:
// obtain document of object
var objectDoc = document.getElementById('testObject').contentDocument;
// obtain stylesheet
var stylesheet = objectDoc.getElementById('style1').sheet;

// find a certain rule
var rule2 = Array.from(stylesheet.cssRules).find(function (rule) {
    // make sure you reference a style rule and identify by selector string
    return rule.type === CSSRule.STYLE_RULE && rule.selectorText === '.fill2';
});

// get fill value
rule2.style.getPropertyValue('fill');
// set a different fill
rule2.style.setProperty('fill', '#676869');


text:
Q: Is this loop invariant and its informal proof correct? (CLRS 3rd ed. exercise 2-1-3) Given the following algorithm for linear-search (referring to index 1 as the index of the first element in an array of elements):
found_idx = nil
for i = 1 to A.length
  if A[i] == value
    found_idx = i
    return found_idx
  end-if
end-for
found_idx

I was wondering if this loop-invariant is correct:
" At the start of each iteration of the for-loop, found_idx is the index in the array ending at i-1 at which value exists if that value exists"
Here is my proposed informal explanation of this loop-invariant according to the format in CLRS:

*

*Initialization: This is true before the first iteration because i = 1 and the array ending at i-1 is empty, and found_idx is therefore nil.

*Maintenance: This is true after each iteration because at each value of i, A[i] is checked and then i is incremented, meaning that all elements up to i-1 have been checked prior to each new iteration.

*Termination: This terminates when i > A.length, meaning that all elements up to and including A.length have been checked.

My main point of concern is that it feels incorrect to refer to the index ending at i-1 because the loop starts with i at 1, which is the first element of the array. In other words, it feels fallacious to refer to a subarray of an array, wherein the subarray ends at an index less than the starting index of the array for which the subarray is supposed to be a subarray in the first place. This seems to imply that the loop invariant given above is actually false before the very first iteration of the loop.
Thoughts?

A: Since the loop terminates early, its invariant is as follows:
found_idx = nil && ∀k<i : A[k] ≠ value

The part after && means "All of A's elements at indexes below i are not equal to value".

*

*This is trivially true before entering the loop

*Conditional either keeps found_idx at nil, or terminates the loop early

*Loop terminates when i reaches A.length
Loop's post-condition is found_idx = nil && ∀k<A.length : A[k] ≠ value, which simply means that value is not among A's elements. It also means that you can eliminate found_idx by rewriting your loop as follows:
for i = 1 to A.length
    if A[i] == value
        return i
    end-if
end-for
return nil


text:
Q: Does arithmetic on a random number reduce its entropy? For instance, as I was reading this post on betterexplained.com, the author mentioned transforming a random number that lies in the range (0,1) to a random number that lies in the range (5,10) by multiplying and then adding by 5.
Do operations such as these decrease the entropy of the number? If so how/why? I understand that operations like floor or ceiling would decrease the entropy because information is lost. Information is also lost when we use the modulo operator, or even when we hash the number. Entropy should also be lost when squaring or taking the absolute value of a random number (obviously this doesn't apply to a number between 0 and 1), because the sign of the number is lost, and these operations cannot be undone.
Both of the functions applied to our initial number have inverses (/5 and -5, respectively), so information shouldn't be lost. But I can't help but think that it is, because of floating point approximations.
Please help me understand why my intuition is or is not the case, both with a theoretical random number of infinite precision, and the real world case.

A: Using IEEE-754 format the following ranges have the same number of doubles:
   0.125-  0.25
   0.25 -  0.5
   0.5  -  1.0
   1.0  -  2.0
   2.0  -  4.0
   4.0  -  8.0
   8.0  - 16.0

Moreover, they are equidistant in each of these ranges.
From this it should be clear that there are many more doubles in the range 0 - 1 than there are in the range 5 - 10. Since 5 - 10 is 3/4 of one plus 1/4 of another range combined 5 - 10 has the same number of doubles as any of the ranges mentioned.
However, that doesn't settle it. You have to ask how the random number generator is generating numbers in the range 0 - 1. A simple way is to generate random numbers in the range 1 - 2 and then subtract one, taking advantage of the equidistance in the range 1 - 2. But there are other methods e.g. flip a coin if it is head map 1 - 2 to 0.5 - 1. If tails flip the coin again, if heads now, map 1 - 2 to 0.25 - 0.5, etc. This way you could generate pretty much any double in the range 0 - 1 (ignoring denormalized numbers) while maintaining uniformity.

A: This is not true in theory (because these operations are invertible (more generally, because they are measurable isomorphisms)) but on a physical computer, due to floating point precision yielding a different number of permissible floating point values within different ranges (e.g. more possible valid floating point values in [0,1] than in [5,10], assuming the same precision), it can be true about psuedorandom numbers generated by the computer.
Here is a good reference discussing some of this: < http://engineering.medallia.com/blog/2014/08/a-plea-for-an-equal-opportunity-random/ >.

A: I'd add this question in the comments however I don't yet have enough points to add comments - Why are you trying to find the entropy in a random number?
In order to answer your question, lets look at what a random number actually is and how it's generated in the first place. I found this reference just to give some background: http://computer.howstuffworks.com/question697.htm
Essentially I think entropy depends more-so on the source of your original random number. It can be random due to some effect of nature or it can be pseudo-random where nobody really knows the algorithm that created it and therefore has great difficulty in reproducing the string.
You could argue that if one can understand the source of the random number at a deep enough level, then entropy could essentially be reduced to near-zero. Are you using an entropy formula? Here is one: http://mathworld.wolfram.com/Entropy.html.
Your intuition may be telling you that entropy reduces if you perform operations on the source random number because it involves understanding the source better. By this I simply mean you are adding known steps to the equation - which you can back-trace to the source.
I believe as in all things it depends on the context - I highly doubt you will find an infinitely precise random number in this universe.
Hope this adds some perspective.


text:
Q: How can I subdivide large lists into sublists and use them to create new lists I have 4 large lists of data that I need to split into 4 sublists and use them to create other lists that have elements from each group of the "master lists".
So for example I have my master lists
l1 = ['ability','able','about','above','accept','according',
'account', 'across', 'act','action', 'activity']
l2 = ['benefit','best','better','between','beyond','big','bill',
'billion','bit','black','blood','blue','board','body','book']
l3 = ['civil','claim','class','clear','clearly','close','coach','cold','collection']
l4 = ['detail','determine','develop','development','die','difference',
 'different','difficult','dinner','direction']

And I need to have 4 final lists that contain a balanced number of items with different properties from the initial lists, so in this example, every final lists will contain one fourth of words beginning with 'a','b','c' and 'd'. Each target lists will have therefore 1/4 of the 'a' list, 1/4 of the 'b' list, 1/4 of the 'c' list and 1/4 of the 'd' list.
Is there an efficient way to do this in python?
Thank you very much for your help.

A: Yes there is!
The great zip() bulit-in function
l1 = ['red', 'yellow', 'pink']
l2 = ['apple', 'orange','banana']
l3 = ['coffee', 'tea', 'milk']
l4 = ['guitar', 'saxophone', 'piano']

for one, two, three, four in zip(l1, l2, l3, l4):
    print(one, two, three, four)

This outputs
red apple coffee guitar
yellow orange tea saxophone
pink banana milk piano

EDIT
Like how @Tomerikoo has commented, you can just do this
target = [item for item in zip(l1, l2, l3, l4)]

# Target is a list of tuples, so you can access each tuple like
print(target[0])
print(target[2])

# ('red', 'apple', 'coffee', 'guitar')
# ('pink', 'banana', 'milk', 'piano')


text:
Q: What's wrong with this Winform C# code? It will run fine in Windows, but in mono(Linux), will throw a NullReferenceException The error is:
System.NullReferenceException: Object reference not set to an instance of an object. I know that this error occurs when an object was used but was not initialize or being initialized but was later declared null but was nevertheless being accessed that caused the exception. But I can't figure out where the offending object was so I can correct it myself. The error will show after I selected a string from a Listbox control a second time. At first it will work and then if I select another item a second time the program will quit abruptly, the error will show at the command line in Linux.
I can show the complete error after running mono win_binary_file if needed.
After debugging, I've found this offending code that will throw the NullReferenceException:
public void fListItems(DataGridView datagridview1, string param_name)
    {
        NpgsqlDataAdapter dr = default(NpgsqlDataAdapter);
        DataSet ds;
        string sql;
        NpgsqlConnection dbcon;
        string connectionstr = "SERVER=" + DataBaseHost + ";DATABASE=" + DatabaseName + ";USER ID=" + DatabaseUser + ";PASSWORD=" + DatabasePassword + ";pooling=true; port=" + DatabasePort;
        dbcon = new NpgsqlConnection(connectionstr);
        try
        {
            sql = "SELECT * FROM purchase_order" +
           " WHERE purchase_request_num= '" + param_name + "' ORDER BY id ASC; ";
            dbcon.Open();
            ds = new DataSet("purchase_order");
            dr = new NpgsqlDataAdapter();
            dr.SelectCommand = new NpgsqlCommand(sql, dbcon);
            dr.Fill(ds, "purchase_order");
            datagridview1.DataSource = ds.Tables["purchase_order"];
        }
        catch (ApplicationException ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            dbcon.Close();
        }
    }

This code will call the function above:
private void listboxPR_SelectedIndexChanged(object sender, EventArgs e)
    {
        Cursor = Cursors.WaitCursor;
        string prnumberSelect;
        if (varname == 180)
        {
            //Somecode here for condition varname=180
            prnumberSelect = listboxPR.Text.ToString();
            Class1.fListItems(DataGridRequests, prnumberSelect);
        }
        else
        {
            prnumberSelect = listboxPR.Text.ToString();
            Class1.fListItems(DataGridRequests, prnumberSelect);
        }
        Cursor = Cursors.Default;

    }

The complete error:
System.NullReferenceException: Object reference not set to an instance of an object
  at purchase_requisition.frmmain.DataGridRequests_SelectionChanged (System.Object sender, System.EventArgs e) [0x00000] in <filename unknown>:0
  at System.Windows.Forms.DataGridView.OnSelectionChanged (System.EventArgs e) [0x00000] in <filename unknown>:0
  at System.Windows.Forms.DataGridView.SetSelectedRowCore (Int32 rowIndex, Boolean selected) [0x00000] in <filename unknown>:0
  at System.Windows.Forms.DataGridView.SetSelectedRowCoreInternal (Int32 rowIndex, Boolean selected) [0x00000] in <filename unknown>:0
  at (wrapper remoting-invoke-with-check) System.Windows.Forms.DataGridView:SetSelectedRowCoreInternal (int,bool)
  at System.Windows.Forms.DataGridViewBand.set_Selected (Boolean value) [0x00000] in <filename unknown>:0
  at System.Windows.Forms.DataGridViewRow.set_Selected (Boolean value) [0x00000] in <filename unknown>:0
  at System.Windows.Forms.DataGridView.ClearSelection () [0x00000] in <filename unknown>:0
  at System.Windows.Forms.DataGridView.MoveCurrentCell (Int32 x, Int32 y, Boolean select, Boolean isControl, Boolean isShift, Boolean scroll) [0x00000] in <filename unknown>:0
  at System.Windows.Forms.DataGridView.ClearBinding () [0x00000] in <filename unknown>:0
  at System.Windows.Forms.DataGridView.set_DataSource (System.Object value) [0x00000] in <filename unknown>:0
  at (wrapper remoting-invoke-with-check) System.Windows.Forms.DataGridView:set_DataSource (object)
  at purchase_requisition.dbquery.PRMonitoringGrid (System.Windows.Forms.DataGridView DatagridRequests, System.String Purchase_Number) [0x00000] in <filename unknown>:0
  at purchase_requisition.frmmain.listboxPR_SelectedIndexChanged (System.Object sender, System.EventArgs e) [0x00000] in <filename unknown>:0
  at System.Windows.Forms.ListBox.OnSelectedIndexChanged (System.EventArgs e) [0x00000] in <filename unknown>:0
  at System.Windows.Forms.ListBox.OnItemClick (Int32 index) [0x00000] in <filename unknown>:0
  at System.Windows.Forms.ListBox.OnMouseUpLB (System.Object sender, System.Windows.Forms.MouseEventArgs e) [0x00000] in <filename unknown>:0
  at System.Windows.Forms.Control.OnMouseUp (System.Windows.Forms.MouseEventArgs e) [0x00000] in <filename unknown>:0
  at System.Windows.Forms.Control.WmLButtonUp (System.Windows.Forms.Message& m) [0x00000] in <filename unknown>:0
  at System.Windows.Forms.Control.WndProc (System.Windows.Forms.Message& m) [0x00000] in <filename unknown>:0
  at System.Windows.Forms.ListBox.WndProc (System.Windows.Forms.Message& m) [0x00000] in <filename unknown>:0
  at System.Windows.Forms.Control+ControlWindowTarget.OnMessage (System.Windows.Forms.Message& m) [0x00000] in <filename unknown>:0
  at System.Windows.Forms.Control+ControlNativeWindow.WndProc (System.Windows.Forms.Message& m) [0x00000] in <filename unknown>:0
  at System.Windows.Forms.NativeWindow.WndProc (IntPtr hWnd, Msg msg, IntPtr wParam, IntPtr lParam) [0x00000] in <filename unknown>:0

A: I've found out that the function fListItems() is not at fault at all. It was the DatagridREquests_SelectionChanged event's code that triggers the exception. I transferred the offending code under the listboxPR_SelectedIndexChanged event, because what I need is to get data from the datagrid after it was populated by the function fListItems().
private void listboxPR_SelectedIndexChanged(object sender, EventArgs e)
{
    Cursor = Cursors.WaitCursor;
    string prnumberSelect;
    if (varname == 180)
    {
        //Somecode here for condition varname=180
        prnumberSelect = listboxPR.Text.ToString();
        Class1.fListItems(DataGridRequests, prnumberSelect);
        //Transferred code from DatagridRequests_SelectionChanged event
        if (DataGridRequests.RowCount > 0 ) {
            intVar1 = Convert.ToInt32(DataGridRequests.CurrentRow.Cells["column"].Value);
        }
    }
    else
    {
        prnumberSelect = listboxPR.Text.ToString();
        Class1.fListItems(DataGridRequests, prnumberSelect);
        if (DataGridRequests.RowCount > 0 ) {
            intVar1 = Convert.ToInt32(DataGridRequests.CurrentRow.Cells["column"].Value);
        }
    }
    Cursor = Cursors.Default;

}

Thank you guys for helping me....


text:
Q: Market prediction, utility and information A country is home to several million citizens; all citizens are risk averse, and
each citizen is exposed to an independent risky loss each year of 1,000 dollars with a probability of $\frac{1}{40}$.
The country's Financial Regulator licences the first insurance company and allows it to write up to $10 000$ policies. The insurance company charges a premium of 35 dollars for full insurance.
However, a study of the population shows that the risk of loss is in fact just $\frac{1}{60}$ for the three-quarters of the population with Blood Group 'O', and $\frac{1}{20}$ for the other Blood Groups. Citizens are easily able to check their blood group, but regulations do not permit insurers to request or to use medical information. Assuming all people have the utility function $u(w) = 1 - e^{-0.001w}$, predict what will happen to the country's insurance market.
So it's easy to check that only the "other Blood groups" (probability $\frac{1}{20}$-ones) would prefer to buy the insurance (by comparing expected utilities with and without it). How to proceed after that?

A: Once you've done that, you should compare the premium income from the insurer, which comes from $\frac{1}{4}$ of the population, i.e. $35\frac{P}{4}$ where $P$ is the number of policies written (max $10,000)$,
with the expected outgo from paying claims, which will be $1000\frac{P}{4}\frac{1}{20}$. This is the profit which the insurance company makes. As you can tell, the insurance company is going to go bust pretty quickly unless it allows patients to use their medical information.


text:
Q: CodeIgniter routing in Google App Engine After some hard work getting CI to work initially in App Engine, I am struggling when it comes to routes.
My index controller works, as do any controllers that are in the root controller folder.
However, anything that is inside a folder e.g. controllers/admin/index.php doesn't work.
Running on a LAMP stack, this would work fine, without any extra routing.
Do I need to add a new route, and if so, what should it be?
Or do I need to add in a handler in the app.yaml file, again, if so, what should it be?
My app.yaml file at the moment looks like this:
application: <project-name>
version: 1
runtime: php
api_version: 1
threadsafe: false

handlers:
- url: /.*
  script: index.php

And this works (well, I can access the main index controller and other top level controller scripts (controllers/index.php, controllers/page.php etc))


text:
Q: How to restore Acronis True Image 2014 backup to another HDD In earlier versions of Acronis True Image, there was a function in "Restore" section: Select .TIB file to restore and select destination device/partition. But I can't figure out how to restore (for ex.) mybackup.tib file to my external HDD. Is this function removed from version 2014 ?
Bulid 5560.  Sync Agent Version 17.0.0.1646  OS: Windows 8.1 x64


text:
Q: Salesforce Lookup Search - Lightning I am at case record and want to perform a lookup search without any inputs. I have used lookup criterio in my field so that the subscriptions shown should be the ones that have as an account the one who is on the Case. But how can i show all the Subscriptions when clicking and without the need to type 3 characters?

A: If this is the standard lookup, then you won't be able to change the behavior. You will need to create a custom implementation for this.
Also from UX standpoint showing all subscriptions at one go is won't be a good idea if there are more than 10 subscriptions.


text:
Q: While trying to sort sort elements according to their frequency using comparator I got this error : Comparision violates its general contract So I was trying to solve a question on sorting elements based on their frequencies using a comparator and got this error message.
The question is :

Given an array A[] of integers, sort the array according to frequency of elements. That is elements that have higher frequency come first. If frequencies of two elements are same, then smaller number comes first.

I have attached the code and the corresponding error message down below.
Error message:
Runtime Error:
Runtime ErrorException in thread "main" java.lang.IllegalArgumentException: Comparison method violates its general contract!
    at java.util.TimSort.mergeHi(TimSort.java:899)
    at java.util.TimSort.mergeAt(TimSort.java:516)
    at java.util.TimSort.mergeForceCollapse(TimSort.java:457)
    at java.util.TimSort.sort(TimSort.java:254)
    at java.util.Arrays.sort(Arrays.java:1512)
    at java.util.ArrayList.sort(ArrayList.java:1460)
    at java.util.Collections.sort(Collections.java:175)
    at Main.sortEleByFreq(File.java:50)
    at Main.main(File.java:30)

Code:
import java.util.*;
class Main
{
    static class pair
    {
        int val;
        int freq;

        pair(int val,int freq)
        {
            this.val = val;
            this.freq=freq;
        }
    }

    public static void main (String[] args)
    {
    Scanner sc = new Scanner(System.in);
        int t =sc.nextInt();
        while(t-->0)
        {
            int n =sc.nextInt();
            int a[] = new int[n];

            for(int i =0 ;i <n ; i++)
            {
                a[i]= sc.nextInt();
            }

            sortEleByFreq(a,n);
        }
    }

      static void sortEleByFreq(int a[],int n)
      {
        Arrays.sort(a);
        HashMap<Integer,Integer> map = new HashMap<>();
        for(int i=0;i<n;i++)
        {
            if(map.containsKey(a[i]))
                map.put(a[i],map.get(a[i])+1);
            else
                map.put(a[i],1);
        }

        ArrayList<pair> res = new ArrayList<>();
        for(int i=0;i<n;i++)
           res.add(new pair(a[i],map.get(a[i])));

       Collections.sort(res,new CustomSort());

       StringBuilder sb = new StringBuilder();
       for(int i=0;i<n;i++)
            sb.append(res.get(i).val+" ");

       System.out.println(sb);

      }

      static class CustomSort implements Comparator<pair>
      {
          public int compare(pair p1,pair p2)
          {
              if(p1.freq<p2.freq||p1.freq==p2.freq && p1.val>p2.val)
                return 1;

              return -1;
          }
      }

}

So I have stored the frequency and value of the element as a pair, and then used a comparator to sort it.

A: You need to return 0 as well in case of p1.val == p2.val,
static class CustomSort implements Comparator<pair>
      {
          public int compare(pair p1,pair p2)
          {
              if(p1.freq<p2.freq||p1.freq==p2.freq && p1.val>p2.val)
                return 1;
              if (p1.val == p2.val)
                   return 0;
              return -1;
          }
      }

A: You Comparator should handles all the cases, and you're not at the moment, here is how :

*

*handle p1.freq < p2.freq and p1.freq > p2.freq

*if not they are equal, sort on val field
static class CustomSort implements Comparator<pair>{
    public int compare(pair p1,pair p2){
        if(p1.freq < p2.freq)
            return 1;
        if(p1.freq > p2.freq)
            return -1;
        return Integer.compare(p1.val, p2.val);
    }
}


text:
Q: CakePHP 2.2 saveAll multiple models validation I'm trying to validate multiple models on saveAll. The validations in the first model are being triggered but when it comes to the related model, nothing seems to be happening. I even tried to check if the beforeValidate() and beforeSave() methods are being called by putting an exit; in them but the code continues to execute as normal.
ContactDetails Model:
<?php
class ContactDetails extends ContactAppModel {
    public $actsAs = array("MapValidate");
    public $hasMany = array(
        'ProjectLocation' => array(
            'className'     => 'ProjectLocation',
            'foreignKey'    => 'project_id'
        )
    );

    public $validate = array(
        'name' => array(
            'required' => array(
                'rule' => array('notEmpty'),
                'message' => 'Contact name is required'
            )
        ),
        'address1' => array(
            'required' => array(
                'rule' => array('notEmpty'),
                'message' => 'Contact address 1 is required'
            )
        ),
        'email' => array(
            'required' => array(
                'rule' => array('notEmpty'),
                'message' => 'Contact email is required'
            ),
            'email' => array(
                'rule' => array('email'),
                'message' => 'Contact email format is not valid'
            )
        )
    );
}

ProjectLocation Model:
<?php
class ProjectLocation extends ContactAppModel {
    public $actsAs = array("MapValidate");
    public $belongsTo = array(
        "ContactDetails" => array(
            "className" => "ContactDetails",
            "foreignKey" => "project_id"
        );
    );

    public $validate = array(
        'lat' => array(
           'checkLocation' => array(
                'rule'    => array('checkMap', 'lat'),
                'message' => 'One or more positions on the map are invalid.'
            )
        )
    );
}

This is the $this->request->data that I'm trying to save:
Array
(
    [ContactDetails] => Array
        (
            [id] => 1
            [name] => PreeoStudios
            [address1] => 4, Stivala Street
            [address2] => Mosta, MST 3205
            [address3] => Malta
            [telephone] => 34562737
            [email] => info@preeostudios.com
            [fax] => N/A
            [skype] => N/A
        )

    [ProjectLocation] => Array
        (
            [0] => Array
                (
                    [lat] => 35.886277456343024
                    [lon] => 14.428907312499973
                )

            [1] => Array
                (
                    [lat] => 35.886277456343024
                    [lon] => 14.528907312499973
                )

        )

)

The saveAll call:
$this->ContactDetails->saveAll($this->request->data, array('validate' => 'first'))

EDIT
I also tried to remove the validation rules from the associated model and put an exit in the beforeSave function... the code just keeps executing
<?php
class ProjectLocation extends ContactAppModel {
    public $actsAs = array("MapValidate");
    public $belongsTo = array(
        "ContactDetails" => array(
            "className" => "ContactDetails",
            "foreignKey" => "project_id"
        );
    );

    public function beforeSave(){
        exit;
    }

    public $validate = array(

    );
}

A: Try adding the option deep:
$this->ContactDetails->saveAll($this->request->data, array('validate' => 'first', 'deep' => true))

From: http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-saveassociated-array-data-null-array-options-array

A: You can get validation result for multiply models using saveAll:
$validate = $this->Model->saveAll($this->request->data, array('validate' => 'only'));


text:
Q: Create column to flag rows within a date period in R I need to create a "flag" column within my main data frame that flags rows where the date is within a specific time range.  That time range comes from a second data frame.  I think I'm just stuck on the ifelse (or if) statement because there are NA's in the flag column.  Maybe ifelse isn't the way to go.  Here's some sample data:
    # main data frame
date <- seq(as.Date("2014-07-21"), as.Date("2014-09-11"), by = "day")
group <- letters[1:4]
datereps <- rep(date, length(group))
groupreps <- rep(group, each = length(date))
value  <- rnorm(length(datereps))
df <- data.frame(Date = datereps, Group = groupreps, Value = value)

# flag time period data frame
flag <- data.frame(Group = c("b", "d"),
        start = c("2014-08-01", "2014-08-26"),
        end = c("2014-08-11", "2014-09-01"))

# Merge flag dates into main data frame
df2 <- merge(df, flag, by = "Group", all.x = T)

# Execute ifelse statement on each row
df2$flag <- "something"
df2$flag <- ifelse(df2$Date >= as.Date(df2$start) & df2$Date <= as.Date(df2$end), "flag", "other")

The result is that in rows where a "start" and "end" date are specified, "flag" and "other" are labeled, but where "start" and "end" are NA, I get Na values for df2$flag. This happens even when I initiate df2$flag with "something". I want "other" for all values that are not defined as "flag".  Look at rows 50:68.
df2[50:68,]

A: If I was doing this I'd skip the intermediate dataframe (df2) and the merge step and use ifelse with | which means OR.
date <- seq(as.Date("2014-07-21"), as.Date("2014-09-11"), by = "day")
group <- letters[1:4]
datereps <- rep(date, length(group))
groupreps <- rep(group, each = length(date))
value  <- rnorm(length(datereps))
df <- data.frame(DateTime = datereps, Group = groupreps, Value = value)

This applies flag to the criteria you specified:
df$flag <- ifelse(df$DateTime >= as.Date("2014-08-01") & df$DateTime <= "2014-08-11" |
                    df$DateTime >= as.Date("2014-08-26") & df$DateTime <= "2014-09-01",
                  "flag", "other")

Then you can have a look:
df[df$flag=="flag",]

A: Change your last line to:
for (i in 1:nrow(df2)) {
    if (is.na(df2$start[i])) {
        df2$flag[i] = 'other'
    } else if (df2$Date[i] >= as.Date(df2$start[i]) & df2$Date[i] <= as.Date(df2$end[i])) {
        df2$flag[i] = "flag"
    } else {
        df2$flag[i] = "other"
    }
}

Its ugly but it does the job. This code is not vectorized, so its fine for your situation, but would be slow for larger applications.


text:
Q: Appending a byte to String in java using escape sequence I wish to append a byte i.e. 16 = 0x10 to a String, using escape sequence to do it in single line of code:
String appendedString = new String('\16'+"String");

This results in a hex representation of appendedString = 0x0E,0x74,0x72,0x69,0x6E,0x67
using a \2 like this:
String appendedString = new String('\2'+"String");

works fine resulting in a hex representation of appendedString = 0x02,0x74,0x72,0x69,0x6E,0x67
using a \10:
String appendedString = new String('\10'+"String");

results in a hex representation of appendedString = 0x08,0x74,0x72,0x69,0x6E,0x67
Someone may kindly explain this and suggest a solution. Thanks.

A: \10 is in octal which is why you're getting U+0008.
I don't believe there are any escape formats which use decimal; I'd suggest using the \uxxxx format, or specific escape sequences for supported characters (\r, \n etc). So for the second case you could use \u000a - or just use \n in this case. For the first, you'd use \u0010.
See section 3.10.6 of the JLS for more details about escape sequences.
I'd also strongly recommend that you stop thinking of these as bytes - they're characters (or UTF-16 code units, if you want to be really precise).

A: The problem is that you are using an octal escape.  The Java Language Specification, Section 3.10.6, defines escapes, including octal escapes.

OctalEscape:
      \ OctalDigit
      \ OctalDigit OctalDigit
      \ ZeroToThree OctalDigit OctalDigit

So, \16 is the character 14 in decimal, or 0x0E in hexadecimal.
The character \2 remains 2 in decimal and hexadecimal.
The character \10 is 8 in decimal, or 0x08 in hexadecimal.
To use hexadecimal escapes, use a Unicode escape, defined in JLS Section 3.3:

UnicodeEscape:
\ UnicodeMarker HexDigit HexDigit HexDigit HexDigit

UnicodeMarker:
u
UnicodeMarker u

such as \u0016, \u0002, and \u0010.


text:
Q: Understanding the notation of uniform norm I'm currently struggling my way through Real Analysis and I don't know how to "read" the notation for a uniform norm.

$\left\lVert f\right\rVert_{\infty}:=\sup_{x \in X}|f(x)|$

Could someone please break down the meaning of each symbol and the information it is trying to tell me? I'll outline were I'm specifically confused,
For $\left\lVert f\right\rVert_{\infty}$, the double verticle bars represents the norm or "length" of vector within a Euclidean Space. So we would have the length of the function $f$. But what is the meaning and purpose of the subscript infinity? What information is this suppose to tell me?
For $\sup_{x \in X}|f(x)|$, $\sup$ is the lowest upper bound of some value. So we have the lowest upper bound for the absolute value of the function $f(x)$. But what is the meaning of the subscript ${x \in X}$?
The final question is how both these statements are equal but I first need to know the purpose of the notation to answer that.

A: $\sup_{x\in X}|f(x)|$ is the lowest upper bound of the set
\begin{equation}
\{|f(x)|, x\in X\}\subset {\mathbb R}
\end{equation}
The $\infty$ in the norm notation comes from the fact that for a collection of numbers $f_1\cdots f_n$ one has
\begin{equation}
\max_i |f_i| = \lim_{p\to \infty} \left(\sum_i |f_i|^p\right)^{1/p}
\end{equation}
Its purpose is to differentiate this particular norm from other function norms that could be defined on $X$. It is a cultural element.


text:
Q: How would you design this component in Angular 6? I have a rather basic question concerning proper component design.
I created a basic accordion component, which I'm using to display a title and a description. If the title is clicked, the description is displayed or hidden (toggled).
@Input() title: String;
@Input() description: String;

Currently I'm passing the title and description in the template as props.
<div *ngFor="let project of individualProjects">
  <app-accordion-item
    [title]="project.title"
    [description]="project.description"
    [chips]="project.tags">
  </app-accordion-item>
</div>

Accordion template
<div class="accordion-description" *ngIf="opened">
  {{ description }}
</div>

With this structure, rendering a simple paragraph without any list items or new lines is not a problem.
However, assume an item of the individualProjects array is as follows:
{
  title: "Project title",
  description: `
  The overall project involved the following:

    Project detail 1
    Project detail 2
    Project detail 3
  ..

  Some more text about project`,
  tags: ["tag"]
},
...

Some more text here

I'd like to be able to render the "Project detail x" items as list elements, which suggests I need a different structure here. I realize I may encounter many different scenarios concerning this issue, which would require me to update this structure.
Is this a reasonable point to use ng-content? Otherwise, how would you suggest I approach this?
Thank you


text:
Q: Change page according to fetched GET Parameters I want to write plugin which has the ability to change the start page according to a get parameter:
The following code is the full plugin.
function GET_Different_Page_on_front_parameter() {
if (!session_id()) {
        session_start();
    }

if(!($_SESSION['start'])){
$_SESSION['start']=$_GET['view'];
    }
    else{}

}

add_action( 'init', 'GET_Different_Page_on_front_parameter');

add_action( 'pre_get_posts', 'redirect_another_homepage');
function redirect_another_homepage(){
$front_page_slug=$_SESSION['start'];
$front_page_id=get_page_by_path($front_page_slug);
$content = $content.$front_page_id->ID;
if(is_home()){
$page=get_permalink($front_page_id->ID);
?>
<script type="text/javascript">
<!--
window.location.href = "<?php echo $page;?>";
//–>
</script>
<?php
}else{}}

I thought it was working yesterday but maybe it just look like it was working.
I also could put you as contributor in WordPress plugin repository.

A: I think you could use the template_redirect hook.  I needed to change your code a bit for my own readability:
<?php

/*
Plugin Name: Homepage redirect for SEOT
Plugin URI:
Description:
Version: 0.0.1
Author: Douglas L Sesar
Author URI:
License: GPLv2
*/

function GET_Different_Page_on_front_parameter() {

    if (!session_id()):
            session_start();
    endif;

    if(!($_SESSION['start'])):
        $_SESSION['start']=$_GET['view'];
    endif;

}

add_action( 'init', 'GET_Different_Page_on_front_parameter');

add_action( 'template_redirect', 'redirect_another_homepage');

function redirect_another_homepage(){

    $front_page_slug=$_SESSION['start'];

    $front_page_id=get_page_by_path($front_page_slug);

    $content = $content.$front_page_id->ID;

    if(is_home()):

        $page=get_permalink($front_page_id->ID);

        wp_redirect( $page );
        exit();

    endif;

}

I did not check your session logic, but I think this should work for you (did not test).  It should at least give you a direction to try.

A: I found the solution...crazy to answer my own question but here is the solution
http://wordpress.org/plugins/get-different-front-page/
Thanks for your help. Why is_home() not working in this context I still don't know.
function GET_Different_Page_on_front_parameter() {
if (!session_id()) {
        session_start();
    }

}

 add_action( 'init', 'GET_Different_Page_on_front_parameter');
 /* The fucntion GET_Different_Page_on_front_parameter() simply starts a session,
 so that one viewer gets the same homepage every time */

add_filter( 'template_redirect', 'redirect_another_homepage_gdfp');

function redirect_another_homepage_gdfp(){

if(!($_SESSION['start'])){
        $_SESSION['start']=$_GET['view'];
    }
    else{} // this if is capturing the GET parameter of the start

$front_page_slug=$_SESSION['start'];
$front_page_id=get_page_by_path($front_page_slug);

$perma=get_permalink( $front_page_id);
if(is_front_page()){ // I still not know why is_home is not working here

     wp_redirect( $perma);
     exit();

}else{}

}


text:
Q: Marking rows, based on value of other rows I have a tibble of multiple values, most importantly containing date and name. For each row of that tibble, I want to check the other rows of that tibble to see if any of the the other dates is equal to the data plus 60 seconds. If so, the row can be marked not unique and removed, if not, the row is marked as unique.
This should be done until all remaining rows are marked unique.
Via dplyr and piping I have made the tibble, but can't seem to filter it properly.
# A tibble: 9 x 3
  date                name      unique
  <dttm>              <chr>     <lgl>
1 2019-05-10 17:57:00 Item Name FALSE
2 2019-05-10 17:57:00 Item Name FALSE
3 2019-05-10 18:11:00 Item Name FALSE
4 2019-05-10 18:12:00 Item Name FALSE
5 2019-05-10 18:13:00 Item Name FALSE
6 2019-05-10 18:13:00 Item Name FALSE
7 2019-05-10 18:14:00 Item Name FALSE
8 2019-05-10 18:14:00 Item Name FALSE
9 2019-05-10 18:15:00 Item Name FALSE

So, this tibble is shown pre-filter, all unique values are still set to false. Now in essence, I'd want to run;
lookup <- rawlist %>%
  filter(date == date + 60)

On every row, row by row and if the result comes back with a rowcount higher then 0, mark the row as not unique and remove it. If it comes back as 0, mark it as unique.
Obiviously, that doesn't work as it just compares the date to itself every row. I feel like I am missing some sort of recursion method here.
One more catch is, if a row is already marked unique, it shouldn't be considered a match for the function.
So, row 1 and 2 should be marked unique.
And row 3 shouldn't be, since row 4 is exactly 60 seconds more.
The intermediate tibble should look like this, but I can't get to that point;
# A tibble: 9 x 3
  date                name      unique
  <dttm>              <chr>     <lgl>
1 2019-05-10 17:57:00 Item Name TRUE
2 2019-05-10 17:57:00 Item Name TRUE
3 2019-05-10 18:11:00 Item Name FALSE
4 2019-05-10 18:12:00 Item Name FALSE
5 2019-05-10 18:13:00 Item Name FALSE
6 2019-05-10 18:13:00 Item Name FALSE
7 2019-05-10 18:14:00 Item Name FALSE
8 2019-05-10 18:14:00 Item Name TRUE
9 2019-05-10 18:15:00 Item Name TRUE

The desired tibble looks like this;
# A tibble: 9 x 3
  date                name      unique
  <dttm>              <chr>     <lgl>
1 2019-05-10 17:57:00 Item Name TRUE
2 2019-05-10 17:57:00 Item Name TRUE
8 2019-05-10 18:14:00 Item Name TRUE
9 2019-05-10 18:15:00 Item Name TRUE

A: You could arrange the date, subtract the date with the lagged date and filter only the rows which have duration less than 60 seconds.
library(dplyr)

df %>%
  arrange(date) %>%
  filter(difftime(date, lag(date, default = first(date)), unit = "secs") < 60)

If you want to add the column unique
df %>%
  arrange(date) %>%
  mutate(unique = difftime(date, lag(date, default = first(date)),
                   units = "secs") < 60) %>%
  filter(unique)

Or in base R
df1 <- df[order(df$date), ]
df[c(TRUE, difftime(df1$date[-1], df$date[-nrow(df)], units = "secs") < 60), ]


text:
Q: What movie has a spaceship with spikes on the front impaling a ship returning to earth? When I was a kid, during the mid 90's, I once watched the first minutes of a sci-fi movie that scared me quite a bit back then.
From what I recall the movie was about a small group of people piloting a spaceship as they were returning to Earth after some kind of mission.
As they were somewhere between Mars and Jupiter they encountered a huge abandoned ship moving towards them. With an extreme manoeuvre the crew managed to avoid the drifting ship that soon changed its direction, hitting the small ship with its front spikes.
The ship was composed of 4-5 square blocks and it had long, narrow spikes on the front, something like this:

A: I am almost positive that the movie you're talking about it is Project Shadowchaser III

A: That sounds like a scene from the TV show "Firefly" or the movie "Serenity".
Though, from your doodle, the movie that you are thinking about sounds like the remake of "Dune".

A: The plot and ship description remind me of the sf/horror film Lifeforce (1985), where a British space expedition to Halley's Comet discovers an alien ship, although some of the details differ.

A: Could it be the Sulaco?  It's kind of blocky and has spikes out the front.  Don't remember it ramming any other ships though.


text:
Q: redirect from 127.0.0.1 to localhost I am running a project on localhost on ubuntu system.It runs finely when I use either localhost or 127.0.0.1. ( That is -  loclhost/myproject or 127.0.0.1/myproject). When I use localhost/myproject and navigate to other pages, say 'contact us' page, it redirects to 127.0.0.1/myproject/contactus. It is not a problem since it displays the page correctly.
when I try to run the same project on another ubuntu system using localhost, there comes some problems. The page is not loading When I try 127.0.0.1/myproject. When I use localhost:8080/myproject, the page is loading, but the css files are not loading since it shows it is loaded from 127.0.0.1/assets/css.
even if I use localhost:8080/myproject and navigate to other pages,it redirects to 127.0.0.1/myproject/page.
I am running a PHP project using codeigniter framework in ubuntu system.
And When I try to run this on windows Xampp, it is redirecting from localhost/myproject to [::1]/myproject, How can I avoid that redirection?
How can I make the page load from localhost only? Please help.

A: I think codeigniter does some rewrites depending on your config.
It looks like something is incorrect in your setup.

*

*Check codeigniter setting base_url in config.php

*Check .htaccess for any mention of domains


text:
Q: Градиент фона сайта. Здравствуйте. Не подскажете, как фон страницы залить вертикальным градиентом? И еще вопрос. Форматирую параметры текста, заданные в css, но они не хотят меняться. Чем менять, чтобы наверняка? Я <basefont>-ом пыталась.
A: css3 (для поддержки старых браузеров используй полоску грдиента с repeat-x)

body {
    background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#f4f4f4), to(red));
    background-image: -moz-linear-gradient(#f4f4f4, red);
    background-image: -o-linear-gradient(#f4f4f4, red);
    background-image: linear-gradient(#f4f4f4, red);
}

По поводу шрифтов, то тут 2 варианта:

*

*неправильно записан селектор;

*используется стиль который перекрывает твои, в этом случае после свойства указывай через пробел !important (например, color: #992200 !important;)

A: RedMonkey всё правильно указал, но я хотел бы дополнить, что
если вы беспокоитесь о кроссбраузерности, то использование линейного градиента -
это не есть гуд. А вообще, подробно почитать можно в этой статье
A: Вопросов как Ваш, по новым средствам/возможностям/утилитам море. Для многих вопросов есть универсальные решения. Например сервисы. Как этот, который позволяет визуально редактировать градиент, видеть результат и гибко настраивать, в соответствии с правилами (референсом). Есть css-фреймворки, которые упрощают подобного вида задачи, сокращают возможное количество ошибок. Всем советую - мой любимый фреймвор Blueprint. Смотрите, с чем лучше уживётесь:)


text:
Q: Add a dictionary to a `set()` with union I just ran across something interesting that I thought I'd ask about.
Adding a dictionary to a set, I had assumed that the dictionary would be added as a full dictionary, it isn't. Only the keys are added:
dicty = {"Key1": "Val1", "Key2": "Val2"}
setunion = set()
setunion.union(dicty)
=> set(['Key2', 'Key1'])

When you attempt to add it using set.add() you get an error:
setadd = set()
setadd.add(dicty)
Traceback (most recent call last):
  File "python", line 1, in <module>
TypeError: unhashable type: 'dict'

Obviously, this behaviour is very different from lists:
   listy = []
   listy.append(dicty)
   listy
=> [{'Key2': 'Val2', 'Key1': 'Val1'}]

In the docs it says that sets are unordered collections of hashable objects, which is a hint to some of the issues above.
Questions
What's going on here? Set items have to be hashable, so clearly that has to do with why I'm only adding the keys to the set with .union(), but why the error with .add()?
Is there some usability reason behind the difference in behavior of sets from lists?
Is there a datatype in Python (or a library) that essentially functions like a list, but only keeps unique items?

A: Using set.union(), ask for the elements of the argument to the method to be added to the set, not the object itself. Iterating over a dictionary gives you the keys. You'd get similar results if you used set.union() on a list, a tuple or a string, the contents of those are added to the set:
>>> s = {42}
>>> s.union('foo')
set([42, 'o', 'f'])

The single-character strings 'o' and 'f' were added, not the string 'foo'.
You cannot add dictionaries to a set, because they are mutable; sets only support storing hashable objects, and one of the requirements for an object to be hashable, is that they are immutable.

A: No that's impossible by definition. The way hash tables (like dicts and sets) do lookups is fundamentally unique from the way arrays (like lists) do lookups. The logical error is that if you have a datatype that only saves duplicates, what happens if you mutate one of the elements to be non-unique?
a, b = [0], [0, 1]
s = SpecialSet(a, b)
a.append(1)  # NOW WHAT?!

If you want to add a dictionary to a set, you can add the dict.items view of it (which is really just a list of tuples), but you have to cast to tuple first.
a = {1:2, 3:4}
s = set()
s.add(tuple(a.items()))

Then you'd have to re-cast to dict that once it leaves the set to get a dictionary back
for tup in s:
    new_a = dict(tup)

A built-in frozendict type was proposed in PEP416 but ultimately rejected.


text:
Q: Disabled DropDownList in Cascade MVC 3 I have two DropDownList in cascade
DD2 dependent on DD1.
how do I disable the DD2 if the D1 does not contain data for the selected item?
 $(function () {
         $('#DD1').change(function () {
             var selected1 = $(this).val();
             $.getJSON('@Url.Action("GetCiudadList", "ConsultorioSuper", new { Area = "Superusuario", controller = "Consultorio" })', { IdDD: selected }, function (myData) {
                 var Select2 = $('#DD2');
                 Select2.empty();
                 $.each(myData, function (index, itemData) {
                     citiesSelect.append($('<option/>', {
                         value: itemData.Value,
                         text: itemData.Text
                     }));
                 });
             });
         });

     })

 @Html.DropDownListFor(x => x.SelectedId1, new SelectList(ViewBag.IdUniversidad, "Id1", "Name"), "-- Select --", new { id = "DD1" })
 @Html.DropDownListFor(x => x.SelectedId2, new SelectList(Enumerable.Empty<SelectListItem>(), "Id2", "Name"), "-- Select --", new { id = "DD2" })

Blessings

A:
how do I disable the DD2 if the D1 does not contain data for the selected item?

How do you know that D1 doesn't contain data for the selected item? What does your controller action return in this case? An empty array I guess. If that's the case a simple if condition would do the job:
$.getJSON('@Url.Action("GetCiudadList", "ConsultorioSuper", new { Area = "Superusuario", controller = "Consultorio" })', { IdDD: selected }, function (myData) {
    var Select2 = $('#DD2');
    if (myData.length == null || myData.length == 0) {
        // null or empty data => disable the second ddl and stop executing
        // this function
        Select2.attr('disabled', 'disabled');
        return;
    }

    // at this stage we know that the myData array contains element =>
    // rebind the second dropdown list with those elements
    Select2.empty();
    $.each(myData, function (index, itemData) {
        citiesSelect.append($('<option/>', {
            value: itemData.Value,
            text: itemData.Text
        }));
    });
});


text:
Q: some delay processing message in MessageInterceptor Sorry, my english is not quite well.
I'm new in programming world and tried to create an application using messageinterceptor on windows mobile 6.5.3.
but when i send text message to my phone, there was delay about 30 seconds or  more before the message is processed, either text message which contain keywords or not.
I read several sources before deciding to try to make my own application, but these source are using Windows Form (GUI), instead of using Windows Form, i make it run in console mode.
here is the code:
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using Microsoft.WindowsMobile.PocketOutlook.MessageInterception;
using Microsoft.WindowsMobile.PocketOutlook;
using Microsoft.WindowsMobile;
using System.IO;

namespace PenerimaPesan
{
    class Program
    {

        static void Main(string[] args)
        {

            string applicationID;
            applicationID = "tracker";

            MessageInterceptor pesanmasuk = null;
            pesanmasuk = new MessageInterceptor();
            pesanmasuk.EnableApplicationLauncher(applicationID);

            if (MessageInterceptor.IsApplicationLauncherEnabled(applicationID))
            {
                string keyword;
                StreamReader key = new StreamReader(@"\Windows\conf.txt");
                string data = key.ReadToEnd();
                string[] isi = data.Split(new char[] { '\n' });
                keyword = isi[1];
                keyword = keyword.Replace(" ", "");

                pesanmasuk = new MessageInterceptor(InterceptionAction.NotifyAndDelete, false);
                pesanmasuk.MessageCondition = new MessageCondition(MessageProperty.Body, MessagePropertyComparisonType.StartsWith, ""+keyword);
                pesanmasuk.MessageReceived += new MessageInterceptorEventHandler(pesanmasuk_MessageReceived);
            }
        }

        static void pesanmasuk_MessageReceived(object sender, MessageInterceptorEventArgs e)
        {
            SmsMessage pesan = e.Message as SmsMessage;

            if (pesan != null)
            {
                string perintah;
                string[] command = pesan.Body.Split(new char[] { '.' });
                perintah = command[1];

                if (perintah == "helo")

                /*do some Stuff*/
            }
        }
    }

A: I've never used MessageInterceptor, so I decided I'd try to implement this code in my application. To test it, I renamed Main to Main2, then cleaned it up to match "my style".
Anyway, I ran into errors when I tried wrapping the MessageInterceptor in a using block - not because MessageInterceptor does not implement IDispose, but because you have declared a new instance of it.
Take a look at this snippet of your code:
MessageInterceptor pesanmasuk = new MessageInterceptor();
pesanmasuk.EnableApplicationLauncher(applicationID);
if (MessageInterceptor.IsApplicationLauncherEnabled(applicationID)) {
  string keyword;
  StreamReader key = new StreamReader(@"\Windows\conf.txt");
  string data = key.ReadToEnd();
  string[] isi = data.Split(new char[] { '\n' });
  keyword = isi[1];
  keyword = keyword.Replace(" ", "");
  pesanmasuk = new MessageInterceptor(InterceptionAction.NotifyAndDelete, false);

OK, right there. Stop. You created a new instance of your pesanmasuk variable, set Properties, did some checking, worked with data from a text file, then...
Created a new instance of your pesanmasuk variable.
All of your previous settings are now whipped out.
I'm guessing your first instance is running and perhaps the second instance has to wait for the first instance to time out before it can be created.
At this point, I'm interested to learn just how to use this MessageInterceptor on MSDN, looked into the example there, and came up with this [untested] version:
static void Main2(string[] args) {
  const string stackOverflowUrl = @"http://stackoverflow.com/questions/8520488/some-delay-processing-message-in-messageinterceptor";
  string empty = String.Empty;
  StreamReader key = new StreamReader(@"\Windows\conf.txt");
  string data = key.ReadToEnd();
  string[] lines = data.Split(new char[] { '\n' });
  string keyword = lines[1].Replace(" ", empty);
  string applicationID = "trackingApplication";
  using (MessageInterceptor smsInterceptor = new MessageInterceptor(applicationID, false)) {
    smsInterceptor.InterceptionAction = InterceptionAction.NotifyAndDelete;
    smsInterceptor.MessageCondition = new MessageCondition(MessageProperty.Body, MessagePropertyComparisonType.StartsWith, empty + keyword);
    smsInterceptor.MessageReceived += new MessageInterceptorEventHandler(Intercept_MessageReceived);
    smsInterceptor.EnableApplicationLauncher(applicationID);
    if (MessageInterceptor.IsApplicationLauncherEnabled(applicationID)) {
      // Here, you'd need to launch your Form1 or enable some timer,
      // otherwise the code will return immediately and the MessageInterceptor
      // instance will be disposed of.
    }
    smsInterceptor.MessageReceived -= MessageInterceptorEventHandler;
  }
}

static void Intercept_MessageReceived(object sender, MessageInterceptorEventArgs e) {
  SmsMessage newMessage = e.Message as SmsMessage;
  if (newMessage != null) {
    Console.WriteLine("From: {0}", newMessage.From.Address);
    Console.WriteLine("Body: {0}", newMessage.Body);
    string[] command = newMessage.Body.Split(new char[] { '.' });
    string line = command[1];
    if (line == "helo") {
      /*do some Stuff*/
    }
  }
}

I hope this helps, but keep in mind that I've never actually used this control and my code has not been tested.


text:
Q: Intern functional tests on Chrome not scrolling to elements I've got a HTML page that I want to run tests on. The page consists of a grid of boxes, and each box goes to a different page. I want my tests to click on each one, verify the destination exists and then go back to the main page to repeat.
The tests run fine until it reaches the boxes that go outside of the current window, and then returns that the element is not clickable at any point.
This error does not happen in Internet Explorer which scrolls the page down to the elements, and only happens on Chrome for me.
So my question is how can I make Chrome act like IE and scroll down to the element to click it?
Here is an example of one of my tests:
bdd.it("blah", function() {
  return remote
    .get(main page url)
    .findByLinkText("blah")
    .click()
    .getCurrentUrl()
    .then(function(url) {
        expect(url).to.equal("url to match against")
    });
});

As I mentioned these tests run fine until the elements are below the window.


text:
Q: Fire trigger on insert statement when 0 rows inserted Im showing 5 tables from library database
BOOK(book_id, title, total_num, borrowed_num)
BOOK_COPY(copy_id,book_id,status)
READER(reader_id)
BORROWED_BOOKS(reader_id,copy_id)
QUEUE(reader_id, copy_id)
// status represents enum{free, borrowed}

*

*INSERT INTO BORROWED_BOOKS(reader_id, copy_id) SELECT somereader_id, copy_id FROM BOOK_COPY WHERE book_id = somebook_id AND status = 'free' LIMIT 1;

*My question is: How to write a trigger that - when above INSERT returns 0 inserted rows - adds reader to queue table?


text:
Q: How to upload image to canvas and draw squares on it and get the squares' coordinates I'm trying to upload an image to canvas and draw squares on it and get the squares' coordinates to send it to the backend for keys identification.
But something not right, I can't draw squares on my images.
This is my javascript which I use:
    var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var rect = {};
var drag = false;
var imageObj = null;

function init() {
    imageObj = new Image();
    imageObj.onload = function () { ctx.drawImage(imageObj, 0, 0); };
    imageObj.src =
    canvas.addEventListener('mousedown', mouseDown, false);
    canvas.addEventListener('mouseup', mouseUp, false);
    canvas.addEventListener('mousemove', mouseMove, false);
}

function mouseDown(e) {
    rect.startX = e.pageX - this.offsetLeft;
    rect.startY = e.pageY - this.offsetTop;
    drag = true;
}

function mouseUp() { drag = false; }

function mouseMove(e) {
    if (drag) {
        ctx.clearRect(0, 0, 500, 500);
        ctx.drawImage(imageObj, 0, 0);
        rect.w = (e.pageX - this.offsetLeft) - rect.startX;
        rect.h = (e.pageY - this.offsetTop) - rect.startY;
        ctx.strokeStyle = 'red';
        ctx.strokeRect(rect.startX, rect.startY, rect.w, rect.h);
    }
}
//
init();
</script>
<script type="text/javascript">
document.getElementById('imageLoader').onchange = function(e) {
  var img = new Image();
  img.onload = draw;
  img.onerror = failed;
  img.src = URL.createObjectURL(this.files[0]);
};
function draw() {
  var canvas = document.getElementById('canvas');
  canvas.width = this.width;
  canvas.height = this.height;
  var ctx = canvas.getContext('2d');
  ctx.drawImage(this, 0,0);
}
function failed() {
  console.error("The provided file couldn't be loaded as an Image media");
}

and HTML:
 <canvas id="canvas" ></canvas>
 <input type="file" id="imageLoader" name="imageLoader"/>

A: You just need to assign the image to imageObj.
function draw() {
  canvas.width = this.width;
  canvas.height = this.height;
  ctx.drawImage(this, 0,0);

  imageObj = this; //here
}

JSFiddle here


text:
Q: Java array with empty second brackets In Java you can do this
int[][] i = new int[10][];

Does this just create 10 empty arrays of int? Does it have other implications?

A: It creates a 10-entry array of int[]. Each of those 10 array references will initially be null. You'd then need to create them (and because Java doesn't have true multidimensional arrays, each of those 10 int[] entries can be of any length).
So for instance:
int i[][] = new int [10][];
i[0] = new int[42];
i[1] = new int[17];
// ...and so on

A: Executing your code creates an array of size 10, each element of which can hold a reference to a int[], but which are all initialized to null.
In order to use the int[]s, you would have to create new int[] for each of the element, something like this:
for (int n = 0; n < 10; n++)
    i[n] = new int[10]; // make them as large as you need

A: Yes, it does; however, each of those arrays are null. You have to then initialize each of those sub-arrays, by saying int[10][0] = new int[MY_SIZE], or something similar. You can have arrays with different lengths inside the main array; for example, this code would work:

int[][] i = new int[10][];
for(int ind = 0; ind<10;ind++){
    i[ind]=new int[ind];
}

It is just an array of arrays.

A: Here you create ten new int[0] arrays. You have to manually initialize it, it's useful when you don't need square matrix:
    int[][] array = new int[10][];
    for (int i = 0; i < array.length; i++) {
        array[i] = new int[i];
    }

If you need square matrix you can do:
    int[][] array = new int[10][10];

And it will be initialized with default values.

A: That is just the declaration, you need to initialize it. The 10 arrays would be null initially.