Q:

Infrequent segmentation fault in accessing boost::unordered_multimap or struct

I'm having trouble debugging a segmentation fault. I'd appreciate tips on how to go about narrowing in on the problem.
The error appears when an iterator tries to access an element of a struct Infection, defined as:
struct Infection {
public:
  explicit Infection( double it, double rt ) : infT( it ), recT( rt ) {}
  double infT; // infection start time
  double recT; // scheduled recovery time
};

These structs are kept in a special structure, InfectionMap:
typedef boost::unordered_multimap< int, Infection > InfectionMap;

Every member of class Host has an InfectionMap carriage. Recovery times and associated host identifiers are kept in a priority queue. When a scheduled recovery event arises in the simulation for a particular strain s in a particular host, the program searches through carriage of that host to find the Infection whose recT matches the recovery time (double recoverTime). (For reasons that aren't worth going into, it's not as expedient for me to use recT as the key to InfectionMap; the strain s is more useful, and coinfections with the same strain are possible.)
assert( carriage.size() > 0 );
pair<InfectionMap::iterator,InfectionMap::iterator> ret = carriage.equal_range( s );
InfectionMap::iterator it;
for ( it = ret.first; it != ret.second; it++ ) {
  if ( ((*it).second).recT == recoverTime ) { // produces seg fault
    carriage.erase( it );
  }
}

I get a "Program received signal EXC_BAD_ACCESS, Could not access memory. Reason: KERN_INVALID_ADDRESS at address..." on the line specified above. The recoverTime is fine, and the assert(...) in the code is not tripped.
As I said, this seg fault appears 'randomly' after thousands of successful recovery events.
How would you go about figuring out what's going on? I'd love ideas about what could be wrong and how I can further investigate the problem.

Update
I added a new assert and a check just inside the for loop:
assert( carriage.size() > 0 );
assert( carriage.count( s ) > 0 );
pair<InfectionMap::iterator,InfectionMap::iterator> ret = carriage.equal_range( s );
InfectionMap::iterator it;
cout << "carriage.count(" << s << ")=" << carriage.count(s) << endl;
for ( it = ret.first; it != ret.second; it++ ) {
  cout << "(*it).first=" << (*it).first << endl; // error here
  if ( ((*it).second).recT == recoverTime ) {
    carriage.erase( it );
  }
}

The EXC_BAD_ACCESS error now appears at the (*it).first call, again after many thousands of successful recoveries. Can anyone give me tips on how to figure out how this problem arises? I'm trying to use gdb. Frame 0 from the backtrace reads
"#0  0x0000000100001d50 in Host::recover (this=0x100530d80, s=0, recoverTime=635.91148029170529) at Host.cpp:317"
I'm not sure what useful information I can extract here.

Update 2
I added a break; after the carriage.erase(it). This works.

A:

Correct me if I'm wrong but I would bet that erasing an item in an unordered multimap invalidates all iterators pointing into it.  Try "it = carriage.erase(it)".  You'll have to do something about ret as well.
Update in reply to your latest update:
The reason breaking out of the loop after calling "carriage.erase(it)" fixed the bug is because you stopped trying to access an erased iterator.


Q:

Performselector - argument 2 makes pointer from integer without cast

I have this code:
[self performSelector:@selector(animationWithType:) withObject:PasscodeAnimationTypeConfirm afterDelay:0.2];

To this method:
-(void)animationWithType:(PasscodeAnimationType)type;

Putting this in it's place:
[self performSelector:@selector(animationWithType:) withObject:[NSNumber numberWithInt:PasscodeAnimationTypeConfirm] afterDelay:0.2];

returns an NSLog of "1", which my method doesn't class as the same value as PasscodeAnimationTypeConfirm. How can i fix this?

A:

Yeah, as far as I know, you can only do performSelector:blahBlah:withDelay: with objects as parameters, not types (ints, chars, etc.).
You can create another function to help you, like this:
-(void)animationWithNumber:(NSNumber)type{
    [self animationWithType:[NSNumber intValue]];
}

And using this one from the code you posted:
[self performSelector:@selector(animationWithType:) withObject:[NSNumber numberWithInt:PasscodeAnimationTypeConfirm] afterDelay:0.2];


Q:

Does INotifyPropertyChanged require invoke in all properties

I have a model
    private List<POStatusModel> _postatuslist;
    public List<POStatusModel> PoStatusList
    {
        set
        {
            _postatuslist = value;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("PoStatusList"));
        }
        get { return _postatuslist; }
    }

    public class POStatusModel
    {
        public int pocount { set; get; }
        public string postatus { set; get; }
        public DateTime timestamp { set; get; }
        public System.Windows.Media.Brush brushColor { set; get; }
        public POStatusModel()
        { }

    }

Which is bound to the items control
        <ItemsControl Name="PoStatusItemsControl" Grid.Row="1" Margin="10,2,2,0" ItemsSource="{Binding PoStatus.PoStatusList}">
            <ItemsControl.ItemTemplate>
            <DataTemplate>
                <TextBlock Foreground="{Binding brushColor}">
                    <Run Text="{Binding pocount}"></Run>
                    <Run Text="-"></Run>
                    <Run Text="{Binding postatus}"></Run>
                </TextBlock>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
     </ItemsControl>

Once in a while the list refreshes and different data may appear. But it doesn't change. Even though the invoke gets raised.
This is how i update the list int he view model
   public MetricPoStatusModel PoStatus { get; set; }

and under timer it does this
PoStatus = new MetricPoStatusModel(Connection);
Should i be doing propertychanged invoke for elements under the PoStatus model class as well?
Thank you.

A:

Do not use lists but ObservableCollection which already implement stuff related to notification. When you add a new item to the collection, It will be added automatically to the control
You use INotifyProperty changed on classes you want to be represented by controls and which will trigger a UI update when the data updates. So if you would like the timestamp  from POStatusModel to be shown and updated, POStatusModel would need to implement the interface
Do not, ever, includeUI stuff into your VieModel, like you did with the brush. You can include a string that represents a name, and with a binding definition you would define a, so called, converter. It is a class that gets in between the data and the UI element. If you store in the VM's string a color name "red" and the VM is bound to a control, then the converter you define would take the string and try to turn it into the color object it requires. Sounds like a small overhead, but it is actually really usefull and amazing. Once you gather a collection of about 20-30 converters, your productivity will rocket sky high, esspecialy once you discover parameters to the converters
Use Fody, It will really save you a ton of time.
You will never need to use custom properties to show you a custom formating of a date, you can specify the format in XAML

I did not go too deep into details, but using the basic buzwords, you should be able to find a ton of resource on google.


Q:

Excel: Apply function to each cell inside formula

I am trying to devise a non-vba Excel function which checks each cell in multiple ranges for different parameters and then returns the number of applicable occurrences. My specific problem occurs when applying the HOUR function to a range of date-cells and counting how many of these cells are equal to a certain hour.
To clarify, in VBA I would write something like (please assume that column A contains dates):
Sub tester33()
Dim r As Range
Dim c
Dim a As Integer
Set r = Range("A1:A10")
a = 0
For Each c In r
    If (Hour(c) = 5) Then 'time is 5 am, other if conditions are omitted
        a = a + 1
    End If
Next c
MsgBox (a)
End Sub

What I would like to have working is
=COUNTIF(HOUR(A:A);"=5")

My search so far returned nada. Please note that I found answers to this question here and here, that unfortunately won't work for nonmathematical Excel functions.
I hope this isn't a completely trivial problem, as I am new to in-sheet formulas.

A:

An alternative (non-array) formula is to use
=SUMPRODUCT(--(HOUR(A:A)=5))
which doesn't require committing the formula using Ctrl+Shift+Enter. It's ultimately a matter of preference.
Also, if your data doesn't stretch the entire length of column A, consider using only the range occupied by data (e.g. A1:A50 instead of A:A), as Excel then doesn't have to iterate through blank cells, which can clunk things up.


Q:

Failure to add opacity transition via javascript

Essentially my ultimate goal was to get a fading text effect from left to right, and after a few days of trial and error I ended up here.
The function is supposed to grab all divs determined by class name, loops through the divs, and per each div assign the text out of it to a string, then iterate over each character in the string and apply opacity transition effects. I was trying to get it to work so I could tell if the transition would happen concurrent with for loop iterations, or does the loop wait until the transition is complete before going to the next character, which wouldnt get it to where I want. If somehow thats the case I was thinking of maybe a recursive algorithm if its possible javascript (have the loop go to the next character and begin transitioning when the 1st transition reached a certain percent so the original transition triggers the next etc etc)
<DOCTYPE! Html>

 this text should appear from left to right

 this text should appear from left to right

Updated attempt: Will go from 1 to 0, but not 0 to 1.
<DOCTYPE! Html>

 this text should appear from left to right

 this text should appear from left to right

A:

So based off the update above I ended up here, and it works perfectly. Thanks for everyone's efforts and inputs.
What this does is take all divs with the text class, and create a new string of characters wrapped in span tags in order to hide them individually and allow for a incremented fade in effect
<DOCTYPE! Html>

 this text should appear from left to right

 this text should appear from left to right


Q:

How do I delay a while loop?

I'm trying to make a while loop that increments a double by 0.1 once every second:
    public void keyReleased(KeyEvent e)
    {
    //When a key is released, look for any collision problems
    airOrGround(xPos, yPos);
    collision(xPos, yPos);
    //As long as onGround (which is set to false or true in airOrGround) is false,
    //yPos should increment by 1 every second
    while(onGround == false)
    {
        try {
            Thread.sleep(1*1000);
        } catch (InterruptedException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        yPos += 0.1;
        yPos = (Math.round(yPos * 10) / 10.0);
        start.setText("X = " + xPos + ", Y = " + yPos);
        airOrGround(xPos, yPos);
    }
}

Once I run it, as soon as the keyReleased() runs, the program freezes. I've also tried putting the while loop inside the try, but that doesn't work either. No errors appear in the console and without the Thread.sleep part it doesn't freeze

A:

You should look at javax.swing.Timer class.
public class Whatever
{
    javax.swing.Timer t = new javax.swing.Timer( 1000, new MyListener() );
    ...
    t.start();
}

public class MyListener() implements ActionListener
{
    public void actionPerformed( ActionEvent e )
    {
        if( !onGround )
        {
            ...
        }
    }
}

For clarity I should explain that this means you don't actually need a while loop. The Timer does the sleeping part for you, effectively.
Also, when I've used the Timer class I've had the ActionListener class (my implementation) be an inner class, so it shares instance variables.


Q:

node.js (core / framework)

I have just completed reading & implementing the awesome "The Node Beginner Book" by Manuel Kiessling. Didn't find a better resource on node.js for a newbie like me. Now I need to make a full fledged application (something like a restaurant review website) with backend handled by node.js
What should be my approach? core or framework(express/geddy)?
I would also need a nosql database like mongodb ? how do I incorporate that into my node app?
Should i also consider jade and stylus into my app?
What should be my plan of action?
I'm open to suggestions.
Thanks in advance.

A:

I recommend to start from express framework http://expressjs.com/
If you plan to use mongo database - use http://mongoose.com  ORM
If you plan to use SQL databases - use http://sequelizejs.com/
For dealing with users and authorization, you can use http://passportjs.org
Probably you can try to use my framework, build on top of expressJS
https://npmjs.org/package/hunt
it have a lot of important nodejs modules preconfigured, but i'm still working on documentation...
Anyway, take a look at http://expressjs.com/ first - this is mainstream - easy to use and minimalistic framework


Q:

Upper bound of convergence rate for unbiased estimators?

Just like we have a lower bound for the variance of unbiased estimators (Cramér-Rao), I was wondering if we have an upper bound for their convergence rate. Why do I keep seeing root-n convergence? Is it impossible to go faster than that? Why?

A:

It certainly is possible to go faster than this.
Suppose we want to "explain" the change in a variable by time,
$$
y_t=\alpha+\delta\cdot t+\epsilon_t=(1,t)'\beta+\epsilon_t,
$$
where $\epsilon_t$ is an independent sequence with $E(\epsilon_t)=0$, $E(\epsilon_t^2)=\sigma^2$ and $E(\epsilon_t^4)<\infty$. Consider the sampling error
$$\left(
\begin{array}{c}
\widehat{\alpha}-\alpha \\
\widehat{\delta}- \delta\\
\end{array}
\right)=(X'X)^{-1}X'\epsilon
$$
With $\sum_{t=1}^nt=n(n+1)/2$ and $\sum_{t=1}^nt^2=n(n+1)(2n+1)/6$ it follows that
\begin{equation}
X'X=\left(\begin{array}{cc}
n & n(n+1)/2 \\
n(n+1)/2 & n(n+1)(2n+1)/6
\end{array} \right)
\end{equation}
$X'X/n$ thus does not converge to a finite matrix. The sampling error scaled with $\sqrt{n}$ would converge to a degenerate random variable. It turns out that the appropriate scaling for $\widehat{\delta}$ is $n^{3/2}$. Thus, assign separate convergence rates to the coefficients,
\begin{equation}
\Upsilon:=\left(
\begin{array}{cc}
\sqrt{n} & 0 \\
0 & n^{3/2} \\
\end{array}
\right)
\end{equation}
Then, the suitably scaled error becomes
\begin{eqnarray*}
\Upsilon(b-\beta)&=&\left(
\begin{array}{c}
\sqrt{n}(\widehat{\alpha}-\alpha) \\
n^{3/2}(\widehat{\delta}- \delta) \\
\end{array}
\right)\\
&=&\Upsilon(X'X)^{-1}X'\epsilon\\
&=&\Upsilon(X'X)^{-1}\Upsilon\Upsilon^{-1}X'\epsilon\\
&=&\left[\Upsilon^{-1}(X'X)\Upsilon^{-1}\right]^{-1}\Upsilon^{-1}X'\epsilon\\
&=:&Q_n^{-1}v_n
\end{eqnarray*}
Inserting yields
\begin{equation}
Q_n=\left(
\begin{array}{cc}
1 & \frac{n+1}{2n} \\[.4ex]
\frac{n+1}{2n} & \frac{(n+1)(2n+1)}{6n^2} \\
\end{array}
\right)\;\;\text{ and }\;\;v_n=\left(
\begin{array}{c}
\frac{1}{\sqrt{n}}\sum_{t=1}^n\epsilon_t \\[.4ex]
\frac{1}{\sqrt{n}}\sum_{t=1}^n(t/n)\epsilon_t \\
\end{array}
\right)
\end{equation}
It is easily seen that
$$
Q_n\rightarrow Q:=\left(
\begin{array}{cc}
1 & \frac{1}{2} \\[.3ex]
\frac{1}{2} & \frac{1}{3} \\
\end{array}
\right)= O_p(1)
$$
One can furthermore show that, via a martingale difference CLT, $v_n$ converges in distribution and hence also is $O_p(1)$. Thus, the convergence rate of $\widehat{\delta}$ is $O_p(n^{3/2})$.
One could extend the example by also considering polynomial time trends. (Of course, whether, in any given application, a polynomial model is plausible is quite another question, and any good in-sample fit may well be due to overfitting.)
That you nevertheless keep seeing $\sqrt{n}$ is due to the fact that in many applications, the signal (regressor, feature, or other terminology) and the dependent variable can be seen as iid draws from an underlying population, or maybe a stationary process. In either case, the convergence rate will be $\sqrt{n}$.
That the convergence rate is faster here is due to the fact that there is "more signal" in the regressor $t$, as its values get larger and larger.


Q:

How a devotee of God leaves his body for Moksha?

Our body is city of 9 gates.  My question is how a devotee leaves a body and is different from a Yogi who quits his body for Moksha.
Generally in Tantric Yoga it is said one whose soul exits through Sushumna Nadi/skull will get Moksha.
If that's the case, how a devotee would leave his body for Moksha?

A:

Have a look at the following verse from Kathopanishad's (Kath UP) Tritiya Valli:

ShataichekA cha hridasya nAdyastAsAm murdhAnamabhinihsritaikA |
  TayorddhvamAyannmritatvameti vishvanganyA utkramane bhavanti ||
Among the 101 NAdis, that emerge from the region of heart, only one
  has gone up to the Brahmarandhra. During the time of death, only if
  the [the vital breath] is made to travel upwards through this NAdi
  bestows immortality or Moksha. If this moving out [of the vital
  breath] happens through any other NAdis then SamsAra Gati (i.e
  rebirths) is the result.
Kath Up 2.3.16

There can be many NAdis but the three principle ones among them are - IdA, PingalA and SushumnA. Of which the SushumnA is the one that is only capable of bestowing salvation.
The one NAdi being talked about in the above verse is the same SushumnA which ends in the orifice at the crown of the head (Brahmarandhra).

The Kundalini Sakti is of the form of eight Prakritis (matter) and
  coils itself eight ways or (times). The movement of Vayus (vital airs)
  checks duly the food and drink all round by the side of Skandha. It
  closes by its head (the opening of) the Brahmarandhra and during the
  time of (the practice of) Yoga is awakened by the fire (in the Apana);
  then it shines with great brilliancy in the Akasa of the heart in the
  shape of wisdom. Depending upon Kundalini which is situated in the
  centre, there are fourteen principal Nadis (viz.,) Ida, Pingala,
  Susumna, Sarasvati, Varuni, Pusha, Hastijihva, Yasasvini, Visvodhari,
  Kuhuh, Sankhini, Payasvini, Alambusa and Gandhari. Of them, Susumna is
  said to be the sustainer of the universe and the path of salvation.
  Situated at the back of the anus, it is attached to the spinal column
  and extends to the Brahmarandhra
(From the minor Upanishad called Sandilya Upanishad)

So, the summary is, it does not matter who's getting Moksha - it can be a Yogi, one who is not a Yogi, a devotee or a non-devotee - but the method remains the same for all of them. That is the vital breath must leave the body only through the Brahmarandhra in all such cases.
So, to answer your question, even for a devotee, the vital breath must leave the body through the Brahmarandhra only, if he/she has to get Moksha.
If it moves out through any other orifices then rebirth is the result.


Q:

Conflict between Gauss' theorem and the example $\mathbb{Z}[\sqrt{-5}]$

Gauss' theorem says that if $R$ is a UFD then so is $R[t]$.
However, it is clear that in $\mathbb{Z}[\sqrt{-5}]$, there exists irreducible elements that are not prime ($x=1+\sqrt{-5}$). Since an element in a UFD is irreducible iff it is prime, we can see $\mathbb{Z}[\sqrt{-5}]$ is not a UFD - but Gauss' theorem says it is.
What am I missing here? Is there some other condition that applies to the $R$ in Gauss' theorem? How to resolve the apparent conflict? Or is there no conflict and I've misunderstood something?

A:

Gauss's Theorem applies exclusively to the polynomial ring $R[x]$. $\mathbb{Z}[\sqrt{-5}]$ is not a polynomial ring in $\mathbb{Z}$, it's the quotient of a polynomial ring by $x^2+5$.


Q:

c program to divide a number and show mod of a number won't work

Hi I made a program which integer divides a number by 50 and shows the mod of that number also but the compiler tells me that "value requires left operand of assignment" for"/" I'm not sure what to do. Here's the code:
#include <stdio.h>

int main()
{
    int num;
    int i;
    int m;

    printf("enter number: ");
    scanf("%d", &num);

    num / 50 = i;
    num % 50 = m;

    printf("the division is: %d\n", i);
    printf("the remainder is: %d", m);

return(0);
}

A:

your assignment statement is backwards
use:
i = num / 50;
m = num % 50;

A:

This:
num / 50 = i;
num % 50 = m;

Is seriously illegal in C. You have to do this:
i = num / 50;
m = num % 50;

Why? Because the equals sign in C doesn't work the way it does in math. In math, an equals sign establishes that two expressions are already equal. It tells you something new about them, but doesn't change them.
In C, it's expressly used to change a variable, something you can't really do in traditional math notation. It copies the value on the right into the variable address on the left. That's why some people call it "gets" instead of "equals," as in "i gets num / 50." It makes sense when you read it that way.


Q:

SOAP request envelope not generating correctly in PHP

I am trying to create a SOAP request and have tried using both SoapClient and Zend\Soap\Client, but I just can't seem to get it to build up correctly. Here's the envelope as it is supposed to look:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
   xmlns:tem="http://tempuri.org/"
   xmlns:imag="http://custom-url-here">
   <soapenv:Header/>
   <soapenv:Body>
      <tem:Logon>
         <tem:request>
            <imag:Password>XXXXXXXX</imag:Password>
            <imag:User>XXXXXXXX</imag:User>
         </tem:request>
      </tem:Logon>
   </soapenv:Body>
</soapenv:Envelope>

I'm not experienced with SOAP (REST & JSON kicks its ass, but anyway), but here's what I've managed so far:
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:ns1="http://tempuri.org/"
    xmlns:ns2="custom-url-here">

    <SOAP-ENV:Header>
        <ns2:imag/>
    </SOAP-ENV:Header>
    <SOAP-ENV:Body>

    <ns1:Logon>
        <request>
            <Password>XXXXXX</Password>
            <User>XXXXXXX</User>
        </request>
    </ns1:Logon>

    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

As you can see, it's wrong, but it's getting there. Here's the code I used:
$wsdl = 'http://url-of-wsdl';
$namespace = 'http://custom-url-here';

$client = new Client($wsdl);
$client->setSoapVersion(SOAP_1_1);

$header = new \SoapHeader($namespace, 'imag');
$client->addSoapInputHeader($header);

$params = [
    new \SoapVar([
        new \SoapVar($password, XSD_STRING, null, $namespace, 'Password'),
        new \SoapVar($username, XSD_STRING, null, $namespace, 'User'),
     ], SOAP_ENC_OBJECT, null, $namespace, 'request'),
];
$result = $client->Logon(new SoapVar($params, SOAP_ENC_OBJECT));

Can someone point out what i have done wrong? As I say, I usually work with JSON REST interfaces, so there could be several things wrong with this!
Thanks! :-)

A:

Ok, I have managed to get it to return the response I needed! I changed these lines:
$params = [
            new \SoapVar([
                new \SoapVar($password, XSD_STRING, null, null, 'ns2:Password'),
                new \SoapVar($username, XSD_STRING, null, null, 'ns2:User'),
            ], SOAP_ENC_OBJECT, null, null, 'ns1:request'),
        ];

It works, but the generated envelope still doesn't look like the original, so this isn't the best answer, and if anyone can explain how to get it identical I will be very happy!
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
                   xmlns:ns1="http://tempuri.org/"
                   xmlns:ns2="http://my-custom-url">
    <SOAP-ENV:Header>
        <ns2:imag/>
    </SOAP-ENV:Header>
    <SOAP-ENV:Body>
        <ns1:Logon>
            <ns1:request>
                <ns2:Password>XXXXXX</ns2:Password>
                <ns2:User>XXXXXX</ns2:User>
            </ns1:request>
        </ns1:Logon>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>


Q:

Map loop javascript in function not returning desired value

I have an array that contains objects that looks like this.
const arr = [
    {
        value: -1,
        label: "None"
    },
    {
        value: 24*60*60,
        label: "24 hours"
    },
    {
        value: 7*24*60*60,
        label: "7 days"
    },
    {
        value: 30*24*60*60,
        label: "1 month"
    },
    {
        value: 90*24*60*60,
        label: "3 months"
    }
];

I have the below function which 'kind of' works, but it is not returning the value. Can anyone spot what I am doing wrong?
The following is a react method
class Test extends Component {

    ......

   getLabelFromValue(arr, value) {

      arr.forEach((item) => {

        if(item.value === value) {

            return item.label;

        }

    });

}

const value = getLabelFromValue(arr, 86400); //value is equal to undefined

A:

Callum Linington has already given a short explanation and solution how to solve the problem with your .forEach() construct.
Based on the code, getLabelFromValue should return a single value only.
Hence I would use another method of Array -> Array.prototype.find
"The find() method returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned."
getLabelFromValue(arr, value) {
    let item = arr.find(i => i.value === value);
    return item ? item.label : undefined /* or any other default value... */;
}


Q:

Check for background color or image

I'm working on a blog theme which uses a mixture of featured images and featured colors when the writer publishes their post. I'd like to have the script run through three things:

Check if there is a featured image. If so, use that.
If there is no featured image, is there a featured color? If so, use that.
If neither are set, generate a random color.

I've got a snippet of JavaScript which almost works, and I think there may be a problem with the logic I'm using in the if statement.
Script
$(".post").each(function randomColor() {
        var bgCol = $(".post").css('backgroundColor');
        if ( bgCol != "rgb(0,0,0)" || (bgCol.attr('style').indexOf('image') !== -1 )) {
          var color = "#"+(Math.random()*0xFFFFFF<<0).toString(16);
          $(this).css("background-color", color)
        }
        else { return }
      });

I set up a jsFiddle to demonstrate the problem. It keeps the images, but overrides the featured color if it's set.
Any thoughts on how I can improve the if loop?
I have a demo (very sparse) of the blog theme so you can see what I'm going for.

A:

jsBin demo
I would check for the computed styles:
$(".post").each(function() {
  var cs = window.getComputedStyle(this);
  if (cs.backgroundImage==="none" &&
      cs.backgroundColor==="transparent" ||
      /0\)$/.test(cs.backgroundColor) ) {
    var color = "hsl("+ ~~(Math.random()*360) +",60%,70%)";
    $(this).css("background-color", color);
  }
});

This line /0\)$/.test(cs.backgroundColor) just tests if the rgba value ends with 0 alpha opacity 0) (Webkit returns rgba(0, 0, 0, 0) instead of "transparent" which is basically the same).
Using hsl() Hue, Saturation, Lightness (instead of hex #) will give you more control over the random generated color intensity (so you can best suit it to the general website lightness and feel).


Q:

Null pointer in my Facade :(

I've written a task manager, and well it;'s a long story... all in Java by the way. So I wrote a Facade which you can see below there is a problem with the HashMap and I suspect that the values which I attempt to add into the HashMap during the construction aren't going so well. The method that is triggering the null pointer exception is the create method. the input parameters to the method have been verified by me and my trusty debugger to be populated.
any help here would be great... I'm sure I forgot to mention something so I'll reply to comments asap as I need to get this thing done now.
package persistence;

import java.util.UUID;
import java.util.HashMap;

import persistence.framework.ComplexTaskRDBMapper;
import persistence.framework.IMapper;
import persistence.framework.RepeatingTaskRDBMapper;
import persistence.framework.SingleTaskRDBMapper;

public class PersistanceFacade {

    @SuppressWarnings("unchecked")
    private static Class SingleTask;
    @SuppressWarnings("unchecked")
    private static Class RepeatingTask;
    @SuppressWarnings("unchecked")
    private static Class ComplexTask;

    private static PersistanceFacade uniqueInstance = null;
    @SuppressWarnings("unchecked")
    private HashMap<Class, IMapper> mappers;

    public PersistanceFacade() {
        mappers = new HashMap<Class, IMapper>();
        try {
            SingleTask = Class.forName("SingleTask");
            RepeatingTask = Class.forName("RepeatingTask");
            ComplexTask = Class.forName("ComplexTask");
            mappers.put(SingleTask, new SingleTaskRDBMapper());
            mappers.put(RepeatingTask, new RepeatingTaskRDBMapper());
            mappers.put(ComplexTask, new ComplexTaskRDBMapper());
        }
        catch (ClassNotFoundException e) {}

    }

    public static synchronized PersistanceFacade getUniqueInstance() {
        if (uniqueInstance == null) {
            uniqueInstance = new PersistanceFacade();
            return uniqueInstance;
        }
        else return uniqueInstance;
    }

    public void create(UUID oid, Object obj) {
        IMapper mapper = (IMapper) mappers.get(obj.getClass());
        mapper.create(oid, obj);
    }

    @SuppressWarnings("unchecked")
    public Object read(UUID oid, Class type) {
        IMapper mapper = (IMapper) mappers.get(type);
        return mapper.read(oid);
    }

    public void update(UUID oid, Object obj) {
        IMapper mapper = (IMapper) mappers.get(obj.getClass());
        mapper.update(oid, obj);
    }

    @SuppressWarnings("unchecked")
    public void destroy(UUID oid, Class type) {
        IMapper mapper = (IMapper) mappers.get(type);
        mapper.destroy(oid);
    }

}

A:

My guess is that your problem lies in the constructor:
    try {
        SingleTask = Class.forName("SingleTask");
        RepeatingTask = Class.forName("RepeatingTask");
        ComplexTask = Class.forName("ComplexTask");
        mappers.put(SingleTask, new SingleTaskRDBMapper());
        mappers.put(RepeatingTask, new RepeatingTaskRDBMapper());
        mappers.put(ComplexTask, new ComplexTaskRDBMapper());
    }
    catch (ClassNotFoundException e) {}

You silently ignore the ClassNotFOundException. If you add logging to the catch I expect it to tell you that the class SingleTask is not found, as I expect that you did not put those classes in the default package.
Given your reply to comments these classes are in the domain. package, so you could try to change to:
    try {
        SingleTask = Class.forName("domain.SingleTask");
        RepeatingTask = Class.forName("domain.RepeatingTask");
        ComplexTask = Class.forName("domain.ComplexTask");
        mappers.put(SingleTask, new SingleTaskRDBMapper());
        mappers.put(RepeatingTask, new RepeatingTaskRDBMapper());
        mappers.put(ComplexTask, new ComplexTaskRDBMapper());
    }
    catch (ClassNotFoundException e) {
        log.warn("Cannot load class", e);
    }

Btw, adding logging to your code will help to find the reasons behind unexpected behaviour.


Q:

Compare scala.xml.Elem object in unit test

I have two scala.xml.Elem objects (actual, expected). I am using JUnit 4, but have also included XMLUnit 1.3.
Is there any easy way to compare the two objects for equality, ignoring attribute order and insignificant whitespace in the XML?
I tried XMLUnit.assertXMLEqual(), but it complains that the types are scala.xml.Elem.
I know that I can use equals or ==, but I would like the benefit of having the assertion print the two values when they are not equal. If I use assertTrue(actual.equals(expected)), and they are not equal, the only output will be "assertion failed".

A:

If you want to compare to XML Elem objects ignoring whitespaces you can remove the whitespaces from them with scala.xml.Utility.trim method.
scala> val a = <foo>bar</foo>
a: scala.xml.Elem = <foo>bar</foo>

scala> val b = <foo>   bar   </foo>
b: scala.xml.Elem = <foo>   bar   </foo>

scala> a == b
res8: Boolean = false

scala> import scala.xml.Utility.trim
import scala.xml.Utility.trim

scala> trim(a) == trim(b)
res9: Boolean = true

Scala does not care about the order of the attributes if you use XML literals:
scala> val a = <foo first="1" second="2" />
a: scala.xml.Elem = <foo first="1" second="2"></foo>

scala> val b = <foo second="1" first="1"  />
b: scala.xml.Elem = <foo first="1" second="1"></foo>

scala> a == b
res22: Boolean = true

I would recommend ScalaTest for unit testing there you have the ShouldMatchers:
// Scala repl started with scalatest-1.2.jar in the classpath

scala> val a = <foo>bar</foo>
a: scala.xml.Elem = <foo>bar</foo>

scala> val b = <foo>bar</foo>
b: scala.xml.Elem = <foo>bar</foo>

scala> a should equal(b)

scala> val b = <foo>bar2</foo>
b: scala.xml.Elem = <foo>bar2</foo>

scala> a should equal(b)
org.scalatest.TestFailedException: <foo>bar</foo> did not equal <foo>bar2</foo>
    at org.scalatest.matchers.Matchers$class.newTestFailedException(Matchers.scala:148)
    at org.scalatest.matchers.ShouldMatchers$.newTestFailedException(ShouldMatchers.scala:2329)
    at org.scalatest.matchers.ShouldMatchers$ShouldMethodHelper$.shouldMatcher(ShouldMatchers.scala:871)
    at org.scalatest.matchers.ShouldMatchers$SeqShouldWrapper.should(ShouldMatchers.scala:1724)
    at .<init>(<console>:15)
    at .<clinit>(<console>)
    at RequestResult$.<init>(<console>:9)
    at RequestResult$.<clinit>(<console>)
    at RequestResult$scala_repl_result(<console>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.Delega...

A:

Use the version of assertTrue that allows passing custom messages
public static void assertTrue(java.lang.String message,
                              boolean condition)

and (for example) diff to produce the string with the descendand nodes that aren't equal
scala> val xml1 = <person><name>john</name><lastname>smith</lastname></person>
xml1: scala.xml.Elem = <person><name>john</name><lastname>smith</lastname></person>

scala> val xml2 = <person><name>jane</name><lastname>smith</lastname></person>
xml2: scala.xml.Elem = <person><name>jane</name><lastname>smith</lastname></person>

scala> assert(xml1 == xml2, xml1.child diff xml2.child mkString(", "))
java.lang.AssertionError: assertion failed: <name>john</name>
        at scala.Predef$.assert(Predef.scala:91)
        at .<init>(<console>:8)
        at .<clinit>(<console>)


Q:

Numerical approximation of an integral

I read a problem to determine the integral $\int_1^{100}x^xdx$ with error at most 5% from the book "Which way did the bicycle go". I was a bit disappointed to read the solution which used computer or calculator. I was wondering whether there is a solution to the problem which does not use computers or calculators. In particular, is there way to prove that the solution given in the book has a mistake because it claims that
$$\frac{99^{99}-1}{1+\ln 99}+\frac{100^{100}-99^{99}}{1+\ln 100}\leq \int_1^{100}x^xdx$$
gives a bound $1.78408\cdot 10^{199}\leq \int_1^{100}x^xdx$ but I think the LHS should be $1.78407\cdot 10^{199}\leq \int_1^{100}x^xdx$? I checked this by Sage and Wolfram Alpha but I was unable to do it by pen and paper.

A:

Because your integrand grows so fast the whole integral is dominates for $x\approx 100$. We can write $x^x = \exp[ x \ln(x)]$ and then expanding $x \ln(x) = 100 \ln(100) + [1+ \ln(100)] (x- 100) + \cdots$ around $x = 100$ (note that it is important to expand inside the exponent). The integral can therefore be estimated as
$$\int_1^{100} dx \, x^x \approx 100^{100} \int_{-\infty}^{100} dx\, e^{[1+ \ln(100)] (x- 100) }
= \frac{100^{100}}{1 + \ln (100)}.$$ Numerics shows that this result is off by $3\times 10^{-4}$.

A:

$x^x$ grows really fast.  Notice
$$n^n>\frac{1}{n}\sum_{i=1}^{n-1} i^i.$$
In short $100^{100}$ is a lot bigger then $99^{99}$, so $$\frac{99^{99}-1}{1+\ln99}+\frac{100^{100}-99^{99}}{1+ln100}\sim \frac{100^{100}}{1+\ln100}=10^{99}\frac{10}{1+\ln100}$$
By calculator $$\frac{10}{1+\ln100}=1.78407,$$ (notice the same as above) but we can get bascially that by hand.  First show $4<\ln100<5$.  Then $$1.6=\frac{10}{6}\leq  \frac{10}{1+\ln100}\leq \frac{10}{5}=2.$$
But lets do better.  Use the fact that $$\sum_{i=1}^n\frac{1}{i}=\ln n +\gamma +E$$ where $|E|\leq \frac{1}{2n}$, and $n\geq 4$.
Then $$\ln(100)=1+\frac{1}{2}+\frac{1}{3}+\cdots +\frac{1}{100}-0.577+E$$ and diligently adding this together (under 5 minutes) gives $\ln(100)\sim 4.6$.  From here we get the coefficient $\frac{25}{14}$ with an error bounded by $\frac{2}{100}$ or 2%.  (We gained error because I cut off 4.61 to 4.6)


Q:

How to choose two random variables taking values in a finite space, with given distributions, such that probability that they are equal is maximized?

Let A = {1, 2, ..., n}, and let X and Y be two random variables on the same space, taking values in A, and distributions given by:
P(X = i) = $p_i$, and P(Y = i) = $q_i$, for any i in {1,2,...,n}
What is the maximum possible value of P(X = Y)?
Basically, we have to choose a good joint distribution of X and Y, such that the sum of diagonal entries in the joint distribution table/matrix is maximized. For n = 2, this is easy to do, and I get the answer (1 - |$p_1$ - $q_1$|). But even for n = 3, I am not able to do much. A  solution/strategy for general n would be appreciated.

A:

First for any $n$ we must have $P(X=Y=n)\leq p_i\wedge q_i$.
Set $$\pi = \sum_{i=1}^n p_i\wedge q_i.$$
We aim to choose a distribution such that $P(X=Y)=\pi$.
To do this set $$\begin{align}p'_i &= p_i - (p_i\wedge q_i) \\ q'_i &= q_i - (p_i\wedge q_i)\end{align}$$
Then
$\sum_{i=1}^n p'_i = \sum_{i=1}^nq'_i=1-\pi$.
So proceed as follows.
$\circ\qquad$With probability $\pi$ assign $X=Y$ according to the distribution $\dfrac{p_i\wedge q_i}{\pi}$.
$\circ\qquad$With probability $1-\pi$ assign $X$ and $Y$ independently.
So set
$$P(X=i,Y=j)=\begin{cases}p_i\wedge q_i &:\mathop{if}\,i=j, \\
\frac{p'_i\cdot q'_j}{1-\pi} &:\mathop{if}\,i\neq j.
\end{cases}$$
Then summing over $j$ we have
$$\begin{align}P(X=i) &= (p_i\wedge q_i) + \sum_{j=1}^n \frac{p'_i\cdot q'_j}{1-\pi} \\
&= (p_i\wedge q_i) + p'_i\sum_{j=1}^n \frac{ q'_j}{1-\pi} \\
&=p_i.\end{align}$$


Q:

2nd derivative test , Maximum point

A study shows that a human body reaction R to a dosage D of a certain drug is given by
$$ R = D^2(\frac{k}{2} - \frac{D}{3}) $$
Show that he rate of change in the reaction $R$ with respect to the dosage $D$ is maximum if $D = K/2 $
My first derivative is
$R' = KD - D^2 $,
Dosage for maximum reaction = $k$
My second derivative is
$R''= K - 2D $
$R(\frac{k}{2}) = k - 2(\frac{k}{2}) = 0 $
But 0 is neither negative or positive , how do I show that it's a maximum (negative) ?

A:

Use the first derivative test on $R'$. It's immediate that $R''>0$ when $D < k/2$, and $R''<0$ when $D>k/2$. Thus, since $R''(k/2)=0$, it follows that $R'$ has a local maximum at $D=k/2$. But since there's only one critical point, it follows that the local maximum is, in fact, a global maximum.

However, if you prefer, you can use the second derivative test. The second derivative of $R'$ is $R'''$ which is identically $-2$. In particular, $R'''(k/2)<0$, hence, since $R''(k/2)=0$, it follows that $R'$ has a local maximum at $D=k/2$. But once again, since there's only one critical point, it follows that the local maximum is, in fact, a global maximum.

An even simpler approach is to note that $R'$ is a quadratic function of $D$ with negative leading coefficient, hence the critical value for $R'$ (i.e., $D=k/2)$ is where $R'$ attains a global maximum.

A:

As I mentioned in my comment, you are confused with what the question being asked is. It wants you to show that the rate of change, $R'$, (not $R$) achieves a maximum at $\frac{k}{2}$.
By setting $R''=0$, you have shown that there is a critical point at $\frac{k}{2}$, now you only have to show that it is a maximum.
I will take the approach of the second derivative test as you mentioned in the title.
We must find the second derivative of $R'$, namely, $R'''$.
$R'''=\frac{d}{dD}(R'')=\frac{d}{dD}(K-2D)=-2.$
Since $R'''$, the second derivative of $R'$, is negative regardless of what $D$ is, then $D= \frac{k}{2}$ which we found as the only critical point is a maximum.


Q:

Sort a set of fractions with respect to numerator or denominator?

I would like to know how to sort a set of fractions with respect to numerator (or denominator) or both. For example sort
$$
3/5, 13/21, 19/30, 2/3, 5/7, 11/15, 3/4, 11/14, 4/5, 5/6, 7/8, 9/10, 1
$$
with respect o numerator to get
$$
1,2/3,3/5,3/4,4/5,5/7,5/6,7/8,9/10,11/15, 11/14,13/21, 19/30
$$
or with respect to both (first numerator, then denominator)
$$
1,2/3,3/4,3/5,4/5,5/6,5/7,7/8,9/10,11/14,11/15,13/21,19/30
$$
Thanks!

A:

From SortBy >> Details:

So, for the second requirement, you can simply do
SortBy[lst, {Numerator, Denominator}]

A:

Here is one way, more or less similar to what others have already suggested.
list = {3/5, 13/21, 19/30, 2/3, 5/7, 11/15, 3/4, 11/14, 4/5, 5/6, 7/8,
9/10, 1};

SortBy[list, Numerator]
(*{1, 2/3, 3/5, 3/4, 4/5, 5/7, 5/6, 7/8, 9/10, 11/15, 11/14, 13/21, \
19/30}*)

SortBy[list, Denominator]
(*{1, 2/3, 3/4, 3/5, 4/5, 5/6, 5/7, 7/8, 9/10, 11/14, 11/15, 13/21, \
19/30}*)

EDIT: In the case where the list should first be sorted by numerator, and then such that successive runs of identical numerators are sorted by denominator, one could do this by using SplitBy, Map and Flatten. This is probably not the only way to go about it, but anyway:
listnumsort = SortBy[list, Numerator];

listnumsortsplit = SplitBy[listnumsort, Numerator];

listfullsortsplit = Map[SortBy[#, Denominator] &, listnumsortsplit];

listfullsort = Flatten[listfullsortsplit]
(*{1, 2/3, 3/4, 3/5, 4/5, 5/6, 5/7, 7/8, 9/10, 11/14, 11/15, 13/21, \
19/30}*)

Above, the list is first sorted by numerator, and then split into sublists of successive runs of identical numerators. Each of these sublists is sorted by denominator, and the result is glued back together.


Q:

read output from a class executed as a process

I am using Runtime.getRuntime().exec(test.class) to create a process and launch a test.class file.
test.class:
public class test {
    public static void main(String[] args) {
        doReturn();
    }

    public static String doReturn() {
        System.out.println("printed output");
        return "returned output";
    }
}

in the Java application launching this process, I'd like to retrieve the output of this test.class
The code I use looks like:
Process proc = null;
String[] cmd = { "java", "test"};
proc = Runtime.getRuntime().exec(cmd);

InputStream inputStream = proc.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

String line;
while ((line = bufferedReader.readLine()) != null)
{
    System.out.println(line);
}

This snippet of code does not work: nothing is printed and I get an Exitvalue of 1 for my process.
=> How should I modify it (and / or modify test.class) to return "printed output" to my java application?
=> Is it possible to return "returned output" as well?
(I am new to Java so could you please be very detailed in your answers! Thx!)

A:

I don't know what are you want to do but try to remove the .class
String[] cmd = { "java", "test"};


Q:

Why can `s => x.Append(s)` can be passed as an Action but `x.Append` can't?

I noticed something strange when trying to pass a StringBuilder's Append method to a function that took an Action<string>.
public void DoStuff(Action<string> handler)
{
    // Do stuff, call handler("data");
}

For testing purposes, I just want to write the data into a StringBuilder, so I tried to call it like this:
var output = new StringBuilder();
DoStuff(output.Append);

However, this gives a compile error, because the Append method does not match the required signature (it returns a reference back to the StringBuilder, not void as my method wants):

'System.Text.StringBuilder System.Text.StringBuilder.Append(string)' has the wrong return type

Without thinking, I changed the code to this:
var output = new StringBuilder();
DoStuff(s => output.Append(s));

This compiled fine.
Then I got confused; realising that s => output.Append(s) should also return the StringBuilder, aren't they the same?
So, why does this work? Why can s => output.Append(s) have the return value discarded silently, yet output.Append cannot?

A:

s => output.Append(s) creates a new lambda expression, which is inferred (from the context) to have a return type of void.
Therefore, the value of the expression body is ignored.
This is compiled to a separate method that calls Append() and returns void (this exactly matching the delegate)
In contrast, when you attempt to convert a method group to a delegate, the conversion must match exactly.
The spec (§6.5) says:

Specifically, an anonymous function F is compatible with a delegate type D provided:

If the body of F is an expression, and either D has a void return type or F is async and D has the return type Task, then when each parameter of F is given the type of the corresponding parameter in D, the body of F is a valid expression (wrt §7) that would be permitted as a statement-expression (§8.6).


Q:

Listen to event fired when the content has changed in CKEditor 5

How can I listen to the "input" event in ckeditor5 ? I would like to be able to use Observables like this:
Observable.fromEvent(this.editor, "input").debounceTime(250).subscribe(() => {});

So far, I've been able to listen to some events like this:
Observable.fromEvent(this.editor.editing.view, 'selectionChangeDone').subscribe(() => { });

But I don't find the name of the event that would be fired as soon as data changed in the editor. I tried "change" but it only fires when the editor get or lost focus.

A:

Since CKEditor5 v11.0.0 (since 21 July 2018)
What you probably need is the Document#change:data event fired by editor's document.
editor.model.document.on( 'change:data', () => {
    console.log( 'The data has changed!' );
} );

This event is fired when the document changes in such a way which is "visible" in the editor data. There's also a group of changes, like selection position changes, marker changes which do not affect the result of editor.getData(). To listen to all these changes, you can use a wider Document#change event:
editor.model.document.on( 'change', () => {
    console.log( 'The Document has changed!' );
} );

Prior to CKEditor5 v11.0.0
What you probably need is a change event fired by editor's document.
editor.model.document.on( 'change', () => {
    console.log( 'The Document has changed!' );
} );

As the documentation of this event says:

Fired after each enqueueChange() block or the outermost change() block was executed and the document was changed during that block's execution.
The changes which this event will cover include:

document structure changes,
selection changes,
marker changes.

If you want to be notified about all these changes, then simply listen to this event like this:
  model.document.on( 'change', () => {
      console.log( 'The Document has changed!' );
  } );

If, however, you only want to be notified about structure changes, then check whether the differ contains any changes:
  model.document.on( 'change', () => {
      if ( model.document.differ.getChanges().length > 0 ) {
          console.log( 'The Document has changed!' );
      }
  } );

The last code snippet is useful when implementing features like auto-save.

A:

First of all, I see you are using Observable.fromEvent which seems to be a part of RxJS and works with jQuery events. CKEditor 5 does not use RxJS nor jQuery. It uses custom events and custom observables which are something different than observable you want to use.
So note that:
Observable.fromEvent(this.editor.editing.view, 'selectionChangeDone');

is not a proper way of listening to the event and works most probably only because of some duck typing.
The proper way of listening on CKE5 events is:
this.editor.editing.view.on( 'selectionChangeDone', () => { /*...*/ } );

Second, 'input' is not an event but a command. If you want to listen in this command execution you can do:
this.editor.commands.get( 'input' ).on( 'execute', ( evt, args ) => {
    console.log( evt, args );
} );

However, this is a very fresh API, which will be introduced in the next version of ckeditor-core (0.9.0), so you need to use the current master branch to use it.


Q:

Where are the Microsoft downloaded app compat updates stored?

Where are the Microsoft application compatibility update settings stored on a Windows XP, Windows Vista, and Windows 7 computer?
Microsoft periodically release application compatibility updates (e.g. KB929427), where they list the shims that should be applied to a program in order to workaround known bugs in the software. Where are these app compat flags stored, and how can i see what shims are being applied?
i have a feeling that a recent app compat update included a flag to force a particular piece of software, that we use, to require administrator. Because the task is scheduled to run nightly, and the running user does not have administrative privelages, the task is failing to start.
The application is requiring to be elevated. It has the UAC shield overlay. The application has no RT_MANIFEST resource, and the compatibility option Run this program as administrator is disabled (per-user and all users). So all that's left is some secret global setting.
i know user-specified compat flags are stored in:
HKEY_LOCAL_MACHINE
   \SOFTWARE
     \Microsoft
       \Windows NT
         \CurrentVersion
           \AppCompatFlags
             \Layers

A:

They are probably in a database file in c:\Windows\AppCompat.
But your best bet is to download the latest Application Compatibility Toolkit as the "Compatibility Administrator" contains their complete database.  You could use it to disable some or all shims from being applied to your backup application.


Q:

ejecutar string como codigo php

Acabo de añadir un fragmentos de codigo PHP más HTML y todo eso lo añadi a mi tabla TBLPRUEBA, el problema es que al momento de llamar el codigo NO SE EJECUTA EL CODIGO PHP, pero si llega a colocarse el codigo HTML.
Tabla en Oracle
CREATE TABLE TBLPRUEBA
(
ID_ACORDEON NUMBER PRIMARY KEY,
DESCRIP_ACORDEON CLOB
);

Codigo PHP + HTML

                                            <?php echo $cabecera[0]["NOMBRE_CABECERA"]; ?>

                                                <?php echo $cabecera[1]["NOMBRE_CABECERA"]; ?>

                                                <?php require_once "include/ficha_de_valoracion_de_gestion_educativa_1.php"; ?>

                                                <?php echo $cabecera[2]["NOMBRE_CABECERA"]; ?>

                                                <?php require_once "include/ficha_de_valoracion_de_gestion_educativa_2.php"; ?>

                                                <?php echo $cabecera[3]["NOMBRE_CABECERA"]; ?>

                                                <?php require_once "include/ficha_de_valoracion_de_gestion_educativa_3.php"; ?>

                                                <?php echo $cabecera[4]["NOMBRE_CABECERA"]; ?>

                                                <?php require_once "include/ficha_de_valoracion_de_gestion_educativa_4.php"; ?>

                                                <?php echo $cabecera[5]["NOMBRE_CABECERA"]; ?>

                                                <?php require_once "include/ficha_de_valoracion_de_gestion_educativa_5.php"; ?>

                                            <?php echo $cabecera[6]["NOMBRE_CABECERA"]; ?>

                                                <?php echo $cabecera[7]["NOMBRE_CABECERA"]; ?>

                                                <?php require_once "include/ficha_de_evaluacion_de_promocion_educativa_zonales_1.php"; ?>

                                                <?php echo $cabecera[8]["NOMBRE_CABECERA"]; ?>

                                                <?php require_once "include/ficha_de_evaluacion_de_promocion_educativa_zonales_2.php"; ?>

                                                <?php echo $cabecera[9]["NOMBRE_CABECERA"]; ?>

                                                <?php require_once "include/ficha_de_evaluacion_de_promocion_educativa_zonales_3.php"; ?>

                                                <?php echo $cabecera[10]["NOMBRE_CABECERA"]; ?>

                                                <?php require_once "include/ficha_de_evaluacion_de_promocion_educativa_zonales_4.php"; ?>

                                                <?php echo $cabecera[11]["NOMBRE_CABECERA"]; ?>

                                                <?php require_once "include/ficha_de_evaluacion_de_promocion_educativa_zonales_5.php"; ?>

                                            <?php echo $cabecera[12]["NOMBRE_CABECERA"]; ?>

                                                <?php echo $cabecera[13]["NOMBRE_CABECERA"]; ?>

                                                <?php require_once "include/ficha_de_evaluacion_de_coordinacion_educativa_zonales_1.php"; ?>

                                                <?php echo $cabecera[14]["NOMBRE_CABECERA"]; ?>

                                                <?php require_once "include/ficha_de_evaluacion_de_coordinacion_educativa_zonales_2.php"; ?>

                                                <?php echo $cabecera[15]["NOMBRE_CABECERA"]; ?>

                                                <?php require_once "include/ficha_de_evaluacion_de_coordinacion_educativa_zonales_3.php"; ?>

                                                <?php echo $cabecera[16]["NOMBRE_CABECERA"]; ?>

                                                <?php require_once "include/ficha_de_evaluacion_de_coordinacion_educativa_zonales_4.php"; ?>

                                                <?php echo $cabecera[17]["NOMBRE_CABECERA"]; ?>

                                                <?php require_once "include/ficha_de_evaluacion_de_coordinacion_educativa_zonales_5.php"; ?>

                                            <?php echo $cabecera[18]["NOMBRE_CABECERA"]; ?>

                                                <?php echo $cabecera[19]["NOMBRE_CABECERA"]; ?>

                                                <?php require_once "include/ficha_de_valoracion_de_coordinacion_academica_est_1.php"; ?>

                                                <?php echo $cabecera[20]["NOMBRE_CABECERA"]; ?>

                                                <?php require_once "include/ficha_de_valoracion_de_coordinacion_academica_est_2.php"; ?>

                                                <?php echo $cabecera[21]["NOMBRE_CABECERA"]; ?>

                                                <?php require_once "include/ficha_de_valoracion_de_coordinacion_academica_est_3.php"; ?>

                                                <?php echo $cabecera[22]["NOMBRE_CABECERA"]; ?>

                                                <?php require_once "include/ficha_de_valoracion_de_coordinacion_academica_est_4.php"; ?>

                                                <?php echo $cabecera[23]["NOMBRE_CABECERA"]; ?>

                                                <?php require_once "include/ficha_de_valoracion_de_coordinacion_academica_est_5.php"; ?>

                                            <?php echo $cabecera[24]["NOMBRE_CABECERA"]; ?>

                                                <?php echo $cabecera[25]["NOMBRE_CABECERA"]; ?>

                                                <?php require_once "include/ficha_de_evaluacion_del_desempeno_docente_1.php"; ?>

                                                <?php echo $cabecera[26]["NOMBRE_CABECERA"]; ?>

                                                <?php require_once "include/ficha_de_evaluacion_del_desempeno_docente_2.php"; ?>

                                                <?php echo $cabecera[27]["NOMBRE_CABECERA"]; ?>

                                                <?php require_once "include/ficha_de_evaluacion_del_desempeno_docente_3.php"; ?>

EJECUTAR SCRIPT
<?php echo $tabla[0]["DESCRIP_ACORDEON"] -> load()?>

A:

puedes hacero asi:

nota:
  todas las variable deberian existir antes de esta ejecucion!
  debo agregar es que es un codigo sumamente peligroso.
  que no deberia ser llevado a produccion ni puesto en practica.
  lo agrego como metodo de ilustrativo de estudio y posible solucion a una interrogante.
  no es un solucion viable. recomiendo re-evaluar la logica y sacar todo codigo php del la base de datos!

// almacenamos el primer resultado de la base de datos
$resultado = $res["DESCRIP_ACORDEON"][0];

// creamos un array dividiendo por el codigo php
$html = preg_split("'<\?php(.*?)\?>'", $resultado);
// seleccionamos todo el codigo php
preg_match_all("'<\?php(.*?)\?>'", $resultado, $php);
// seleccionamos el elemento 1 que contiene el resultado del preg_match_all!
$php = $php[1];

// hacemos un loop para cada elemento html
for ($i=0; $i < $html ; $i++) {
    // imprimimos el html
    echo $html[$i];
    // validamos que exista codigo php para esa posicion
    if (isset($php[$i])) {
        // aplicamos eval que evalua y ejecuta nuestro codigo!
       eval($php[$i]);
    }
}


Q:

How to store a JSON object into an object property?

I made a quiz with jQuery, very poorly coded. And now im recoding it using OOP. However, I have a problem storing JSON information into my model property.
var quizModel = {
    currentQuestion: 0,
    correctAnswers: 0,

    init: function() {
        "use strict";
        $('.quiz').append('

');
        $('.form').append('<form id="form"></form>');
        quizView.addQuestion();
    },
    getJson: function() {
        "use strict";
        return JSON.parse($.ajax({
            type: 'GET',
            url: 'package.json',
            dataType: 'json',
            global: false,
            async:false,
            success: function(data) {
                return data;

            }
        }).responseText);
    },
    answerDatabase: this.getJson()
};

I cant store the JSON object into the answerDatabase property. And I dont know why. When I wasnt using OOP I was able to do store the returned object into a variable and have access to that object across my javascript file. Anyone have a clue how to fix this?
The console says (Uncaught TypeError: Cannot read property 'getJson' of undefined)

A:

answerDatabase: this.getJson() is being called before your object definition is complete, so in scope this is probably the window object. You will need to restructure your code to something like (this is not a perfect example)
var quizModel = {
    currentQuestion: 0,
    correctAnswers: 0,

    init: function() {
        "use strict";
        $('.quiz').append('

');
        $('.form').append('<form id="form"></form>');
        quizView.addQuestion();
    },
    getJson: function() {
        "use strict";
        return JSON.parse($.ajax({
            type: 'GET',
            url: 'package.json',
            dataType: 'json',
            global: false,
            async:false,
            success: function(data) {
                return data;

            }
        }).responseText);
    },
    answerDatabase: {};
};

quizModel.answerDatabase = quizModel.getJson();


Q:

Which automation tool should be learn for mobile devices?

I am working as a manual tester.I need to learn automation because my company has mobile application projects in pipeline process.
So please suggest which tool should I learn ? Thanks in advance

A:

This question is very broad and is one of those question which is bound to get biased replies based on User's opinions.
So when you say,

So please suggest which tool should I learn

There is no definitive, clear-cut answer, until we understand the projects that are in pipeline are.
Nevertheless, on the top of my head, I can name quite a few mobile automation tools here :

Appium
Calaba.sh
Robotium
Monkeytalk
Ranorex

Here is a link of such tools, which I compiled in my blog few months ago :
https://qatechnicals.wordpress.com/testing-tools/best-mobile-automation-tools/


Q:

"The ( kind/type ) of stress those activities tend to (cause/give/provoke/other) ...". Which noun and verb should I use?

In this context:

"The kind/type of stress those activities tend to (verb)..."

I've found that kind / type are used interchangeably, is one more appropiate than the other?
Talking about the verb, I've found very few examples of sentences like "X gives/causes me stress", so I'm not sure if I could use one of them here or if there's another more suitable verb.

So: Which noun (kind/type) and verb (give/cause/provoke/other) would be appropiate for this sentence?

A:

I would say:

The kind of stress those activities tend to cause...

using kind for undefined or loosly defined cases. To the average person, stress is probably a loosely defined condition.

What kind of lunch are you having?

since there are more variations of food items than you would have in mind.
I would use type when referring clearly defined cases.
For example, if I was a psychologist, I might say:

The type of stress those activities tend to cause...

because I would know specific types of stress one may experience.
type is also used to describe specific conditions, like:

What type of diabetes do you have?
  I have type 2 diabetes.

Finally, in the above examples I would use cause for the verb, as this phrase describes a cause and effect relationship.


Q:

QTreeView policy subclass. Is this sane?

I am kinda sick of making subclasses for each minor modification I need to make in QWhateverView behaviour so I got an idea:
What if I make a ProxyView for most commonly overriden functions that will essentially do stuff like:
//(mousePress used as an example)
void ProxyView::mousePressEvent ( QMouseEvent * event )
{
    if(mousePressFunctionHandler != nullptr)
       functionHandler(this, event);
    else
       QTreeView::mousePressEvent(event);
}

While it's true that I won't have access to view's internals this way, I often don't need it anyway... The only thing stopping me so far is that I am not sure if this idea is sane or not... :)
Or is there better way?

A:

It seems you need to use event filters.


Q:

Why doesn't Unity voice recognition work for single letters?

I am trying to create a voice recognition game in unity. What i don't understand is when i use word such as "left" or "forward", it easily detects it. But when it comes to just using a letter, it doesn't detect it at all even though i followed same method to detect.The game requires using only single letter.Does anybody knows how to detect letters through voice recognition in unity?
Following is the code i used:
private KeywordRecognizer keywordRecognizer;
private Dictionary<string, Action> actions = newDictionary<string,Action>();

void Update{
actions.Add("Left", Left);//this works
actions.Add("A", Alpha);//this doesn't

keywordRecognizer = new KeywordRecognizer(actions.Keys.ToArray());
keywordRecognizer.OnPhraseRecognized += RecognizedSpeech;
keywordRecognizer.Start();
}

private void RecognizedSpeech(PhraseRecognizedEventArgs speech){
    Debug.Log(speech.text);
    actions[speech.text].Invoke();

    word = speech.text;
    results.text = "You said: <b>" + word + "</b>";
}

private void Left(){
    transform.Translate(-1, 0, 0);
 }

private void Alpha(){
    transform.Translate(1, 0, 0);
}

A:

In Short: Single letter recognition is really hard.
Just imagine the differences between b,p and d.
One thing you can do is set your KeywordRecognizer to low confidence
keywordRecognizer = new KeywordRecognizer(actions.Keys.Array(), ConfidenceLevel.low);

But, this wont help you as you will most likely have way more wrong recognitions afterwards. Further, if you want to say commands back to back the KeywordRecognizer will fail you anyways as he processes over the first keyword and ignores the ones spoken during the processing delay.
An alternative would be DictationRecognizer which does not listen for specific key words, but translates the user voice into a text which you could then scan for your key words / letters. Obviously, this also has a massive delay.
So, if you can't have a delay, then I supppose the only valid solution is to rethink why you need letter recognition and not full keywords like "alpha" instead of "a".


Q:

Is there an option in ReSharper to not remove the blank line I put between the namespace and class definition?

Every time I let ReSharper format my code, it removes the blank line I put between the namespace and class declaration.
From this:
namespace Test {

  public class Test {

To this:
namespace Test {
  public class Test {

It does the same thing with the blank lines at the closing braces of both.
All my "blank line" settings are set to 1, except for single line fields.
Is there an option I'm missing?

A:

This is actually now an option (as of June 2016). Go to ReSharper | Options -> Code Editing | C# | Formatting style | Other and check Line feed at end of file.

A:

Visual Studio menu: ReSharper > Options...
Type in the search box "Line feed at end of file":

A:

Fsck, just 10 minutes ahead of me. Well, I'll answer anyway. Bad news is that it's a long-time feature request http://youtrack.jetbrains.com/issue/RSRP-74903
Good news is that it would fixed in the tomorrow's 7.1 EAP build. There would be new options in ReSharper | Options -> Code Editing | C# | Formatting style | Blank Lines:

Remove blank lines after "{" and before "}" in declarations (turn it off to prevent ReSharper from removing blank line) and
Around namespace and Around type (set it to non-zero value to force ReSharper to add blank lines).


Q:

How much do “where did you hear about us?” type questions impact signup/conversion rates?

There's a truism I often hear - claiming that the less complicated the signup process for a web-service, the higher the conversion rate (as a rough measure of complexity, count mouse clicks to signup completion).
Has anyone A/B tested or otherwise measured this impact and reported on their results, comparing a signup process with a "where did you hear about us?" form to one without?

A:

Honestly speaking from personal experience,the only time I would bother to answer the question is I was applying for a job and I felt that selecting "employee referral" (provided I was referred by an employee :) ) might get me an interview or atleast get my resume in front of a recruiter.
That said,every additional field that you require the user the fill up is preventing them from actually signing up and reducing your conversion rate.
This article actually found that reducing the number of fields from 11 to 4 increased the conversion rate by 64 %. The results summary of that

Number of forms submitted increased 140%
Conversion ratio increased 120%

Here is another blog which highlights the impact of shorter forms on increased conversion rates
That said,with regards to the question you had raised about the "How did you find about us field",this article gives some input about what happened to their form when they got rid of it. To summarize their results :

Many years ago we had a client who was having the debate about whether
  or not to include the ‘how did you hear about us?’ question on their
  form. To solve it once and for all, they included a wacky choice in
  the drop down— “billboard,” and although the client never ran a
  billboard ad, this ended up being the most selected choice. Question
  removed from form forever.

A:

This might be helpful. I'll remove it if it breaks the rules.
I once converted a long and gruelling sign up form and chopped it up into wizard-like steps and compared them A/B style. In both cases there was a "Where did you hear about us?" field (I failed to get stakeholders to allow me to drop it).
In both cases it was an optional step and I found that the field was completed way more often in the wizard version than in the long form.


Q:

Buscar conjunto de registros por data

Atualmente estou criando um programa Java/Mysql Desktop.
Ao inserir no banco, a tabela está bem simples:
id - dataInserido - códigoProduto - qtd

Eu gostaria, por meio de um SQL, agrupar em ordem decrescente os últimos registros inseridos na mesma data.
Exemplo: tenho atabela de produtos inseridos
id - data - produto - qtd
1 - 20/05/2017 - 10001 - 100
1 - 24/05/2017 - 10002 - 10
1 - 27/05/2017 - 100010 - 30
1 - 29/05/2017 - 100020 - 60
1 - 29/05/2017 - 100060 - 70
1 - 29/05/2017 - 100010 - 100

Como agrupar os últimos (29/05/2017), sendo 100020, 100060 e 100010, uma vez que tenho que montar essa tabela no Java ? Uma espécie de filtro solicitado pelo usuário.
ps: eu não desejo levar nenhuma data pelo java, mas sim uma consulta pelo próprio sql.

A:

O que você precisa é filtrar pela coluna data utilizando a cláusula WHERE com NOT EXISTS:
SELECT t.id,
       t.data,
       t.produto,
       t.qtd
  FROM tabela t
 WHERE NOT EXISTS(SELECT 1
                    FROM tabela t2
                   WHERE t2.data > t.data)
 ORDER BY t.produto DESC

A cláusula ORDER BY irá ordenar os registros de acordo com a coluna que foi especificada.
Note que respeitei o nome das colunas dado no exemplo e não na sua descrição.


Q:

Avoid Wrapping Text only in first column of R datatable

I'm struggling with keeping text in one column of a datatable from wrapping.

I'd like to avoid wrapping text in the first column (as it's the only part that makes the row size bigger), but keep the option in the headers (to avoid having to scroll).
I've tried adjusting the width of the first column, but the text keeps wrapping no matter what size I use.
DT::datatable(chartfilter,
    rownames = FALSE,
    options=list(iDisplayLength=7,
                 bPaginate=FALSE,
                 bLengthChange=FALSE,
                 bFilter=FALSE,
                 bInfo=FALSE,
                 rowid = FALSE,
                 autoWidth = FALSE,
                 ordering = FALSE,
                 scrollX = TRUE,
                 columnDefs = list(list(width='500px', targets = list(1)))

I've also found a solution that turns text wrapping off in the entire table - but I don't want that for my column labels. Adding this in the UI in front of the tableoutput:
tags$style(HTML("#charttable  {white-space: nowrap;  }")),

Is this possible, or do I just have to accept wrapping text in the first column? Appreciate any help I can get, and let me know if more info is needed.

A:

Use the formatStyle() function to apply a specific style to a column:
datatable() %>% formatStyle("Region","white-space"="nowrap")

This function comes from the same library (DT). More info on formatStyle() can be found here: https://rstudio.github.io/DT/010-style.html


Q:

This row has been removed from a table and does not have any data

This row has been removed from a table and does not have any data.  BeginEdit() will allow creation of new data in this row.
I have a method where I'm trying to delete all duplicate rows (using the date) and I'm getting the above exception with my code. I understand what the exception means but I don't understand what I'm doing wrong in my code to cause it. I have looked over it several times with no luck.
            using (OldStockRatingsTableAdapter ratingsAdapter = new OldStockRatingsTableAdapter())
            using (DataSet.OldStockRatingsDataTable ratingsTable = new DataSet.OldStockRatingsDataTable())
            {
                ratingsAdapter.ClearBeforeFill = true;
                ratingsAdapter.Adapter.UpdateBatchSize = 500;
                ratingsAdapter.FillByMarketSymbol(ratingsTable, market, symbol);

                var masterQuery = from c in ratingsTable
                            where c.Symbol == symbol && c.Market == market
                            select c;
                List<DataSet.OldStockRatingsRow> masterRows = masterQuery.ToList();
                List<DataSet.OldStockRatingsRow> masterDistinctRows = masterQuery.DistinctBy(i => i.Date).ToList();

                for (int i = 0; i < masterDistinctRows.Count; i++)
                {
                    var dateQuery = from c in masterRows
                                    where c.Date == masterDistinctRows.ElementAtOrDefault(i).Date
                                    select c;
                    List<DataSet.OldStockRatingsRow> dateRow = dateQuery.ToList(); // getting the exception here

                    if (dateRow.Count > 1)
                    {
                        for (int j = 1; j < dateRow.Count; j++)
                        {
                            ratingsTable.RemoveOldStockRatingsRow(dateRow.ElementAtOrDefault(j));
                            Console.WriteLine("Stock rating deleted for " + symbol + " in the " + market + " market!");
                        }
                    }
                }

                // update everything here
                DataSet.OldStockRatingsDataTable tempRatingsTable = new DataSet.OldStockRatingsDataTable();
                tempRatingsTable = (DataSet.OldStockRatingsDataTable)ratingsTable.GetChanges();

                if (tempRatingsTable != null)
                {
                    ratingsAdapter.Adapter.UpdateCommand.UpdatedRowSource = UpdateRowSource.None;
                    ratingsAdapter.Adapter.DeleteCommand.UpdatedRowSource = UpdateRowSource.None;
                    ratingsAdapter.Adapter.InsertCommand.UpdatedRowSource = UpdateRowSource.None;
                    ratingsAdapter.Update(tempRatingsTable);
                    tempRatingsTable.Dispose();
                    Console.WriteLine("Stock rating calculations finished for " + symbol + " in the " + market + " market!");
                }
 }

A:

I don't know about your code but if all that you are trying to do is delete duplicates then maby this code is of some use to you:
delete duplicate query
with x as (
select *, row_number() over(partition by <COLUMN>, checksum(<Columns to validate>) order by <COLUMN>) as rn
from <TABLE>
)
delete x where rn > 1
//it will validate multiple columns if more are given

Note: this code was not made by me, I'll link the origional post here. The code was posted by @dean.


Q:

If I deleted a question of mine, does other user's rep go away?

Say I have a question and somebody answers. He gets upvotes and I even make him the best answer. But later I delete my question. Does his rep go away because I deleted my own question? Or only the rep I gave him. Like when I gave him an upvote and best answer. And the other people who upvoted for him stays?

A:

Someone else would need to downvote the answer for you to be able to delete it (questions that have an answer with a positive score cannot be deleted by their author), but if someone else did cast such a downvote, then yes, the answerer would lose the 8 rep they had gained from the answer.


Q:

No visible WebSecurityExpressionHandler instance could be found in the applicationContext

Am trying to implement Section level security using Spring3.1. Using Thymeleaf2.0 for my view part.  Here is the configuration i have made to do so,
Jars Used## - All spring3.1 jars and thymeleaf-extras-springsecurity3.jar (version 1.0.0.beta-1)
SpringWebFlow-Servlet.xml
<bean id="templateEngine" class="org.thymeleaf.spring3.SpringTemplateEngine">
     ...
     <property name="additionalDialects">
     <set>
         <bean class="org.thymeleaf.extras.springsecurity3.dialect.SpringSecurityDialect"/>
     </set>
     </property>
     ...
</bean>
<bean id="webexpressionHandler" class="org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler" />

spring-security.xml
 <http auto-config="true" use-expressions="true">
     <intercept-url pattern="/productSelection" access="hasRole('ROLE_ADMIN')"/>
    .....
 </http>

xxx.html
<div sec:authorize="hasRole('ROLE_ADMIN')">
    This only be seen if authenticated user has role ROLE_ADMIN.
</div>

Issue

Getting an Exception stating :
No visible WebSecurityExpressionHandler instance could be found in the applicationContext

In Spring3.1, DefaultWebSecurityExpressionHandler doesn't implement WebSecurityExpressionHandler and the interface is deprecated. Please let me know the workaround as Thymeleaf is trying to search for the instance of WebSecurityExpressionHandler which is not available in ApplicationContext.

A:

You'll need to define the bean in your application (root) context not in your servlet context.
<bean id="webSecurityExpressionHandler" class="org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler"/>

I had same problem moved it from servlet-context.xml to root-context.xml and the bean is picked up.
Depending on your spring setup it can be in another xml file so check your web.xml for the Spring context root.
In your case if spring-security.xml is imported in your Spring root context you can add it there.


Q:

Forming word combinations from file

I am looking for ideas to optimize the below code for speed.  I'm also looking for some good improvement in execution time.
This code reads a text file. The text file has many lines of ASCII text. Then it finds words out of them (space/tab delimiter). It has to neglect any punctuation symbol in the file. Then it uses those words to form a combinations as [word1][word2] to pass to the hashing function to get a result.
#include "stdio.h"
#include "string.h"
#include "stdlib.h"
#include "ctype.h"

main(int argc,char *argv[])
{
    FILE *fin;
    unsigned int i,k,j=0,m=0;
    char c;
    char *ptr, *p;
    char line_buf[1500];
    char word[75];
    unsigned int line_no = 1;
    char encrypted_pass[120];//Currently it would support MD5,DES,SHA256,SHA512(max - 104 character encrypted password)
    char *result;
    char pass_key[120];
    char num[6] = {'0','2','4','8','\0'};
    unsigned int words_found = 0,len=0;

    char words[1500][8];

    fin = fopen(argv[1], "rt");
    if(fin == NULL)
    {
        //Exit if file not found
        printf("Error opening input file,...exiting...\n");
        exit(-1);
    }

    //Read lines from the file until end of file
    while(!feof(fin))
    {
        //Initialize a index to point to current character in line buffer
        i=0;
        //Initialize a index to current character to be stored in word string
        k=0;
        //read one line at time, from the file
        ptr = fgets(line_buf,1500,fin);

        if(ptr == NULL)//End of file has reached,stop reading
        {
            break;
        }

        if(line_buf[i] == '\n')//End of line has reached,continue to read next line
        {
            continue;
        }

        if(line_no == 1)//This is the line containing encrypted password
        {
            line_no++;
   //Remove any leading spaces,tabs present in the encrypted password line
            while(isspace((unsigned char)(line_buf[m])))
            {
                 m++;
            }
   strcpy(encrypted_pass,&line_buf[m]);

   //Remove any trailing spaces,tabs present in the encrypted password line
   len = strlen(encrypted_pass);
   while ((len > 0) && (isspace((unsigned char)encrypted_pass[len - 1])))
   {
                encrypted_pass[--len] = 0;
            }

   len = strlen(encrypted_pass);
   if(len == 15)//DES-based algorithm where encryped password is 13 characters
   {
    if(encrypted_pass[len-2] == '\r')
    {
     encrypted_pass[len-2] = '\0';//for \r\n newline character
    }
   }
   else if(len == 14)//DES-based algorithm where encryped password is 13 characters
   {
    if(encrypted_pass[len-1] == '\n')
    {
     encrypted_pass[len-1] = '\0';//for \n newline character
    }
   }
   else if(len == 36)//MD5-based algorithm where encryped password is 34 characters
   {
    if(encrypted_pass[len-2] == '\r')
    {
     encrypted_pass[len-2] = '\0';//for \r\n newline character
    }
   }
   else if(len == 35)//MD5-based algorithm where encryped password is 34 characters
   {
    if(encrypted_pass[len-1] == '\n')
    {
     encrypted_pass[len-1] = '\0';//for \n newline character
    }
   }
    /*
    else if(len == 63)//SHA256-based algorithm where encryped password is 61 characters
    {
        if(encrypted_pass[len-1] == '\n')
        {
            encrypted_pass[len-1] = '\0';//for \n newline character
        }
    }

    else if(len == 62)//SHA256-based algorithm where encryped password is 61 characters
    {
        if(encrypted_pass[len-1] == '\n')
        {
            encrypted_pass[len-1] = '\0';//for \n newline character
        }
    }
    else if(len == 106)//SHA512-based algorithm where encryped password is 104 characters
    {
        if(encrypted_pass[len-1] == '\n')
        {
            encrypted_pass[len-1] = '\0';//for \n newline character
        }
    }
    else if(len == 105)//SHA512-based algorithm where encryped password is 104 characters
    {
        if(encrypted_pass[len-1] == '\n')
        {
            encrypted_pass[len-1] = '\0';//for \n newline character
        }
    }
    */

   continue;
  }

  //Parse any leading space/tabs present at start of line
  //while(((line_buf[i] == ' ')||(line_buf[i] == '\t'))&&((line_buf[i+1] == ' ')||(line_buf[i+1] == '\t')))
  while((isspace((unsigned char)(line_buf[i])))&&(isspace((unsigned char)(line_buf[i+1]))))
  {
   i++;
  }
  //while((line_buf[i] == '\t')||(line_buf[i] == ' '))
  while(isspace((unsigned char)(line_buf[i])))
  {
   i++;
  }
        //Parse each character in the current line to construct words from it
        while((c=line_buf[i])!=' ')
        {
           /*
           if(line_buf[i] == 0)//End Of File reached
           {
            break;
           }
           */
            if((c=='(')||(c=='[')||(c=='{'))//neglect these characters
            {
                i++;
                continue;
            }

            //Deduce that a word is found based on these character delimeters
            if((c==',')||(c=='.')||(c==';')||(c=='!')||(c=='?')||(c==')')||(c==']')||(c=='}'))
            {
                i++;
                //Insert a null character to terminate the word string
                word[k] = '\0';
                //Check the length of the word found
                //len = strlen(word);
                len = k;

                //Only those words whose length is less than 7 characters are valid due to restriction on password length(8 chars)
                if(len != 0)
                {
                    if(len < 7)
                    {
                        //one word found, so increment the counter
                        words_found++;
                        //convert that word to lower case as password consists of lower case words only
                        //lower_case_str(word);
                        for (p = word; *p != '\0'; p++)
                        {
                           *p = (char) tolower(*p);
                        }
                        //store the word from word string to the word buffer
                        strcpy(words[j],word);
                        //Point to the next row in the 2D words buffer array for words found in the file
                        j++;
                    }
                }
                //reset the index in the word string
                k=0;
                if(line_buf[i] == '\n')//It is end of current line, go to read next line
                {
                    break;
                }

    //while(((line_buf[i] == ' ')||(line_buf[i] == '\t'))&&((line_buf[i+1] == ' ')||(line_buf[i+1] == '\t')))//there are multiple space characters, so consume them as long as you reach non-space char
    while((isspace((unsigned char)(line_buf[i])))&&(isspace((unsigned char)(line_buf[i+1]))))
    {
     i++;
    }
    //while((line_buf[i] == ' ')||(line_buf[i] == '\t'))
    while(isspace((unsigned char)(line_buf[i])))
    {
     i++;
    }
    /*
    while(((line_buf[i] == '\t')||(line_buf[i] == ' '))&&((line_buf[i+1] == ' ')||(line_buf[i+1] == '\t')))//there are multiple tabs here, so consume them as long as you reach non-tab char
    {
     i++;
    }

    while((line_buf[i] == '\t')||(line_buf[i] == ' '))
    {
     i++;
    }
    */
                if((line_buf[i] == ' '))//Continue to parse next character
                {
                    i++;
                    if(line_buf[i] == '\n')//It is end of current line, go to read next line
                    {
                        break;
                    }
                }

                continue;//Continue to parse next character
            }
   if(isalpha((unsigned char)(c)))
            {
                //Current character is a valid alphabetic letter, so
                //Store the current character in the word string
                word[k] = c;
    //Point to the next position in the word string
                k++;
            }
            else
            {
                //Current character is not a alphabetic letter, so neglect it
                word[k] = '\0';
            }
            //Point to the next character in the line buffer
            i++;

   if(line_buf[i] == 0)//End Of File reached
   {
    word[k] = '\0';
    //len = strlen(word);
    len = k;
    if(len != 0)
    {
     if(len < 7)
     {
      words_found++;
      //lower_case_str(word);
      for (p = word; *p != '\0'; p++)
        {
           *p = (char) tolower(*p);
        }
      strcpy(words[j],word);
      j++;
     }
    }

    break;
   }

   if((line_buf[i] == ' ')&&((line_buf[i-1] != '\t')&&(line_buf[i-1] != ' ')&&(isalpha((unsigned char)(line_buf[i-1])))))//A word found, based on space delimiter
   {
    i++;
    word[k] = '\0';
    //len = strlen(word);
    len = k;
    if(len != 0)
    {
     if(len < 7)
     {
      words_found++;
      //lower_case_str(word);
      for (p = word; *p != '\0'; p++)
        {
           *p = (char) tolower(*p);
        }
      strcpy(words[j],word);
      j++;
     }
    }
    k=0;
   }

   if((line_buf[i] == '\t')&&((line_buf[i-1] != ' ')&&(line_buf[i-1] != '\t')&&(isalpha((unsigned char)(line_buf[i-1])))))//A word found, based on horizontal tab delimiter
   {
    i++;
    word[k] = '\0';
    //len = strlen(word);
    len = k;
    if(len != 0)
    {
     if(len < 7)
     {
      words_found++;
      //lower_case_str(word);
      for (p = word; *p != '\0'; p++)
        {
           *p = (char) tolower(*p);
        }
      strcpy(words[j],word);
      j++;
     }
    }
    k=0;
   }

   if((line_buf[i] == '-')&&(isalpha((unsigned char)(line_buf[i-1]))))//A word found, based on - delimeter
   {
    i++;
    word[k] = '\0';
    //len = strlen(word);
    len = k;
    if(len != 0)
    {
     if(len < 7)
     {
      words_found++;
      //lower_case_str(word);
      for (p = word; *p != '\0'; p++)
        {
           *p = (char) tolower(*p);
        }
      strcpy(words[j],word);
      j++;
     }
     //strcpy(pass_key,word);
     //puts(pass_key);
    }
    k=0;
   }

   if((isspace((unsigned char)(line_buf[i])))&&(k>0))
   {
    i++;
    word[k] = '\0';
    //len = strlen(word);
    len = k;
    if(len != 0)
    {
     if(len < 7)
     {
      words_found++;
      //lower_case_str(word);
      for (p = word; *p != '\0'; p++)
        {
           *p = (char) tolower(*p);
        }
      strcpy(words[j],word);
      j++;
     }
     //strcpy(pass_key,word);
     //puts(pass_key);
    }
    k=0;

   }

   if((ispunct((unsigned char)(line_buf[i-1])))&&(k>0))
   {
    i++;
    word[k] = '\0';
    //len = strlen(word);
    len = k;
    if(len != 0)
    {
     if(len < 7)
     {
      words_found++;
      //lower_case_str(word);
      for (p = word; *p != '\0'; p++)
        {
           *p = (char) tolower(*p);
        }
      strcpy(words[j],word);
      j++;
     }
     //strcpy(pass_key,word);
     //puts(pass_key);
    }
    k=0;

   }

   //while(((line_buf[i] == ' ')||(line_buf[i] == '\t'))&&((line_buf[i+1] == ' ')||(line_buf[i+1] == '\t')))//there are multiple space characters, so consume them as long as you reach non-space char
   while((isspace((unsigned char)(line_buf[i])))&&(isspace((unsigned char)(line_buf[i+1]))))
   {
       i++;
      }
   //while((line_buf[i] == ' ')||(line_buf[i] == '\t'))
   while(isspace((unsigned char)(line_buf[i])))
   {
    i++;
   }

   /*
   while(((line_buf[i] == '\t')||(line_buf[i] == ' '))&&((line_buf[i+1] == ' ')||(line_buf[i+1] == '\t')))//there are multiple tabs here, so consume them as long as you reach non-tab char
   {
       i++;
      }

   while((line_buf[i] == '\t')||(line_buf[i] == ' '))
   {
    i++;
   }
   */

            if(line_buf[i] == '\n')//Last character in the current line(newline).
            {
                //Insert a null character to terminate the word string
                word[k] = '\0';
                //Check the length of the word found
                //len = strlen(word);
                len = k;
                //Only those words whose length is less than 7 characters are valid due to restriction on password length(8 chars)
                if(len != 0)
                {
                    if(len < 7)
                    {
                        //one word found, so increment the counter
                        words_found++;
                        //convert that word to lower case as password consists of lower case words only
                        //lower_case_str(word);
                        for (p = word; *p != '\0'; p++)
                        {
                           *p = (char) tolower(*p);
                        }
                        //store the word from word string to the word buffer
                        strcpy(words[j],word);
                        //Point to the next row in the 2D words buffer array for words found in the file
                        j++;
                    }
                }
                break;//go to read next line
            }
            else//in between a word, continue scanning for next character
            {
                continue;//Continue to parse next character
            }
        }
    }

     //Remove duplicate words
     for (i = 0; i < words_found; i ++)
    {
        j = i + 1;
        while (j < words_found)
        {
            if (strcmp(words[i], words[j]) == 0)
            {
                memmove(words + j, words + (words_found - 1), sizeof(words[0]));
                -- words_found;
            }
            else
                ++ j;
        }
    }

    for(k=0;k<4;k++)
    {
        //Form all possible combination of 2 words found with a number in between
        for(i=0;i<words_found;i++)
        {
            for(j=i+1;j<words_found;j++)
            {

                strcpy(pass_key,words[i]);

                strncat(pass_key,(const char*)(&num[k]),1);

                strcat(pass_key,words[j]);
                len = strlen(pass_key);

                if((len >= 5)&&(len <= 8))
                {

                    result = crypt(pass_key, encrypted_pass);

                    if(!strcmp(result,encrypted_pass))
                    {

                        printf("%s\n",pass_key);
                        exit(-1);
                    }

                }

            }
        }
    }

    fclose(fin);

}

A:

First, a note for those who might wonder why I'd help somebody who's apparently trying to build a tool to do dictionary attacks on passwords. The reason is pretty simple: first, there are tools that do the job pretty well already, so this is hardly unleashing anything new on the world. Second, this doesn't seem to allow for salt, which means it's pretty much obsolete anyway (and anybody who doesn't use salt deserves to be broken into in any case). Ultimately it comes down to this: I don't think helping out on this will cause any real reduction in security.
While I suppose I can guess at why you've crammed everything into main, I think it's a mistake anyway. On a reasonably modern processor, the overhead of calling a function is extremely minimal (to the point of being essentially impossible to even measure, in most cases). At the same time, the size of cache (especially level 1 cache) is limited, so eliminating redundancy can and will help speed by fitting more of your code into the cache.
Other than that, your code seems to have quite a bit of redundancy. For example:
if((line_buf[i] == ' ')&&(

    (line_buf[i-1] != '\t')&&
    (line_buf[i-1] != ' ')&&
    (isalpha((unsigned char)(line_buf[i-1]))))

)

Now, let me ask a question: do you think it's possible for isalpha(x) to return true, if x=='\t' or x==' ' was true? I'm pretty sure the definition of isalpha precludes that possibility, so you can dispense with those tests. All you appear to need is:
if(line_buf[i] == ' ') && isalpha((unsigned char)line_buf[i-1]))

If you're trying to avoid the "overhead" of calling isalpha, be aware that in most C libraries it's implemented as a macro that uses a table lookup, so testing for ' ' and '\t' separately is more likely to be a loss than a gain. Even when/if it's a function, modern processors reduce function call overhead to the point that the extra tests are probably a loss anyway.
You then have code like:
  for (p = word; *p != '\0'; p++)
    {
       *p = (char) tolower(*p);
    }
  strcpy(words[j],word);

This is quite inefficient. First it walks through the code modifying it in place, then it copies the modified data to a new location. You should be able to improve speed by combining the two:
for (i=0; p[i]; i++)
    words[j][i] = tolower(p[i]);
words[j][i] = '\0';

Looking at a slightly higher level, you seem to care very little about the overall line structure of the input, and are interested primarily (exclusively?) in words. That being the case, you'd probably be better off not reading a line at a time. The result would be simpler, and probably faster as well. For example, you have a pretty big block of code to read the encrypted/hashed password and eliminate leading/trailing white space:
        if(line_no == 1)//This is the line containing encrypted password
        {
            line_no++;
   //Remove any leading spaces,tabs present in the encrypted password line
            while(isspace((unsigned char)(line_buf[m])))
            {
                 m++;
            }
   strcpy(encrypted_pass,&line_buf[m]);

   //Remove any trailing spaces,tabs present in the encrypted password line
   len = strlen(encrypted_pass);
   while ((len > 0) && (isspace((unsigned char)encrypted_pass[len - 1])))
   {
                encrypted_pass[--len] = 0;
            }

   len = strlen(encrypted_pass);
   if(len == 15)//DES-based algorithm where encryped password is 13 characters
   {
    if(encrypted_pass[len-2] == '\r')
    {
     encrypted_pass[len-2] = '\0';//for \r\n newline character
    }
   }
   else if(len == 14)//DES-based algorithm where encryped password is 13 characters
   {
    if(encrypted_pass[len-1] == '\n')
    {
     encrypted_pass[len-1] = '\0';//for \n newline character
    }
   }
   else if(len == 36)//MD5-based algorithm where encryped password is 34 characters
   {
    if(encrypted_pass[len-2] == '\r')
    {
     encrypted_pass[len-2] = '\0';//for \r\n newline character
    }
   }
   else if(len == 35)//MD5-based algorithm where encryped password is 34 characters
   {
    if(encrypted_pass[len-1] == '\n')
    {
     encrypted_pass[len-1] = '\0';//for \n newline character
    }
   }

It appears that this entire block of code works our roughly equivalent to:
fscanf(" %119[^ \r\n]", encrypted_pass);

I've changed the maximum length to 119 based on the buffer length you provided. If you prefer to limit it to 34, that's pretty easy to handle as well. I'd note, however, that not only is this dramatically shorter, but probably faster as well -- for example, your code copies data you don't really want, then walks through all that data to find the length, truncates some of it, walks through to find the length again, and redundantly attempts to truncate the same data again (perhaps you didn't realize that '\r' and '\n' are classified as white space, at least in the "C" locale?) Using fscanf, you read (only) the data you care about, and you're done.
Similarly, most of the rest of your code for reading words from the file can probably be collapsed down to a single call to fscanf with an appropriate conversion. I haven't looked at all of it in sufficient detail to be sure of the exact conversion, but it looks like %7[A-Za-z] is somewhere in the ballpark of a reasonable start.
Ultimately, however, all of this is pretty much a fart in a hurricane as far as effect on speed goes. You can scan and copy buffers dozens of extra times, and the time it takes will still be down in the noise level compared to what it takes to copy that data from the disk drive into memory. There are really two places you can gain enough to notice:

More efficient disk transfers
parallel processing in the dictionary attack

Note that the two aren't mutually exclusive, but both generally require non-portable code (e.g., on Linux, you'd probably use mmap, but on Windows CreateFile and ReadFile to read the data).
At a guess, the latter is the part that's taking the most time, and also the place you stand the best chance of improving speed enough to care much about.


Q:

OpenCV camera calibration - general understanding of working principle

I'm playing around with camera calibration based on the code from http://dsynflo.blogspot.de/2010/03/camera-calibration-using-opencv.html
This generates an intrinsic matrix and distortion coefficients as well as corner points, shows them in the images and then shows the original raw image and the undistorted image.
And the last point makes me a bit helpless: there is nearly no difference between raw and undistorted corrected) image. I would have assumed the undistorted image shows something that is close to the original checkerboard, means no more foreshorten squares but plain 90 degrees angles and more or less exact squares. Instead of this only marginal changes can be seen. So: is this a bug in the example implementation from that Blog, is it a nug in OpenCV or is that the intended result?

A:

The undistort only corrects the features which stop the lens being a perfect pinhole (ie optical distortions) perspective effects still occur in a perfect lens and so aren't removed.
Creating a flat view (birds eye projection) of the imaged scene is part of the capabilities of opencv but needs more steps - you need a 3D model of the actual position of the objects.

A:

This is an often discussed procedure.
I highly recommend this tutorial, as already mentioned in this thread.
Understanding the underlying techniques is often key in finding bugs and why things don't work as expected.
Take a look at some tutorials until you are familiar with the concepts and everything suddenly falls in place ;)
Good luck!