Q:

When a binary file runs, does it copy its entire binary data into memory at once? Could I change that?

Does it copy the entire binary to the memory before it executes? I am interested in this question and want to change it into some other way. I mean, if the binary is 100M big (seems impossible), I could run it while I am copying it into the memory. Could that be possible?
Or could you tell me how to see the way it runs? Which tools do I need?

A:

The theoretical model for an application-level programmer makes it appear that this is so. In point of fact, the normal startup process (at least in Linux 1.x, I believe 2.x and 3.x are optimized but similar) is:

The kernel creates a process context (more-or-less, virtual machine)
Into that process context, it defines a virtual memory mapping that maps
from RAM addresses to the start of your executable file
Assuming that you're dynamically linked (the default/usual), the ld.so program
(e.g. /lib/ld-linux.so.2) defined in your program's headers sets up memory mapping for shared libraries
The kernel does a jmp into the startup routine of your program (for a C program, that's
something like crtprec80, which calls main). Since it has only set up the mapping, and not actually loaded any pages(*), this causes a Page Fault from the CPU's Memory Management Unit, which is an interrupt (exception, signal) to the kernel.
The kernel's Page Fault handler loads some section of your program, including the part
that caused the page fault, into RAM.
As your program runs, if it accesses a virtual address that doesn't have RAM backing
it up right now, Page Faults will occur and cause the kernel to suspend the program
briefly, load the page from disc, and then return control to the program. This all
happens "between instructions" and is normally undetectable.
As you use malloc/new, the kernel creates read-write pages of RAM (without disc backing files) and adds them to your virtual address space.
If you throw a Page Fault by trying to access a memory location that isn't set up in the virtual memory mappings, you get a Segmentation Violation Signal (SIGSEGV), which is normally fatal.
As the system runs out of physical RAM, pages of RAM get removed; if they are read-only copies of something already on disc (like an executable, or a shared object file), they just get de-allocated and are reloaded from their source; if they're read-write (like memory you "created" using malloc), they get written out to the ( page file = swap file = swap partition = on-disc virtual memory ). Accessing these "freed" pages causes another Page Fault, and they're re-loaded.

Generally, though, until your process is bigger than available RAM — and data is almost always significantly larger than the executable — you can safely pretend that you're alone in the world and none of this demand paging stuff is happening.
So: effectively, the kernel already is running your program while it's being loaded (and might never even load some pages, if you never jump into that code / refer to that data).
If your startup is particularly sluggish, you could look at the prelink system to optimize shared library loads. This reduces the amount of work that ld.so has to do at startup (between the exec of your program and main getting called, as well as when you first call library routines).
Sometimes, linking statically can improve performance of a program, but at a major expense of RAM — since your libraries aren't shared, you're duplicating "your libc" in addition to the shared libc that every other program is using, for example. That's generally only useful in embedded systems where your program is running more-or-less alone on the machine.
(*) In point of fact, the kernel is a bit smarter, and will generally preload some pages
to reduce the number of page faults, but the theory is the same, regardless of the
optimizations

A:

No, it only loads the necessary pages into memory. This is demand paging.
I don't know of a tool which can really show that in real time, but you can have a look at /proc/xxx/maps, where xxx is the PID of your process.


Q:

Removing bullets from unordered list

Edit
The html and css for the site I am working on can be found at http://http://new.oranaschool.com/
/Edit
I am trying to remove the bullets showing in the top horizontal menu (Home...Contact). I have tried the advice given in Removing "bullets" from unordered list <ul> but still the bullets persist.
Can someone have a look at the CSS and tell me what I need to add to which CSS class? This has been driving me nuts now for a couple of hours.

A:

remove background-image from this
.navigation ul.sf-menu > li:before {
     background: url(../images/menu_bull.png) 0 0 no-repeat; /** remove this */
}

and if you don't want to edit the original code add
.navigation ul.sf-menu > li:before {
         background: url('');
    }


Q:

User Defined File Reading Function Causes NullPointerException Java

I have to read some information from text file to different String arrays. So, I wrote a method for this task. Here is the code:
private String[] stateNames;
.
.
.
readHelper(stateNames);
.
.
.
private void readHelper( String[] str ) // str is stateNames
    {
        try
        {
            strLine = bufferReader.readLine();
            String[] tokens = strLine.split(",");
            str = new String[ tokens.length ];
            copyStr2Str(tokens, str);
            insertionSort( str ); // Everything is fine, str contains the data
        }
        catch (IOException ex)
        {
            Logger.getLogger(Generator.class.getName()).log(Level.SEVERE, null, ex);
        }

    } // End of readHelper()

However after readHelper() is executed stateNames becomes null. I think, I cause some pointer errors.

A:

In Java, arguments are passed as a copy of the reference.
When you do,
str = new String[ tokens.length]

you discard the reference passed by the method call and create a new one (which only lives until the end of the try scope in which was created). The original stateNames keeps pointing to the original value, which was null.
Modify the method to return the str array and assign it to stateNames.
UPDATE to answer comment:
To understand this, try this code.
public class MyClass {
    private List<String> originalList1 = new ArrayList<String>();
    private List<String> originalList2 = new ArrayList<String>();

    public void run() {
       this.test(originalList1, originalList2);
    }

    public void test(List<String> list1, List<String> list2) {
       list1 = new ArrayList<String>();
       list1.add(new String("Hello"));
       list2.add(new String("World"));
       System.out.println("list1.size -> " + list1.size());
       System.out.println("originalList1.size -> " + originalList1.size());
       System.out.println("list2.size -> " + list2.size());
       System.out.println("originalList2.size -> " + originalList2.size());
    }
  }

Since you assign a new object to list1, the original reference is lost so the original object is not affected (but with list2, you are still using the original object). Since in your code you create a new String[], you no longer work in the original one.


Q:

How to display the function name into the function itself

How to dispaly the function name into the function?
#!/bin/sh
toto()
{
    echo "$something"
}

toto

the above code should display
toto

I m using bash linux from busybox

A:

You can use $FUNCNAME to do so.
$ toto()
> {
> echo "this function name is $FUNCNAME"
> }
$ toto
this function name is toto


Q:

'Finally' statement executes twice in a recursive function [Python 3.6]p

I tried googling it but couldn't find a similar problem. I am sure it's something silly but I can't seem to get it.
I have the following code:
def f(a):
    try:
        4 / a
    except:
        f(2)
    else:
        print('else')
    finally:
        print("finally")

When I call the function with 0 as the argument: f(0)
It returns:
else
finally
finally

So in my understanding here is what should happen:

0 gets fed to the function;
try statement can't execute it;
except statement gets triggers, which calls the function again with a legal argument, 2.
try statement is now okay;
else statement prints else
finally statement prints finally

Why does finally gets printed twice?

A:

When you invoke with f(0), the finally block is called twice. Once for the call to f(2) and then again for the enclosing call to f(0).
This is because 4 / 0 leads to an exception, which triggers the second call to f via f(2).
finally will be invoked first for the call to f(2), then for the call to f(0) - because f(2) is invoked from f(0).


Q:

CakePHP 3.0 - How to create a postLink with confirmMessage?

I started working in CakePHP 3.0 (beta) today.
In CakePHP 2.0 there was an option for adding a confirm message to a postlink. This would result in an alert when clicking on the link.
More info about the postLink in CakePHP 2.0:
http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::postLink
More info about the postLink in CakePHP 3.0:
http://book.cakephp.org/3.0/en/views/helpers/form.html#Cake\View\Helper\FormHelper::postLink
In the 3.0 version the confirmMessage is gone. Does anybody know if CakePHP 3.0 has an alternative for this?

A:

It's not gone, it was just moved into an option named confirm:
$this->Form->postLink('title', 'url', ['confirm' => 'Are you sure?'])

See also http://api.cakephp.org/3.0/class-Cake.View.Helper.FormHelper.html#_postLink


Q:

LabVIEW: Have multiple indicators (different styles) for a single variable

A variable gets changed throughout the VI several times. I would like to display it in on two different tabs in the front panel, in different styles (thermometer, numeric indicator).
This answer does not work for me, since there is no "digital display" available if the variable is already displayed elsewhere.
Thanks!

A:

You can wire any number of indicators to the same data source. Just use the wiring tool to link up the terminals on the block diagram.
If you're writing data to a local variable of one indicator and you want the second one to update at the same time, you have a few options:

Just wire the same data to a local variable of the second indicator in each place. This is the easiest option if your VI is relatively simple.
Place a while loop on your diagram that reads a local variable of the first indicator every 100 ms (say) and updates the second one.
Instead of writing to a local each time, send the data to a notifier. Place a while loop on your diagram that waits for a notification and each time it receives one, updates both indicators.
If you have the Full or Professional development systems, you can probably do something similar with a user-defined event structure.

If you choose one of the options with a while loop, you'll need to figure out how to stop the loop when the rest of your program is finished. Notifiers are handy because when you release the notifier with 'force destroy' True, any wait on notification operations will stop waiting and return an error value which you can wire to your loop terminal.


Q:

Nginx: How to Send to Client Result of a Python Script?

I have a simple python script: the generates an x-icon from a hex colour given to it, then it returns a valid byte-stream (BytesIO).
I want to get something like this (please, do not laugh, I'm using Nginx for about two days):
location ~^/icons/(?<colour>[a-fA-F0-9]{6})\.ico$ {
    send 200 (./favicon.py colour); # System call to `favicon.py` with `colour` argument.
}

Is it possible at all?

A:

The following config should do the work:
location ~^/icons/(?<colour>[a-fA-F0-9]{6})\.ico$ {
    content_by_lua '
        local command = "./favicon.py colour"
        local handle = io.popen(command)
        local content = handle:read("*a")
        handle:close()
        ngx.print(content)
    ';
}

Basically it uses Lua for executing and providing the content
NOTE: your nginx should be compiled with the lua module for this solution to work


Q:

REST WCF not supporting List

This is very strange, i'm trying to post JSON data to my WCF service.
<OperationContract>
<WebInvoke(Method:="POST", RequestFormat:=WebMessageFormat.Json, ResponseFormat:=WebMessageFormat.Json, BodyStyle:=WebMessageBodyStyle.WrappedRequest)>
Function getProvinciasByAsignacion(asignaciones As List(Of String)) As List(Of String)

It works perfectly fine. But... the strange thing here, is if i change string list to integer list, the wcf service returns 400 (bad request).
This is the JSON code that i send (through angular)
{"asignaciones":[290,291]}

Is this a bug? or a limitation? I'm very lost here! Hope someone could help me...
Cheers.

A:

I found the problem. When I enabled includeExceptionDetailInFaults in my web.config I was able to see that my function was doing an invalid cast in the return statement.
If I just do that first instead of asking... what a shame.
Bye!


Q:

How do I download last working project from TFS server and replace my local, which does not work?

Apparently I have some problems with my local work-space and I not able to deploy anything to TFS server successfully.
Is it possible to download last working solution and replace my local?
If so, how?
Thank you for you help in advance.

A:

In the source control explorer, right click on the folder you want to replace, navigate to "Advanced", and choose "Get Specific Version".


Q:

SQL Server: BCP queryout fail

This code works well
USE BellariaNetAssets
DECLARE @printFile VARCHAR(1000)
SELECT ip FROM fnMuninCfg()

However this code fails:
USE BellariaNetAssets
DECLARE @printFile VARCHAR(1000)
SET @printFile = 'BCP "SELECT ip FROM fnMuninCfg()" queryout "C:\users\aag\desktop\munin'
+ '.cfg" -c -T -t "|" '
EXEC xp_cmdshell @printFile

The errors are:

Error = [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Invalid object name 'fnMuninCfg'.
  Error = [Microsoft][ODBC Driver 13 for SQL Server]Unable to resolve column level collations
  BCP copy out failed

Might a good soul explain to me why the BCP affirms that the object name is invalid? The function appears to be OK (code #1).

A:

Try fully qualifying the function name (e.g. Adventureworks.dbo.fnMuninCfg())
My guess is that when you are calling it, I believe that xp_cmdshell runs in the context of the master db and so when you call an unqualified function, it is by default looking in the master db for your function.  Let me know if it works!


Q:

List key value with unique key as an object or enum

Question

I would like a list of key value pair such as a HashMap for instance or other if recommended.
This list should contains unique keys objects used to retrieve the values.
Keys should NOT be a STRING, since string is not unique and any value can be passed.
Also constants are limited and are using the concepts of strings as well and should not be considered.

Example

What is wanted is for instance list[Color.Red] = "Red".
At this stage, i have created an enum containing all the keys.
For instance enum Color{RED,BLUE} then add it to a new HashMap.
So the only way to retrieve a color, is to use the enum as a key list[Color.RED].

Implementation
public final static Map<Color, String> colors = new HashMap<>();
public final static enum Color{RED, BLUE;}
static
{
   colors.put(RED, "red");
   colors.put(BLUE, "blue");
}
public static string getColor(Color color)
{
   return colors.get(color);
}

Need Help
Is there a type of Collection in Java that could do the job ?
If not then what might be the best practice to do so ?

A:

Potential Solution
After checking around enum and its possibilities, there is a way to assign values to a Key in an enum, like follow.

Create a new enum and assign Key such as public enum Color{RED;}.
Add a constructor parameter to it such as public enum Color{RED("red");}
Add a constructor to the enum such as public enum Color{RED("red"); Color(){}}
Add a new field inside enum called value such as private String value; public String getValue() {return value;}
Set field value in constructor of enum such as Color(String value) {this.value = value;}
Enum work in that way, for each Key you add it creates a new instance field String value linked to the Key, then it will use the constructor you have declared to save the value.

Full Implementation
public enum Color
{
   //[PROP]
   RED("red"),
   GREEN("green"),
   BLUE("blue");

   private String value;
   public String getValue {return value;}

   //[BUILD]
   Color(String value) {this.value = value;}

   //[UTIL]
   Color[] getKeys() {return this.values;} //values method is already a method existing in enum class, we are just proposing another method name here as a facade for simplicity.
}

If we want to retrieve an item we just simply do Color.RED.value, in this way only existing keys returned wanted value.
Note that value doesn't needs to be the name of the key but could be a totally different value.

Please comment if you have any simpler solution without putting more complexity to the solution.


Q:

How do I copy all files to a sub directory based on the file name?

I am sure this is possible with a bash script, but I want to make sure I'm not missing something obvious.  Google hasn't been much help, so maybe you can be.
Assume a directory has the following files
dir/file1
dir/newfile2
dir/oldfile3

I would like to figure out the best solution for copying all files in the folder to a folder 2 levels deep based on the first two letters of the filename, so the result would be
dir/f/i/file1
dir/n/e/newfile2
dir/o/l/oldfile3

A:

Something like this should do it:
cd dir
for file in *; do
    newpath="${file:0:1}/${file:1:1}"
    mkdir -p "$newpath"
    cp "$file" "$newpath"
done

Be sure all your filenames are two chars or more, though.
${var:n:m} is simply Bash syntax for "substring of var starting at n of length m."
If there can also be arbitrary subdirectories, either add -r to the cp command if you want to copy recursively or add a test to ignore directories in the for loop:
cd dir
for file in *; do
    if [ -f "$file" ]; then
        newpath="${file:0:1}/${file:1:1}"
        mkdir -p "$newpath"
        cp "$file" "$newpath"
    fi
done


Q:

Modify hosts file on Android without rooting device

Is it possible to add entry to hosts file on Android without rooting phone?
I am contractor working in remote and I have to use AirWatch and Cisco AnyConnect to get access to VPN, but if I root Samsung tablet (SM-T700, 5.0.2) then I can't get access to VPN. All what I actually need is to access web application behind that VPN with either Firefox or Chrome. It's just adding: ip.ip.ip.ip jbossWorker100.intranetOfCompany.com
I already rooted tablet, changed host file, but then I can't get access VPN, and if I unroot it then I can get through VPN but I can't get to the app.

A:

This is not possible. You can, however, run your own DNS server on a local network, that could emulate this behaviour on all appliances that are connected via it.


Q:

Is cross-origin postMessage broken in IE10?

I'm trying to make a trivial postMessage example work...

in IE10
between windows/tabs (vs. iframes)
across origins

Remove any one of these conditions, and things work fine :-)
But as far as I can tell, between-window postMessage only appears to work in IE10 when both windows share an origin.  (Well, in fact -- and weirdly -- the behavior is slightly more permissive than that: two different origins that share a host seem to work, too).
Is this a documented bug? Any workarounds or other advice?
(Note: This question touches on the issues, but its answer is about IE8 and IE9 -- not 10)

More details + example...
launcher page demo
<!DOCTYPE html>

  <button onclick="window.open('http://jsbin.com/ameguj/1');">
    Open new window
  </button>

launched page demo
<!DOCTYPE html>

This works at: http://jsbin.com/ahuzir/1 -- because both pages are hosted at the same origin (jsbin.com).  But move the second page anywhere else, and it fails in IE10.

A:

I was mistaken when I originally posted this answer: it doesn't actually work in IE10. Apparently people have found this useful for other reasons so I'm leaving it up for posterity.  Original answer below:

Worth noting: the link in that answer you linked to states that postMessage isn't cross origin for separate windows in IE8 and IE9 -- however, it was also written in 2009, before IE10 came around.  So I wouldn't take that as an indication that it's fixed in IE10.
As for postMessage itself, http://caniuse.com/#feat=x-doc-messaging notably indicates that it's still broken in IE10, which seems to match up with your demo.  The caniuse page links to this article, which contains a very relevant quote:

Internet Explorer 8+ partially supports cross-document messaging: it
  currently works with iframes, but not new windows. Internet Explorer
  10, however, will support MessageChannel. Firefox currently supports
  cross-document messaging, but not MessageChannel.

So your best bet is probably to have a MessageChannel based codepath, and fallback to postMessage if that doesn't exist.  It won't get you IE8/IE9 support, but at least it'll work with IE10.
Docs on MessageChannel: http://msdn.microsoft.com/en-us/library/windows/apps/hh441303.aspx

A:

Create a proxy page on the same host as launcher.  Proxy page has an iframe with source set to remote page.  Cross-origin postMessage will now work in IE10 like so:

Remote page uses window.parent.postMessage to pass data to proxy page. As this uses iframes, it's supported by IE10
Proxy page uses window.opener.postMessage to pass data back to launcher page.  As this is on same domain - there are no cross-origin issues. It can also directly call global methods on the launcher page if you don't want to use postMessage - eg. window.opener.someMethod(data)

Sample (all URLs are fictitous)
Launcher page at http://example.com/launcher.htm
<!DOCTYPE html>

        <title>Test launcher page</title>
        <link rel="stylesheet" href="/css/style.css" />

    <button onclick="openProxy();">Open remote</button>

    <textarea cols="150" rows="20" id="logger"></textarea>

Proxy page at http://example.com/proxy.htm
<!DOCTYPE html>

        <title>Proxy page</title>
        <link rel="stylesheet" href="/css/style.css" />

Remote page at http://example.net/remote.htm
<!DOCTYPE html>

        <title>Remote page</title>
        <link rel="stylesheet" href="/css/style.css" />

Remote page

    <input type="text" id="msg" placeholder="Type a message" /><button onclick="remoteSubmit();">Close</button>

A:

== WORKING SOLUTION IN 2020 without iframe ==
Building on answer by tangle, I had success in IE11 [and emulated IE10 mode] using following snippet:
var submitWindow = window.open("/", "processingWindow");
submitWindow.location.href = 'about:blank';
submitWindow.location.href = 'remotePage to comunicate with';

Then I was able to communicate using typical postMessage stack, I'm using one global static messenger in my scenario (alotough I don't suppose it's of any signifficance, I'm also attaching my messenger class)
var messagingProvider = {
    _initialized: false,
    _currentHandler: null,

    _init: function () {
        var self = this;
        this._initialized = true;
        var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
        var eventer = window[eventMethod];
        var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";

        eventer(messageEvent, function (e) {
            var callback = self._currentHandler;
            if (callback != null) {
                var key = e.message ? "message" : "data";
                var data = e[key];
                callback(data);
            }
        }, false);
    },

    post: function (target, message) {
        target.postMessage(message, '*');
    },

    setListener: function (callback) {
        if (!this._initialized) {
            this._init();
        }

        this._currentHandler = callback;
    }
}

No matter how hard I tried, I wasn't able to make things work on IE9 and IE8
My config where it's working:
IE version: 11.0.10240.16590, Update versions: 11.0.25 (KB3100773)


Q:

How to count nodes in a Tree in R

I'm starting to study ML with R. I do the following operations with RStudio:
iris=datasets::iris
tree(Species~., iris)

And I obtain:
 1) root 150 329.600 setosa ( 0.33333 0.33333 0.33333 )
   2) Petal.Length < 2.45 50   0.000 setosa ( 1.00000 0.00000 0.00000 ) *
   3) Petal.Length > 2.45 100 138.600 versicolor ( 0.00000 0.50000 0.50000 )
     6) Petal.Width < 1.75 54  33.320 versicolor ( 0.00000 0.90741 0.09259 )
      12) Petal.Length < 4.95 48   9.721 versicolor ( 0.00000 0.97917 0.02083 )
        24) Sepal.Length < 5.15 5   5.004 versicolor ( 0.00000 0.80000 0.20000 ) *
        25) Sepal.Length > 5.15 43   0.000 versicolor ( 0.00000 1.00000 0.00000 ) *
      13) Petal.Length > 4.95 6   7.638 virginica ( 0.00000 0.33333 0.66667 ) *
     7) Petal.Width > 1.75 46   9.635 virginica ( 0.00000 0.02174 0.97826 )
      14) Petal.Length < 4.95 6   5.407 virginica ( 0.00000 0.16667 0.83333 ) *
      15) Petal.Length > 4.95 40   0.000 virginica ( 0.00000 0.00000 1.00000 ) *

My questions are:

how can I obtain the maximum node depth of the tree?
how can I obtain the number of nodes?

I use packages tree and datasets.
Thank you in advance.

A:

Concerning your 2nd question you can do:
library(tree)

# build your tree
m = tree(Species~., iris)

# count how many times you have <leaf> in the models dataframe
sum(m$frame$var == "<leaf>")

# [1] 6

# count terminal nodes
length(unique(m$where))

# [1] 6

# count nodes
nrow(m$frame)

# [1] 11


Q:

Online Ticketing Purchase Timer

Can someone please guide me as to what is the best way to have the time restriction timer in one of my online application written in Classic ASP with MsAccess database.
Simple process..Once the user shops, the system redirects the user to enter the billing & shipping information where-in this timer is shown and valid for 10 minutes.
Initially I captured the server side time and added 10 minutes using Classic ASP's DateAdd function "DATEADD("n",10, TIME())" and then used JavaScript to match the current time with the expiry time. But since site can be accessed from any part of the world, so taking server time is not helpful as Javascript matching is taking local PC time, so it will never match.
Secondly, when the user refreshes the page, the 10 minute timer will restart.
Appreciate your help. It can be through Javascript or Classic ASP.

A:

In page1, do this
session("shopping_time") = now

In the subsequent pages
do this,
session("current_time" ) = now
time_elapsed = datediff("n",session("current_time" ),session("shopping_time"))
if ( time_elapsed > 10 ) then
    //do something
end if


Q:

How to solve $y'''+2y''-y'-2y= e^x+x^2$?

The equation that needs to be solved is: $$y'''+2y''-y'-2y= e^x+x^2$$
Steps: homogeneous solution and then the particular part.Bbut how do i handle the particular part? Do i need to take them once at a time?

A:

Solving
$$
(*)\;\;y'''+2y''-y'-2y= e^x+x^2
$$
By the method of undetermined coefficients:
First, we find the solution to the homogeneous equation:
$$
(**)\;\;y'''+2y''-y'-2y= 0
$$
By the usual characteristic equation:
$$
m^3+2m^2-m-2=0\Rightarrow m^2(m+2)-1(m+2)=0\Rightarrow m^2=1,m=-2
$$
yielding our solution to $(**)$,
$$
y_h(x)=c_1e^{-x}+c_2e^{x}+c_3e^{-2x}
$$
Then, we need to find some solution $y_p$ to the original equation $(*)$, which we do by a sort of guess and check. We guess that the solution will be of the form
$$
y_p(x)=Axe^{x}+Bx^2+Cx+D
$$
I.e. a second order polynomial summed with an exponential multiplied by a linear factor (called a fix up factor), since an $e^x$ term is already present in our homogenous solution. Then by the conditions of $(*)$ we know that
$$
y_p'''+2y_p''-y_p'-2y_p= e^x+x^2\Rightarrow\\
Axe^{x}+3Ae^{x}+2Axe^x+4Ae^x+4B-Axe^x-Ae^x-2Bx-C-2Axe^x-2Bx^2-2Cx-2D-2Bx^2\\
=x^2+e^x\\
\Rightarrow 6Ae^x+(4B-2D-C)+x(-2B-2C)-2Bx^2=x^2+e^x \\
\Rightarrow 6A=1,4B-2D-C=0,-2B=1,-2B-2C=0
$$
By equating coefficients. Then solving the system of coefficients we see that
$$
A=1/6\\
B=-1/2\\
-B=C=1/2\\
4B-2D-C=0\Rightarrow D=-5/4
$$
$$
y_p(x)=1/6xe^{x}-1/2x^2+1/2x+-5/4
$$
Yielding the solution to $(*)$ of
$$
y_p+y_h=1/6xe^{x}-1/2x^2+1/2x+-5/4+c_1e^{-x}+c_2e^{x}+c_3e^{-2x}
$$


Q:

Is there a way to vectorize the portfolio standard deviation in python pandas

My goal is to calculate an investment portfolio's standard deviation.

I've generated a randomly weighted portfolio of 23 stocks:
X = np.random.dirichlet(np.ones(23),size=1000)
rand_port_wts = pd.DataFrame(X, columns=data.columns)

The matrix is: (1000, 23)
I've generated a covariance table:
annual_sec_std_deviation = (daily_sec_return.std()) * np.sqrt(num_trade_dys_py)

The matrix is: (23,23)
Because the shape of the matrices, understandable I get a value error:
ValueError: shapes (23,23) and (1000,23) not aligned: 23 (dim 1) != 1000 (dim 0)

The only way that I can think of solving the problem is by using a loop to pass 1 row of the of the portfolio weights dataframe (rand_port_wts):
    tbl = []
for i in range(1000):
    tbl.append(np.sqrt(np.dot(rand_port_wts.loc[i].T, np.dot(annual_sec_covariance, rand_port_wts.loc[i]))))

tbl

While this works, it takes forever and it's not elegant. I'm hoping that someone might be able to suggest something that's a little more efficient.
Thanks in advance

A:

Im not 100% sure here but try:
portfolio_vol = rand_port_wts.apply(lambda x: np.dot(x.T, np.dot(cm, x)), axis=1)
where cm is the covariance matrix


Q:

OPENACC function equivalent to CUDA's cudaError_t cudaMemGetInfo

I would like to know the size of the available memory at certain point of the program at runtime. I was wondering if OpenACC has any functions equivalent to CUDA's cudaMemGetInfo().

A:

The OpenACC standard doesn't have this but PGI does have an OpenACC extension API call you can use.  "acc_get_free_memory" will return the amount of free memory on the device while "acc_get_memory" will return the amount of total memory.  Include "accel.h" which is where PGI has the prototypes for it's OpenACC extensions.  Both return an unsigned long.
While I haven't tried myself, you might be able to call "cudaMemGetInfo" directly as well.


Q:

How to get boolean type return from OrientationEventListener?

I have a problem to solve in Android Studio, but I'm pretty new in it. I have to create a variable that increments all the time when onResume() method is called, but if the orientation is changed the variable must not be incremented.
I wanted to solve this with an if-else statement inside the onResume() method (that increments the variable if the OrientationEventListener returns false, and doesn't effect the variable if the orientation changed(true)), and with toasts to write out the value of the variable. But, I don't know how to get boolean type return from it, even though I searched for the answer for hours.
There were similar problems, but I couldn't implement their soultions with success. Here is my code if it helps:
public class MainActivity extends Activity {
    public static final String MY_TAG = "tagged";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void mOrientationListener = new OrientationEventListener(this SensorManager.SENSOR_DELAY_NORMAL) {
        @Override
        public void onOrientationChanged(int orientation) {

        }
    };

    public void onResume() {
        super.onResume();
        setContentView(R.layout.activity_main);
        int sum = 0;
        int ak = int onOrientationChanged;
        if ( != 0) {
            Log.i(MY_TAG, "onResume");
            tToast("onResume:");
            sum++;
            nToast(sum);
        }else {
            nToast(sum);
        }
    }
    private void tToast(String s) {
        Context context = getApplicationContext();
        int duration = Toast.LENGTH_SHORT;
        Toast toast = Toast.makeText(context, s, duration);
        toast.show();
    }
    private void nToast(Integer a) {
        Context context = getApplicationContext();
        int duration = Toast.LENGTH_SHORT;
        Toast toast = Toast.makeText(context, a, duration);
        toast.show();
    }
}

A:

OrientationEventListener is used when you need to know the precise orientation of the device's rotation in degrees (from 0 to 359). I assume that you're talking about orientation in the landscape/portrait sense, so OrientationEventListener isn't really the right way to solve this.
I think the best thing to do would be to check the orientation in onCreate() each time, and compare that with the previous orientation to set a flag didChangeOrientation or something like that, and then you could use this flag in your onResume() operations.
private int orientation;
private boolean didChangeOrientation;

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt("orientation", orientation);
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    orientation = getResources().getConfiguration().orientation;

    if (savedInstanceState != null) {
        int previousOrientation = savedInstanceState.getInt("orientation");
        didChangeOrientation = (orientation != previousOrientation);
    }
    else {
        didChangeOrientation = false;
    }

    ...
}

@Override
public void onResume() {
    super.onResume();

    if (!didChangeOrientation) {
        // your code here
    }
}


Q:

Remove Element from Object list using JavaScript

How can I remove an element from an object list?
I wish to remove the element Kristian from someList. For example:
someList = {"Kristian":"2,5,10",
             "John":"1,19,26,96"};

I want to achieve:
someList = {"John":"1,19,26,96"};

This is similar to Remove Object from Array using JavaScript, but it's implemented differently and the solutions does not work.

A:

You're looking for the delete operator. You can use like so:

const someList = {
  "Kristian": "2,5,10",
  "John": "1,19,26,96"
};

delete someList["Kristian"];
// OR: delete someList.Kristian;

console.log(someList);


Q:

Whose logon is being used in a SQL Server 2008 Agent Job

I have an SSIS package that transfers some tables to CSV files on a network drive; it runs fine from my computer manually. I store it on the server in the MSDB database and execute it from there and it runs fine, but when I create a job that has one step that runs the SSIS package from MSDB it fails saying it can't find the CSV file name.
I spent all day yesterday figuring out this means a permissions issue with whatever logon credentials are being used through the job. The job owner shows to be domain/myuserid and step properties show they are using windows authentication with my username. The problem is, I know I have access to this folder.
The first line of the error log says: "Executed as user: servername\SYSTEM". So I made sure user "SYSTEM" has access to the network folder I want to load the files on, but I still get the same error.
The command line looks like @command=N'/SQL "\SSIS package name" /SERVER servername /CHECKPOINTING OFF /REPORTING E'
edit: I found SQL Server agent job account issue where someone asks who the job is run under and marc_s says "I can't seem to find any definitive answers on that one, really. Since my Jobs typically select and update stuff in the database, I am lead to assume that the "Owner" account will be used by default, unless you specify some other account on a given step"
Which also leads me to believe it is using my logon information that has access

A:

The best practice that we've been able to come up with here is to make a domain account for SSIS and then set up a Proxy in SQL Server that is used to run the SSIS Package in a SQL Job.


Q:

Is '[]' a valid regular expression in Perl?

[ [ 'or', [ 'ar', 1, undef, ['v'] ], ['v'] ] ]

What does this mean? Either in Perl or Perl regular expression? What does it try to pass? Is this valid? I thought [] can only be characters in them for a regular expression.

A:

It doesn't have anything to do with regular expressions in this context. It creates an arrayref that contains other arrayrefs--in other words, a complex datastructure. You could store this in a scalar:
my $foo = [ [ 'or', [ 'ar', 1, undef, ['v'] ], ['v'] ] ];

And print some things out:
say $$foo[0][0];       # "or"
say $$foo[0][1][0];    # "ar"
say $$foo[0][1][3][0]; # "v"


Q:

Re-creating a filesystem on runtime (need more inodes)

I have a machine at a datacenter with 3HDDs and running Debian Wheezy, at one of them I have an ext4 filesystem mounted on /data that has ran out of inodes (I've chosen an inappropriate inode size at install/had more tiny files than expected).
There's no problem in copying the partition content to another one, but I want to know which preventive measures should I have to do this process in a "production environment" (nothing serious btw).
I need to avoid rebooting the machine and make the new filesystem -recreated- mountable at boot
Thanks!
-Rodrigo

A:

If you cannot add/replace disks (in which case, if you used LVM, you could grow your ext4 and hence number of inodes on it), you best path is:

backup data to some other partition having enough free space (using tar(1), or if you need to minimize downtime for accessing data: rsync(1))
this step only if you need to minimize downtime: rsync again, then shutdown access to that partition, do rsync again (which will now be fast, as it only transfers changes), and point/symlink your data directory to new partition directory, and then reenable access to new (temporary) partition directory.
reformat the now unused partition with more inodes
restore data back (using same tricks from (2) if you needed to minimize downtime)
remove temporary .tar.gz/rsync directory (or keep it as free backup)

In production, you'll be using LVM so you can resize your filesystems (ext4 will also grow inodes on resize). And you would always err on the side on too much inodes (or space in general), not too little. And/or using XFS which have dynamic inodes  instead of ext4.


Q:

PHP: strip_tags - remove only certain tags (and their contents)?

I use the strip_tags() function but I need to remove some tags (and all of their contents).
for example :

    Test A

    Test B

    Test C

Let's say, I need to get rid of the P and SPAN tags, and only keep :

    Test C

strip_tags expects as a second parameter the tags that you want to KEEP.
In this particular example I could use striptags($html, "
");
but the html I'm scraping and the tags that need to be removed are different all the time.
I searched for hours for a function that suits my needs, but couldn't find anything useful.
Any idea's?

A:

Use a regular expression. Something like this should work:
$tags = array( 'p', 'span');
$text = preg_replace( '#<(' . implode( '|', $tags) . ')>.*?<\/$1>#s', '', $text);

The demo shows it replacing the desired tags with nothing.
Note that you may need to tweak it more, say, to compensate for whitespace within the tags, or other unknowns that your example does not demonstrate.
Here is the regex to use to capture tags with or without attributes:
'#<(' . implode( '|', $tags) . ')(?:[^>]+)?>.*?<\/$1>#s'


Q:

Xamarin Forms Listview: Deselecting selected item by checking with OnTapped Event

I will be able to deselect my item when i click second time on it.
When I tap an item the background color changed to blue. I want that the background gets the default color when I tap second time to the same item from the list.
Here can you find my code but it isn't working.
XAML
<StackLayout Margin="5,0,5,0" HorizontalOptions="FillAndExpand" VerticalOptions="CenterAndExpand">
    <Frame Style="{StaticResource StandardFrameStyle}" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
      <ListView x:Name="lst_pickList" ItemSelected="OnItemSelected" ItemTapped="OnItemTapped" ItemsSource="{Binding PickList}" HasUnevenRows="True" Style="{StaticResource StandardListViewStyle}">
        <ListView.ItemTemplate>
          <DataTemplate>
            <ViewCell>
              <ViewCell.View>
                <Grid x:Name="grd_pickList" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" >
                  <Grid.RowDefinitions>
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="Auto" />
                  </Grid.RowDefinitions>
                  <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*" />
                    <ColumnDefinition Width="*" />
                    <ColumnDefinition Width="*" />
                    <ColumnDefinition Width="*" />
                  </Grid.ColumnDefinitions>

                  <Label x:Name="lbl_comment" Text="Comment:" FontAttributes="Bold" Grid.Row="0" Grid.Column="0" VerticalTextAlignment="Center" Style="{StaticResource StandardLabelStyle}" />
                  <Label x:Name="lbl_itemNo" Text="ItemNo:" FontAttributes="Bold" Grid.Row="0" Grid.Column="2" VerticalTextAlignment="Center" Style="{StaticResource StandardLabelStyle}" />
                  <Label x:Name="lbl_description" Text="Description:" FontAttributes="Bold" Grid.Row="1" Grid.Column="0" VerticalTextAlignment="Center" Style="{StaticResource StandardLabelStyle}" />
                  <Label x:Name="lbl_restant" Text="Restant:" FontAttributes="Bold" Grid.Row="1" Grid.Column="2" VerticalTextAlignment="Center" Style="{StaticResource StandardLabelStyle}" />

                  <Label x:Name="lbl_comment_binding" Text="{Binding Comment}" Grid.Row="0" Grid.Column="1" VerticalTextAlignment="Center" Style="{StaticResource StandardLabelStyle}" />
                  <Label x:Name="lbl_itemNo_binding" Text="{Binding ItemNo}" Grid.Row="0" Grid.Column="3" VerticalTextAlignment="Center" Style="{StaticResource StandardLabelStyle}" />
                  <Label x:Name="lbl_description_binding" Text="{Binding Description}" Grid.Row="1" Grid.Column="1" VerticalTextAlignment="Center" Style="{StaticResource StandardLabelStyle}" />
                  <Label x:Name="lbl_restant_binding" Text="{Binding Restant}" Grid.Row="1" Grid.Column="3" VerticalTextAlignment="Center" Style="{StaticResource StandardLabelStyle}" />
                </Grid>
              </ViewCell.View>
            </ViewCell>
          </DataTemplate>
        </ListView.ItemTemplate>
      </ListView>
    </Frame>
  </StackLayout>

CodeBehind
public void OnItemTapped(object sender, ItemTappedEventArgs args)
    {
        var newSelectedPick = args.Item as Pick;

        if(selectedPick != null && selectedPick.Id == newSelectedPick.Id)
        {
            lst_pickList.SelectedItem = null;
        }
        else
        {
            selectedPick = newSelectedPick;
        }
    }

A:

Create a boolean property on your Pick object named IsSelected ,then Bind it your grd_pickList's BackgroundColor with a converter.
i.e:
//Xaml
<ListView.Resources>
  <ResourceDictionary>
    <local:BgConverter x:Key="BgConverter"/>
  </ResourceDictionary>
</ListView.Resources>

<Grid x:Name="grd_pickList" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" BackgroundColor="{Binding IsSelected,Converter={StaticResource BgConverter}}" >

//Converter
class BgConverter : IValueConverter
{

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is bool &&(bool)value)
            return Color.Blue;
         else
            return Color.White;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

//Xaml.cs
public void OnItemTapped(object sender, ItemTappedEventArgs args)
{
    var itm = args.Item as Pick;
    itm.IsSelected = !itm.IsSelected;
}

Important: Be Sure IsSelected Property Triggers OnPropertyChanged event.


Q:

What does "DWELLERS" mean?

When I look into upgrading certain rooms, there is a table that shows "Dwellers", then states a CURRENT number and an UPGRADED number.

What are those numbers counting? The amount of dwellers that can work in that room?

A:

Dwellers in this instance is the number of vault dwellers that room increments your maximum vault dweller capacity by. For example if you have a maximum dwellers capacity of 10 and upgrading a room will add another 4, after upgrading the room you will have a maximum dweller capacity of 14.
Dwellers will only be stated on living quarters as the other rooms provide alternate resources (such as water or power) and will thus show these statistics when you open the room upgrade screen.


Q:

HTML Form Validation upon returned error

I am wondering if there is a certain way to validate a HTML form upon an error being returned. For instance, I have a form where the user can input their string which is then used to query data to do with that string.
Ideally, I would like a way for the form to be validated if the user inputs the string wrong i.e. with capitals or spelling mistakes. But I think that could only be realized once the system has tried to get the data responding to that string.
I hope Stack Overflow is an appropriate place to ask this.. after looking around in the hopes to find an answer to my question I can't seem to find a valid way to approach this.
Is there a way in HTML to validate the form in the event that an error is returned?
Apologies if this is obvious, I am quite new to the concept of validating forms.
Thanks in advance.

A:

https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Form_validation
What you're looking for is actually new technology AFAIK. Once upon a time, you needed to use a scripting language, i.e. JavaScript to do something like this. But it turns out you can actually add regular expressions, ranges of values, ranges of lengths, and more straight into your HTML for each input, and the browser will do all the work for you.
An example from the MDN source above
<form>
  <label for="choose">Would you prefer a banana or a cherry?</label>
  <input id="choose" name="i_like" required pattern="banana|cherry" />

  <button>Submit</button>
</form>

Where your input is required, and it must match exactly either banana or cherry. The browser will handle the process of informing the user their input hasn't worked and prevent you from submitting to the server.
Here's a live example I made out of the above code block: https://codepen.io/anon/pen/zjdrbV
Sometimes, though, you might need to validate an input that requires more than what the HTML validation can provide.
In that case, you'll just have to write a little JavaScript. Here's a good example of that: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation under section Limiting the size of a file before its upload. There's tons of resources on that sort of thing, and most likely you'll be able to find plenty of help for virtually any input you need to validate.


Q:

C# - Add values from list in a fluent interface

I am the following code:
var token = new JwtBuilder()
    .WithAlgorithm(new HMACSHA256Algorithm())
    .WithSecret(_Signature)
    .AddClaim("test", 3)
    .Build();

I would like to add multiple values (called 'claims' here):
    .AddClaim("test", 3)
    .AddClaim("test2", 4)
    .AddClaim("test3", 5)

If I have a dictionary:
    Dictionary<string, int> myDictionary;

how can I write the expression so all the values from the dictionary are added? (pseudo code: AddClaim(myDictionary)).
Edit:
I'm looking for a method that fits the 'fluent' flow and not an external loop.

A:

It's not entirely clear what you're asking. If you want a method that's in the API you're using, then that's up to the implementors of the API. E.g. maybe you're using Jwt.Net here, you'd have to have something like that added if you want that feature "out-of-the-box".
Otherwise, you can't get out of writing the loop yourself. But, what you can do is encapsulate the loop in an extension method:
static class JwtExtensions
{
    public static JwtBuilder AddClaims<TKey, TValue>(this JwtBuilder builder, Dictionary<TKey, TValue> dictionary)
    {
        foreach (var kvp in dictionary)
        {
            builder.AddClaim(kvp.Key, kvp.Value);
        }

        return builder;
    }
}

Then you can write something like this:
var token = new JwtBuilder()
    .WithAlgorithm(new HMACSHA256Algorithm())
    .WithSecret(_Signature)
    .AddClaims(myDictionary)
    .Build();


Q:

Linux kill process by cmdline (multiple with same name)

I am writing a bash-file (.command @OS X) to easily update a program at my remote server (Linux). I am stuck trying to figure out which PID to kill. I have different processes with the same name, which is mono, since they are executed by mono.
Using pgrep mono I get all the PIDs using mono, however, I only want to kill the process that has the command line SCREEN -dmSL steambot mono SteamBot.exe.
How do I know what PID to kill? Atm, my .command file looks like this:
ssh xxx@xxxx.com
pgrep mono

I am using ssh-keychain to login also.

A:

like this:
ps -ef | grep '[S]CREEN -dmSL steambot mono SteamBot\.exe' |
  awk '{print $2}' | xargs -r kill


Q:

Embedding a PDF in Firefox

I'm trying to embed a PDF and make it scrollable in Firefox (bonus points for the ability to zoom in/out, but right now I'd just be happy with a simple functional solution).
Basically my code is as follows:

        <button onclick = "history.go(-1);" class="pull-right btn btn-primary" type="submit">Go Back</button>

However, I noticed on Firefox that it simply prompts me to download the PDF file rather than embed it. Meanwhile, my users say it embeds in their browser, but it's sized very small.
How do I make it embed full-screen in Firefox?
On Safari/Chrome, it's fine. On iPad it only shows the first page of the PDF and it's not full-screen.

A:

The solution was that I added a height parameters in absolute pixels, rather than a percentage.


Q:

Installing Zend Framework GData on shared host

Been searching around Google for quite some time and cannot find any clear cut explanation of how to install and use Zend Gdata on a shared host.
I e-mailed my hosting company's support department and they told me that they cannot help with third party installs, pointing me in the direction of the INSTALL.txt that came with the framework. Unfortunately, that tells me to install the framework in my include_path, to which I do not have access.
I placed the framework in /public_html/includes/, which is where I store my third party scripts and such. When I try to access the YouTube Browser in the Demo, I get the following error:
Warning: require_once(Zend/Loader.php) [function.require-once]: failed to open stream: No such file or directory in /home/tappess1/public_html/includes/ZendGdata/demos/Zend/Gdata/YouTubeVideoBrowser/index.php on line 42

Fatal error: require_once() [function.require]: Failed opening required 'Zend/Loader.php' (include_path='.:/usr/lib/php:/usr/local/lib/php') in /home/tappess1/public_html/includes/ZendGdata/demos/Zend/Gdata/YouTubeVideoBrowser/index.php on line 42

I've seen mention of this being "stand-alone" but cannot seem to find any instructions on how to use it in that capacity. How does one use these features without placing the framework where it wants it to be - the include_path?
Thanks

A:

Depending on PHP's and your webserver's configurations you may be able to use an .htaccess file to override the setting using
php_flag include_path ".:/somewhere:/somewhere/else:/and/so/on"

You'll want to be sure that the normal include_path (get it from phpinfo(); ) is included or you'll break everything else.
Otherwise, you'll have to use set_include_path() at the top of every script before you use gdata.


Q:

mybatis @MapperScan not working

I'm trying to set up the Java config for MyBatis & the @MapperScan does not appear to be accomplishing anything.  Note, I can get the application to work with XML config.
What am I missing?  The com.test.mapper package definitely exists & has a file/iterface called TestMapper.  The corresponding xml is in the correct location in the resources folder.

*************************** APPLICATION FAILED TO START

Description:
Field templateMapper in
  com.test.TestController required a
  bean of type 'com.test.mapper.TestMapper' that
  could not be found.
Action:
Consider defining a bean of type
  'com.test.mapper.TestMapper' in your
  configuration.

Autowired that is failing
@Autowired
TestMapper _testMapper;

config
@Configuration
@MapperScan("com.test.mapper")
public class AppConfig {

   @Bean
   public DataSource dataSource() {

     SimpleDriverDataSource dataSource = new SimpleDriverDataSource();
     try {
       dataSource.setDriverClass(com.microsoft.sqlserver.jdbc.SQLServerDriver.class);
       //dataSource.setDriverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
       dataSource.setUrl("jdbc:sqlserver://server;databaseName=db1;integratedSecurity=true;");

     } catch (Exception e) {

     }
     return dataSource;
   }

   @Bean
   public DataSourceTransactionManager transactionManager() {
     return new DataSourceTransactionManager(dataSource());
   }

   @Bean
   public SqlSessionFactoryBean sqlSessionFactory() throws Exception {
     SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();

     sqlSessionFactoryBean.setTypeAliasesPackage("com.test.domain");

     sqlSessionFactoryBean.setDataSource(dataSource());
     return sqlSessionFactoryBean;
   }
}

A:

I solved this.  My issue wasn't with Mybatis.  It was with Spring.  This link to the Spring docs says to "...locate your main application class in a root package above other classes".
I had not done that.  Once I moved application class ( annotated with SpringBootApplication) then the @MapperScan annotation worked.


Q:

How to expose std::pair to python using boost::python?

How to expose std::pair to python using boost::python? When I expose for example vector<string> I simply write:
class_<std::vector<std::string> >("StringVec")
    .def(vector_indexing_suite<std::vector<std::string> >())
;

But I don't know how to deal with std::pair.

A:

I found a solution. The most simple example of exposing std::pair is:
class_<std::pair<int, int> >("IntPair")
    .def_readwrite("first", &std::pair<int, int>::first)
    .def_readwrite("second", &std::pair<int, int>::second);

A:

I'm using the following code to expose std::pair<> as Python tuples:
#include <boost/python.hpp>
namespace py = boost::python

template<typename T1, typename T2>
struct PairToPythonConverter {
    static PyObject* convert(const std::pair<T1, T2>& pair)
    {
        return py::incref(py::make_tuple(pair.first, pair.second).ptr());
    }
};

template<typename T1, typename T2>
struct PythonToPairConverter {
    PythonToPairConverter()
    {
        py::converter::registry::push_back(&convertible, &construct, py::type_id<std::pair<T1, T2> >());
    }
    static void* convertible(PyObject* obj)
    {
        if (!PyTuple_CheckExact(obj)) return 0;
        if (PyTuple_Size(obj) != 2) return 0;
        return obj;
    }
    static void construct(PyObject* obj, py::converter::rvalue_from_python_stage1_data* data)
    {
        py::tuple tuple(py::borrowed(obj));
        void* storage = ((py::converter::rvalue_from_python_storage<std::pair<T1, T2> >*) data)->storage.bytes;
        new (storage) std::pair<T1, T2>(py::extract<T1>(tuple[0]), py::extract<T2>(tuple[1]));
        data->convertible = storage;
    }
};

template<typename T1, typename T2>
struct py_pair {
    py::to_python_converter<std::pair<T1, T2>, PairToPythonConverter<T1, T2> > toPy;
    PythonToPairConverter<T1, T2> fromPy;
};

Within my main BOOST_PYTHON_MODULE(), I can then just use e.g. py_pair<int, int>(); to expose a pair of integers.


Q:

Possessive pronoun: Why "mein Auto", not "meinen Auto"?

Ich wasche mein Auto
Ich sehe meine Kinder
I get that meine is used for plural accusative form
But why is mein correct for first sentence? Shouldn't it be meinen instead?
I am learning using table in
https://www.deutsch-lernen.com/learn-german-online/beginners/lesson_6.php
I am not getting the difference between Possessivpronomen I and Possessivpronomen II
Please help.

A:

Here is a table with the correct forms of mein:
(Note that Auto is not male, not female, but neuter: das Auto)

You find similar tables for dein, sein, euer etc. here:
http://longua.org/possessivartikel-ubersicht.php

A:

The reason why "mein" is correct in your example is the 'gender' of the word "Auto". More specifically, "mein" is for words that have would have the "das" article, while "meine" is female and used for words that would have the "die" article. For words with the male "der" article, "meinen" would be used here.
The same is basically true in the plural form, except words in the plural form usually use the female article "die" (in fact, I can't think of an example where that's not the case).
More examples:

Ich wasche mein T-Shirt (das T-Shirt)
Ich putze mein Haus (das Haus)
Ich wasche mein Trinkglas (das Glas)
Ich sehe mein Kind (das Kind)
Ich sehe meine Kinder (die Kinder, plural)
Ich sehe meine Tochter (die Tochter)
Ich wasche meine Hose (die Hose)
Ich wasche meine Socken (die Socken, plural)
Ich wasche meine Mütze (die Mütze)
Ich putze meine Wohnung (die Wohnung)
Ich putze meinen Herd (der Herd)
Ich putze meinen XBox-Controller (der Controller)
Ich sehe meinen Sohn (der Sohn)
Ich sehe meinen Hund (der Hund)
Ich wasche meinen Pfannenwender (der Pfannenwender)


Q:

How to carry non-Acidic value in Happstack?

I've read Happstack crashcourse. My web server has almost exact way described in the section Passing multiple AcidState handles around transparently
Problem I have is that, I have value which is non-acidic, but want to access within the Happstack application. Specifically speaking, "PushManager" from push-notify-general library,
What I wanted is:
data Acid = Acid
   { acidCountState    :: AcidState CountState
  , acidGreetingState :: AcidState GreetingState
  , acidPushManager   :: AcidState PushManager
  }

I couldn't make this work, because 1) PushManager use so many data types internally, and it is not realistic/robust to make underlying data type SafeCopy compatible by calling $(deriveSafeCopy ...). 2) PushManager not only contains simple value, but also function which is SafeCopy compatible.
Other thing I tried is to "Acid" data declaration to carry not only AcidState, but also non-AcidState data. By looking at the definition of runApp, "Acid" is just used for Reading, so I thought that rewriting with State monad may be able to achive my need. - but it turns out that it was not so simple. My tentative code is:
{-# LANGUAGE MultiParamTypeClasses, GeneralizedNewtypeDeriving,
     TemplateHaskell, TypeFamilies, DeriveDataTypeable,
     FlexibleContexts, ScopedTypeVariables,
     NamedFieldPuns, DeriveFunctor, StandaloneDeriving, OverloadedStrings #-}

import Control.Applicative         ( Applicative, Alternative, (<$>))
import Control.Monad               ( MonadPlus )
import Control.Monad.State.Strict  ( MonadState, StateT, get, put,  evalStateT )
import Control.Monad.Trans         ( MonadIO )
import Data.Acid
import Data.Data                   ( Data, Typeable )

import Happstack.Server

newtype Simple a = Simple { unSimple :: a }
                   deriving (Show)

data CountState = CountState { count :: Integer }
    deriving (Eq, Ord, Data, Typeable, Show)

-- This data is equivalent to the one previously called "Acid"
data States = States {
  simpleState :: Simple Int
  , acidCountState :: AcidState CountState
  }

initialStates :: States
initialStates = States { simpleState = Simple 1, acidCountState = undefined }

newtype App a = App { unApp :: ServerPartT (StateT States IO) a }
    deriving ( Functor, Alternative, Applicative, Monad
             , MonadPlus, MonadIO, HasRqData, ServerMonad
             , WebMonad Response, FilterMonad Response
             , Happstack, MonadState States )

class HasSimple m st where
  getSimple :: m (Simple st)
  putSimple :: (Simple st) -> m ()

instance HasSimple App Int where
  getSimple = simpleState <$> get
  putSimple input = do
    whole <- get
    put $ whole {simpleState = input}

simpleQuery :: ( Functor m
               , HasSimple m a
               , MonadIO m
               , Show a
               ) =>
               m a
simpleQuery = do
  (Simple a) <- getSimple
  return a

simpleUpdate :: ( Functor m
                , HasSimple m a
                , MonadIO m
                , Show a
                ) =>
                a
                -> m ()
simpleUpdate a = putSimple (Simple a)

runApp :: States -> App a -> ServerPartT IO a
runApp states (App sp) = do
  mapServerPartT (flip evalStateT states) sp

rootDir :: App Response
rootDir = do
  intVal <- simpleQuery
  let newIntVal :: Int
      newIntVal = intVal + 1
  simpleUpdate newIntVal
  ok $ toResponse $ ("hello number:" ++ (show newIntVal))

main :: IO ()
main = do
  simpleHTTP nullConf $ runApp initialStates rootDir

It compiled, but every time web page is requested, the page display same number. Looking at my code again, and I felt that evalStateT in runApp is wrong, because it never use updated state value.
Now, I am reading mapServerPartT and ServerPartT, but that is too complex.
Appreciate if anybody can answer the title line: "How to carry non-Acidic value in Happstack?"

A:

The mapServerPartT would not help you either. The issue here is that the handler function you pass to simpleHTTP gets called in a new thread for each request that comes in. And each time it is going to be calling runApp with the initialStates argument. So not only is the value lost at the end of the request, but if multiple threads are handling requests, they will each have their own separate copy of the state.
Once we realize that we want state that is shared between multiple threads, we realize that the answer must rely on one of the tools for doing interthread communication. A good choice would probably be a TVar, http://hackage.haskell.org/package/stm-2.4.3/docs/Control-Concurrent-STM-TVar.html
main :: IO ()
main = do
  states <- atomically $ newTVar initialStates
  simpleHTTP nullConf $ runApp states rootDir

Note that we create the TVar before we start listening for incoming connections. We pass the TVar to all the request handling threads, and STM takes care of synchronizing the values between threads.
a TVar is a bit like acid-state without the (D)urability. Since the data does not need to be saved, there is no need for SafeCopy instances, etc.


Q:

How to make blurred side bar like as given below snapshot?

I tried many methods to get blur side menu bar but no correct way is found. I have been used picasso lib, Blurry lib and other methods.

A:

Either use the android:background property with alpha value.
OR
you can use this library to get a blurred nav drawer :

Blur Navigation Drawer

OR
you can try something like this


Q:

Advantage of using Swing over AWT

Why is Swing preferred over AWT?
Which Swing component could be used for playing a video on it?

A:

AWT is older than Swing and supports only a limited set of components. Otherwise you have to write your own such as tables/data grids for example (typically, you will have to write your own video player, good luck !). Swing is more "modern" as Sun engineers learned from their AWT mistakes and made something better, albeit more complex. Both Swing and AWT are event-based so if you know event-driven programming you will be at home. The learning curve is a bit steeper with Swing because of the larger number of available classes, though by practicing a bit with tutorials you should quickly be fine.
Check out this IBM presentation on SWT, Swing & AWT, it really is a good read. Also AWT vs Swing.
As to how you can play video on Java: https://stackoverflow.com/questions/4569490/how-to-play-video-in-java-using-swing

A:

AWT components are essentially a thin layer on top of native OS GUI controls. To draw for example a checkbox, AWT components were calling underlying OS. Such approach caused two problems:

the same app had a bit different GUI behaviour under different OS
overcoming known differences caused AWT code to be bloated and IIRC a bit buggy

Because of this connection between AWT component and underlying OS control AWT controls were called "heavyweight". In contrast Swing offers, so called "lightweight" controls. They are purely Java, have no dependency on underlying OS and basically "draw themselves" using Java2D primitives (pixels, lines, brushes and so on). This approach has several advantages but what is most important -- it fixes AWT outstanding problems mentioned above.
As for Swing component for video playing, I don't think there is one, at least among standard Swing components. You may want to google for one, as it probably is already written. You can also look at JMF API, but I think you'd have to code a few bits yourself before you can display video.


Q:

Is there an adverb for "example"?

Such as here

With a degree in humanities, you can "examply" be a museum curator,
  librarian, or teacher.

You have to assume those are the only choices listed, but not the only ones available. They are just example jobs.  So what is an adverb I can use where the quotation marks are?  (since examply isn't a word)

A:

To follow up on @1006a's comment, you could use any of the following:

With a degree in humanities, you can be, for example, a museum
  curator, librarian, or teacher.
With a degree in humanities, you can be, e.g., a museum curator,
  librarian, or teacher.
With a degree in humanities, you can be a museum curator, librarian,
  teacher, or pursue any number of other occupations.

Other possible occupations include lawyer, philosopher, and writer. I wouldn't sell the humanities short, not that you are.
There is not a single-word adverb that I am aware of  that conveys the meaning you're seeking.


Q:

VBA Out of Range

I am trying to create an archive workbook once a column (V) is marked as "Yes". I had the macro functioning but when I tested it again this afternoon I received the out of range error. I have checked the names of my workbook/worksheet and they are correct. I've tried to troubleshoot but now when I select "Yes" in column V, the macro doesn't register at all. What could be the issue? Below is what I have been using. (I'm brand new to VBA and am teaching myself, so any help is appreciated!)
Private Sub Worksheet_Change(ByVal Target As Range)
  If Target.Column = 22 Then
  If Target = "Yes" Then
Application.EnableEvents = False
  nxtRow = Workbooks("FPPE Archive.xlsm").Worksheets("EUHM Onboard").Range("V" & Rows.Count).End(xlUp).Row + 1
   Target.EntireRow.Copy _
    Destination:=Workbooks("FPPE Archive.xlsm").Worksheets("EUHM Onboard").Range("A" & nxtRow)
   Target.EntireRow.Delete
End If
End If
Application.EnableEvents = True
End Sub

A:

The reason it doesn't run is probably because during your testing you stopped the macro midway, and EnableEvents was not reset to True.


Q:

ObjectAssign transforms bool to object

I use Redux and I have problems with reducers.
isLoading: true - it's what I send in action.
isLoading: {} - it's what I get in props after reducer.
How to fix it?
I use it:
export function movieDiscoverIsLoading(state = false, action) {
    switch (action.type) {
        case MOVIES_DISCOVER_LOADING:
            return Object.assign({}, state, action.isLoading);
        default:
            return state;
    }
}

export function movieDiscoverItems(state = [], action) {
    switch (action.type) {
        case MOVIES_DISCOVER_RESULTS:
            return Object.assign({}, state, action.items);
        default:
            return state;
    }
}

Logs:

And additional question:
how can I change a few fields in copied object using Object.assign or spread operator?
When I tried something like that:
{ ...state, ...{items: action.items, isLoading: false}}
I've got nested object, where isLoading is inside of items.

A:

You mutate the initial state passed to reducer. Seems like you should return boolean instead of object
export function movieDiscoverIsLoading(state = false, action) {
    // it is already boolean           ^^^^^^^^^^^^^
    switch (action.type) {
        case MOVIES_DISCOVER_LOADING:
            // why do you return an object here instead of boolean
            return Object.assign({}, state, action.isLoading);
        default:
            return state;
    }
}

To fix it just replace:
return Object.assign({}, state, action.isLoading);

to
return action.isLoading;


Q:

JavaScript get attribution from select

Consider:
<select id="test">
   <option attribut="1">test 1</option>
   <option attribut="2">test 2</option>
   <option attribut="3">test 3</option>
   <option attribut="4">test 4</option>
   <option attribut="5">test 5</option>
</select>

I want to get the selected item's attribute. Is there any simple way to do it? The native JavaScript is fine.

A:

There's no attribut attribute defined on the option tag. This is not standard HTML. A more standard way is to use the value attribute:
<select id="test">
   <option value="1">test 1</option>
   <option value="2">test 2</option>
   <option value="3">test 3</option>
   <option value="4">test 4</option>
   <option value="5">test 5</option>
</select>

which allows you to do this:
var value = document.getElementById('test').value;
alert(value); // shows the selected value

A:

You should rename 'attribut' to 'value' in your HTML. You can however define you own attributes and read them too (if validation is of no concern, and for HTML5 you can prefix your custom attribute with 'data-').  Looks like:
<select id="test">
   <option value="1" data-attrib="five">test 1</option>
   <option value="2" data-attrib="four">test 2</option>
   <option value="3" data-attrib="three">test 3</option>
   <option value="4" data-attrib="two">test 4</option>
   <option value="5" data-attrib="one">test 5</option>
</select>

Now for this select you can get the option values and 'attrib' values with something like:
function getOpts(){
  var mySelect = document.getElementById('test')
      , opts = mySelect.options
      , results = ''
      , i=0
      , len = opts.length;
  while (i<len){
        results += opts[i].getAttribute('data-attrib')+'-'+
                   (opts[i].selected
                      ? 'selected value: '+opts[i].value
                      : opts[i].value)+'\n';
        i++;
  }
  return '\n'+results;
}

(If you also seek the text value of the option, you can append opts[i].firstChild.nodeValue to the results variable.)


Q:

How do I set a cursor css for text inside li element?

How do I set a cursor css for text inside li element?
The cursor is an arrow when only on the li, outside of any text inside. When i move it to the text it turns into a text cursor. I want the cursor to stay the same all the time.

A:

li {
    cursor:default;
}

jsFiddle example
You can see the various cursor options at https://developer.mozilla.org/en-US/docs/Web/CSS/cursor


Q:

How to jump from one activity to another and set a fragment

What i want is when i jump from one activity to another with intent it should also automatically set a fragment inside framelayout but i can't figure out how to do that any help will be appreciated.

A:

If I got your question correctly, this code should help you:
In your first activity put this code:
public static final String FRAGMENTA = "FragmentA";
public static final String FRAGMENTB = "FragmentB";
public static final String FRAGMENTC = "FragmentB";

String fragmentToDisplay = FRAGMENTA;
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
intent.putExtra("fragmentToDisplay", fragmentToDisplay);
startActivity(intent);

Then in your second activity in onCreate, receive the intent and set a fragment according to the string intent:
String fragmentToDisplay = getIntent.getStringExtra("fragmentToDisplay");
switch (fragmentToDisplay) {
    case FirstActivity.FRAGMENTA:
        //FragmentTransaction to show Fragment A
        break;
    case FirstActivity.FRAGMENTB:
        //FragmentTransaction to show Fragment B
        break;
    case FirstActivity.FRAGMENTC:
        //FragmentTransaction to show Fragment C
        break;
}


Q:

wget downloads only 5 bytes file

I've got the following issue - the wget command downloads only 5bytes of files on the remote server I need to access.
I know, that the files have 5MB and 1.3MB, so why after wget'ing them i receive only 5b empty files?
===EDIT===
root@app:# wget -c -v XXX.X.X.XXX:139/dbase/dispense.log
--2013-03-28 09:10:27--  http://XXX.X.X.XXX:139/dbase/dispense.log
Connecting to XXX.X.X.XXX:139... connected.
HTTP request sent, awaiting response... 200 No headers, assuming HTTP/0.9
Length: unspecified
Saving to: `dispense.log'

    [ <=>                                   ] 5           --.-K/s   in 0s

2013-03-28 09:10:27 (846 KB/s) - `dispense.log' saved [5]

A:

wget only supports HTTP, HTTPS and FTP protocols. You are using port 139 which is normally not a port such a protocol is run over.
If you're trying to download a file from a Samba/Windows network share, have a look at mount.cifs.


Q:

Getting the ID's of div tags

I have the following HTML snippet

 <input type="button" class="close_button">

 sub header goes here

 content goes here

 footer goes here

 <input type="button" class="close_button">

 sub header goes here

 content goes here

 footer goes here

 <input type="button" class="close_button">

 sub header goes here

 content goes here

 footer goes here

 <input type="button" class="close_button">

 sub header goes here

 content goes here

 footer goes here

How do I:

get the column id depending on which close button is clicked?  So if close_button is clicked which is in portlet-header_3, it should return column_2
get the portlet id depending on which close button is clicked?  So if close_button is clicked which is in portlet-header_1, it should return portlet_1

I have the following, but this returns the closest div, portlet-header_*, which is not what I am after:
$(".close_button").live('click', function(event) {
    event.preventDefault();

    var that = this;
    alert( $(that).closest("div").attr("id") )
});

A:

Try this (using jQuery .parents()):
$(".close_button").live('click', function(event) {
    event.preventDefault();
    var that = this;
    alert( $(that).parents("[id^=column_]").attr("id") )
});

Fiddle: http://jsfiddle.net/maniator/3EJBC/


Q:

How to resolve these errors

I have a program that adds 2 numbers in Java and outputs the sum. (The numbers are input through keyboard). However, I have an error that I need help resolving. I'll explain the error after the code:
package com.sigma.java7;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Addition {

    public static void main(String[] args) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    do {
        try {
           System.out.println("Enter A :");
           String numA = br.readLine();
           int a = Integer.parseInt(numA);
           break;
        } catch (Exception e) {
           System.out.println("Incorrect input. Please enter an integer.");
        }
    } while (true);
    do {
        try {
           System.out.println("Enter B :");
           String numB = br.readLine();
           int b = Integer.parseInt(numB);
           break;
        } catch (Exception e) {
           System.out.println("Incorrect input. Please enter an integer.");
        }
    } while (true);
    System.out.println("The sum of the numbers is: " +(a+b));
    br.close();
  }
}

In the line
"System.out.println("The sum of the numbers is: " +(a+b));"

I'm getting the errors: "a cannot be resolved to a variable and b cannot be resolved to a variable." WHY?

A:

You have bad variable scope. When you define local variables it will work only work in a same block. ex.
{
    int i = 2;
    {
       int k = 4;
       // i can be accessed here.
    }
    // i can be accessed here.
    // k can not be accessed here.
}

A:

Before you first do while loop add:
int a,b;

This will declare the variables to have scope outside of the loops so you can access them anywhere inside the method, instead of just a local loop. If you add this line of code, replace
int a  = Integer.parseInt(numA);

with:
a  = Integer.parseInt(numA);

and the same thing for b


Q:

How to get centriod coordinates of multiple points in binary image_matlab

Hi I need to find the centriod coordinates of each points (multiple points in one binary image).
When I use the code
  A=imread('dotfig.png');
  B=im2bw(A)
  [b,a]=find(B==0);

So, I get coordinates in terms of a,b for rows and cols. I got multiple a and multiple b (for 7 points in pic). Actually, I just would like to get seven a and seven b, which represent coordinates for centriods of seven dots in the pic. I know ginput might give me similar value. But dont' want to use manual input in my codes. Any suggestion is appreciated!

A:

just use regionprops:
 stats = regionprops(B,'Centroid')

Here's a detailed way in how to use it:
First I'll generate some random points
a=zeros(50);
a(ind2sub(size(a),randi(numel(a),7,1)))=1;
a=padarray(a,[10 10]);
a=conv2(a,fspecial('gaussian',7,1),'same');
b=a>0.02;
imagesc(b);

Then use regionprops:
stats = regionprops(b,'Centroid');

This is just to plot the various centroids:
hold on;
for n=1:numel(stats)
plot(stats(n).Centroid(1),stats(n).Centroid(2),'rx'); hold on
text(stats(n).Centroid(1)-4,stats(n).Centroid(2)-4,...
     ['x=' num2str(stats(n).Centroid(1)) ', y=' num2str(stats(n).Centroid(2))],'Color','w' );
end


Q:

SQL Server : how to select top 2 records of the same group?

I'm using SQL Server 2008. I have a problem where I need to get the top 2 records in a group determined by 2 columns Code and Period, that will then be inserted to another table.
Here is a sample table:
Code  |  Period  |  Dept  | DeptWorkPartSum
001      2013-11    D1      53
001      2013-11    D2      33
001      2013-11    D3      12
002      2013-11    D2      30
002      2013-11    D4      28
002      2013-11    D5      15
002      2013-12    D2      100

And what I want to get out of it is:
Code  |  Period  |  Dept  | DeptWorkPartSum
001      2013-11    D1      53
001      2013-11    D2      33
002      2013-11    D2      30
002      2013-11    D4      28
002      2013-12    D2      100

It is probably a very simple solution but I can't figure it out at the moment.

A:

A simple approach is using a CTE with ROW_NUMBER ranking function:
WITH CTE AS
(
    SELECT Code,Period,Dept,DeptWorkPartSum,
           RN = ROW_NUMBER() OVER (PARTITION BY Code,Period, Dept
                                   ORDER BY DeptWorkPartSum)
    FROM dbo.TableName
)
SELECT Code,Period,Dept,DeptWorkPartSum
FROM CTE
WHERE RN <= 2

Demo
However, your desired result seems to be incorrect since Dept is different for all three codes.
Maybe you don't want to group by Dept but order by it, then the result is correct:
WITH CTE AS
(
    SELECT Code,Period,Dept,DeptWorkPartSum,
           RN = ROW_NUMBER() OVER (PARTITION BY Code,Period
                                   ORDER BY Dept, DeptWorkPartSum)
    FROM dbo.TableName
)
SELECT Code,Period,Dept,DeptWorkPartSum
FROM CTE
WHERE RN <= 2

Demo


Q:

Web application to sync data with Android phone application

I already know quite a few tricks with Android java and I have an application that I need to sync with a web application. What it needs to be doing is connect to a server and sync database and download jpg picture uploaded by user. The web application should also be for more users each with his own phone and Android application in it, so it should probably be accesable via login and password.
My problem is that I have zero experience with web applications. All I know is a little HTML. So my question is, how should I start? What language do I use? And what basic structure or principle should my web application have?
Thank you!

A:

I would recommend a PHP - MySQL solution. PHP and MySQL are open source and I know Java can interface with that kind of database. Both languages are well documented and PHP is similar to Java in that it is C-based, so if you know Java fairly well, PHP should be relatively straightforward for you. I would recommend heading over to Lynda.com and searching for PHP Essential Training with Kevin Skoglund. Lynda is a great online video tutorial site and you can access a good amount of the content for free. But if you're serious about developing this web application, I would make the investment (I was, and I did, and I am glad). That's how I learned PHP / MySQL for the most part.
First off, to do any PHP / MySQL development, you'll need to install a server onto your computer, such as WAMP (Windows Apache MySQL PHP - for windows), MAMP (Mac " " - for mac), or LAMP (Linux " " - for Linux), where you will be able to begin developing your application. This is your "test" server, or "development" server. For instance, I use MAMP since I am on a Mac. MAMP is free, as are the other versions, but you can pay for an upgrade. For your purposes, start with the free version. Essentially, *AMP comes with the Apache Server software, MySQL database installation, and PHP installation pre-packaged and ready to go with minimal configuration. From there, you can start writing PHP and MySQL and get your project rolling.
As a matter of fact, that title at Lynda.com, PHP Essential Training, will walk you through ALL of the steps I just stated, AND, uses an exercise project of setting up a basic Content Management System to include password protection, user login and authentication, as well as all of the essential PHP and MySQL that you'll need to go along with it. Seriously, check out Lynda.com.
Good Luck!


Q:

Are the groups $\mathbb{C}$ and $\mathbb{R}^2$ isomorphic under addition?

Are the groups $\mathbb{C}$ and $\mathbb{R}^2$ isomorphic under addition?

A:

Yes. Under the usual definition of $(\mathbb{C},+)$, they are isomorphic by definition. That's because the usual definition is:

$\mathbb{C}=\mathbb{R}^2$;
the addition in $\mathbb C$ is the same as in $\mathbb{R}^2$.


Q:

How do I install the vivaldi browser?

I am new to ubuntu world...

How to install vivaldi browser on ubuntu?
How could we find dependencies, when installing any software on ubuntu?

A:

You can  install the Vivaldi web browser from its repository so it can be updated with apt-get commands
echo "echo deb http://repo.vivaldi.com/stable/deb/ stable main > /etc/apt/sources.list.d/vivaldi.list" | sudo sh
curl http://repo.vivaldi.com/stable/linux_signing_key.pub | sudo apt-key add -
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 1397BC53640DB551
sudo apt-get update
sudo apt-get install vivaldi-stable

A:

Vivaldi can be downloaded from its official site.  The package dowloaded is .deb type, so you can use dpkg -I /path/to/vivaldi*.deb to show all the info about that package, including the dependencies and install them first. Then use sudo dpkg -i /path/to/vivaldi*.deb to install the browser itself


Q:

Magento 2 - Custom contact form not showing up

How would I create a secondary contact form in Magento 2.2? I'd like it to have the following fields:

Name
Phone
Email
Checkbox 1
Checkbox 2
Submit button

I have tried following this thread which does something similar, but couldn't get the module to display anything other than a 404 page: Create Custom Form in Magento2 Frontend
Here's the code I have used based on the above example:

app/code/Company/Module/etc/frontend/routes.xml

<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route id="companymodule" frontName="companymodule">
            <module name="Company_Module"/>
        </route>
    </router>
</config>

app/code/Company/Module/view/frontend/layout/module_index_booking.xml

<?xml version="1.0"?>
<page layout="2columns-left" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">

        <title>HTML title - The booking form page</title>

        <referenceBlock name="navigation.sections" remove="true" />
        <referenceContainer name="content">
            <block class="Company\Module\Block\Booking" name="companymodule.booking" template="Company_Module::booking.phtml"/>
        </referenceContainer>

</page>

app/code/Company/Module/Block/Booking.php

<?php

namespace Company\Module\Block;

class Booking extends \Magento\Framework\View\Element\Template
{
    /**
     * Construct
     *
     * @param \Magento\Framework\View\Element\Template\Context $context
     * @param array $data
     */
    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
         array $data = []
    )
    {
        parent::__construct($context, $data);
       }

    /**
     * Get form action URL for POST booking request
     *
     * @return string
     */
    public function getFormAction()
    {
            // companymodule is given in routes.xml
            // controller_name is folder name inside controller folder
            // action is php file name inside above controller_name folder

        return '/companymodule/index/booking';
        // here controller_name is index, action is booking
     }
}

app/code/Company/Module/view/frontend/templates/booking.phtml

Booking page

<form action="<?php echo $block->getFormAction() ?>" method="post">
    <input name="firstname" type="text">
    <input name="lastname" type="text">
    <input name="phone" type="text">
    <input name="bookingTime" type="date">
    <input type="submit" value="Send booking informations">
</form>

app/code/Company/Module/Controller/Index/Booking.php

<?php

namespace Company\Module\Controller\Index;

use Magento\Framework\Controller\ResultFactory;

class Booking extends \Magento\Framework\App\Action\Action
{
    /**
     * Booking action
     *
     * @return void
     */
    public function execute()
    {
        // 1. POST request : Get booking data
        $post = (array) $this->getRequest()->getPost();

        if (!empty($post)) {
            // Retrieve your form data
            $firstname   = $post['firstname'];
            $lastname    = $post['lastname'];
            $phone       = $post['phone'];
            $bookingTime = $post['bookingTime'];

            // Doing-something with...

            // Display the succes form validation message
            $this->messageManager->addSuccessMessage('Booking done !');

            // Redirect to your form page (or anywhere you want...)
            $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
            $resultRedirect->setUrl('/companymodule/index/booking');

            return $resultRedirect;
        }
        // 2. GET request : Render the booking page
        $this->_view->loadLayout();
        $this->_view->renderLayout();
    }
}

I ran the following commands:
php bin/magento setup:upgrade
php bin/magento setup:di:compile
php bin/magento cache:flush

But I cannot get the frontend to show when going to .../companymodule/index/booking or .../module/index/booking
EDIT:
Big part of this issue was me not having Company/Module/registration.php and Company/Module/etc/module.xml file in place.

A:

Please change the :

app/code/Company/Module/view/frontend/layout/module_index_booking.xml

to:

app/code/Company/Module/view/frontend/layout/companymodule_index_booking.xml

Update:
app/code/Company/Module/Controller/Index/Booking.php
<?php

namespace Company\Module\Controller\Index;

use Magento\Framework\Controller\ResultFactory;

class Booking extends \Magento\Framework\App\Action\Action
{

    //add contructor
    protected $_resultPageFactory;

    public function __construct(
         Context $context,
         \Magento\Framework\View\Result\PageFactory $resultPageFactory
    )
    {
    $this->_resultPageFactory = $resultPageFactory;
    parent::__construct($context);
    }
    /**
     * Booking action
     *
     * @return void
     */
    public function execute()
    {
        // 1. POST request : Get booking data
        $post = (array) $this->getRequest()->getPost();

        if (!empty($post)) {
            // Retrieve your form data
            $firstname   = $post['firstname'];
            $lastname    = $post['lastname'];
            $phone       = $post['phone'];
            $bookingTime = $post['bookingTime'];

            // Doing-something with...

            // Display the succes form validation message
            $this->messageManager->addSuccessMessage('Booking done !');

            // Redirect to your form page (or anywhere you want...)
            $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
            $resultRedirect->setUrl('/companymodule/index/booking');

            return $resultRedirect;
        }
        // 2. GET request : Render the booking page
        $this->_view->loadLayout();
        $this->_view->renderLayout();
    }
}


Q:

Can I use my Windows 7 laptop without any video drivers installed?

For the past two days I've been grappling with an annoying white screen issue that happened whenever I did anything or even at boot, but never at random times.
It's possible that it was the video drivers' fault because after uninstalling and rebooting it hasn't happened yet. Unfortunately, I have no idea if I can continue using this PC or will it cause problems? E.g. can games be played at all? I sense that the framerate is a bit choppy, especially when watching videos.
Sidenote: The versions of the video drivers I used were two different ones, one from some time ago, and the latest one, and I had the same problem with both. Also formatting didn't help, after installing the AMD drivers it started happening again. Do alternatives for drivers exist?
Specs: Windows 7 HP 4520s Laptop, the drivers were these I think:
http://support.amd.com/en-us/kb-articles/Pages/AMDCatalyst15-7-1WINReleaseNotes.aspx

A:

You can run it "without" drivers, although you are using either the standard VGA drivers, or some other Microsoft display drivers. You will definitely run into sub-standard performance issues though since the drivers are not optimized to utilize the video chipset.
OEM's sometimes modify chipset implementation from standards issued by the video chipset manufacturer when used in laptops, that is why most video chipset manufacturers suggest using the drivers provided by the laptop manufacturer vs using their drivers. I would suggest visiting the HP Download page for your product here and select your language and Operating System, then use the recommended AMD drivers issued by HP.


Q:

Ошибка при авторизации SQL Server

В чем может быть проблема?
Текст ошибки:

Подключение к серверу успешно установлено, но затем произошла ошибка при входе. (provider: Shared Memory Provider, error: 0 - С обоих концов канала отсутствуют процессы.) (.Net SqlClient Data Provider)

Использую SQL Server Management Studio 2014.
Пароль ввожу верно.

A:

В настройках SQL Server в пункте Сетевых соединение есть служба Named Pipes , ее надо включить


Q:

How do I get this heatmap on R to not normalise my data?

I'm trying to display some data on heatmap in R comparing expression levels across cyclin types & body parts. If you look at the data below you can see that the expression of cyclin A1 in the brain is the same as cyclin A2 in the brain.
However, when we look at the heatmap they are displayed as different colours. I've tried normalising the data using the scale argument by column (default seems to be row) but that just results in any data without a difference in variance coming out as blank (e.g. brain cyclin A1 & A2 would be displayed as white despite their being expression).
I've attached my code below for a different organism (but the same code was used)- how is it best to fix this?
 #Anolis carelinensis Cyclin A
    #importing data- Anolis carelinensis
    AnolisA<-read.csv(file.choose(),header=TRUE)
    #all data in the matrix must be numerical
    #therefore I need to remove the left column
    AnolisA2<-AnolisA[-grep('X', colnames(AnolisA))]
    #converting dataframe to a matrix
    AnolisA3<-as.matrix(AnolisA2)
    #builting the heatmap
    heatmap(AnolisA3)
    #remove dendogram and reordering of columns/rows
    #no scale argument applied because we are interested in the variation
    #between both organs and cyclin types
    heatmap(AnolisA3, Colv=NA, Rowv=NA)
    #adding axis labels
    heatmap(AnolisA3, Colv=NA, Rowv=NA, xlab="Organ", ylab="Cyclin")
    #creating a vector for column names
    rowname<-c("A1","A2")
    #altering labels
    #labRow- change row names
    rownames(AnolisA3)<-rowname
    #cexCol- alters column text size
    heatmap(AnolisA3, Colv=NA, Rowv=NA, xlab="Organ", ylab="Cyclin",cexCol=1,cexRow=1.5,margins=c(11,4))

A:

You were on the right track with the scale= argument. I think this is what you're looking for with scale="none".
library(tidyverse)
df <- tribble(
  ~brain, ~heart, ~kidney, ~liver, ~skeletal,
  1, 0, 0, 0, 0,
  1, 1, 1, 0, 0
)
mat <- as.matrix(df, nrow = 2, ncol = 5)
rownames(mat) <- c("A1", "A2")
heatmap(mat, Colv=NA, Rowv=NA, xlab="Organ", ylab="Cyclin",
        scale = "none", cexCol=1,cexRow=1.5,margins=c(11,4))

Created on 2019-11-23 by the reprex package (v0.3.0)


Q:

Unable to display Ajax data in table

I am having a web page with two drop down menu, Search button and a table, the table is grabbing information on load using jquery. On loading the table grabs information fine. But when I use drop down menus and search button to update this table, it does not work, How ever the information is there in response console. Here is my code
HTML Code

Jquery for load table
$(document).ready(function(){
    $.ajax({
        url: 'folder/list.php',
        success: function (data) {
            $('#table').html(data);
        },
        error: function(){
            alert('Error: Unable to display');
        }
    });

});
Jquery for search
$(document).on('click', '#cont-search', function(event) {
event.preventDefault();
var cate = $('#cat-search').val();
var city = $('#city-search').val(); //Important

$.ajax({
        url: 'folder/list.php',
        type: 'post',
        dataType: 'json',
        data: {
                cate:cate,
                city:city,
            },
        success: function (data) {
            $('#table').html(data);
        },
        error: function(){
            alert('Error: Unable to display Search');
        }
    });});

PHP CODE
require_once('abc/Item.php');

$cat = $_POST['cate'];
$city = $_POST['city'];

$ser_cont = $item->search_cont($cat,$city);?>

                S.No.
                Category
                R No.
                Name
                City

            <?php
            $sno = 1;
            foreach($ser_cont as $c): ?>

                    <?= $sno++; ?>
                    <?= $c['cate']; ?>
                    <?= $c['registno']; ?>
                    <?= $c['name']; ?>
                    <?= $c['dist']; ?>

            <?php endforeach; ?>

A:

I Solved the issue as it was not a json return so I just removed
dataType: 'json',

from my code and it worked, Thanks to every one for the comments


Q:

Codeigniter 3.x Authentication Library?

With the new Codeigniter 3.0 version what authentication libraries do you use?

Flexi auth was very good and robust with great documentation for CI 2.0 but it is old and as I can see it is discontinued. Of course it does not work out of the box with CI 3.0. I have tested it and tried to migrate it to CI 3.0 but as it uses the old ci_sessions schema I have seen that it has a lot work to be made to rewrite all the code parts that use sessions. It seems to work with file sessions and some alterations on its code though.
Community auth has a CI 3.0 version but as I have seen, it has many bugs and it is nowhere near reliable at this time. I have tested it thoroughly and it cannot work properly as it has problems with its token jar system and its cookie management. Users cannot login most of the times and it is being used as a whole third-party library at Codeigniter, which personally I don't like as it has a lot of files/folders that are time consuming to be maintained. I would prefer simple CI libraries with 1-2 models like flexi-auth. Although, I wouldn't mind Community Auth's approach if it worked properly.
Tank Auth was a reliable solution in the past but not with Codeigniter 3.0 as it has many incompatibilities too. Questions about its compatibility with CI 3.0 were asked but no airplanes in the horizon so far.
DX Auth is an old authentication library and as I can see on its github repository, there are some attempts to migrate it on CI 3.0 but I haven't been able personally to test any of them.

So, has anyone successfully integrated (or migrated) any of the previous mentioned libraries on large CI 3.0 web applications? Did you write your own? Did you stick with CI 2 until further CI 3.0 development for that matter?
Update for the down votes
This post about Authentication libraries in codeigniter was very popular and helpful. I believe that posts that help the community in that way should not be closed at least not before some helpful answers. It is not discussed anywhere before and I would really like to see the opinions of more experienced developers for that.

A:

don't let the down votes get ya down.
check out Ion Auth
https://github.com/benedmunds/CodeIgniter-Ion-Auth
take a look at the read me, you will have to rename two files for codeigniter 3. otherwise you can see that there are recent changes to the lib. the author Ben Edmunds is one of the four developers on the new codeigniter council. http://www.codeigniter.com/help/about

A:

Please check Dnato System Login Its Simple, Fast and Lightweight auth codeigniter.
Feature:
-Add user
-Delete user
-Ban, Unban user
-Register new user sent to email token
-Forget password
-Role user level
-Edit user profile
-Gravatar user profile
-Recaptcha by Google
-And much more

Frontend
With Bootstrap Framework.


Q:

Krull dimension of a completion

How does one study Krull dimension of some I-adic completion of a ring or, more generally, a module? I know that in case of Noetherian local ring Krull dimension of its completion equals Krull dimension of the ring, but what can we say in general case?

A:

For a Noetherian ring R, the Krull dimension of its $I$-adic completion, $\hat{R}$ is given by $\sup h(J)$, where $J$ ranges over all maximal ideals of $R$ containing $I$ and $h(J)$ is the height of $J$. Therefore $\dim \hat R\le \dim R$ with equality only when $I\subset \operatorname{rad} R$. A reference is "Topics in $\mathfrak m$-adic topologies" by S.Greco, P.Salmon