text:
Q: Is it feasible to build and update a Wordpress website offline? It appears that Wordpress is designed to have websites constructed and maintained online - in the live website. I see some posts here that indicate some people are doing such development offline - in Localhost. But the effort to move a website online - especially for updates - appears to be complex, somewhat manual, and not at all automated. In fact, it's not clear of just the changes can be moved, or if the entire website would have to be reloaded. This seems complicated by visitor changes to the live website while updates are being created. And backups or version control of content - well I haven't gone far on that yet.
So what works? Is it just best to make changes to the live website? What would be the best approach for doing development offline?

A: It totally depends on the types of changes being made. If you're modifying a theme or a plugin, depending on what the changes are, you can likely build them locally or on a remote dev server, then push them to production with ease.
That works for a user or two, with more users you need version control - something like Git or SVN - to track and merge changes.
See this: https://stackoverflow.com/questions/9705849/how-to-set-up-a-stageing-enviorment-for-wordpress-wordpress-mu/10837071
I usually prefer to have a remote dev server because it's easier to replicate the production environment, and it's easier to access from multiple machines. The way I set it up is no slower than local development... possibly even faster.

A: Concur with @perpetualstudent about offline development.
If you start by installing on the webserver, then always copy in the direction of your PC dev you won't be overriding user data.
There are two records in the wp_options table that need to be modified each time you copy the database, these are siteurl and home that need to change to point to your local PC webserver.
For this I use the windows /etc/hosts file (on Windows 7 you need to run an editor as administrator to edit this file, and it's at C:\Windows\System32\drivers\etc\hosts ). Create static DNS names for your site(s) like this:
127.0.0.1   website1 bikefun website3

Then edit your webserver config to create virtual hosts. I'm using WAMP, so I edit
C:\wamp\bin\apache\apache2.4.9\conf\extra\httpd-vhosts.conf

and add sections like
<VirtualHost *:80>
    ServerAdmin nik@blah.blah
    DocumentRoot "c:/wamp/www/bikefun"
    ServerName bikefun
</VirtualHost>

then you can point your browser at http://bikefun (e.g.). This is better than just running via http://localhost/src/bikefun for example, apart from anything else it keeps the relative paths the same on your PC vs your production server.
To refresh your local version so it's the same as your webserver, takes two steps. The one you have to do most frequently is the database.  I use SQLyog which can make a copy of the remote database onto your local PC, the first time you do this, you create an empty database on local, then switch to the server, right click on the database name and "copy to different host". Be careful when copying that you don't accidentally overwrite a production database, make sure you are copying to your local PC!
If you are using cPanel you can download a dump of the database and execute that locally.
After copying, you need to change those two fields in the wp_options table.
When setting up your local PC version the first time, you need to copy the webroot files from the webserver, or else duplicate the exact install locally. For example, on the webserver go to webroot and use something like
tar -czf name.tgz website-directory/

then copy name.tgz to your local machine and extract it into your local webroot with something like 7-zip.
Subsequently I rarely repeat the copy of the files, you can keep the local copy synchronised by doing the same version updates and installing the same plugins etc. But you can repeat the file copy anytime if things get messed up on the local PC.
If you are modifying or writing plugins or themes, you need version control. I almost always create a child theme and put it into version control, but this is not necessary if you aren't modifying the theme.  Once I create a new plugin, or edit an existing one, I create a GIT repository in the plugin or theme directory and clone that to github.com. Then I clone from github to the webserver (assuming you created/edited it on your local PC).  That way you can develop locally and push your changes up to github (or your repository of choice) and pull them down into the webserver to upgrade the plugin/theme there.
git pull origin master

This gives you the ability to roll-back should things go wrong despite your careful testing on your local PC.  So both your WordPress webroots will have one or more GIT repositories embedded in wp-content inside plugins or themes directory.  To deploy from github to the live server, I use a simple shell script:
#!/bin/bash
# Argument = -w <website> -t <theme> -n <name>
# if -t is not given, plugin is assumed

usage()
{
cat << EOF
usage: $0 options

Deploy a git repository to a wordpress theme or plugin

OPTIONS:
   -h      Show this message
   -w      website. e.g. bikefun
   -t      it's a theme, otherwise it's a plugin
   -n      name of plugin or theme

EOF
}

THEME="false"
WEBSITE=
NAME=

# anything that needs a parameter has a : after it.
while getopts .htw:n:. OPTION

do
    case $OPTION in
        h)
            usage
            exit 1
            ;;
        t)
            THEME="true"
            ;;
        w)  WEBSITE=$OPTARG
            ;;
        n)
            NAME=$OPTARG
            ;;
        ?)
            usage
            exit
            ;;
    esac
done

if [[ -z $WEBSITE ]]
then
    usage
    exit 1
fi
if [[ -z $NAME ]]
then
    usage
    exit 1
fi

# make sure the repository is up-to-date
cd /home/lamp/webroot
cd $WEBSITE
cd wp-content
if [ $THEME = "true" ]
then
    cd themes
else
    cd plugins
fi

cd $NAME

# overwrite any local changes -
# this gives freedom to hotfix directly on the server and later overwrite it
git fetch origin master
git reset --hard FETCH_HEAD
git clean -df

service apache2 reload

Using GIT scales if you are working with other developers on the same project and each of you has a local dev copy. But I also find it handy because I switch between desktop and laptop.
Sometimes I am working on my laptop where there is no internet connection. It's a great way to fill in a long plane flight and there are no interruptions or distractions while you work! Here's an article about how to stop timeouts from slowing everything down when you are using WordPress offline: http://www.cbdweb.net/wordpress-development-offline/

A: We run all of our development locally on our machines. We use MAMP Pro to host our local environments and databases. Git is used for version control and we deploy those changes to our production servers with Beanstalk.
Once development is done locally (which is mainly done for speed reasons - it's much faster to work on your machine than on a server), we will do an export/dump of the database. Once the database is imported and the files are deployed, it's just a matter of changing a few values in the database and wp-config.php.
I would advise strongly against making any changes to any live website. You want to make changes in a protected (read: not public) environment to make sure you don't royally mess something up. Admittedly, however, it does take quite a bit of work to get an infrastructure in place that makes it easy to modify live sites safely.
For now, I'd stick with getting MAMP (WAMP if your on Windows) running on your machine and getting a local site up and running.

A: I have just upgraded a large WordPress site through a number of environments, taking each one completely offline whilst I performed the upgrade. We're using IIS as the web server, but since I appreciate most people use Apache, I'll try and keep the steps as generic as possible to apply to both setups.
These are the steps:

*

*Take site offline (bear in mind we did this in IIS, so if using Apache, you would need to use Apache's config to do this):
a) Take a note of how 404 redirects are done in the web config. You'll need this later. Change 404 redirects to point to root of the site, e.g. http://example.com
b) Change web server config to point to a holding page in a separate folder structure to the one holding the WordPress site. We set up just one file, index.html with a "Website in maintenance" message.
The site is now shutdown and cannot be accessed or updated. It is effectively static whilst you upgrade it - unless you have another web config pointing to the WordPress folder. If you do, take this offline in the same way.

*Create a backup copy of the files in the WordPress folder.

*Create a backup of the WordPress database. (make sure you know how to restore a database if you need to - we use heidisql to backup and restore).

*Copy all site files to a local web server and set up the local web server to have exactly the same domain as your live site. On a windows machine editing c:\windows\system32\drivers\etc\hosts to add 127.0.0.1 example.com is required to ensure the browser resolves to the local machine.
Note that even though you'll only be upgrading files locally initially, you will be upgrading the live database, and any database backup's/ restores etc refer to the live database ie that used by the live site.

*Make a list of all active plugins.

*Deactivate all plugins

*Upgrade all plugins

*Upgrade WordPress, following steps as proompted including upgrading database.

*Before activating plugins, see if any more plugins need updating (this can happen - even if you've already completed a round of upgrading them)

*Activate each plugin which requires activation 1 by 1. If you're prompted to upgrade plugin at this stage, upgrade it.

*Test the site on both the front and back ends. If you get any unrecoverable errors, restore the back up site files to your local server and restore your live backup database and start again from step 6. If you get the same issues again, you may need to do some research into how to resolve them before going any further. If you need to restore you old live site in the meantime, restore the database, and then follow steps 14 and 15 below.

*Following successful testing of the site on your local machine, copy the files from your local installation back to your live WordPress folder.

*On your local machine, comment out "#" the entry made in your hosts file in 4 above.

*Reverse what was done in 1) above by:
a) Changing web server config to point to live WordPress site.
b) Restoring 404 redirect to what it was before you changed it

*Test your site on the live domain.


text:
Q: Closed Loop Transfer Function - PD Control For the following control system, I am trying to find the characteristics of the system.

I have firstly found the closed loop transfer functions \$T(s) =\frac{C(s)}{R(s)}\$ , to be:
\$G(s) =K_p(s+9)*\frac{10}{s+12}*\frac{1}{s^2+6s+15}\$
\$G(s) =\frac{10K_ps+90K_p}{s^3+18s^2+87s+180}\$
Now as feedback is Uniity Feedback, therefore H = 1, I get;
\$T(s) = \frac{G(s)}{1+G(s)H(s)}\$
Which means \$T(s) = \frac{10K_ps+90K_p}{s^3+18s^2+87s+180+10K_ps+90K_p}\$
My first question for this problem is, is this Transfer Function correct, or have I miscalculated during a particular step up to this point.
Continuing on, I am now trying to find the \$K_p\$ value that leads to less than a 15% Overshoot for the system.
Unfortunately, I am unsure what to do next to find the \$K_p\$ value for this problem.
Any working or help as to how I go about this would be greatly appreciated.

A: To find the \$K_p\$ value that leads to less than a 15% Overshoot for the system. we can use the root locus plot, by looking at the position of the dominant poles (the two closer to the imaginary line). I have also added the sgrid lines showing the \$\zeta\$ and \$\omega\$ positions. Using the formula that
$$ \zeta \geq \frac{-\ln(PO/100)}{\sqrt{ \pi^2 + \ln^2(PO/100) }},$$
we have that
$$ \zeta \geq \frac{-\ln(15/100)}{\sqrt{ \pi^2 + \ln^2(15/100) }}= 0.517.$$
So, by positioning the poles below that 0.55 damping line should get you the overshoot to meet your requirement. Therefore, for a gain in \$K_p \in [-1,2]\$ you would meet that requirement. (the image looks horrible, but if you click on it it gets slightly better)

A: I find it best not to do algebra until it is needed. Loop Gain here is G(s)=Kp(s+9){10/(s+a2)}{1/(s^2+6s+15)}, a gain factor 10*Kp, a zero and three poles.
A Bode plot of this function shows that the unity frequency depends on Kp. You change the phase margin with this parameter. Find the PM needed for your overshoot and adjust Kp to get this PM.
Doing the algebra too early confuses pole-zero information.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why am I getting characters changing in my replace to �? I have hundreds of text files with thousands of records in each. See sample record below.

3"100"56"2016-10-26 03:00:52.107"2016-10-26 07:00:52.000"1509"1"1509"17"1"-21749"-23437"0"2"0"0"0"0"0"0"1"1"80.844208"2"1"0.51136178"3"1"0.4092806"4"1"638"5"1"0"6"1"0"7"1"7"8"1"3"9"1"914"10"1"984"11"1"1094"12"1"817"13"1"1246"14"1"583"15"1"89"16"1"233"17"1"771"18"1"405"19"1"245"20"1"528"21"1"325"0"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL"NULL

These were an export done from SQL that I did not set up.
I am changing the NULL text to "" so that it is truly NULL. Once data has been corrected I am running a bulk insert.
Here is a copy of my Find/Replace code.
Dim fileReader As String = My.Computer.FileSystem.ReadAllText(LBRQFileName).Replace("NULL", "")
    My.Computer.FileSystem.WriteAllText(LBRQFileName, fileReader, False)

This code works great if the delimiter is ',' or ';' or anything normal.
However, a lot of these files have a " character (U+201D : RIGHT DOUBLE QUOTATION MARK {double comma quotation mark}) as the delimiter. In this situation, when I run the find and replace for NULL I end up with something like this (Small example):
1�245�20�1�528�21�1�325�0��������������
(several in a row where "Null" was the value)
I have tried running a find and replace on that double quote, only to have same results. I have tried coming up with ways of setting up the delimiter as the RIGHT DOUBLE QUOTATION MARK(Works in SSMS, but not from VB).
Running the replace for both the RIGHT DOUBLE QUOTATION MARK and "NULL" from notepad......works fine.....
But I have hundreds of files to do. I don't have time to open each one up in notepad.
Update:
Changed code to Read and Write in ASCII. After I ran the replaced code, I was left with a usable delimiter.
Dim fileReader As String = My.Computer.FileSystem.ReadAllText(LBRQFileName, Encoding.ASCII).Replace("NULL", "")
    My.Computer.FileSystem.WriteAllText(LBRQFileName, fileReader, False, System.Text.Encoding.ASCII)

A: Probably because those are right quotes quotes... you need to change the text file encoding
 Dim fileReader As String = My.Computer.FileSystem.ReadAllText(LBRQFileName, System.Text.Encoding.UTF8).Replace("NULL", "")

 My.Computer.FileSystem.WriteAllText(LBRQFileName, fileReader, False, System.Text.Encoding.UTF8)

Default vb.net text files do not support that character.

A: you can achieve the same thing Using System.IO Library
    Using str As New IO.StreamReader("C:\1.txt", System.Text.Encoding.Unicode, True)

        strText = str.ReadToEnd.Replace("NULL", "")
        str.Close()

    End Using

    Using stw As New IO.StreamWriter("C:\1.txt", False, System.Text.Encoding.Unicode)

        stw.Write(strText)
        stw.Close()

    End Using

It works fine for me


text:
Q: global array returns undefined I have a slideshow with button like 1,2,3,4. Also I have define an Array with 4 images url. When click the button, it call the specific corresponding url.

1

2

3

4

Javascript:
var button=document.getElementsByClassName("button")
var image=document.getElementsByTagName("img")[0]
var sources=new Array("images/blue.jpg","images/red.jpg","images/yellow.jpg","images/green.jpg");

for (var i=0;i<sources.length;i++){
    button[i].onclick=function(){
            image.src=sources[i]
            }
}

But when I click the button, the sources[i] alway return undefined.

A: for (var i=0;i<sources.length;i++){
    button[i].onclick= function(i){
       return function(){
            image.src=sources[i]
            }
     }(i);
}

try this http://jsbin.com/puyipiro/1/
P.S. error cause in onclick handler i equal 4 , so must save current value on each iteration with creation handler

A: You have run into one of the most confusing parts of JavaScript, the closure capture problem. To get your code to work re-write it as,
var button=document.getElementsByClassName("button")
var image=document.getElementsByTagName("img")[0]
var sources=new Array("images/blue.jpg","images/red.jpg","images/yellow.jpg","images/green.jpg");

for (var i=0;i<sources.length;i++){
   (function (i) {
     button[i].onclick=function(){
       image.src=sources[i]
     }
   })(i);
}

This uses a immediately executing function to introduce a new scope so each onclick has its own copy of i that has the value of i at the time the function was created instead of sharing the same i which will have the value of sources.length.
If you targeting a browser that supports ES 6 you can use let instead of var which will then allow you to write this as,
var button=document.getElementsByClassName("button")
var image=document.getElementsByTagName("img")[0]
var sources=new Array("images/blue.jpg","images/red.jpg","images/yellow.jpg","images/green.jpg");

for (var i=0;i<sources.length;i++){
  let j = i;
  button[i].onclick=function() {
    image.src=sources[j]
  }
}

The let statement creates a fresh scope for j for each iteration in the loop so the j captured by the onclick functions are different and store the value of i had when the function was created as the immediately executing function above does.
Unfortunately, ES 6 is not yet broadly available so some variant of my original suggestion is what you need.

A: You may store i values within appropriate DOM elements (buttons), e.g. as attributes, then retrieving them in onclick handler. Somehow like this:
for (var i=0;i<sources.length;i++){
    button[i].setAttribute('data-btn_i', i);
    button[i].onclick=function(){
        image.src=sources[this.getAttribute('data-btn_i')];
    }
}


text:
Q: C++ copy constructor called multiple times I was trying to understand the basics of copy constructors and came across the following example.
#include <iostream>

using namespace std;

class Line
{
   public:
      int getLength() const;
      Line( int len );             // simple constructor
      Line( const Line &obj);  // copy constructor
      ~Line();                     // destructor

   private:
      int *ptr;
};

// Member functions definitions including constructor
Line::Line(int len)
{
    cout << "Normal constructor allocating ptr" << endl;
    // allocate memory for the pointer;
    ptr = new int;
    *ptr = len;
}

Line::Line(const Line &obj)
{
    cout << "Copy constructor allocating ptr." << endl;
    ptr = new int;
   *ptr = *obj.ptr; // copy the value
}

Line::~Line()
{
    cout << "Freeing memory!" << endl;
    delete ptr;
}
int Line::getLength() const
{
    return *ptr;
}

void display(Line obj)
{
   cout << "Length of line : " << obj.getLength() <<endl;
}

// Main function for the program
int main( )
{
   Line line1(10);

   Line line2 = line1; // This also calls copy constructor

   //display(line1);
   //display(line2);

   return 0;
}

When executed, it gives the following output.
Normal constructor allocating ptr
Copy constructor allocating ptr.
Copy constructor allocating ptr.
Length of line : 10
Freeing memory!
Copy constructor allocating ptr.
Length of line : 10
Freeing memory!
Freeing memory!
Freeing memory!

The copy constructor is called only once, in the Line line2 = line1; But it seems that the copy constructor is being called twice. So I commented out the
display(line1); and display(line2); . After that the output is something like this.
Normal constructor allocating ptr
Copy constructor allocating ptr.
Freeing memory!
Freeing memory!

So the problem(I don't know if I should call it a problem or its a default standard in C++) is with the display function. Could it be because the display() function automatically creates a copy of the object its processing and that's why the copy constructor is called twice for each instance? Kindly clarify. Thanks.

A: with void display(Line obj), you pass object by value, so create copy.
You should pass by (const) reference to avoid the copies:
void display(const Line& obj)

A:
Could it be because the display() function automatically creates a copy of the object its processing and that's why the copy constructor is called twice for each instance? Kindly clarify. Thanks.

That is exactly what is happening.  If you pass an object into a function by value, it will be copied prior to the function call executing.  If you do not wish this to happen, use a pointer or a reference.


text:
Q: how to search data from datatable using textbox and display it into datagridview in C#? i want to search data from datatable using a textbox, and display it into datagridview (datatable is the datasource for datagridview).
I tried using this code:
DataTable table = new DataTable();
    private void button1_Click(object sender, EventArgs e)
    {
        XmlDocument xdoc = new XmlDocument();
        xdoc.Load(@"C:\ABC.xml");

        table.Columns.AddRange(new DataColumn[3] { new DataColumn("Name"), new DataColumn("Id"), new DataColumn("MobileNo.") });
        XmlNodeList path = xdoc.DocumentElement.SelectNodes("Data");
        foreach (XmlNode node in path)
            {
                String name= node.Attributes["name"].Value;
                String id= node.Attributes["id"].Value;
                String number= node.Attributes["no."].Value;

                table.Rows.Add(name, id, number);

                BindingSource bindingSource = new BindingSource();
                bindingSource.DataSource = table;
                dataGridView1.DataSource = bindingSource;
            }
     }

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        DataView dv = new DataView();
        dv.RowFilter = "Name like '%" + textBox1.Text + "%'";
        dataGridView1.DataSource = dv;
    }

Here I am taking data from an xml, storing it in a datatable and using this as data source for datagridview.
I want to provide a search option for the "Name" using a textbox.
The above code is not working as desired, only the data is displayed in the grid , but unable to search for text entered in textbox.
Kindly help with any other solution you have.

A: got it!
the datasource for dataview was missing.
corrected function:
 private void textBox1_TextChanged(object sender, EventArgs e)
{
    DataView dv = new DataView(table);
    dv.RowFilter = "Name like '%" + textBox1.Text + "%'";
    dataGridView1.DataSource = dv;
}


text:
Q: how would one define a scala implicit in a java library? As a bit of background, I'm using joda DateTime from Scala.  It seems that everywhere a Scala developer uses Joda DateTime, they define some implicit datetimeOrdering, which they then import.  Each library seems to define its own.  Occasionally there are conflicts from having multiple definitions from different libraries in scope.
I'm curious if and how the Java library (in this case joda, but it's just an example) might define such an implicit in its Java source code, such that it would compile to equivalent scala bytecode, so that it could be imported in a scala program.  I know I can do things like implement def +(x:Whatever):Whatever in Java using $plus(...), but I don't know how I would define an implicit.
I'm not a joda developer, just curious how this would work.  Obviously joda could include a single scala file in their project, but I'm curious if other options exist.  Does defining an implicit in Java require the scala-tools.jar being on the classpath?  Can an implicit be defined directly in Java code?  What does the implementation of implicit actually look like?


text:
Q: How to visually let the user know that something is selected? For example, I have a userControl that I want a user to be able to "Select".
Here is the code I'm using:
private void ptbImage_Click(object sender, EventArgs e)
{
    SelectControl();
}

private void SelectControl()
{
    this.BackColor = Color.FromArgb(235, 243, 253);
}

If I have many controls inside of this user control things get messy soon! :P Is there a to globally wrap around every control? Like a Click event for everything inside the control. If there isn't I'll just manually create a click even for every control to globally capture input. Thanks!

A: Yes...
You can link the event of each control to the same event method, like this:
ptbImage1.Click += new System.EventHandler(ptbImage_Click);
ptbImage2.Click += new System.EventHandler(ptbImage_Click);
ptbImage3.Click += new System.EventHandler(ptbImage_Click);

etc..

A: In the form's InitializeComponent method you could run a foreach through every control on the form and set the Click eventhandler to ptbImage_Click

A: foreach (Control ctrl in yourContainerControl.Controls)  {
    ctrl.Click += new System.EventHandler(ctrl_Click);
}

You can also capture events application-wide, and handle them before they are directed to the control itself.


text:
Q: Convert "True" to true JSON Python Im reading json which has a boolean. When loading the file in Python with json.load(), I get True (I've read the specs).
{"XYZ": true}

As I understood I need to use json.dumps() to handle this. My dumps look like this.
convert = json.dumps({"true": True, "false": False})

And my load like this:
jdata = json.load(open(json_path))

When printing jdata I get:
{u'XYZ': True}

My question is, how do I convert the True to true after loading the json file? Later in my code I use the jdata.iteritems() to get all the keys and values.
If I write like this
jdata = json.load(open(json_path))
convert = json.dumps(jdata, {"true": True, "false": False})

it will print out:
{"XYZ": true}

But then I can't do
for key, value in convert.iteritems():
    #code

because I get this error:
AttributeError: 'str' object has no attribute 'iteritems'

How can I fix this?
EDIT
Here is the code
def ReadAndValidate(directory, json_path):

    jdata = json.load(open(json_path))
    path = findAllFiles(directory)

    if os.path.isdir(path):
        for root, dirs, files in os.walk(path):
            for key, value in jdata.iteritems():
                for name in files:
                    with open(os.path.join(root, name)) as fle:
                        content = fle.read()
                    if name.endswith('.txt') and re.search(Wordboundry(key), content):
                        print "Name", key, "was found in", name, "\n"
                        writeToFile(value, content, name, key)
                   else:
                       print "Name", key, "was not found in", name"

def writeToFile(value, file_content, file, name):
    if type(value) is list:
        nrOfvalue = ' '.join([str(myValue) for myValue in value])
        nrOfvalue = "[ " + nrOfvalue + " ]"
        content = regFindName(name, nrOfvalue, file_content)
    else:
        content = regFindName(name, value, file_content)
    writeToFile(file, content)

I am using argumentparser where directory could be "C\Mydir\Dir1" and json_path "C:\MyDir\Dir1\myjson.json
myjson contains:
{"XYZ": true}

Function tries to find "XYZ" in a file. Leys say it finds it in the file "myFile.txt" which contains:
XYZ = false;

I wanna replace false with true if the name matches. The expected output in "myFile.txt" should be:
XYZ = true

The regFindName() finds the "name" (ex XYZ) by using regex++

A: I believe you misunderstand the roles of json.loads and json.dumps (and their cousins, json.load and json.dump).
json.dumps (or json.dump) converts a Python object to a string (or file) which is formatted according to the JSON standard.
json.loads (or json.load) converts a string (or file) in JSON format to the corresponding Python object.
Consider this program:
import json

orig_python_object = { "XYZ": True }
json_string = json.dumps(orig_python_object)
new_python_object = json.loads(json_string)

assert orig_python_object == new_python_object
assert isinstance(orig_python_object, dict)
assert isinstance(new_python_object, dict)
assert isinstance(json_string, str)

for key, value in new_python_object.iteritems():
    pass

Of course one cannot .iteritems() the result of .dumps(). The result of .dumps() is a str, not a dict.
However, you can transmit that str (via file, socket, or carrier pigeon) to another program, and that other program can .loads() it to turn it back into a Python object.
Returning to your question:

how do I convert the "True" to true after loading the json file?

You do so by converting it back to JSON.
python_object = json.load(open("somefile.json"))
for k,v in python_object.iteritems():
    # some code
    pass
json_str = json.dumps(python_object)

assert 'true' in json_str
assert 'True' in str(python_object)

EDIT :
You've posted a larger part of your program in your question, which makes it more apparent where the problem lies. If I were you, I'd do one of two things:
1) I'd modify writeToFile like so:
def writeToFile(value, file_content, file, name):
    if type(value) is list:
        nrOfvalue = ' '.join([str(myValue) for myValue in value])
        nrOfvalue = "[ " + nrOfvalue + " ]"
        content = regFindName(name, nrOfvalue, file_content)
    elif isinstance(value, bool):
        content = regFindName(name, str(value).lower(), file_content)
    else:
        content = regFindName(name, value, file_content)
    writeToFile(file, content)

Or, 2) I'd modify myjson.json like so:
{"XYZ": "true"}


text:
Q: Chessboard in pure js I began js 3 days ago at school, I had some C basics before so the main problem here would be the syntax (I think).
The goal is to produce a chessboard, 8x8 black and white square, but I can't get the code to show anything. What am I missing ?
(the html just have the script src="./x.js" part and the "body" part)
document.body.onload = addElement.innerHTML;

function addElement() {

    var newTable = document.createElement("table");
    for (var i = 1; i < 9; i++) {
        var newTr = document.createElement('tr');
        for (var j = 1; j < 9; j++) {
            var newTd = document.createElement('td');
            if (i % 2 == j % 2) {
                newTd.className = "white";
            } else {
                newTd.className = "black";
            }
            newTr.appendChild(newTd);
        }
        newTable.appendChild(newTr);
    }

    document.body.appendChild(newTable);

    document.getElementByClass("black").style.backgroundColor = "black";
    document.getElementByClass("white").style.backgroundColor = "white";
    document.getElementByTag("newTd").style.width = "25px";
    document.getElementByTag("newTd").style.height = "25px";
}

A: A simpler approach would be to add the attributes when you create each element and not after. Like this:
if (i % 2 == j % 2) newTd.style.backgroundColor = "white";

else newTd.style.backgroundColor = "black";

newTd.style.width = "25px";

newTd.style.height = "25px";

See this fiddle: http://jsfiddle.net/vdquLn65/2/
About your current code you could use getElementsByClassName and getElementsByTagName and iterate over the elements they return to do what you want.

A: As you currently have it, addElement.innerHTML is a reference to the innerHTML property of the addElement variable. addElement is a reference to a function definition, and does not have an innerHTML property.
Try changing your first line to this:
window.onload = addElement;

See: https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload
Edit: I was a bit too quick to post this, and didn't spot the other errors in the code as mentioned in Karan's answer.

A: Hello Jaune and welcome to Stack Overflow. I have added an answer that will create the data first and then map that that data to elements using functions. If you have any questions please let me know.

const field = ([x, y, color]) => {
  const td = document.createElement('td');
  td.setAttribute('data-x', x);
  td.setAttribute('data-y', y);
  td.className = color;
  td.innerHtml = `${x}-${y}`;
  return td;
};
const row = (row) => {
  const tr = document.createElement('tr');
  row.forEach((fieldItem) =>
    tr.appendChild(field(fieldItem)),
  );
  return tr;
};
const table = (tableData) => {
  const table = document.createElement('table');
  tableData.forEach((rowData) =>
    table.appendChild(row(rowData)),
  );
  return table;
};
const tableData = Array.from(Array(8).keys()).map((x) =>
  Array.from(Array(8).keys()).map((y) => [
    x,
    y,
    (x + y) % 2 ? 'black' : 'white',
  ]),
);
document.body.appendChild(table(tableData));
.black {
  width:10px;
  height:10px;
  background-color: black;
}
.white {
  width:10px;
  height:10px;
  background-color: white;
}
table {
  border: 1px solid black;
}

A: There are few mistakes in your code use getElementsByClassName instead of getElementByClass and use getElementsByTagName instead of getElementByTag.
Also you need to loop over each selected elements.
Use window.onload = addElement; or you can simply call addElement(); after function declaration completes.

window.onload = addElement;

function addElement() {
  var newTable = document.createElement("table");
  for (var i = 1; i < 9; i++) {
    var newTr = document.createElement('tr');
    for (var j = 1; j < 9; j++) {
      var newTd = document.createElement('td');
      if (i % 2 == j % 2) {
        newTd.className = "white";
      } else {
        newTd.className = "black";
      }
      newTr.appendChild(newTd);
    }
    newTable.appendChild(newTr);
  }

  document.body.appendChild(newTable);
  var i = 0;
  for (i = 0; i < document.getElementsByClassName("black").length; i++) {
    document.getElementsByClassName("black")[i].style.backgroundColor = "black";
  }
  for (i = 0; i < document.getElementsByClassName("white").length; i++) {
    document.getElementsByClassName("white")[i].style.backgroundColor = "white";
  }
  for (i = 0; i < document.getElementsByTagName("td").length; i++) {
    document.getElementsByTagName("td")[i].style.width = "25px";
    document.getElementsByTagName("td")[i].style.height = "25px";
  }

}

A: As an alternative approach, consider coloring the table itself black and only coloring the corresponding tiles white:

window.onload = addElement;

function addElement() {
  var tbl = document.createElement('table');
  tbl.style.backgroundColor = 'black';

  for (var i = 1; i < 9; i++) {
    var tr = document.createElement('tr');

    for (var j = 1; j < 9; j++) {
      var td = document.createElement('td');
      td.style.width = '25px';
      td.style.height = '25px';

      if (i % 2 == j % 2) {
        td.style.backgroundColor = 'white';
      }

      tr.appendChild(td);
    }

    tbl.appendChild(tr);
  }

  document.body.appendChild(tbl);
}

And also, as Alex G said, it's much simpler to do the styling at the time the element is created instead of trying to iterate over them later. I understand the mindset of separating the logic and style portions of the code, but in this case it isn't really worth the added effort and complexity, and there are better ways to do it anyway.
And besides, if you wanted to separate the style from the logic, that's what CSS files are for. :P


text:
Q: Android Realm storing int[] and String[] Is there a way to store an int[] and a String[], other than creating a new object that contains those, and then storing it in a realmList
I have an object which takes the parameters of a String, int[], and String[]. you cant store int[], and String[] in realm so I made an object
public class Workouts extends RealmObject {

    private String workout;

    public Workouts() {

    }

    public Workouts(String workout) {
        this.workout = workout;
    }

    public String getWorkout() {
        return workout;
    }

    public void setWorkout(String workout) {
        this.workout = workout;
    }
}

and
public class Multiplier extends RealmObject {

    private int multiplier;

    public Multiplier() {

    }

    public Multiplier(int multiplier) {
        this.multiplier = multiplier;
    }

    public int getMultiplier() {
        return multiplier;
    }

    public void setMultiplier(int multiplier) {
        this.multiplier = multiplier;
    }
}

and then I store them like
RealmList multipliers;
RealmList workouts;
I am wondering if there is a way I can store these by just using an array instead of a RealmList

A: Emanuele from Realm here. Right now there's no other way other than wrapping String or int and use RealmList on those. This is for several reasons, including being able to use Realm file on different platforms. Is this an acceptable solution in your use-case or is it a pain?
If you would like, this gist demonstrates how one would use a RealmList to store a group of primitive values within a RealmObject. https://gist.github.com/cmelchior/1a97377df0c49cd4fca9

A: Create RealmString class as below
public class RealmString extends RealmObject {
    private String val;
    public RealmString(){
    }

    public RealmString(String value) {
        this.val = value;
    }

    public String getValue() {
        return val;
    }

    public void setValue(String value) {
        this.val = value;
    }

    @Override
    public String toString() {
        return val;
    }
}

Create new class
public class RealmStringDeserializer implements JsonDeserializer<RealmList<RealmString>> {

    @Override
    public RealmList<RealmString> deserialize(JsonElement json, Type typeOfT,
                                              JsonDeserializationContext context) throws JsonParseException {

        RealmList<RealmString> realmStrings = new RealmList<>();
        JsonArray stringList = json.getAsJsonArray();

        for (JsonElement stringElement : stringList) {
            realmStrings.add(new RealmString(stringElement.getAsString()));
        }

        return realmStrings;
    }
}

If you are using realm with retrofit then add following lines to your retrofit builder class
Gson gson = new GsonBuilder()
                .setLenient()
                .setExclusionStrategies(new ExclusionStrategy() {
                    @Override
                    public boolean shouldSkipField(FieldAttributes f) {
                        return f.getDeclaringClass().equals(RealmObject.class);
                    }

                    @Override
                    public boolean shouldSkipClass(Class<?> clazz) {
                        return false;
                    }
                })
                .registerTypeAdapter(new TypeToken<RealmList<RealmString>>() {
                }.getType(), new RealmStringDeserializer())
                .create();

        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(NetworkConstants.BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .build();
        }

A: I don't like using RealmString and RealmInt. How for example will you keep track of deleting them again when the list changes?
I've built a custom solution for the Realm - GSON (Retrofit) combi, where they share the same model object. I tested only 10 json files. Let me know if you find any problems and I'll perfectionize this.
Firstly, create a String instead of an int[] or String[] in your RealmObject:
/*
 * Languages this user selected. Comma separated String.
 */
@SerializedName("languages")
private String languages;

Then create getters and setters for it. Note that StringUtils.join() is my own method, if none of the libraries you use has it then you can find it anywhere on the net.
/**
 * All user languages.
 */
public void setLanguagesFromList(List<String> languages) {

    String languagesStr = languages == null ? "" : StringUtils.join(languages, ",");
    if (!TextUtils.equals(this.languages, languagesStr)) {
        setDirty(true);
    }
    this.languages = languagesStr;
}

/**
 * Returns an unmodifiableList with all user languages.
 * <p>
 * Use setLanguagesFromList with a new list to make changes.
 *
 * @return
 */
public List<String> getLanguagesList() {

    return Collections.unmodifiableList(
            languages == null ? new ArrayList<>() :
                    Arrays.asList(languages.split(",")));
}

If you use this getter a lot, you might wanna create a List<String> that is not saved in the database (@Ignore) but is used to speed up this method (so that parsing is only done on changes / first access).
Then create a Deserializer for GSON/Retrofit:
/**
 * Used so that string (or any other primitive) arrays are parsed int one String. Realm cannot handle String arrays.
 */
public class RealmPrimitiveArrayDeserializer implements
    JsonDeserializer<String> {

private final static String KOMMA = ",";

  @Override
  public String deserialize(JsonElement json, Type typeOfT,
                          JsonDeserializationContext context) throws JsonParseException {

    if (json.isJsonNull()) {
        return null;
    }

    if (json.isJsonArray()) {

        StringBuilder targetStringBuilder = null;
        JsonArray stringList = json.getAsJsonArray();

        for (JsonElement element : stringList) {

            if (element.isJsonPrimitive()) {

                if (targetStringBuilder == null) {
                    targetStringBuilder = new StringBuilder();
                }

                targetStringBuilder.append(element.getAsString());
                targetStringBuilder.append(KOMMA);
            }
        }

        if (targetStringBuilder != null && targetStringBuilder.length() > 0) {

            // remove the last komma:
            targetStringBuilder.deleteCharAt(targetStringBuilder.length() - 1);

            return targetStringBuilder.toString();
        }
    }

    return json.getAsString();
  }
}

Add this to your GSON configuration used by Retrofit:
GsonBuilder gsonBuilder = new GsonBuilder()
                .registerTypeAdapter(new TypeToken<String>() {
                }.getType(), new RealmPrimitiveArrayDeserializer());

That's it. Good luck.


text:
Q: I am trying to retrieve data from a Ruby cdn of the Pokemon API but I am struggling Below is my Pokemon TCG API key
I have read the documentation but I cannot find a way to retrieve the data I need which is the images of each card in a set. If anyone can help with or give me any pointers on how to retrieve this I would greatly appreciate it.
https://github.com/PokemonTCG/pokemon-tcg-sdk-ruby/blob/master/README.md
This above is the link to the documentation on Github.
Pokemon.configure do |config|
  config.api_key = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
end

sets = Pokemon::Set.where(q: 'legalities.standard:legal').first
p sets

I am expecting to retrieve specific data from the Pokemon TCG API which from above should be within these Ruby classes.

A: p sets.images.symbol will print out the link to:
"https://images.pokemontcg.io/swshp/symbol.png"

p sets.images.logo will print out the link to:
"https://images.pokemontcg.io/swshp/logo.png"

When you are unsure what is contained within the class you're getting, in this case a Pokemon::Set class, you may see all the methods of this resulting variable with sets.methods.sort.each{|m| p m}, there you'll find the images method and can dig deeper to symbol and logo.
In your example you are searching for sets. In case of cards:
cards = Pokemon::Card.where(page: 5, pageSize: 100)
cards.each{|card| p card.images.large}

This will print out all the links to large cards.

Update
Clarification based on comments
How to print out methods and how to know which class you are referring to.
Let's start with you code snippet:
sets = Pokemon::Set.where(q: 'legalities.standard:legal').first
puts sets.class

Output:
Pokemon::Set

It would be more clear if you name your variable as set because you're selecting the .first element of an array.
Back to my cards example:
cards = Pokemon::Card.where(page: 5, pageSize: 100)
puts cards.class

Output:
Array

As I did not select any item from the array cards naming makes perfect sense, and this array will contain a card:
card = cards.first
puts card.class

Output
Pokemon::Card

Printing methods
So, given we are now well aware of class each variable contains and what we are referring to, we are ready to print out the methods for both:
sets.methods.sort.each{|method| p method}
cards[0].methods.sort.each{|method| p method}

Output:
…
:hash
:hp
:hp=
:id
:id=
:images       <== Here!
:images=
:inspect
:instance_eval
:instance_exec
:instance_of?
…

Once again, mind the [0] selection of the first item. When we want to know methods, we want to know it either for Pokemon::Set or Pokemon::Card.


text:
Q: Azure App Service crash due to StackOverflowException in MicrosoftInstrumentationEngine_x86.dll We are experiencing random Azure App Service crashes, multiple times a day. Every time the application crashes the App Service is restarted.
The application is an ASP.NET MVC 5 application running .NET Framework 4.7.
Crash monitoring is enabled and the results of the crash dumps leads us to the following exceptions:
Unhandled exception at 0x737DB347 (MicrosoftInstrumentationEngine_x86.dll) in w3wp.exe: 0xC00000FD: Stack overflow (parameters: 0x00000001, 0x4DDF2FFC).

Unhandled exception at 0x73187E33 (clr.dll) in Microsoft.ApplicationInsights.Metrics

The application uses Microsoft Application Insights SDK (latest version 2.15) and we also have the Application Insights Site Extension fully enabled on the site to use SQL Profiling, (running Pre-Installed Site Extension, version 2.8.37.4238).
My conclusions is that the exception is related to Application Insights Site Extensions, but I can't find out why and how to solve it (without fully disabling Application Insights).
Should we use either the SDK or the Site extensions instead of both? Could it be conflicts?
Have anyone else experienced similar issues?


text:
Q: Show and lighting options do not work together I am trying the example from this demonstration, but it is not working properly.
plane = ParametricPlot3D[{u, v, -2}, {u, -7, 7}, {v, -7, 7},
    PlotPoints -> 200,
    MaxRecursion -> 2,
    Mesh -> None,
    Axes -> False,
    Boxed -> False];

Manipulate[
  Show[plane,
    Lighting -> {
     {"Spot", RGBColor[1, 0, 0], {{0, r, 5}, {0, r, 0}}, Pi/8},
     {"Spot", RGBColor[0, 1, 0], {{-r Sin[θ], r Cos[θ], 5}, {-r Sin[θ], r Cos[θ], 0}}, Pi/8},
     {"Spot", RGBColor[0, 0, 1], {{r Sin[ϕ], r Cos[ϕ], 5}, {r Sin[ϕ], r Cos[ϕ], 0}}, Pi/8}
    },
    PlotRange -> {(3 + r) {-1, 1}, (3 + r) {-1, 1}, Automatic},
    ImageSize -> {350, 320}],

 {{r, 2, "spacing"}, 0, 3.5},
 {{θ, 2 π/3, "green angle"}, π, 0},
 {{ϕ, 2 π/3, "blue angle"}, π, 0},
 "XYZ" -> {{RGB, {1, 1, 1}}, {0, 0, 0}, {1, 1, 1}},
 SaveDefinitions -> True]

It is not drawing any circles, only the plane.
Could you please suggest what is not right with my code?
Note 1: I am using 10.4 version of Mathematica, in 8.0 code works.

A: Works with Mathematica 10.4.
Manipulate[
 ParametricPlot3D[{u, v, -2}, {u, -7, 7}, {v, -7, 7},
  PlotPoints -> 200, MaxRecursion -> 2, Mesh -> None, Axes -> False,
  Boxed -> False,
  PlotStyle -> {Black, Specularity[10]},
  Lighting ->
    {{"Spot", RGBColor[RGB[[1]], 0, 0], {{0, r, 5}, {0, r, 0}}, Pi/8},
    {"Spot", RGBColor[0, RGB[[2]], 0], {{-r Sin[theta], r Cos[theta], 5}, {-r Sin[theta],
       r Cos[theta], 0}}, Pi/8},
    {"Spot", RGBColor[0, 0, RGB[[3]]], {{r Sin[phi], r Cos[phi], 5}, {r Sin[phi],
       r Cos[phi], 0}}, Pi/8}}],
 {{r, 2, "spacing"}, 0, 3.5},
 {{theta, 2 Pi/3, "green angle"}, Pi, 0},
 {{phi, 2 Pi/3, "blue angle"}, Pi, 0},
 {{RGB, {1, 1, 1}}, {0, 0, 0}, {1, 1, 1}}]


text:
Q: nmake - simple question about escaping I'd like to make below nmake code to produce check.mak file with the following contents:
$(A)
instead I get the following error:
"NMAKE : fatal error U1040: internal error : macro expansion"
Any suggestions?
My nmake version is 9.00.30729.01 (VC 2008).
OPTION = A
FILE = check.mak

all :
    @echo "$$($(OPTION))" > $(FILE)

A: This looks like a bug in NMAKE.  After some experimentation I found that the following work-around gives you the output you want, although it's a little ugly:
OPTION=A
FILE=check.mak
LPAREN=(
RPAREN=)

all:
        echo $$$(LPAREN)$(OPTION)$(RPAREN) > $(FILE)

For what it's worth, I also tried your original with the NMAKE emulator that my company sells, and found that it was able to process the makefile with no errors, which is why I feel confident in saying that the observed behavior is a bug in the NMAKE implementation rather than a limitation of the NMAKE syntax.
Hope that helps,
Eric Melski


text:
Q: How EAR packages and beans can share session id? I have 3 EAR packages which combined together makes one huge web java application. Is it possible to configure the beans into the packages to share the session id data between them. My idea is to develop a login form which registers users into database tables using session id. Every time then users browse the application their session id is used to identify the users. The tricky part comes when users switch between different EAR packages and beans. The session id will change and other beans won't know what is the new session id. Is there a way to configure the beans into the EAR packages to share the data which contains the session id.

I created two identical EAR packages and I placed context.xml file in each one. This is the file structure:
SR_57
├── pom.xml
├── SR_57-ear
│   ├── pom.xml
│   ├── src
│   │   └── main
│   │       └── application
│   │           └── META-INF
│   │               └── MANIFEST.MF
│   └── target
│       ├── application.xml
│       ├── maven-archiver
│       │   └── pom.properties
│       ├── SR_57-ear-1.0-SNAPSHOT
│       │   ├── META-INF
│       │   │   ├── application.xml
│       │   │   └── MANIFEST.MF
│       │   ├── SR_57-ejb-1.0-SNAPSHOT.jar
│       │   └── SR_57-web-1.0-SNAPSHOT.war
│       └── SR_57-ear-1.0-SNAPSHOT.ear
├── SR_57-ejb
│   ├── pom.xml
│   ├── src
│   │   ├── main
│   │   │   ├── java
│   │   │   │   └── com
│   │   │   │       └── SR_57
│   │   │   └── resources
│   │   │       └── META-INF
│   │   │           └── MANIFEST.MF
│   │   └── test
│   │       └── java
│   │           └── com
│   │               └── SR_57
│   └── target
│       ├── classes
│       │   └── META-INF
│       │       └── MANIFEST.MF
│       ├── endorsed
│       │   └── javaee-endorsed-api-6.0.jar
│       ├── maven-archiver
│       │   └── pom.properties
│       ├── SR_57-ejb-1.0-SNAPSHOT.jar
│       └── surefire
└── SR_57-web
    ├── faces-config.NavData
    ├── nb-configuration.xml
    ├── pom.xml
    ├── src
    │   ├── main
    │   │   ├── java
    │   │   │   └── com
    │   │   │       └── SR_57
    │   │   │           └── userCheck.java
    │   │   ├── resources
    │   │   └── webapp
    │   │       ├── home.xhtml
    │   │       ├── index.html
    │   │       ├── resources
    │   │       │   ├── css
    │   │       │   │   ├── sr_style.css
    │   │       │   │   └── style.css
    │   │       │   ├── images
    │   │       │   │   ├── 1.jpg
    │   │       │   │   ├── 2.jpg
    │   │       │   │   ├── 3.jpg
    │   │       │   │   ├── 4.jpg
    │   │       │   │   ├── 5.jpg
    │   │       │   │   ├── 6.jpg
    │   │       │   │   ├── 7.jpg
    │   │       │   │   ├── bg_1.jpg
    │   │       │   │   ├── bg.jpg
    │   │       │   │   ├── overlay_1.png
    │   │       │   │   ├── overlay.png
    │   │       │   │   ├── title_1.png
    │   │       │   │   └── title.png
    │   │       │   └── js
    │   │       │       ├── ChunkFive_400.font.js
    │   │       │       ├── cufon-yui.js
    │   │       │       ├── jquery.easing.1.3.js
    │   │       │       └── jquery.min.js
    │   │       ├── userNav.xhtml
    │   │       └── WEB-INF
    │   │           ├── context.xml
    │   │           ├── faces-config.xml
    │   │           ├── java.sql.Driver
    │   │           └── web.xml
    │   └── test
    │       └── java
    │           └── com
    │               └── SR_57
    └── target
        ├── classes
        │   └── com
        │       └── SR_57
        │           └── userCheck.class
        ├── endorsed
        │   └── javaee-endorsed-api-6.0.jar
        ├── generated-sources
        │   └── annotations
        ├── maven-archiver
        │   └── pom.properties
        ├── SR_57-web-1.0-SNAPSHOT
        │   ├── home.xhtml
        │   ├── index.html
        │   ├── META-INF
        │   ├── resources
        │   │   ├── css
        │   │   │   ├── sr_style.css
        │   │   │   └── style.css
        │   │   ├── images
        │   │   │   ├── 1.jpg
        │   │   │   ├── 2.jpg
        │   │   │   ├── 3.jpg
        │   │   │   ├── 4.jpg
        │   │   │   ├── 5.jpg
        │   │   │   ├── 6.jpg
        │   │   │   ├── 7.jpg
        │   │   │   ├── bg_1.jpg
        │   │   │   ├── bg.jpg
        │   │   │   ├── overlay_1.png
        │   │   │   ├── overlay.png
        │   │   │   ├── title_1.png
        │   │   │   └── title.png
        │   │   └── js
        │   │       ├── ChunkFive_400.font.js
        │   │       ├── cufon-yui.js
        │   │       ├── jquery.easing.1.3.js
        │   │       └── jquery.min.js
        │   ├── userNav.xhtml
        │   └── WEB-INF
        │       ├── classes
        │       │   └── com
        │       │       └── SR_57
        │       │           └── userCheck.class
        │       ├── context.xml
        │       ├── faces-config.xml
        │       └── web.xml
        ├── SR_57-web-1.0-SNAPSHOT.war
        └── surefire

64 directories, 75 files

I placed the context.xml file into WEB-INF directory and I added this line:
<?xml version="1.0" encoding="UTF-8"?>
<SessionCookie path="/" />

I added a java code which takes from the beans the cookie number and writes them into database. Then I run bought EAR packages to see are they going to share one session id. It turns out that that the cookie id from one client with one browser is different. The configuration is not working. I use JBoss 7.1.0
Maybe I have mistaken the directory where I have to place the context.xml file?

A: I think the proper way is to go for Single Sign On options. There are few open source projects available like JOSSO, OpenSSO etc.

A: Session cookies are by default tied to the context path. You'd like to tie them to the domain root instead (assuming that all webapps runs on the same domain) so that the browser will return the same session cookie back to all webapp contexts running in the same domain. You could do it by either a custom cookie which is tied to the domain instead of the context path by setting the cookie's path accordingly:
Cookie cookie = new Cookie(name, value);
cookie.setPath("/");

or by configuring the servlet container to tie the default session cookie to the domain instead of the context path. In case of JBoss, check the <SessionCookie> setting in context.xml:
<SessionCookie path="/" />


text:
Q: I want to convert variable from percentage to absolute I want to convert percentage values into absolute, without mutate, in a long list of variables.
key b  c d
25 2.2 6.1 4.4
34 9.2 3.1 5.4
23 3.2 9.1 6.4
45 5.2 6.2 7.4

here b, c, d variabes are in percentage. Lets assume key shows total no. And I want to convert b,c, d into absolute. so b = key*b/100, and similarly c and d.
I have use dplyr, but did not get success so far.
Many thanks, things are working:

A: 1) Base R If b, c, d are percentages and key is the total then, as already noted in the comments, the absolute amount for b is key * b / 100 (and not the formula shown in the question) so applying that to all columns at once we have the following.  mutate is not used and, in fact, no packages at all are used.
ix <- 1  # columns not to change.  Must include at least key column.
replace(DF, -ix, DF[-ix] * DF$key / 100)

giving:
  key     b     c     d
1  25 0.550 1.525 1.100
2  34 3.128 1.054 1.836
3  23 0.736 2.093 1.472
4  45 2.340 2.790 3.330

2) %>% pipe If you want to use dplyr then it could be written with %>% :
library(dplyr)
DF %>% replace(-ix, .[-ix] * .$key / 100)

3) %$% pipe or with magrittr %$% :
library(magrittr)
DF %$% replace(., -ix, .[-ix] * key / 100)

Note
DF in reproducible form is assumed to be:
Lines <- "key b  c d
25 2.2 6.1 4.4
34 9.2 3.1 5.4
23 3.2 9.1 6.4
45 5.2 6.2 7.4"
DF <- read.table(text = Lines, header = TRUE)

A: As mentioned by @jogo if you want to calculate absolute value based on key, formula should be
df[-1] * df$key/100

which in dplyr would be
library(dplyr)
df %>% mutate_at(-1, ~ . * key/100)

#  key     b     c     d
#1  25 0.550 1.525 1.100
#2  34 3.128 1.054 1.836
#3  23 0.736 2.093 1.472
#4  45 2.340 2.790 3.330


text:
Q: Partitions into 0,1, and 2 with a partial sum condition. On a tangent to a problem I've been working on, I've run into a combinatorial/partition-theoretic problem that I wondered if anyone had run into before.
Let $N$ be a positive integer, and ad-hoc-ly call an (ordered) non-negative partition of $N$ into exactly $N$ parts
$$
N=n_1+n_2+\cdots+n_N
$$
valid if

*
*$0\leq n_i\leq 2$ for all $i$; and

*
*$\sum\limits_{k=1}^i n_k<i$ for all $i<N$.
So these are something like partitions where the running total is always bounded by the number of terms added thus far.  (So the running average of the elements of the partition is less than 1.)  In particular, this forces $n_1=0$ and $n_N=2$.
I'm more interested in whether this notion of a "valid" partition has arisen previously in the literature than an explicit count of how many of them there are for a given $N$ (probably a reasonably straight-forward linear recurrence or something), so any such references would be appreciated.

A: This is A168049 or, with slightly different indexing, the Motzkin numbers.
The general question of counting nondecreasing sequences which stay below the diagonal is very common in combinatorics and goes by the name Lukasiewicz words. Stanley has a good discussion Enumerative Combinatorics II, Sections 5.3 and 5.4 and I wrote up some notes when I taught this material last Fall.
In general, to count Lukaswiecz sequences from $(0,0)$ to $(n,n)$, one uses the generating function relation
$$P = x W(P(x))$$
where $W = \sum w_k x^k$ and sequences are counted with weight $w_0^{a_0} \cdots w_i^{a_i}$, where $a_i$ is the number of times you increase by $i$. In your case, you want to permit increases by $(0,1,2)$, and not keep track of how many of each you are using, so you want to look at
$$P = x(1+P+P^2)$$
which has the solution $P(x) = (-1 + x + \sqrt{1 - 2 x - 3 x^2})/(2 x)$. Unlike the Catalan case, I don't think you can get any simpler than this.
To make my notes match up with your indexing, discard the final $2$ from your sequence, and take your $n_i$ to be my $d_i$, if I am not mistaken.
To add a bit of self promotion, call your sequence $a(n)$. It starts out $1$, $1$, $2$, $4$, $9$, $21$, $51$ ... Define $b(n)$ so that $a(n) = b(n) + b(n+1)$. So the $b$'s start out $1$, $0$, $1$, $1$, $3$, $6$, $15$, $36$ ... That sequence is A005043 and I blogged about it.

A: Sounds like ballot paths and Catalan numbers. Replace each 0,1,2 with UU,UR,RR respectively to get an Up Right path from (0,0) to (n,n) which stays above the diagonal until the end.


text:
Q: What is a document in MongoDB? I've read quite some docs now (and also found the question here, but it is still unclear what a document is.
Take the following example:
"users": [
    {
        name: { first: "Alan", last: "Turing" },
        contact: { phone: { type: "cell", number: "111-222-3333" } }
    },
    {
        name: { first: "John", last: "Doe" },
        contact: { phone: { type: "cell", number: "111-222-3333" } }
    }
]

My current assumption is that
{
    name: { first: "Alan", last: "Turing" },
    contact: { phone: { type: "cell", number: "111-222-3333" } }
}

is one document. So the 16MB limit applies to this whole array element. So whatever is in this document, like phone and name, are only embedded documents and therefore do not have this 16MB limit on their own.
Is this correct?

A: An every single document has a 16 MB size restriction, basically the document is an each data set / a record wrapped inside a "{ }" and which is immediate child of a collection (not nested / embedded document)  is a single document, each such a document has a 16 MB of size limit because it is loaded in the memory to read / write data as a single complete record (like row in a relational DB)
Mongo DB has restriction on its document size maximum 16 MB so it should not take more memory inside RAM to represent in BSON format for its efficient memory management


text:
Q: Usar explode para separar categorias boa tarde como eu poderia usar o explode nesse trecho de código para ele ter mais de uma categoria por filme? agradeço a ajuda
$categoria = $_GET['category'];
$sql = "SELECT * FROM filme WHERE categoria IS NOT NULL AND categoria LIKE '%$categoria%' ORDER BY nome LIMIT 25";

a variavel $categoria ela e um get e esta sendo chamada no index no href com ?category=acao
ou se nao for filmes de acao ficaria em outro href ?category=aventura

A: Embora o que você está fazendo está sujeito ao SQL Injection, você pode usar o implode() para transformar um array para um string.
Supondo que seu $_GET é assim:
http://site.com.br/filmes?category=acao&category=romance&category=thriller

Você poderia fazer algo assim:
$categoria = $_GET['category'];
$likes = implode("%' OR categoria LIKE '%",$categoria);
/* esse implode faz um array assim:
  [0] => 'acao',
  [1] => 'romantico',
  [2] => 'thriller'

  ficar assim:

  "acao%' OR categoria LIKE '%romantico%' OR categoria LIKE '%thriller"
*/

$sql = "SELECT * FROM filme WHERE categoria IS NOT NULL AND ( categoria LIKE '%$likes%' ) ORDER BY nome LIMIT 25";

O explode() pega um string e se torna em array, por exemplo:
$str = "este,e,um,string";
$array = explode(",",$str);
//devovle:
/*
  [0] => "este",
  [1] => "e",
  [2] => "um",
  [3] => "string"
*/

Então para usar o explode(), o $_GET teria que ser assim:
http://site.com.br/filmes?category=acao,romance,thriller

E aí a única coisa que muda é:
$categoria = explode(',', $_GET['category']);

Elaboração
Foi esclarecido que seu problema é o fato que acao também devolve animacao devido a mesmas letras acao.
Nesse caso, teria que mudar seu SQL. Tem algumas opções:

*

*Use o IN(), para igualar certinho. Assim, retorna filmes onde categoria é IGUAL "acao", mas não "animacao" ou "acao-terror".
SELECT * FROM filme WHERE categoria IN ( 'acao' )

*Use o LIKE, mas com menos %. Assim, retorna filmes onde categoria tem "acao" na frente e nao como final de palavra.
SELECT * FROM filme WHERE categoria LIKE 'acao%'
Aqui está um SQLFiddle, mostrando um exemplo de ambos os casos.

A: Supondo que o conteúdo de $_GET['category'] seja por exemplo:
$_GET['category'] = "ação, comédia, romance";

Você poderia fazer assim:
$categorias = !empty($_GET['category']) ? $_GET['category'] : '';

$categorias = implode("', '", explode(', ', $categorias));

$sql  = "SELECT *
         FROM filme
         WHERE
            categoria IS NOT NULL AND
            categoria IN ('{$categorias}')
         ORDER BY nome LIMIT 25";

O trecho $categorias = implode("', '", explode(', ', $categorias)); está fazendo o seguinte:
A parte explode(', ', $categorias) explode o conteúdo da variável que é "ação, comédia, romance" em um array ["ação", "comédia", "romance"].
Então a parte implode("', '", explode(', ', $categorias)) "cola" esse conteúdo que foi "explodido" em uma string usando como separador de cada parte a string ', ' então o resultado agora é "ação', 'comédia', 'romance".
Com esse resultado podemos usar na condição IN do SQL para dizer que o campo tem que ter um valor semelhante a algum dos elementos ou seja categoria IN ('ação', 'comédia', 'romance') que quer dizer que o valor do campo categoria tem que ser igual a ação ou comédia ou romance.
Ou você pode ainda concatenar vários LIKEs, como estava fazendo:
$categorias = explode(', ', $categorias);

$sql  = "SELECT *
         FROM filme
         WHERE
            categoria IS NOT NULL AND (";

foreach ($categorias as $categoria) {
    $sql .= " categoria LIKE '%{$categoria}%' OR ";
}

$sql = rtrim($sql, ' OR ') . ") ORDER BY nome LIMIT 25";

A:
Sugiro que edite a sua pergunta, pois conforme você mencionou, em uma resposta, o seu problema é outro.

Minha resposta para o problema:
Utilize essa função, chamada clean, para remover os espaços ou traços entre os caracteres:

function clean($string) {
   $string = str_replace(' ', '', $string); // Substitui os espaços vazios.
   $string = str_replace('-', '', $string); // Substitui os traços

   return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Remove todos os special chars.
}

echo clean('anim a c a o');
echo '<br />';
echo clean('anim-a-c-a-o');

Saída:
animacao
animacao

EXEMPLO ONLINE


text:
Q: Sublime - expand selection only to matches Sublime-Text-3 Expands the selection in a weird manner.I have the following Code-Snippet:
    appName = "Weired Application"
    for i in appName:
        print i

When i select i and want to expand selection to the next occurrence, it will select the i of the word in. How can i expand selections only to matches? When i mark "i" it will show the correct selection, which is the i next to print but its expanding to the next occurring character.
I already tried almost every combination in search/replace (as those options are related to CTRL + D as well)

A: Did you tried to just place the cursor next to i then CTRL + D? in my case(Windows 8.1), selecting a block on i then CTRL + D and placing cursor before/next to i then CTRL + D gave me different outcome, and placing cursor(not making a block) gave me the result that you wanted.


text:
Q: Figuring out the complexity of the code I wrote a simple code trying to understand the BigOh notation evaluation.
based on the link:
big-o-how-do-you-calculate-approximate-it
My code is here [It was just random, no specific reason why I ended up with this code]:
public class ScratchPad {

    /**
     * @param args
     */
    public static void main(String[] args) {
        int[] data = {1,2,3,4,5,6};
        int result = 0;
        int N = 6; //From 0 through 6
        for (int i =0;i<N;i++)
        {
            result += data[i];
        }

        System.out.println("Final result: "+result);
    }

}

The series of N and f(N) based on the actual result by running this code snippet is:
Values of N:    0, 1, 2, 3, 4,  5,  6
Values of f(N): 0, 1, 3, 6, 10, 15, 21

My question:
What formula is f(N) following? something like 2*N^2 or N+N*1-1 etc.
I tried some of these and the equation does not work out.

A: f(N) is the sum of all integers which are less or equals to N.
f(N) = N + f(N-1)
     = N + N-1 + N-2 + ... + 2 + 1
     = N*(N+1) / 2


text:
Q: How Do I create a log using performance monitor in SQL? A company I deal with have their own server, and a couple of sites using SQL server 2005 on it.  They are getting random, intermitten freezes and its pointing to SQL Server so the company who they got the server from said to
"create a log using performance monitor in SQL"
I have RD Access... Is this a simple setting I just need to put on?  Or is it more technical?

A: With SQL Performance Monitor you can create Data Collector Sets
Start SQL Performance Monitor - User Defined (Right click) - New - Data Collector Set
It will create a file in a directory you can change during the wizard.
Run it - Stop it.
There is a "log" you can open with SQL Performance Monitor

A: Use SQL Profiler and when you setup the new trace you can choose "Save to file" as an option.
Depending on your usage, you may need to filter out a lot of the trace to only show relevent databases and/or queries.

A: Yes it is. The performance monitor creates the tables that you need and log the information that you want.


text:
Q: Shutting Down or Hibernating Overnight? This question is for the all important reason of winning a bet.
Which of the following is more energy efficient?

*

*Leave a Windows 7 computer sleeping overnight

*Leave a Windows 7 computer hibernating overnight

*Shut Down a Windows 7 computer and start it in the morning
More importantly, is there a way to measure this?  From a Layman's point of view is seems obvious that number three is the right answer, but when I started thinking about the lower power drawn in a sleep/hibernation state, and the Hard Work™ a computer needs to do when it starts up, I started wondering if this might be one of those counter intuitive things.

A: You measure it by getting something like a Kill-A-Watt.
And the answer will be that #2 and #3 are the same, and involve the lowest power levels.
Sleep mode involves keeping parts of the computer powered for a quick restart. Hibrenate involves pushing everything to disk, then doing a full hardware shutdown, so hibernate and shutdown are the same (power-wise), while sleep needs a little bit of power to keep things alive.

A: The only difference between a hibernate and a power-off is that hibernation backs up the contents of RAM to the hard drive first, followed by a power-off.  Both states leave the computer in the lowest-power state possible.
#1 is standby.  It's a lower power state, but it's still using enough power to keep the contents of RAM refreshed, and the CPU is still running in a low-power idle state.
Wven when powered off, the system still consumes a tiny amount of power.
The only truly zero power state is to unplug it.

A: Hibernating and shutdown the computer should be identical. The difference is as follows:

*

*Sleep: Most of your hardware is powered off, or put into a low power state. The contents of RAM are kept alive through continuos refreshes, which uses some power. This mode is the fastest to wake up from, but not as power saving as the others

*Hibernate: The contents of your RAM are written to disk, and your computer is powered off. When you wake it up, it loads your data back into RAM. This saves more power, but takes longer to wake from

*Off: From a power consumption point of view, this should be equivalent to hibernation, but you will not be restored to the previous state when you turn the computer back on.
If you want to know how much of a difference in power consumption there is between these different modes, you can use a device like Kill-A-Watt (as Michael Kohne wrote in his answer).


text:
Q: Using UINavigationItem on UITabBarController I have a project with a UITabBarController and a couple of views.  Sort of like this:

In this project, the tab bar controller is called by tapping the Tab button on the UIViewController.  I would like to get rid of the back button with "Title", and replace it with an "X" icon.  When tapped, the "X" icon would dismiss the UITabBarController and return to the caller.  I do this all of the time on UINavigationController using a UINavigationItem, but that does not appear to work in this situation.  I drag the UINavigationItem to the view and it allows it, but it does not show up on the view and any UIBarButtonItem that I drag and drop on it do not appear.
Is there a way to actually do this?  I'd even be ok with leaving the existing back button as it is and just getting rid of "Title"

A: I figured it out right after posting the question.  Just a bit more research is all it took.
To fix this, add the following to the UITabBarController code.
override func viewDidLoad() {
    super.viewDidLoad()

    let buttonImage = UIImage(named: "back")

    let leftButton = UIBarButtonItem(image: UIImage(named: "back"), style: .plain, target: self, action: #selector(dismissTabBar))
    leftButton.tintColor = UIColor.black

    self.navigationItem.leftBarButtonItem = leftButton
}

@IBAction func dismissTabBar() {
    self.navigationController?.popToRootViewController(animated: true)
}

This gives me a black back button with my image.  When I tap it, it brings me back to the calling 'UIViewController.


text:
Q: Grails: Ajax response empty I want to change the layout when there is an ajax request. So I setup an Filter for that:
class AjaxFilters {

def filters = {
    ajaxify(controller: '*', action: '*') {
        after = { Map model ->

    if(model==null) {
        model = new HashMap()
    }

    // only intercept AJAX requests
    if (!request.xhr) {
        model.put("layout", "mainUsers")
        return true
    }

    // find our controller to see if the action is ajaxified
    def artefact = grailsApplication
        .getArtefactByLogicalPropertyName("Controller", controllerName)
    if (!artefact) { return true }

    // check if our action is ajaxified
    def isAjaxified = artefact.clazz.declaredFields.find {
        it.name == 'ajaxify'
    } != null

    def ajaxified = isAjaxified ? artefact.clazz?.ajaxify : []
    if (actionName in ajaxified || '*' in ajaxified) {
        model.put("layout", "ajax")
        return false
    }
    return true
        }
    }
}
}

This creates a view model named "layout" which should define what layout to use.
Here is an example view which uses the layout model:

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
<meta name="layout" content="${layout}"/>
<title>Profile</title>

Edit Profile

This is the controller:
class SettingsController {
def springSecurityService
static ajaxify = ["profile", "account"]

def profile() {
    User user = springSecurityService.currentUser

    UserProfile profile = UserProfile.findByUser(user)

    if(profile == null) {
        flash.error="Profile not found."
        return
    }

    [profile: profile, user: user]
}
}

A normal request works as expected, but when I try an ajax one the response is completly empty. Only headers are sent.

A: You are returning true or false for ajax requests which will return blank. You should convert the model object as JSON using render function or convert the model object to JSON and return it.
You don't need to check if action is ajaxified; just return the JSON object.

A: After your model.put("layout", "ajax") you don't want to return false but rather true.  Returning false indicates the filter failed in some way and halts all further processing, which will result in an empty response being returned to the browser.  If you return true, the updated model will continue through the processing chain and be rendered in your gsp.


text:
Q: smoothness and symmetry imply smoothness in two variables Suppose that a function  $f:\mathbb C\times\mathbb C\to \mathbb R$ has the following properties:

*

*$f$ is symmetric; which means $f(x,y)=f(y,x)$

*For any $x\in \mathbb C$, the map $f(x,\cdot):\mathbb C\to\mathbb R$ is $C^\infty$.

Is it true that $f$ is a $C^\infty$ function on $\mathbb C\times\mathbb C$?

A: Counterexample:
$$
f(x,y) =
\begin{cases}
\dfrac{\operatorname{Re} (xy)}{|x|^2 + |y|^2}, &(x,y)\ne(0,0),\\[2ex]
0, &(x,y)=(0,0).
\end{cases}
$$
This function is not even continuous at $(0,0)$.


text:
Q: I am working in Deseq2 package in R and trying to export data using write.csv( dataframe, file=" file.csv") but was unable to get the data in the file resSig <- subset(res, res$padj < 0.05 )

Using this code i create a vector resSig
head( resSig[ order( resSig$log2FoldChange ), ], 500)

I print top 500 genes
 baseMean log2FoldChange     lfcSE      stat       pvalue         padj
                 <numeric>      <numeric> <numeric> <numeric>    <numeric>    <numeric>
ENSG00000096006   1987.812       -14.1212  1.286311 -10.97807  4.87215e-28  5.77837e-25
ENSG00000170477 125694.012       -11.3416  0.519680 -21.82421 1.36677e-105 1.37784e-101
ENSG00000143536   7731.399       -11.2569  1.504429  -7.48249  7.29248e-14  7.90489e-12
ENSG00000016602   5531.968       -10.5545  0.417882 -25.25705 9.47707e-141 1.91077e-136
ENSG00000178690    151.547       -10.4074  1.255369  -8.29030  1.12959e-16  2.01547e-14
...                    ...            ...       ...       ...          ...          ...

Now, I am trying to export this data to a csv file

A: You should start by storing the data into a data frame and then call write.csv()
resSig <- subset(res, res$padj < 0.05 )
resSig<-resSig[ order( resSig$log2FoldChange ),]
resSig_top500<-resSig[1:500,]

write.csv(resSig_top500,"resSig_top500.csv")

cheers


text:
Q: Iterating an optimize function through rows of a csv Something about how I've written this optimize function is not letting it refer to existing values in my "Input" data set to fill in a new column, "Opt":
Input=read.csv("....csv")
Input$Opt=0
Input$Opt <- optimize(f = function(x) abs(10.16 - KozakTaper(Bark='ob',
                                                SPP=Input$Species,
                                                DHT=x,
                                                DBH=Input$DBH,
                                                HT=Input$Ht,
                                                Planted=0)),
         lower=Input$Ht*.25, upper=Input$Ht+1,
         maximum = FALSE,  tol = .Machine$double.eps^0.25)[[1]]

I get the error

invalid function value in 'optimize'

Here is a brief definition of "KozakTaper" so you have some context for what I'm trying to do. The trick, and why I need to use optimize or something like it, is that I don't want y (which is what KozakTaper returns). I want to know what DHT is if y=10.16, but because the equation can't be rearranged to solve for DHT, I'm using optimize to return the DHT value that minimizes the difference between y and 10.16.
KozakTaper=function(Bark,SPP,DHT,DBH,HT,Planted){
  if(Bark=='ob' & SPP=='AB'){
    a0_tap=1.0693567631
    a1_tap=0.9975021951
    a2_tap=-0.01282775
    b1_tap=0.3921013594
    b2_tap=-1.054622304
    b3_tap=0.7758393514
    b4_tap=4.1034897617
    b5_tap=0.1185960455
    b6_tap=-1.080697381
    b7_tap=0}
  else if(Bark=='ob' & SPP=='RS'){
    a0_tap=0.8758
    a1_tap=0.992
    a2_tap=0.0633
    b1_tap=0.4128
    b2_tap=-0.6877
    b3_tap=0.4413
    b4_tap=1.1818
    b5_tap=0.1131
    b6_tap=-0.4356
    b7_tap=0.1042}
  else{
    a0_tap=1.1263776728
    a1_tap=0.9485083275
    a2_tap=0.0371321602
    b1_tap=0.7662525552
    b2_tap=-0.028147685
    b3_tap=0.2334044323
    b4_tap=4.8569609081
    b5_tap=0.0753180483
    b6_tap=-0.205052535
    b7_tap=0}
  p = 1.3/HT
  z = DHT/HT
  Xi = (1 - z^(1/3))/(1 - p^(1/3))
  Qi = 1 - z^(1/3)
  y = (a0_tap * (DBH^a1_tap) * (HT^a2_tap)) * Xi^(b1_tap * z^4 + b2_tap * (exp(-DBH/HT)) +
                                                    b3_tap * Xi^0.1 + b4_tap * (1/DBH) + b5_tap * HT^Qi + b6_tap * Xi + b7_tap*Planted)
  return(y=round(y,4))}

If you have a different approach for finding DHT for each row of data, I'm open to other suggestions.  The optimize strategy works fine for one data point (a tree of given species, diameter, and height), but since I've put in the references to column names, it's hitting the error.
All advice on what to modify is appreciated!
-KB
Research Fellow, Appalachian Mountain Club
A simplified example of the input data:
> dput(head(Input))
structure(list(Species = structure(c(3L, 3L, 3L, 3L, 8L, 8L), .Label = c("AB",
"BC", "BF", "EH", "PB", "PR", "RM", "RS", "SM", "ST", "WA", "WP",
"YB"), class = "factor"), DBH = c(6.9000001, 8.1000004, 5.8000002,
6.5999999, 9.5, 7.5999999), Ht = c(44, 43, 34, 41, 56, 58)), .Names = c("Species",
"DBH", "Ht"), row.names = c(NA, 6L), class = "data.frame")

A: Your function f returns a vector, not a scalar, as you apply it to the whole data frame. optimize cannot operate on vector-valued functions, thus outputs the message "invalid function value".
Instead, I assume you want to find an optimizing solution for every line of the data frame. Then just do it.
Bark='ob'; Planted=0
for (i in 1:6) {
SPP=Input$Species[i]; DBH=Input$DBH[i]; HT=Input$Ht[i];
f <- function(x) abs(10.16 - KozakTaper(Bark,SPP,x,DBH,HT,Planted))
o <- optimize(f, lower=Input$Ht[i]*.25, upper=Input$Ht[i]+1,
              maximum = FALSE,  tol = .Machine$double.eps^0.25)
cat(o$minimum, '  ')
}
## 11.00059   10.75038   8.500041   10.25055   26.2004   26.75473

(I changed '&' to '&&' in the KozakTaper function to avoid warnings.)


text:
Q: Why is this "the" functional of Laplace's equation? Halfway through a discussion of the finite element method for solutions to Laplace's equation, Sadiku (2000) drops in a formulation of the work functional for an electric field:

Algebraically and physically, I buy this--it looks like a true statement to me. But why bring this in? It motivates the rest of the algebra, true, but I don't see why this particular formulation is justifiably useful here. (By comparison, note that the finite difference method doesn't require this recourse.)
Sadly, Wikipedia doesn't have much to say about this specific case in either the "functional" or "energy functional" articles. I understand that minimizing with respect to a bilinear/quadratic form is a common and well-characterized thing in optimization (and minimizing a functional conditions solutions), but that doesn't answer the question in a physical sense.
The only guess that sits well with me is that since this chapter is looking for an electrostatic solution, the energy of the system should be minimized. Is that what is going on here?

A: *

*The Lagrangian density of the electromagnetic field is
$${\cal L} ~=~-\frac{1}{4\mu_0}F_{\mu\nu}F^{\mu\nu}\pm J^{\mu}A_{\mu} ~=~\frac{\varepsilon_0E^2}{2} - \frac{B^2}{2\mu_0} -\rho \phi + {\bf J}\cdot {\bf A}, \tag{1}$$
[with Minkowski sign convention $(\mp, \pm,\pm, \pm)$], while the energy density is
$${\cal E} ~=~\frac{\varepsilon_0E^2}{2} + \frac{B^2}{2\mu_0} +\rho \phi - {\bf J}\cdot {\bf A}. \tag{2}
$$

*If only the first term $\frac{\varepsilon_0E^2}{2}$ is present, as in OP's case of electrostatics without sources, then clearly it is equivalent to find stationary points for the Lagrangian (1) and the energy (2) with pertinent boundary conditions.

*The variation principle (1) leads to Maxwell's equations with source terms
$$d_{\mu}F^{\mu\nu}~=~\mp J^{\nu}, \tag{3}$$
i.e. Gauss's law & Ampere's law with Maxwell's displacement term. The source-free Maxwell's equations are implicitly assumed, cf. this Phys.SE post.

A: The key is that the minimization of that functional yields the original BVP for the exact problem, and the FEM system of equations for the numerical problem. The chain of logic goes something like this:
A. Start with a boundary value problem (p.d.e. plus boundary conditions)
B. Construct a functional, which is in units of energy, for which the BVP is the stationary point. In other words, the solution to the BVP minimizes the energy.
C. Write the solution quantity (in this case, the electric potential $V$) as a linear sum of some given basis functions. The coefficients of this expansion are unknown. This defines a finite dimensional subspace of the original infinite dimensional space.
D. Minimize the functional with respect to the unknown coefficients. This will yield the finite dimensional linear system of equations, where the coefficients of expansion in C. are the unknowns. Solving for these unknowns provides the approximate numerical solution.

In more detail for your problem:
A. The BVP is $\nabla^2 V(x,y,z) = 0\label{a}\tag{1}$
with some additional boundary conditions, which are important, but I'm going to leave out of this discussion so as to not complicate things. I'm also assuming all real quantities.
B. The functional
$W[V] = \frac{1}{2} \int \epsilon | \nabla V |^2 dv\label{b}\tag{2}$
is constructed so that $\eqref{a}$ is the stationary point. To get from $\eqref{b}$ back to $\eqref{a}$, we enforce
$\delta W = \lim_{h \rightarrow 0} ( W[V+h]-W[V] ) = 0 \label{c}\tag{3}$
$\lim_{h \rightarrow 0} ( \frac{\epsilon}{2} \int |\nabla(V+h)|^2 - |\nabla V|^2 dv ) = 0\label{d}\tag{4}$
$\epsilon \int \nabla V \cdot \nabla h dv\label{e}\tag{5} = 0 \hspace{1cm} \forall h$
$\int \nabla^2 V h dv\label{f}\tag{6} = 0 \hspace{1cm} \forall h$
To get from $\eqref{d}$ to $\eqref{e}$ involves taking the first term from a Taylor expansion of $|\nabla V|^2$ w.r.t. $\frac{\partial V}{\partial x}$,
$\frac{\partial V}{\partial y}$, and $\frac{\partial V}{\partial z}$. Details can be found in e.g. Calculus of Variations by Gelfand and Fomin.
From $\eqref{e}$ to $\eqref{f}$ is an integration-by-parts. Boundary terms are ignored, and depend on the boundary conditions, which I've also ignored.
When I say $\forall h$, I really mean for all admissible $h$, or all $h$ for which $\eqref{f}$ is valid. This depends on the function space of $\nabla^2 V$.
$\eqref{f}$ is the weak form of $\eqref{a}$, which means they are equivalent. To show this is true, note that for every region in which $\nabla^2 V$ doesn't change signs, I can construct a sufficiently smooth $h$ which is positive in that region and zero everywhere else, so $\nabla^2 V$ must be zero in that region. By separately doing this for all regions in which $\nabla^2 V$ doesn't change signs, it becomes clear that $\eqref{a}$ is the only choice which satisfies $\eqref{f}$ for all admissible $h$.
C. We look for an approximation $V_e$ of $V$ in a subspace of the possible solutions by expanding in terms of basis functions.
$ V_e(x,y,z) \equiv \sum_i x_i \alpha_i(x,y,z)\label{g}\tag{7}$
Here, $\alpha_i$ are given basis functions which define the subspace, often piecewise polynomials, and $x_i$ are as-yet-unknown coefficients.
D. We create another functional, based on $\eqref{b}$ which we wish to minimize
$W_e[\vec{x}] = \frac{1}{2} \int \epsilon | \nabla V_e |^2 dv\label{h}\tag{8}$
$W_e[\vec{x}] = \frac{\epsilon}{2} \int  \sum_i (x_i \nabla\alpha_i) \cdot \sum_j (x_j \nabla\alpha_j) dv\label{i}\tag{9}$
$W_e[\vec{x}] = \frac{\epsilon}{2}   \sum_i \sum_j x_i x_j \left( \int \nabla\alpha_i \cdot \nabla\alpha_j dv\right) \label{j}\tag{10}$
Minimizing this function with respect to each coefficient $x_k$ means
$\frac{\partial}{\partial x_k} W_e[\vec{x}] = 0\label{k}\tag{11}$
which yields
$\sum_i x_i \left( \int \nabla\alpha_i \cdot \nabla\alpha_j dv\right) = 0 \hspace{1cm} \forall j \label{l}\tag{12}$
This is the final matrix equation. In a real problem, the right-hand side of $\eqref{l}$ would be non-zero, due to either a boundary condition or a non-zero right-hand side to $\eqref{a}$.

As an aside, $\eqref{l}$ can also be developed by:

*

*Starting from the weak form $\eqref{f}$,

*Substituting the expansion $\eqref{g}$,

*Instead of "testing" with all admissible $h$, only testing with $h = \alpha_j$ for all $j$,

*Performing an integration-by-parts

Maybe it's just two different ways to get to the same place, but I've never understood the necessity of bringing all of this functional analysis into it.


text:
Q: How to add external libraries in NetBeans IDE? I downloaded the jar 4.3.1-bin.zip in http://hc.apache.org/downloads.cgi
But I don't know how to use it, I added JAR in Lib folder in Netbeans but it not resolved my problem
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

these imports yet "org.apache.http.xxxxx" does not exist
Can anybody help me? Thanks!

A: Quick solution in NetBeans 6.8.
In the Projects window right-click on the name of the project that lacks library -> Properties -> The Project Properties window opens. In Categories tree select "Libraries" node -> On the right side of the Project Properties window press button "Add JAR/Folder" -> Select jars you need.


text:
Q: Handling a collection of data in a Yesod Form Is it possible in Yesod to handle forms that contain a collection of data?
I have a form that the user can add multiple people to, on the frontend it currently looks like this:
{ people.map((person, key) => (
  <td>
    <input type="hidden" name={ `person[${key}][firstName]` } value={person.firstName} />
    <input type="hidden" name={ `person[${key}][lastName]` } value={person.lastName} />
    { person.firstName } { person.lastName }
  </td>
)) }

I then want to be able to translate that over to the backend like so:
[Person "Michael" "Snoyman", Person "Ed" "Kmett"]

This list is variable in length, so it could have as many people in the people value as the user likes. So far I've been unable to work out how to replicate this kind of thing using FormInput in Yesod.

A: You could create your own FormInput by defining the unFormInput function. This function could pull the field names from the form, extract the keys, and then you could use ireq to promote the relevant fields.
This could look something like
getPeople :: FormInput (your handler type) [People]
getPeople = FormInput $ \m l env fenv ->
    (unFormInput (peopleField peopleKeys)) m l env fenv
        where
            peopleKeys = getPeopleKeys env

getPeopleKeys
This helper function would produce all the key values for the people in your form. They wouldn't need to be valid yet, since field parsing will take care of that later.
getPeopleKeys :: Env -> [Text]
getPeopleKeys env = mapMaybe extractKey (keys env)
    where
        extractKey :: Text -> Maybe Text
        extractKey key = ... -- you could use e.g. regex here
                             -- to pull the keys out of the field names
                             -- and return Nothing otherwise

peopleField
This helper produces the FormInput. It

*

*takes a list of keys,

*generates a FormInput from each one

*

*generates a field for the first name and last name

*turns those fields into FormInputs

*produces a FormInput which combines them into a Person

*concatenates the FormInputs' results into a FormInput ... [Person]

peopleField :: Monad m => RenderMessage (HandlerSite m) FormMessage => [Text] -> FormInput m [Person]
peopleField = mapM personField
    where
        personField :: Text -> Field ... Person
        personField key = (liftA2 (Person)) (personFNameField) (personLNameField)
            where
                personFNameField = (ireq hiddenField) . fNameField key
                personLNameField = (ireq hiddenField) . lNameField key

fNameField key = ... -- this outputs "person[${key}][firstName]"
lNameField key = ... -- etc.


text:
Q: Using ADO.NET MetaDataWorkspace, how do I get a list of all foreign keys for each entity? Thanks for looking.
I have a need to interrogate my entity class in order to get a list of all entities (tables) and, for each entity/table, I need a list of all foreign keys (navigation properties?) as well as a count of the records stored in that entity's corresponding data table.
So far, I have figured out how to get a list of all entities, but I am stuck as to how to get the foreign keys and record count for each.  Any help is appreciated.
Here is my code so far:
 public static void GetAllEntities(SomeEntityContext db)
        {
            int trick = db.Some_Table.Count(); //The code below won't work without running some initial call against the entity context.  Not sure why.

            //Get a list of entities / tables
            IEnumerable<EntitySet> tables = db.MetadataWorkspace.GetItemCollection(DataSpace.SSpace)
                .GetItems<EntityContainer>()
                .Single()
                .BaseEntitySets
                .OfType<EntitySet>()
                .Where(s => !s.MetadataProperties.Contains("Type")
                            || s.MetadataProperties["Type"].ToString() == "Tables");

            foreach (var table in tables)
            {
                var tableName = table.MetadataProperties.Contains("Table")
                    && table.MetadataProperties["Table"].Value != null
                  ? table.MetadataProperties["Table"].Value.ToString()
                  : table.Name;

                //Print out some data
                System.Diagnostics.Debug.WriteLine(tableName);

                //ALSO NEED THE FOLLOWING:
                //--Count of records in table
                //--List of foreign keys for table

            }
        }

A: Try creating a DbContext Extension as follows:
e.g.  http://weblogs.asp.net/ricardoperes/entity-framework-metadata
These methods should allow you to determine FKs from the TableNavigationColumns, etc.

*

*GetTables

*GetTableName

*OneToMany

*OneToOne

*ManyToOne

*ManyToMany

*GetIdProperties

*GetNavigationProperties

*GetTableKeyColumns

*GetTableColumns

*GetTableNavigationColumns


text:
Q: Type inference & new in F# Using F# 2.0 and FSI I have the following:
let foo = List(xs)//works
let bar = new List(xs) //need type parameter 'The type System.Collectsion.Generic<_> expects 1 type argument 0 was given

now of course I can do:
let baz = new List<TypeOItemsInXs>(xs)//why?

Now is there something I reasonably can do?
Why do I have to choose between working type inference or warnings free code (if 'List' is disposable you get a warning that you should use 'new' to be explicit about it).
Any workaround? Is this a bug or something?

A: Yin Zhu answer is correct, I'd like to add one detail. In F# you can call .NET constructors with or without the new keyword. If new is omitted there's no need to add the generic parameter, but if you use new then you must add a generic parameter, even if you let type inference do the work using a wildcard _.
Thus, you can say:
> ResizeArray([1; 2; 3;]);;
val it : System.Collections.Generic.List<int> = seq [1; 2; 3]

or
> new ResizeArray<_>([1; 2; 3;]);;
val it : ResizeArray<int> = seq [1; 2; 3]

but not:
> new ResizeArray([1; 2; 3;]);;

  new ResizeArray([1; 2; 3;]);;
  ----^^^^^^^^^^^

C:\Temp\stdin(5,5): error FS0033: The type 'Microsoft.FSharp.Collections.ResizeArray<_>' expects 1 type argument(s) but is given 0

A: You can still use type inference with a wildcard _:
open System.Collections.Generic
let xs = [1;2;3]

let bar = new List<_>(xs)

BTW, to distinguish F# list and .NET List<T> container, F# has renamed the .NET List<T> to ResizeArray<T>, which is in Microsoft.FSharp.Collections and this namespace is opened by default:
let bar2 = new ResizeArray<_>(xs)


text:
Q: On the convexity of the convolution of two strictly decreasing functions Let's say I got two functions $f(z)$ and $g(y)$ and these are strictly decreasing functions, so $f(0) \gt f(1) \gt f(2) \gt \dots$ and $g(0) \gt g(1) \gt g(2) \gt \dots$. I then define a third function $h(x, y)$ which is a sum of $f$ and $g$:
$$h(x, y)= f(x-y) + g(y)$$, where $x \ge y$.
For example: $$h(10, 2) = f(8) + g(2)$$
Question
Can we, with only knowing this about these 2 functions $f$ and $g$, state that their convolution function $h$ is a convex function? If yes, how? And if no, why not? Do we need to know something about the derivatives of functions $f$ and $g$?

A: $h(x, y) = f(x-y) + g(y)$ is convex if and only if both $f$ and $g$ are convex.
The "if" is a straight-forward calculation:
$$
 h(\lambda x_1 + (1-\lambda)x_2, \lambda y_1 + (1-\lambda)y_2) \\
 = f(\lambda(x_1 -y_1) + (1-\lambda)(x_2 - y_2)) + g(\lambda y_1 + (1-\lambda) y_2) \\
 \le \lambda f(x_1-y_1) + (1-\lambda) f(x_2 - y_2) + \lambda g(y_1) + (1-\lambda) g(y_2) \\
 = \lambda h(x_1, y_1) + (1-\lambda) h(x_1, y_2) \, .
$$
The "only if" follows from $f(x) = h(x,0)-g(0)$ and $g(y) = h(y, y) - f(0)$.
The monotony of $f$ and $g$ is irrelevant here.


text:
Q: Creating a simple Chat Client/Server i was trying creating Client/server Chat in console "not gui" , in gui case i can add action listener to the JTextField and every time that user hit enter the data will be send it to the client and vise versa , in console java application how can i do that ?? i mean how could i listen to the console (or) should i listen to the BufferReader so if it full then read the Buffer ???

A: You can do smth like :
String StrRead() {
    byte[] enter = new byte[256];
    int num = 0;
    String str = new String();
    try {
        num = System.in.read(enter);
    }
    catch (Exception e)
    {
        System.out.println(e.toString());
    }
    str = new String(enter,0,num);
    return str.trim();
}

and then just call String s = StrRead();