text:
Q: jquery if div id has children This if-condition is what's giving me trouble:
if (div id=myfav has children) {
   do something
} else {
   do something else
}

I tried all the following:
if ( $('#myfav:hasChildren') ) { do something }
if ( $('#myfav').children() ) { do something }
if ( $('#myfav:empty') ) { do something }
if ( $('#myfav:not(:has(*))') ) { do something }

A: The jQuery way
In jQuery, you can use $('#id').children().length > 0 to test if an element has children.
Demo

var test1 = $('#test');
var test2 = $('#test2');

if(test1.children().length > 0) {
    test1.addClass('success');
} else {
    test1.addClass('failure');
}

if(test2.children().length > 0) {
    test2.addClass('success');
} else {
    test2.addClass('failure');
}
.success {
    background: #9f9;
}

.failure {
    background: #f99;
}

   Children

   No children

The vanilla JS way
If you don't want to use jQuery, you can use document.getElementById('id').children.length > 0 to test if an element has children.
Demo

var test1 = document.getElementById('test');
var test2 = document.getElementById('test2');

if(test1.children.length > 0) {
    test1.classList.add('success');
} else {
    test1.classList.add('failure');
}

if(test2.children.length > 0) {
    test2.classList.add('success');
} else {
    test2.classList.add('failure');
}
.success {
    background: #9f9;
}

.failure {
    background: #f99;
}

   Children

   No children

A: This snippet will determine if the element has children using the :parent selector:
if ($('#myfav').is(':parent')) {
    // do something
}

Note that :parent also considers an element with one or more text nodes to be a parent.
Thus the div elements in
some text
 and
some text
 will each be considered a parent but

 is not a parent.

A: if ( $('#myfav').children().length > 0 ) {
     // do something
}

This should work. The children() function returns a JQuery object that contains the children. So you just need to check the size and see if it has at least one child.

A: Another option, just for the heck of it would be:
if ( $('#myFav > *').length > 0 ) {
     // do something
}

May actually be the fastest since it strictly uses the Sizzle engine and not necessarily any jQuery, as it were. Could be wrong though. Nevertheless, it works.

A: There's actually quite a simple native method for this:
if( $('#myfav')[0].hasChildNodes() ) { ... }

Note that this also includes simple text nodes, so it will be true for a
text
.

A: and if you want to check div has a perticular children(say
 use:
if ($('#myfav').children('p').length > 0) {
     // do something
}

A: You can also check whether div has specific children or not,
if($('#myDiv').has('select').length>0)
{
   // Do something here.
   console.log("you can log here");

}


text:
Q: Cannot write to path within iOS document provider I am trying to write an iOS document provider (iOS 9), and have used the available Apple documentation and code as a stating point. However, I am running into a strange issue where I cannot write to the location pointed to by the storage URL. I am testing an import operation.
Here is the value I am getting for documentStorageURL:
file:///private/var/mobile/Containers/Shared/AppGroup/4F0A350D-8CD7-4A25-83ED-2C6120CD30FA/File%20Provider%20Storage/

However when I try to write to that location, I get the following error:
Error Domain=NSCocoaErrorDomain Code=4 "The file "test.txt" doesn't exist." UserInfo={NSFilePath=/private/var/mobile/Containers/Shared/AppGroup/4F0A350D-8CD7-4A25-83ED-2C6120CD30FA/File Provider Storage/test.txt, NSUnderlyingError=0x15f5ba010 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}

One thing that is odd is the containerURL returned from containerURLForSecurityApplicationGroupIdentifier is actually different:
file:///private/var/mobile/Containers/Shared/AppGroup/A92110D1-D0B9-4DA7-8048-A4C63FF931D5/

I am actually able to write to this latter path and read it back to verify, but then when I call dismissGrantingAccessToURL I get an error that says the path I returned back is not the documentStorageURL.
Here is the relevant code which is being called after I press a button in the UI of the document provider:
NSURL *container = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:@"group.com.jdw.DocumentProvider"];
NSLog(@"container url = %@", container);
NSLog(@"openDocument: storage uRL = %@", self.documentStorageURL);
NSURL* documentURL;

if (self.documentStorageURL != nil)
    documentURL = [self.documentStorageURL URLByAppendingPathComponent:@"test.txt"];
else
    documentURL= [container URLByAppendingPathComponent:@"test.txt"];

NSString *fileName = [documentURL path];

NSString *contents = @"this is a dynamically created text file";

NSLog(@"write to file = %@", fileName);

NSError *err;

[contents writeToFile:fileName
          atomically:NO
            encoding:NSStringEncodingConversionAllowLossy
                error:&err];

NSLog(@"write: error = %@", err);

A: I tried this again today and things magically worked, without any significant code changes that should have fixed the issue. I did reset the iPhone though.
I'm pretty sure this is a iOS or XCode bug. For reference, I'm using XCode 7.2 and iOS 9.2

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python Mock: raise 3rd party exception for unit testing Let's say i have a method is_validate, which internally calls validate method from library gateway.service
import gateway.service
from gateway.service.exception import ValidatorException

def is_validate():
   try:
       gateway.service.validate() # which throws ValidatorException
       return True
   except ValidatorException ex:
       return False

How to unit test is_validate method, mocking gateway.service.validate to throw ValidatorException ?

A: You can do this with a combination of:

*

*mocking a function (creating a fake version of the function dictating what it returns);

*monkeypatching the actual function with your mock version;

*and using pytest to actually run the test.

I've written a description of how to do this (pulled from my own work) here, in case an example I know works is useful.
But this is what I think you'll need to do in your code:
Define a pytest fixture to mock the scenario you want to test, using monkeypatch to fake the results you want from the parts of the is_validate().
And a test to check that a ValidatorException is raised; the code that raises the error in the test is in the pytest fixture. The entire pytest fixture defined there is passed as a parameter to the test.
import pytest
from unittest import TestCase

import gateway.service
from gateway.service.exception import ValidatorException

# Create object for accessing unittest assertions
assertions = TestCase("__init__")

@pytest.fixture
def validation_fails(monkeypatch):
    """
    Mocks a call to gateway.service.validate().
    """

    def mock_validate(*args, **kwargs):
        """Mock an absolute file path."""
        raise ValidatorException

    # Replace calls to existing methods with the mocked versions
    monkeypatch.setattr(gateway.service, "validate", mock_validate)

def test_validation_fails(validation_fails):
    """Test validation."""

    # check that the correct exception is raised
    with assertions.assertRaises(ValidatorException):
        is_validate()

Note: This does not include whatever setup is required to get pytest working for your project.

A: -------------------------------------
mymodule.py
-------------------------------------

import os
def remove(file_path):
    if os.path.exists(file_path):
        os.remove(file_path)
    else:
        print('File does not exist')

-------------------------------------

from mymodule import remove
import mock
import unittest
class RemoveTestCase(unittest.TestCase):

    @mock.patch('mymodule.os.path')
    @mock.patch('mymodule.os.remove')
    def test_remove(self, mock_os_remove, mock_os_path):
        mock_os_path.exists.return_value = True
#side_effect
        remove("any path")
        mock_os_remove.assert_called_with("any path")

I was able to mock gateway.service.validate by referencing it with module name where is_validate method is present.
ex:  @mock.patch('mymodule.gateway.service.validate')
Reference this doc for more info


text:
Q: Rewrite command from php to javascript Below is the code i have developed till now:
$extension = pathinfo($_SERVER['SERVER_NAME'], PATHINFO_EXTENSION);

if($extension == "de")
{
echo "this is a german site";
}

The above function is simple and works well in php, though i need it in javascript, how should i rewrite it?

A: Capture the current hostname and break it into an array:
var host = window.location.hostname.split('.');

Then check it:
if(host[host.length-1] === 'de'){
    alert('this is a german site');
}

The last item in the array you capture will be the extension.
An alternative if you don't need to deal with older browsers (IE8 or older) is to use the lastIndexOf function:
if((window.location.hostname.lastIndexOf('.')+1) === 'de'){
    alert('this is a german site');
}

No need to capture in a variable that way, if you only need to call it once.

A: This should work:
var domain = (location.host)
var arr=domain.split(".")
extension=arr[arr.length-1]

if(extension=="de")
{
alert("this is a german site");
}


text:
Q: Autolayout heights proportionally but with upper limit constraint
I am trying to use Autolayout and only Interface Builder to produce the following scene with 2 views in all four iPhone devices. As the picture indicates I would like that view2 (the bottom view) be no smaller than 45points on a iPhone 4 and never get higher than 65 points. View2 does not have to be exactly the indicated number of points in the attached image if for example your idea for a solution uses some kind of proportions.

A: horizontal constraints are obvious. Vertical constraints:

*

*view1 top to navigation bar bottom

*view2 bottom to superview bottom

*view1 bottom equals to view 2 top

*aspect ratio (~1/10) constraint between view 2 and view1 with high (=750) priority

*height of view 2 is greater than 45 with required (=1000) priority

*height of view 2 is less than 65 with required (=1000) priority


text:
Q: Collapsing Results of a Union in a Postgres View Basic Question
Is there a way in Postgres 9.2 to create a view that aggregates data from two tables, with a bit of logic involved?
The logic we need is:

*

*Data in one table takes precedence over the other

*Subsequent rows with the same key (a combination of multiple fields) overwrite previous ones.

*Rows with a status of D delete any preceding rows for a given 'key'.

More Details and Example
I have 2 schemas in a Postgres database. They each have identical tables and columns, but different data.  One is for official data, and one is for proposed changes.
Note: I'm sure there is a better way, but this is a legacy setup and can't be changed.  This is a very simplified, fictionalized example, but shows the situation and result I need.
So we have a table of characteristics, describing a widget. There is only one of each type of data in the official data (a widget will have one size, one color, etc).
Proposed changes, once approved, change the official data. There may be multiple pending changes for a given type of data.
official schema
CREATE TABLE characteristics (
    widget_id      integer NOT NULL,
    variation_id   integer NOT NULL,
    value          varchar(10),
    action_date    date,
    status         char(1)
);

Sample data in official.characteristics:
1,1,GI Joe,12/25/2012,C
1,2,Green,12/25/2012,C
1,3,M,12/25/2012,C
1,4,Plastic,12/25/2012,C
2,1,GI Joe,12/25/2012,C
2,2,Green,12/25/2012,C
2,3,L,12/25/2012,C
2,4,Plastic,12/25/2012,C

So we have 2 widgets, one is medium, green and plastic.  One is large, green, and plastic.
proposed schema
CREATE TABLE characteristics (
    widget_id      integer NOT NULL,
    variation_id   integer NOT NULL,
    value          varchar(10),
    action_date    date,
    status         char(1)
);

Sample data in proposed.characteristics:
1,2,Blue,2/22/2013,C
1,4,Plastic,2/22/2013,D
2,2,Purple,2/10/2013,C
2,2,Green,2/22/2013,D
2,3,XL,2/22/2013,C

If we want to see what the result of all the proposed changes would be, we can query both tables, with newer data replacing old, or D rows deleting any previous ones.
SELECT
  'o' as src,
  lpad(widget_id::text,4,'0'::text) || '_' || lpad(variation_id::text,4,'0'::text) as key,
  *
FROM
  proposed.characteristics
ORDER BY
  key ASC,
  action_date::date ASC

The 2nd query is the same, but on the other table and with 'p' as the src.
Using PHP, I can query each table, official first, proposed changes second, and put the data into an array with the key (widget_id || '_' || variation_id) as key. Any new rows overwrite old ones. If the status is D (for delete), then the row with the key is deleted (though a subsequent proposed change may re-add it).
So for the data above we would end up with:
o,0001_0001,1,1,GI Joe,12/25/2012,C
p,0001_0002,1,2,Blue,2/22/2013,C
o,0001_0003,1,3,M,12/25/2012,C
o,0002_0001,1,1,GI Joe,12/25/2012,C
p,0002_0003,2,3,XL,2/22/2013,C
o,0002_0004,2,4,Plastic,12/25/2012,C

Summary
Is there a way I can create a view where I can directly query the results above?
And still have the D for delete work, and newer changes overwrite previous changes or official data?

A: Assuming current version PostgreSQL 9.2 for lack of information.
One way to do it is a CTE with a UNION ALL of both tables, and get the last valid version for each widget with a NOT EXISTS anti-semi-join:
CREATE VIEW my_viw AS
WITH x AS (
   SELECT 'o' as src, * FROM official.characteristics
   UNION ALL
   SELECT 'p' as src, * FROM proposed.characteristics
   )
SELECT lpad(widget_id::text, 4, '0')
       || '_' || lpad(variation_id::text, 4, '0') AS key, * -- pick columns
FROM   x
WHERE  NOT EXISTS (
   SELECT 1 FROM x y
   WHERE  y.widget_id = x.widget_id
   AND    y.variation_id = x.variation_id
   AND    y.action_date > x.action_date
   )
AND   (status <> 'D' OR status IS NULL)
ORDER  BY widget_id, variation_id

Returns the result you outlined, except for the mistake I pointed out in the comment.
->sqlfiddle
Step by step

*

*Fetch all rows from both tables with a simple and fast UNION ALL in a CTE

*Exclude rows, where a later row for the same (widget_id, variation_id) exists with NOT EXISTS

*Exclude rows with status = 'D'.

*ORDER BY and synthesize key from widget_id, variation_id.

Major points

*

*It's most likely faster to operate with the original columns widget_id, variation_id and only synthesize the key in the final SELECT. Less code, easier to index.

*Use a CTE, because the result is needed in two places.

*The columns status should be defined NOT NULL, would make the WHERE conditions simpler.

*A multicolumn index like the following on both tables might help performance. Not sure it can be used after the UNION ALL. Test with EXPLAIN ANALYZE to see.
CREATE INDEX characteristics_mult_idx
ON official.characteristics (widget_id, variation_id, action_date DESC)


text:
Q: Is it possible to inject a component that doesn't have a prefab/GameObject associated with it? I have a game object (a cube, let's say) which exists in the scene, and I want it to have an injectable component.  I want to be able to say, for example: My cube has an IShotFirer member, which can resolve to either a BoomShotFirer or a BangShotFirer MonoBehavior component, both of which implement IShotFirer.  When binding happens, I want this component to be added to the cube object.
public class CubeBehavior : MonoBehaviour
{
    [Inject]
    private IShotFirer shotFirer;
}

Is it possible to do this without 1) needing an existing prefab which contains one of these Bang/Boom components, or 2) needing an existing scene object which has one of these components attached?
In other words, I want to be able to dynamically add the component to my game object depending on the bindings, and not relying on anything other than the script files which define either BoomShotFirer or BangShotFirer.  But the docs seem to imply that I need to find an existing game object or prefab (e.g. using .FromComponentsInChildren(), etc.)

A:
Is it possible to do this without 1) needing an existing prefab which
  contains one of these Bang/Boom components, or 2) needing an existing
  scene object which has one of these components attached?

Yes, it is.
Zenject provides a host of helpers that create a new components and bind them -- quoting the docs:

*

*FromNewComponentOnRoot - Instantiate the given component on the root of the current context. This is most often used with GameObjectContext.
Container.BindInterfacesTo<BoomShotFirer>().FromNewComponentOnRoot();

*FromNewComponentOn - Instantiate a new component of the given type on the given game object
Container.BindInterfacesTo<BoomShotFirer>().FromNewComponentOn(someGameObject);

*FromNewComponentOnNewGameObject - Create a new game object at the root of the scene and add the Foo MonoBehaviour to it
Container.BindInterfacesTo<BoomShotFirer>().FromNewComponentOnNewGameObject();

For bindings like this one that create new game objects, there are also extra bind methods you can chain:

*

*WithGameObjectName = The name to give the new Game Object associated with this binding.

*UnderTransformGroup(string) = The name of the transform group to place the new game object under.

*UnderTransform(Transform) = The actual transform to place the new game object under.

*UnderTransform(Method) = A method to provide the transform to use.

That list is not even exhaustive, be sure to check the readme and the cheatsheet (from both of which I have extracted the info above).

Also understand that, as usual, you can append .AsSingle(), .AsTransient() and .AsCached() to achieve the desired result.


text:
Q: What is the purpose of the new "form" attribute on the "object" element in HTML5? In HTML5, the object element now has a form attribute.
http://dev.w3.org/html5/spec/Overview.html#attr-fae-form
This attribute associates the object element with a form.  I'm trying to understand purpose (or result or impact) of this association.  I've figured out a couple things:
1) It allows the object element to appear outside of the form element:
http://www.w3.org/TR/html5-diff/#new-attributes
2) It is used to construct the data set:
http://dev.w3.org/html5/spec/Overview.html#categories
Is the object submitted with the rest of the form inputs?  Does the server (to whom the form is submitted) now have access to this object (via POST) for processing?  What am I missing?
Edit:  Still hoping for answers for the 2 questions above regarding form submission...

A: From the W3 site, it sounds like this solves a pretty big problem with HTML4:  "This feature allows authors to work around the lack of support for nested form elements."  http://dev.w3.org/html5/spec/Overview.html#form-owner


text:
Q: C++ Newbie in Linker Hell Using g++ and having linker errors.  I have a simple program in split into two modules: main.cpp and Dice.h Dice.cpp.
main.cpp:
#include <iostream>
#include "Dice.h"

int main(int argc, char **argv) {

    int dieRoll = Dice::roll(6);
    std::cout<<dieRoll<<std::endl;

    std::cin.get();

    return 0;
}

Dice.h:
#ifndef DieH
#define DieH

namespace Dice
{
    int roll(unsigned int dieSize);
}

#endif

Dice.cpp:
#include <ctime>
#include <cstdlib>
#include "Dice.h"

namespace Dice
{
    int roll(unsigned int dieSize)
    {
        if (dieSize == 0)
        {
            return 0;
        }
        srand((unsigned)time(0));
        int random_int = 0;
        random_int = rand()%dieSize+1;

        return random_int;
    }
}

I compile and link these files using g++ as follows:
g++ -o program main.cpp Dice.cpp

And I get the following linker error:
Undefined symbols:
"Dice::roll(int)", referenced from:
  _main in ccYArhzP.o
ld: symbol(s) not found
collect2: ld returned 1 exit status

I'm completely flummoxed. Any help would be greatly appreciated.

A: Your code is well-formed.
Ensure that your don't have conflicting file names, the files exist and contain what you think they do. For example, perhaps you have a Dice.cpp that's empty, and you're editing a newly created one somewhere else.
Minimize possible discrepancy by removing unnecessary files; only have main.cpp, dice.h, and dice.cpp.
Your errors do not match your code: "Dice::roll(int)". Observe that this is looking for an int, but your functions take an unsigned int. Make sure your header matches.

Try the following:
g++ main.cpp -c

This will generate main.o, the compiled but not-linked code for main. Do the same with dice.cpp:
g++ dice.cpp -c

You now have two object files that need to be linked together. Do so with:
g++ main.o dice.o

And see if that works. If not, do the following:
nm main.o dice.o

This will list all the available symbols in an object, and should give you something like this:
main.o:
00000000 b .bss
00000000 d .ctors
00000000 d .data
00000000 r .eh_frame
00000000 t .text
00000098 t __GLOBAL__I_main
00000069 t __Z41__static_initialization_and_destruction_0ii
         U __ZN4Dice4rollEj
         U __ZNSi3getEv
         U __ZNSolsEPFRSoS_E
         U __ZNSolsEi
         U __ZNSt8ios_base4InitC1Ev
         U __ZNSt8ios_base4InitD1Ev
         U __ZSt3cin
         U __ZSt4cout
         U __ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_
00000000 b __ZStL8__ioinit
         U ___gxx_personality_v0
         U ___main
00000055 t ___tcf_0
         U _atexit
00000000 T _main

dice.o:
00000000 b .bss
00000000 d .data
00000000 t .text
00000000 T __ZN4Dice4rollEj
         U _rand
         U _srand
         U _time

C++ mangles function names, which is why everything looks so weird. (Note, there is no standard way of mangling names, this is how GCC 4.4 does it).
Observe that dice.o and main.o refer to the same symbol: __ZN4Dice4rollEj. If these do not match, that's your problem. For example, if I change part of dice.cpp to be this:
// Note, it is an int, not unsigned int
int roll(int dieSize)

Then nm main.o dice.o produces the following:
main.o:
00000000 b .bss
00000000 d .ctors
00000000 d .data
00000000 r .eh_frame
00000000 t .text
00000098 t __GLOBAL__I_main
00000069 t __Z41__static_initialization_and_destruction_0ii
         U __ZN4Dice4rollEj
         U __ZNSi3getEv
         U __ZNSolsEPFRSoS_E
         U __ZNSolsEi
         U __ZNSt8ios_base4InitC1Ev
         U __ZNSt8ios_base4InitD1Ev
         U __ZSt3cin
         U __ZSt4cout
         U __ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_
00000000 b __ZStL8__ioinit
         U ___gxx_personality_v0
         U ___main
00000055 t ___tcf_0
         U _atexit
00000000 T _main

dice.o:
00000000 b .bss
00000000 d .data
00000000 t .text
00000000 T __ZN4Dice4rollEi
         U _rand
         U _srand
         U _time

Note, this gives two different symbols. main.o looking for this: __ZN4Dice4rollEj and dice.o containing this __ZN4Dice4rollEi. (The last letter differs).
When trying to compile these mismatched symbols (with g++ main.o dice.o), I get:
undefined reference to `Dice::roll(unsigned int)'

A: Your problem is that you're calling Dice::roll(int) and you wrote a Dice::roll(unsigned int) function. The function it's looking for doesn't actually exist (internally, argument types of a function matter just as much as its name; this is how overloading works). Try passing it an unsigned int (6u for example) and see if that works. Alternately, your header file may not match in both files, and main.cpp thinks your function takes a (signed) int.

A: I know you don't want to hear anything like it, but "It works for me!".
Your errors look suspiciously old - what version of GCC are you using? This look like GCC 2.x!
Also, try to type dieRoll in main.cpp as unsigned, that might resolve namespace problem on this old compiler.


text:
Q: chield flex-direction row not working react native? i'm new to react native. i'm implement restaurant app. when i try flex direction row in parent is working but when i try chield it is now working
that is my design enter image description here
but i need like enter image description here
i try this code
 <View style={{ flexDirection: 'row' }}>
                    <View>
                        <Image style={{ width: 100, height: 100 }} source={require('../../Assets/restaurant.jpg')} />
                    </View>

                    <View>
                        <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }}>
                            <View>
                                <Text style={{ fontSize: commonStyles.simpleTextValue, fontWeight: 'bold', color: 'black' }}>RajDhani</Text>
                            </View>
                            <View>
                                <Text style={{ fontSize: 12, fontWeight: 'bold', color: 'gray' }}>12PM to 10PM</Text>
                            </View>
                        </View>
                    </View>
                    </View>

A: You are missing the parent component width,
<View style={{ flexDirection: 'row' }}>
                    <View>
                        <Image style={{ width: 100, height: 100 }} source={require('../../Assets/restaurant.jpg')} />
                    </View>
     <View style={{ width:'100%'}}>
            <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', width:'100%', backgroundColor:'red' }}>
                <View>
                    <Text style={{  fontWeight: 'bold', color: 'black', width:'100%' }}>RajDhani</Text>
                </View>
                <View>
                    <Text style={{ fontSize: 12, fontWeight: 'bold', color: 'gray' }}>12PM to 10PM</Text>
                </View>
            </View>
        </View>
</View>

A: Try Below code
<View style={{ flexDirection: 'row' }}>
  <View style={leftView}>
    <Image source={{uri: 'some image'}} style={someStyle}/>
    <Rating />
  </View>
  <View style={rightView}>
    <View style={{flexDirection:'row,justifyContent:'space-between'}}>
      <Text>Raj Dhani</Text>
      <Text>12pm to 10pm</Text>
    </View>
    <View style={{flexDirection:'row,justifyContent:'space-between'}}>
      <Text>Rajastani Lunch</Text>
      <Text>20% off on Dinner</Text>
    </View>
    <View style={{flexDirection:'row,justifyContent:'space-between'}}>
      <Text>Rs 600/head</Text>
      <Text>Tuesday Lunch @225</Text>
    </View>
  </View>
</View>

P.S:
Please add other styles on you own ;)


text:
Q: Eliminating duplicate middle clicks I'm using Microsoft mouse software with either a trackball or the Explorer 3 mouse. Sometimes, when I middle-click, instead of the new tab opening on button-up, it happens on button-down and button-up. Sometimes it happens twice on button-up. This means if I middle-click a link in chrome, I might get from 1-3 tabs opened. I can't figure out how to eliminate this behavior.
I am using a Microsoft IntelliMouse Explorer 3.0 on a 2014 MBP 15" running Yosemite 10.10.4. I'm running the intellipoint 8.2 drivers, and "mouse wheel click" is set to "Handled by Mac OS". At one point I was using USB overdrive, but I uninstalled it. Removing/inserting the mouse doesn't seem to help. The behavior is inconsistent - it seems to come and go in bursts.

A: @Tetsujin's comment was correct - this mouse was actually defective. It took a while to find one, but I compared to another identical model and didn't have the same problems.


text:
Q: DiskCache non-image files without checking directory I'm using ImageResizer to resize profile pictures (uploaded by users) on the fly. The profile pictures are stored with the filename being their ID, and without an extension. They are also in a directory that contains other files uploaded by users that may not be images. I reference the file in my cshtml file using something like this:

<img src="//localhost:34754/8FF479AC7724A82A001603EF1566A7EFD852D35561BC2E14B1A01D99CEC035C7F265A3FF7F2642098DD2999217EC7A94?width=100" />

I want ImageResizer to know not to ignore this request, even though it doesn't have an image extension. I found this page: http://imageresizing.net/docs/howto/cache-non-images
This describes how to solve an issue similar to mine, except it requires specifying a directory. But I don't want ImageResizer to handle all requests from this directory, since there are non-images stored there as well. Is there some other way I can tell ImageResizer not to ignore the URL? Maybe by adding something to the query string? Thanks for your help.

A: The sample event handler uses a directory and a file extension as an example; you are free to use a querystring key or any other kind of indicator as you wish; it's just an example.
Config.Current.Pipeline.PostAuthorizeRequestStart += delegate(IHttpModule sender2, HttpContext context) {
  var query = Config.Current.Pipeline.ModifiedQueryString;

  if (query["flag"] != "true") return;

  Config.Current.Pipeline.SkipFileTypeCheck = true; //Skip the file extension check.

  //Non-images will be served as-is
  //Cache all file types, whether they are processed or not.
  Config.Current.Pipeline.ModifiedQueryString["cache"] = ServerCacheMode.Always.ToString();
};


text:
Q: Checking for 'isUniqueUsername' in cakephp doesn't seem to work? I have a register form where when a user registers it asks for their Username, Password and email. For the username, I have a few rules such as:

*

*Must be 5-12 characters

*Must be unique

*Must use only alpha, numbers, and dashes

With that being said, I can't seem to get my form to catch duplicate usernames, I was hoping someone could help me solve this!
Here is my User.php Model's Validate:
public $validate = array(
        'username' => array(
            'nonEmpty' => array(
                'rule' => array('notEmpty'),
                'message' => 'A username is required',
                'allowEmpty' => false
            ),
            'between' => array(
                'rule' => array('between', 5, 15),
                'required' => true,
                'message' => 'Usernames must be between 5 to 15 characters'
            ),
             'unique' => array(
                'rule'    => array('isUniqueUsername'),
                'message' => 'This username is already in use'
            )
        )
);

I removed the 3rd rule (alpha/number/dash) for the sake of the example
Followed by my function to check my DB for the username:
function isUniqueUsername($check) {

$username = $this->find(
    'all',
    array(
        'fields' => array(
            'User.id',
            'User.username'
        ),
        'conditions' => array(
            'User.username' => $check['username']
        )
    )
);

if(!empty($username)){
    if($this->data[$this->alias]['id'] == $username['']['id']){
        return true;
    }else{
        return false;
    }
}else{
    return true;
}

}
here is the Controller function for "Register"
public function register() {
        if ($this->request->is('post')) {

            $this->User->create();
            if ($this->User->save($this->request->data)) {
                $this->Session->setFlash(__('The user has been created'));
                $this->redirect($this->Auth->redirect());
            } else {
                $this->Session->setFlash(__('The user could not be created. Please, try again.'));
            }
        }
    }

A: Change
'unique' => array(
    'rule'    => array('isUniqueUsername'),
    'message' => 'This username is already in use'
 )

To
 'unique' => array(
     'rule' => 'isUnique',
     'message' => 'This username is already in use'
 )

You do not need that function to check for uniqueness, Cake does it for you with magic.


text:
Q: JAXB complains about a namespace being present when it should be there I have a set of unit tests that unmarshal a stored XML file into JAXB objects.  They were working.  These tests were using PowerMock (1.6.6) because of one detail in the CUT (code under test) that required a "whenNew" clause.
I decided to make a change to abstract that behind an object factory, which allowed me to move to pure Mockito.
When I did that, I started getting inexplicable problems when unmarshalling XML files into JAXB objects, during the test.  It was simply not storing certain elements into the JAXB objects.
The method that does the unmarshalling looks like this:
protected JAXBElement<?> unmarshallToObject(Node node, Class<?> nodeClassType) throws ServiceException {
    try {
        return getUnmarshaller().unmarshal(node, nodeClassType);
    } catch (JAXBException ex) {
        baseLogger.error(null, ex, "JAXB Exception while un-marshalling");
        throw new ServiceException(UslErrCodes.BACKEND_APP.createServiceErr(BackendConfig.USL.getId(),
                "JAXB Exception while un-marshalling"), ex);
    }
}

I changed it to the following to get more information:
protected JAXBElement<?> unmarshallToObject(Node node, Class<?> nodeClassType) throws ServiceException {
    try {
        Unmarshaller unmarshaller = getUnmarshaller();
        unmarshaller.setEventHandler(new javax.xml.bind.helpers.DefaultValidationEventHandler());
        return unmarshaller.unmarshal(node, nodeClassType);
    } catch (JAXBException ex) {
        baseLogger.error(null, ex, "JAXB Exception while un-marshalling");
        throw new ServiceException(UslErrCodes.BACKEND_APP.createServiceErr(BackendConfig.USL.getId(),
                "JAXB Exception while un-marshalling"), ex);
    }
}

What I found was that the unmarshalling process was refusing to store some elements in the JAXB instances because it was getting xml schema errors.
For instance, after changing this code, I saw messages like the following.  I refer here to namespace "http://namespace1.xsd", which obviously wasn't it's original name, but all the places where that specific namespace are shown in these examples, I use this "namespace1.xsd" name.
JAXB Exception while un-marshalling:unexpected element (uri:"http://namespace1.xsd", local:"securityFeeRequired"). Expected elements are <{}securityFeeRequired>,<{}proprietarySegmentFlag>,<{}Treatment>,<{}creditScoreMessage>,<{}ServiceEligibility>,<{}warningMessage>,<{}creditScoreResult>,<{}creditBand>

As you can see, the XML document stated that the element is in a namespace, but the "{}" seems to imply that no namespace was expected.
This is an excerpt from the generated JAXB class:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = { "creditScoreResult", "creditScoreMessage", "warningMessage",
        "securityFeeRequired", "treatment", "creditBand", "proprietarySegmentFlag", "serviceEligibility" })
public static class FooResult implements Serializable {
    private static final long serialVersionUID = 1L;
    protected String creditScoreResult;
    protected String creditScoreMessage;
    protected String warningMessage;
    protected boolean securityFeeRequired;

And here is the @XmlSchema annotation from the generated "package-info" from the same package:
@XmlSchema(namespace="http://namespace1.xsd", elementFormDefault=XmlNsForm.QUALIFIED)

So, after getting this error, I decided to try making a "this couldn't possibly work" change.
I changed the XML file such that this is the analogous excerpt:
    <ExecuteFooResponse xmlns:ns1="http://namespace1.xsd" xmlns:ns2="http://namespace2.xsd">
        <FooResult>
            <securityFeeRequired>false</securityFeeRequired>
            <Treatment>A001
                <message>No additional fee is required at this time</message>
            </Treatment>
            <ServiceEligibility>
                <productCode>BAR</productCode>
                <serviceEligibilityIndicator>true</serviceEligibilityIndicator>
            </ServiceEligibility>
        </FooResult>
        <Response>
            <ns2:code>0</ns2:code>
            <ns2:description>Success</ns2:description>
        </Response>
    </ExecuteFooResponse>

The only change I made was the namespace prefix for "namespace1.xsd".  It was failing with "" (blank), which is correct, as far as I can see.  I changed it to "ns1", but only in the declaration.  I'm clearly not referencing that prefix in the body of the element.  This makes the test PASS.
Please restore my sanity.

A: The problem ended up being that the XML documents the tests were using were actually not schema-valid.  They had subtle issues that caused validation to fail, but those issues were place there intentionally by other developers because they found that the PowerMock tests would not pass without those ERRORS being in place.  I'm still trying to figure out why PowerMock would only work with the files in that state, but my documents are now schema-valid, and the Mockito tests are working.


text:
Q: HTTP Status 500 - javax.servlet.ServletException: java.lang.NullPointerException I'm having a problem in REST services, using jersey.
The following code waits for me to write the User Login.
AccessUser.java
public String login (Connection con, String login) throws SQLException
{
    String toReturn = "Login not successful";
    String password = "dea6d5362b7750f77c31a7412f0c0acb";

    try {
            pstmt = connection.prepareStatement("SELECT setEventUserLogin(?,?,?)");
            pstmt.setString(1, login);
            pstmt.setString(2, password);
            pstmt.setLong(3, System.currentTimeMillis());
            res  = pstmt.executeQuery();

    if(res.next())
    {
        if (!res.getString(1).equals("0"))
            toReturn = "Login successful!";
    }
    } catch (SQLException ex) {
        System.out.println("SQLException: " + ex);
    }
    return toReturn;
}

UserManager.java
public String login(String login) throws Exception
{
    String response = null;
    Database db = new Database();
    Connection con = db.getDBConnection();
    AccessUser access = new AccessUser();
    response = access.login(con, login);
    return response;
}

UserFacadeREST.java
@PUT
@Path("login")
@Produces({"application/json", "text/plain"})
@Consumes("application/json")
public String logon(String login) throws Exception
{
    String response = null;
    response = new UserManager().login(login);
    return response;
}

So, when I write the user login, I receive this error:

    [#|2013-03-19T10:08:44.410+0000|WARNING|glassfish3.1.2|javax.enterprise.system.container.ejb.com.sun.ejb.containers|_ThreadID=111;_ThreadName=Thread-2;|EJB5184:A system exception occurred during an invocation on EJB UserFacadeREST, method: public java.lang.String service.UserFacadeREST.login(java.lang.String) throws java.lang.Exception|#]

[#|2013-03-19T10:08:44.411+0000|WARNING|glassfish3.1.2|javax.enterprise.system.container.ejb.com.sun.ejb.containers|_ThreadID=111;_ThreadName=Thread-2;|javax.ejb.EJBException
    at com.sun.ejb.containers.BaseContainer.processSystemException(BaseContainer.java:5215)
    at com.sun.ejb.containers.BaseContainer.completeNewTx(BaseContainer.java:5113)
    at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4901)
    at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2045)
    at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:1994)
    at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:222)
    at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:89)
    at sun.proxy.$Proxy472.login(Unknown Source)
    at service.__EJB31_Generated__UserFacadeREST__Intf____Bean__.login(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
    at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$TypeOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:185)
    at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
    at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:288)
    at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
    at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1469)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1400)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339)
    at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
    at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
    at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:708)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:770)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1550)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
    at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
    at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
    at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
    at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
    at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
    at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
    at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
    at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
    at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
    at java.lang.Thread.run(Thread.java:722)
Caused by: java.lang.NullPointerException
    at entities.AccessUser.login(AccessUser.java:61)
    at others.UserManager.login(UserManager.java:35)
    at service.UserFacadeREST.login(UserFacadeREST.java:71)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1052)
    at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1124)
    at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:5388)
    at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:619)
    at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:800)
    at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:571)
    at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doAround(SystemInterceptorProxy.java:162)
    at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:144)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:861)
    at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:800)
    at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:370)
    at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:5360)
    at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:5348)
    at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:214)
    ... 47 more
|#]

[#|2013-03-19T10:08:44.413+0000|WARNING|glassfish3.1.2|javax.enterprise.system.container.web.com.sun.enterprise.web|_ThreadID=111;_ThreadName=Thread-2;|StandardWrapperValve[ServletAdaptor]: PWC1406: Servlet.service() for servlet ServletAdaptor threw exception
java.lang.NullPointerException
    at entities.AccessUser.login(AccessUser.java:61)
    at others.UserManager.login(UserManager.java:35)
    at service.UserFacadeREST.login(UserFacadeREST.java:71)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1052)
    at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1124)
    at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:5388)
    at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:619)
    at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:800)
    at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:571)
    at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doAround(SystemInterceptorProxy.java:162)
    at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:144)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:861)
    at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:800)
    at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:370)
    at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:5360)
    at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:5348)
    at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:214)
    at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:89)
    at sun.proxy.$Proxy472.login(Unknown Source)
    at service.__EJB31_Generated__UserFacadeREST__Intf____Bean__.login(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
    at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$TypeOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:185)
    at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
    at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:288)
    at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
    at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1469)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1400)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339)
    at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
    at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
    at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:708)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:770)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1550)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
    at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
    at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
    at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
    at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
    at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
    at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
    at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
    at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
    at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
    at java.lang.Thread.run(Thread.java:722)
|#]

And that's strange because I've done a Logout method very similar, and is working fine...
Can you help me, please?

A: Perhaps you mixed con and connection
pstmt = con.prepareStatement("SELECT setEventUserLogin(?,?,?)");

???

A: The cause of NPE may be connection object or res.getString() returns null.


text:
Q: Running the wizard again after a new system installation I'm interested in installing Linux Mint on old laptops and giving them away.
During initial installation, I'm going to add VNC (or other tools to allow remote support), but interested in leaving the installation similar to that when you receive a new computer from a major vendor.
Example, if you buy a Dell machine and power it own, it asks you basic questions, Full Name, username, password, timezone, etc.
Is there a way I can setup Ubuntu (or Linux Mint preferred) to allow run a similar wizard on next reboot? See this as essential, since I'm not likely to ever meet the person that receives the machine I've just built. Figured it would be good to have that 'initial setup' wizard to make the person feel as if they are making the machine their own/custom.

A: I barely know anything about Linux Mint anymore as they seem to have been diverting from Ubuntu for some time. But Ubuntu has an OEM install option. I think it's maybe only available on the DVD. You'll select "Install Ubuntu" and press F4 to display options. You'll find OEM Install, which will do what you want.


text:
Q: How to set custom font with fontfamily in XML. Api 16 Im currently using android studio 2.3.1.
I want to be able to set the font on my textview from the xml instead of programmatically.
I have my fonts in an assets folder.
So how do I access my font from my assets folder?
I saw Android O will come with a resource folder called "font".

A: create the TypeFactory.java class as shown below.
public class TypeFactory {

    private String A_BOLD= "Amble-Bold.ttf";
    private String A_LIGHT="Amble-Light.ttf";
    private String A_REGULAR= "Amble-Regular.ttf";
    private String O_ITALIC= "OpenSans-Italic.ttf";
    private String O_REGULAR="OpenSans-Regular.ttf";

    Typeface ambleBold;
    Typeface ambleLight;
    Typeface ambleRegular;
    Typeface openSansItalic;
    Typeface openSansRegular;

    public TypeFactory(Context context){
        ambleBold = Typeface.createFromAsset(context.getAssets(),A_BOLD);
        ambleLight = Typeface.createFromAsset(context.getAssets(),A_LIGHT);
        ambleRegular = Typeface.createFromAsset(context.getAssets(),A_REGULAR);
        openSansItalic = Typeface.createFromAsset(context.getAssets(),O_ITALIC);
        openSansRegular = Typeface.createFromAsset(context.getAssets(),O_REGULAR);
    }

}

The CustomTextView.java class is given below.
public class CustomTextView extends TextView {

    private int typefaceType;
    private TypeFactory mFontFactory;

    public CustomTextView(Context context, AttributeSet attrs) {
        super(context, attrs);

        applyCustomFont(context, attrs);
    }

    public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        applyCustomFont(context, attrs);
    }

    public CustomTextView(Context context) {
        super(context);
    }

    private void applyCustomFont(Context context, AttributeSet attrs) {

        TypedArray array = context.getTheme().obtainStyledAttributes(
                attrs,
                R.styleable.CustomTextView,
                0, 0);
        try {
            typefaceType = array.getInteger(R.styleable.CustomTextView_font_name, 0);
        } finally {
            array.recycle();
        }
        if (!isInEditMode()) {
            setTypeface(getTypeFace(typefaceType));
        }

    }

    public Typeface getTypeFace(int type) {
        if (mFontFactory == null)
            mFontFactory = new TypeFactory(getContext());

        switch (type) {
            case Constants.A_BOLD:
                return mFontFactory.ambleBold;

            case Constants.A_LIGHT:
                return mFontFactory.ambleLight;

            case Constants.A_REGULAR:
                return mFontFactory.ambleRegular;

            case Constants.O_LIGHT:
                return mFontFactory.openSansItalic;

            case Constants.O_REGULAR:
                return mFontFactory.openSansRegular;

            default:
                return mFontFactory.ambleBold;
        }
    }

    public interface Constants {
        int A_BOLD = 1,
                A_LIGHT = 2,
                A_REGULAR = 3,
                O_LIGHT = 4,
        O_REGULAR=5;
    }

}

R.styleable.CustomTextView is defined inside the attrs.xml file as shown below.
 <?xml version="1.0" encoding="utf-8"?>
    <resources>

        <declare-styleable name="CustomTextView">
            <attr name="font_name">
                <enum value="1" name="ambleBold"/>
                <enum value="2" name="ambleLight"/>
                <enum value="3" name="ambleRegular"/>
                <enum value="4" name="openSansItalic"/>
                <enum value="5" name="openSansRegular"/>
            </attr>
        </declare-styleable>

    </resources>

Our updated activity_custom_fonts.xml layout is given below

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context="com.journaldev.customfonts.MainActivity">

    <com.journaldev.customfonts.CustomTextView
        app:font_name="ambleBold"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Amble Bold"
        android:textSize="28sp"
        android:id="@+id/ambleBold"
         />

    <com.journaldev.customfonts.CustomTextView
        app:font_name="ambleLight"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Amble Light"
        android:textSize="28sp"
        android:id="@+id/ambleLight"
        />

    <com.journaldev.customfonts.CustomTextView
        app:font_name="ambleRegular"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Amble Regular"
        android:textSize="28sp"
        android:id="@+id/ambleRegular" />

    <com.journaldev.customfonts.CustomTextView
        app:font_name="openSansRegular"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="OpenSans Regular"
        android:textSize="28sp"
        android:id="@+id/opRegular" />

    <com.journaldev.customfonts.CustomTextView
        app:font_name="openSansItalic"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="OpenSans-Italic"
        android:id="@+id/opItalic"
        android:textSize="28sp"
        />

    <Button android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:text="Pacifico"
        android:id="@+id/pacifico"/>

</LinearLayout>

you can also use the calligraphy :https://github.com/chrisjenx/Calligraphy


text:
Q: PowerShell - Taking Action Based Off of User Input? I want to request user input via PromptForChoice and then, based on what they select, do a certain action.
In my code I have three options: Laptop, Tablet, and Workstation . If the user selects one, I want to do a certain action as opposed to the other actions assigned to the other options.
In the code, I do not really understand the line containing the decision variable, or what the number 1 means either after $choices. I have put asterisks around the parts of the code I don't understand.
I do not know how to assign certain actions to one button. The first part of code is what I want to do but isn't working, and the last part is the actual script.
$decision = $Host.UI.PromptForChoice($title, $question, $choices, **1**)
if ($decision -eq **Laptop**)

$title    = 'PC Type Selection'
$question = 'Select Object Type'
$choices  = '&Laptop','&Tablet' ,'&Workstation'

$decision = $Host.UI.PromptForChoice($title, $question, $choices, 1)
if ($decision -eq 0) {
Write-Host 'confirmed'
} else {
Write-Host 'cancelled'
}

A: In the ISE or the console host, notwithstanding; you don't get back a string from this code. You get an array/index number.
$title    = 'PC Type Selection'
$question = 'Select Object Type'
$choices  = '&Laptop','&Tablet' ,'&Workstation'

<#
Using PowerShell's variable squeezing to assign the results and
output to screen at the same time.

This, not a requirement, just a demo of how to see your variable
content on use.
#>
($decision = $Host.UI.PromptForChoice($title, $question, $choices, 1))
# Results
<#
0
#>

# Results
<#
1
#>

# Results
<#
2
#>

So, you need to ask for that number, then branch to whatever else you'd want to do, using conditional logic. Multiple or nested if/then/else, try/catch. or switch statement.
$title    = 'PC Type Selection'
$question = 'Select Object Type'
$choices  = '&Laptop','&Tablet' ,'&Workstation'

$decision = $Host.UI.PromptForChoice($title, $question, $choices, 1)

switch ($decision)
{
    0 {'You selected Laptop'}
    1 {'You selected Tablet'}
    2 {'You selected Workstation'}
    Default {}
}

# Results
<#
You selected Laptop
#>

# Results
<#
You selected Tablet
#>

# Results
<#
You selected Workstation
#>


text:
Q: Is it possible to query a specific DSN server for a web page? I have the IP address of the DNS server from the WebHost. Since we do not own the Domain Name (Its the client's DN) I would like to query the WebHost DNS directly to see if it works before asking the client to point his DN to the WebHost DNS.
Am I missing something here? I'm kinda confused when it comes to configures online services.

A: From Windows Command Prompt:
nslookup
server x.x.x.x (put the WebHost DNS IP address there)
www.yourdomain.com  (type the name of the domain you want resolved)
quit


text:
Q: Return number of rows php mvs I am trying to return the number of results found on my page above an html table. I am using an mvc framework for the first time so it's very new to me how the process works.
My query works and displays the tabular results successfully, my issue is [probably] with the positioning of my return code?
I have included my code for reference;
Model
public function categoryView()
{
    $sth = $this->db->prepare("SELECT
    b.id,
    b.title,
    b.category,
    FROM book
    WHERE status != 'Archive' AND category = :cat ORDER BY id DESC LIMIT 15");

    $sth->bindValue(':cat', $_GET['category']);
    $sth->execute();

    $result = $sth->fetchAll(PDO::FETCH_ASSOC); // won't run when included
    return count($result); // won't run when included

    $all_books = array();

    foreach ($sth->fetchAll() as $book) {
        $all_books[$book->id] = new stdClass();
        $all_books[$book->id]->id = $book->id;
        $all_books[$book->id]->title = $book->title;
        $all_books[$book->id]->category = $book->cat_name;
    }
    return $all_books;
}

View
Found <?php echo count($result); ?> records

<?php
foreach ($this->books as $book) {
    echo "
";
    echo ''.$book->id.'	';
    echo ''.$book->title.'	';
    echo ''.$book->category.'	';
    echo "
";
}
?>

Controller
function categoryView()
{
    $categoryView_model = $this->loadModel('Books');
    $this->view->books = $categoryView_model->categoryView();
    $this->view->render('books/categoryView');
}

I receive the error errors on my view page
Warning: `Invalid argument supplied for foreach() ... on line 51`

and
Found
Notice: Undefined variable: result in ... on line 47
0 records

Line 47 contains Found <?php echo count($result); ?> records
Line 51 contains foreach ($this->books as $book) { ... }
Any advice or help is appreciated.

A: Remove these two lines
$result = $sth->fetchAll(PDO::FETCH_ASSOC); // won't run when included
return count($result); // won't run when included

In your view change
Found <?php echo count($result); ?> records

to
Found <?php echo count($this->books); ?> records

The reason you have to do this is because you're storing the results returned from categoryView() into the books property of the view when you run the following line
$this->view->books = $categoryView_model->categoryView();

Note that the count will always be a maximum of 15. If you want to display the total # of found results you should issue a separate select count(*) without a limit clause.

A: It would help us a lot if you specified the framework. Honestly I have only worked in Zend as a php framework but over there you have to assign the property to your view:
   $this->view->property = $all_books; //or any other property

and to retrieve it in the view
  <?php echo $this->property; ?>

I find it hard to beleive that your MVC calls the function (action),which in zend needs to be named in a specific way, from the view and so uses a return. I an tell you one thing, your way of sending the variable to the view is wrong, the return must not be the correct way of sending it. Without your framework this is the only way I can help you in addition I would tell you to actually echo an isset f both variables and you will see my theory is right you are not sending the variables from the controller, action or function correctly


text:
Q: Evaluation of limit with summation till infinity. The question to be solved is:
$$ \lim_{n \to \infty} \left( \ \sum_{k=10}^{n+9} \frac{2^{11(k-9)/n}}{\log_2 e^{n/11}}  \ - \sum_{k=0}^{n-1} \frac{58}{\pi\sqrt{(n-k)(n+k)}} \ \right)$$
The first thing that occured to me was to transform the limits into definite integrals using the limit definition of integrals, so it'll become easier to evaluate.
However, I have no clue how to convert them into definite integrals. Could anyone please shed some light on how to proceed? Or is there a better way to solve this problem?

A: $$ \lim_{n \to \infty} \left( \ \sum_{k=10}^{n+9} \frac{2^{11(k-9)/n}}{\log_2 e^{n/11}}  \ - \sum_{k=0}^{n-1} \frac{58}{\pi\sqrt{(n-k)(n+k)}} \ \right)$$
By putting $k=m+9$ in the first sum, we get
\begin{align}
\sum_{k=10}^{n+9} \frac{2^{11(k-9)/n}}{\log_2 e^{n/11}}
&=\frac 1{\log_2 e^{n/11}}\sum_{m=1}^{n}(2^{11/n})^m\\
&=\frac 1{\log_2 e^{n/11}}\frac{(2^{11/n})^{n+1}-2^{11/n}}{2^{11/n}-1}\\
&=\frac{11\log(2)}{n}\frac{2^{11/n}(2^{11}-1)}{2^{11/n}-1}\\
&=\frac{11\log(2)}{n}\frac{2^{11/n}(2^{11}-1)}{e^{11/n\log(2)}-1}\\
&\sim\frac{11\log(2)}{n}\frac{2^{11}-1}{11/n\log(2)}\\
&\xrightarrow{n\to\infty}2^{11}-1
\end{align}
For the second sum
\begin{align}
\sum_{k=0}^{n-1} \frac{58}{\pi\sqrt{(n-k)(n+k)}}
&=\frac{58}\pi\sum_{k=0}^{n-1} \frac 1{\sqrt{1-(\frac kn)^2}}\frac 1n\\
&\xrightarrow{n\to\infty}\frac{58}\pi\int_0^1\frac{\mathrm dx}{\sqrt{1-x^2}}\\
&=\frac{58}\pi\frac\pi 2\\
&= 29
\end{align}

A: For converting an sum to definite integral :
Convert your sum having limits $a$ to $b$ to the form $f(k/n) * 1/n$.
Take $k/n$ as $x$, $1/n$ as $dx$ and set the limits as $\frac{a}{n}$ and $\frac{b}{n}$.  This is actually the sum of all tiny rectangles (vertical ones) when we break the area under a curve into small rectangles of width $\frac{1}{n}$.
For the first term, simplify the denominator and take $k-9=t$ . The first term becomes $2^{11\frac{t}{n}}$ $\frac{11\ln2}{n}$. You can now convert it to an Definite Integral and evaluate it. (It comes out to be $2^{11} - 2^0$).
For the second term, take 'n' out of the denominator and convert it to an integral to get $29$.
The answer comes out to be 'this year'.

A: The first summation is essentially a geometric series, and with $j:=k+9$,
$$\frac{2^{11(k-9)/n}}{\log_2 e^{n/11}}=\frac{\left(2^{11/n}\right)^j}{\dfrac{n}{11}\log_2e}.$$
Then summing from $1$ to $n$,
$$\frac{2^{11/n}(2^{11}-1)}{\dfrac n{11}\log_2e(2^{11/n}-1)}.$$
As
$$2^{11/n}-1=e^{11\ln2/n}-1=1+\frac{11\ln2}{ n}+\cdots-1,$$ the limit reduces to $2^{11}-1$.

As an integral,
$$\frac{2^{11(k-9)/n}}{\log_2 e^{n/11}}\to 11\ln2\,2^{11x}dx$$ which integrates as $2^{11x}$, from $0$ to $1$.


text:
Q: Add UIView Above All Section in UITableView Swift i am not talking about a section i want put a uiview on the above of every section
This is the layout

here Menu and LeftOver are uiView
Staters and new are sections

A: What you're looking for is a section header. You can easily configure your own custom view by implementing the UITableViewDataSource method
For example:
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let headerView = UIView()
    // configure view, note the method gives you the section to help this process
    return headerView
}

you may also want to implement this function
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 50 // or whatever it is
}

Do keep in mind that header are sticky be default
in the past I've gotten around this fairly easily doing something like this:
    let dummyViewHeight = CGFloat(49) // height of header (set in storyboard)
    self.tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: self.tableView.bounds.size.width, height: dummyViewHeight))
    self.tableView.contentInset = UIEdgeInsets(top: -dummyViewHeight, left: 0, bottom: 0, right: 0)

which basically just makes the table header "stick" to this inset on top of the table. (unless you really do want it hovering over the section at the top)
Edit:
Given the OP considers this "not satisfying" I'm like 99% confident when I say the ONLY other reasonable option (if you don't wan't to use section header or footer views) is to then make a new UITableViewCell subclass. Then that new subclass would appears at the top of each section.
So in the cellForIndexPath: method you'd check if indexPath.row == 0and if so dequeue a cell with a different identifier. That way the header just becomes a cell that is built differently.
If you're doing it programmatically just be sure to register that cell (tableView.register(MyNewHeaderCellSubclass.self, forCellReuseIdentifier: "MyNewHeaderCellSubclass")) or otherwise go to the table view on the storyboard and toggle the option for two types of dynamic cell classes.
The section header is exactly what this use case is for however. I cant think of any other solution without just abandoning UITableView completely which I think would be a big mistake. Good luck to you otherwise if so.


text:
Q: Access blocked by CORS policy I recently started learning web development, appreciated if someone could help me fix CORS policy error.
I am trying to connect my React application with my node.js application. I am using axios http service.
http service setup in react application.
import axios from "axios";
import { toast } from "react-toastify";

axios.defaults.baseURL = process.env.REACT_APP_API_URL;
// axios.defaults.headers.common["Access-Control-Allow-Origin"] = "*";
axios.defaults.headers.post["Content-Type"] =
  "application/x-www-form-urlencoded";

console.log(axios.defaults.baseURL);

axios.interceptors.response.use(null, (error) => {
  const expectedError =
    error.response &&
    error.response.status >= 400 &&
    error.response.status < 500;

  if (!expectedError) {
    console.log("Logging the error", error);
    console.log(error.response);
    // toast.error("Unexpected error occured");
  }

  return Promise.reject(error);
});

export default {
  get: axios.get,
  post: axios.post,
};

using http service to make get and post to back end.
import http from "./httpService";

const apiEndPoint = "/email";

export function sendMail(sender) {
  // console.log(sender);
  return http.post(apiEndPoint, {
    name: sender.name,
    email: sender.email,
    phone: sender.phone,
    company: sender.company,
    message: sender.message,
  });

  // return http.get(apiEndPoint);
}

Back end http get and post methods.
const express = require("express");
const router = express.Router();
const { validate } = require("../model/contact");
const nodemailer = require("nodemailer");

router.get("/", (req, res) => {
  res.header({ "Access-Control-Allow-Origin": "*" }).send("Hello world");
});

router.post("/", (req, res) => {
  res.header({ "Access-Control-Allow-Origin": "*" });

  const { error } = validate(req.body);
  console.log(error);
  if (error) return res.send(error.details[0].message);

  const output = `

You have a new contact request

Contact Details

Name: ${req.body.name}

Company: ${req.body.company}

Email: ${req.body.email}

Phone: ${req.body.phone}

Message

${req.body.message}

  `;

  // create reusable transporter object using the default SMTP transport
  let transporter = nodemailer.createTransport({
    host: "smtp.gmail.com",
    port: 465,
    secure: true, // true for 465, false for other ports
    auth: {
      user: "XXXX", // generated ethereal user
      pass: "XXXX", // generated ethereal password
    },
    tls: {
      rejectUnauthorized: false,
    },
  });

  // setup email data with unicode symbols
  let mailOptions = {
    from: '"Nodemailer Contact" XXXX', // sender address
    to: "XXX", // list of receivers
    subject: "Node Contact Request", // Subject line
    text: "Hello world", // plain text body
    html: output, // html body
  };

  // send mail with defined transport object
  transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
      return console.log(error);
    }
    console.log("Message sent: %s", info.messageId);
    console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info));

    res.send("Email Sent!!");
  });
});

module.exports = router;

I have also set the proxy on both client and server.
surprisingly get request is working but post request throws CORS error.
Any help would be appreciated.
Thank you

A: Like Daniel said in the comment, you should probably use the the cors module rather than setting headers directly in this case.
The bit about GET working but POST not is the big giveaway to what's going on. When you do a cross-domain POST, browsers do use a preflight request with the OPTIONS http verb to see what sort of stuff the endpoint supports (since POST requests can be quite large the idea is that it saves on bandwidth and a few other things). If you use the module, this will be taken care of for you. Alternately you can implement it yourself.


text:
Q: Why does Symfony EventDispatcher use arbitrary names for events instead of class-based propagation? I'm looking to implement Observer Pattern into my app (not php, that's why not using Symfony's component).
I found it strange though that the component is not using classes to propagate or listen to events since that would allow listening on whole tree of events using inheritance.
I can't see the single advantage of using name-based listeners, would you help me with my pondering?

A: Symfony2, in my opinion, favors cohesion over coupling and that's why they use this pattern (Mediator pattern).
From Symfony docs:

Objected Oriented code has gone a long way to ensuring code
  extensibility. By creating classes that have well defined
  responsibilities, your code becomes more flexible and a developer can
  extend them with subclasses to modify their behaviors. But if he wants
  to share his changes with other developers who have also made their
  own subclasses, code inheritance is no longer the answer.
Consider the
  real-world example where you want to provide a plugin system for your
  project. A plugin should be able to add methods, or do something
  before or after a method is executed, without interfering with other
  plugins. This is not an easy problem to solve with single inheritance,
  and multiple inheritance (were it possible with PHP) has its own
  drawbacks.
The Symfony2 Event Dispatcher component implements the
  Mediator pattern in a simple and effective way to make all these
  things possible and to make your projects truly extensible.


text:
Q: jquery plugin defaults with ajax.load Im creating a jQuery (ajax.load) plugin which triggers the plugin based on a set data-attribuut. The value of this attribute overwrites the default setting.
All works fine, but:
1) if the value is kept empty, the empty value overwrites my defaults, which i dont want.
The only way I can prevend this now, is by doing this while setting the options object:
content_url_el: $(element).find('a[data-attribute]').attr('data-attribute') || 'content'.
(where content is the default value.)

There must be a better way for this so i can use my default setting in:
$.fn[pluginName].defaults = {
   content_url_el: 'content', // class element on url to get content from.
 };

2) If the content_url_el, which is the class in the loaded ajax-page, is not found, is there a way to check this. In the ajax.response the whole page is returned, not only the content in the class element and thereby ajax status = success.
Thanks for your help.


text:
Q: Oracle stored procedure - Loop within cursor I have a stored proc Procedure1,

*

*Within Procedure1, I am calling another procedure Procedure2 which returns sys_refcursor ProcResult2.

*I need to traverse through each row of this cursor and insert the data into a table

The code
Create Procedure1()
as
ProcResult1 Sys_refcursor;
begin
    Procedure2(ProcResult2);
    For eachrow in ProcResult2
      Loop
        insert into test_table(ProcResult2.Id);
      end loop;
end ;\

Any idea, pointers on how to achieve the 2. functionality ? That is traverse through each row returned in ProcResult2 and insert into a new table.

A: You are almost there:
Create Procedure1()
as
    ProcResult1 Sys_refcursor;
    v_record ???; -- See below
begin
    Procedure2(ProcResult2);
    Loop
        fetch ProcResult2 into v_record;
        exit when ProcResult2%notfound;
        insert into test_table(v_record.Id);
    end loop;
    close ProcResult2;
end;

You need to declare the variable v_record with a structure that matches what the cursor returns - i.e. you need to know the structure of the cursor record when you build the procedure.  If the cursor returns "select * from mytab" then you could use:
v_record mytab%rowtype;

But if it only selects certain columns e.g. "select col1, col3 from mytab" then you would need to manually define the structure:
type v_record_type is record (col1 number, col3 varchar2(10));
v_record v_record_type;


text:
Q: In how many ways can we arrange 16 persons in 8 buildings and each building should have only 2 persons In how many ways can we arrange $16$ persons in $8$ buildings so that each building has only $2$ people?
My answer is $16!/(2^8)$ but I'm not sure.

A: Your answer is correct:
Firstly, put all $16$ people in line like this:
$$A_1A_2A_3A_4\cdots A_{16}$$
The line can also be:

*

*First person in building $1$

*Second person in building $1$

*First person in building $2$

*Second person in building $2$

*$\cdots$

*First person in building $9$

*Second person in building $8$
Of course there are $16!$ ways of putting them in line.
Now, sort them into eight groups:
$$A_1A_2|A_3A_4|A_5A_6|A_7A_8|A_9A_{10}|A_{11}A_{12}|A_{13}A_{14}|A_{15}A_{16}$$
We will take just one case: $A_1$ and $A_2$ in building $1$, $A_3$ and $A_4$ in building $2$,... $A_{15}$ and $A_{16}$ in the building $8$.

*

*$A_1$ and $A_2$ in building $1$: two ways to switch them in building $1$.

*$A_3$ and $A_4$ in building $2$: two ways to switch them in building $2$.
$\cdots$

*

*$A_{15}$ and $A_{16}$ in the building $8$: two ways to switch them in building $8$.

So there are $2^8$ ways to swap pairs of people around just their buildings for each case, but we only count once for each case, so the answer is $16!/2^8$.


text:
Q: CSS3 Translate: Translate an element on an Ellipse path I've been searching the answer for awhile but all I can see is translating an object in circular path. Is there a way to translate an element on an ellipse path given the semiminor and semimajor axis? Thanks alot!
the jfiddle of belows answer
css3

A: Have a look at this page, it explains mostly all you should know about translations with CSS3. Just as reminder: it is also possible to set keyframes you could use to definie your edge points of a spline you want to animate.
keyframes are explained here.
in your case it is a animation of two nested elements.
#1 for the picture or element you want to animate, where you define a X tranlate with ease
#2 and one as outer box for that #1 you animate the Y translate with.
if you arrange them clever in the same timescale but different ease in or out you can make your ellipse happen.


text:
Q: Email address null from UserPrincipal using Active Directory Getting EmailAddress NULL from Active Directory (AccountManagement UserPrincipal)
Refering to the above thread, can anyone purpose the exact solution. I know my code is working fine with lots of Active Directory Servers but there is one Active Directory deployment causing this issue.
I have checked the user properties and email using LDAP query and explorer  and it seems fine to me. Below is the code that works fine and fetches all email addresses for domain abc.com.pk.
DirectoryEntry entry = new DirectoryEntry("LDAP://abc.com.pk");
            DirectorySearcher dSearch = new DirectorySearcher(entry);
            dSearch.Filter = "(objectClass=user)";
            Console.WriteLine("Email addresses configure in your domain are");
            var allUsers =  dSearch.FindAll();
            foreach (SearchResult sResultSet in allUsers)
            {
                if (sResultSet.Properties["mail"].Count > 0)
                {
                    Console.WriteLine(i+": "+sResultSet.Properties["mail"][0]);
                    i++;
                }

            }

Here is my code that is not working and it should work fine.

    using (var principalContext = new PrincipalContext(ContextType.Domain | ContextType.Machine))
                            {
                                using (UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(principalContext, identity.Name))
                                {
var emailAddress = UserPrincipal.EmailAddress; // this is null
}}

Above answer made some sense but I need details if anyone can help.
Thanks

A: Issue that I have understood so far :
The web application running on IIS under a specific identity. This pool identity account doesn't has enough permissions to access AD.
Just change the permissions or change your pool identity to one of default i.e. NetworkServices or IdentityPool
Thanks


text:
Q: How to get Zomato restaurant ID using restaurant link? I want to get details of a restaurant in Zomato. I have it's link as the input (https://www.zomato.com/mumbai/fantasy-the-cake-shop-kalyan?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1). By browsing the documentation of Zomato APIs, I didn't found a way to get it.
I tried searching for the restaurant using search API but it returns many results.
Any help will be appreciated

A: It's a two-step process:

*

*Find out restaurant's city id, in your case, Mumbai's city id through the /cities API. It's a simple query search.

*Use the city id from the above API call in the /search API, like, https://developers.zomato.com/api/v2.1/search?entity_type=city&entity_id=3&q=fantasy%20the%20cake%20shop%20kalyan
This would give all the basic information about a restaurant.

A: View the page's source and search for window.RES_ID

A: I had the same issue as you described. This Zomato's API approach is at least odd. It's almost immposible to GET any information about restaurant if you don't know res_id in advance and that's not possible to parse since Zomato will deny access.
This worked for me:

*

*Obtain user-key from Zomato API Credentials (https://developers.zomato.com/api)

*Search restaurant url via API (https://developers.zomato.com/api/v2.1/search?entity_id=84&entity_type=city&q=RESTAURANT_URL&category=7%2C9). The more specific you will be, the better results you'll get (This url is specified by city to Prague (ID = 84) and categories Daily menus (ID = 7) and Lunch (ID = 9). If there is possibility do specify city, category or cuisine, it helps, but should't be necessary. Don't forget to define GET method in headers.

*Loop or filter through json results and search for the wanted url. You might need to use method valueOf() to search for the same url. Be careful, you might need to add "?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1" at the end of your wanted url so it has the same format. Check that through Zomato API Documentation page.

for (i in body.restaurants) {
    var url_wanted = restaurant_url + '?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1'
    var url_in_json = body.restaurants[i].restaurant.url;
    if (url_wanted.valueOf() == url_in_json.valueOf()) {
        var restaurant_id = body.restaurants[i].restaurant.id;
    }
    console.log('Voala! We have res_id:' + restaurant_id);
}

*There you have it. It could be easier though.

Hope it helps!

A: once you have the url of the rseraunt's page you can simply look for a javascript object attribute named "window.RES_ID" and further use it in the api call.


text:
Q: What does only "git pull" do in a certrain branch? I have a branchA and branchB (main branch). After some code review, I tried to run this first in branchA to pull changes from branchB
git pull --rebase origin branchB

followed by
git push origin -u branchA

but I get this error
! [rejected](fetch first)
error: failed to push some refs to '<url>'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

Also i see this on command prompt

After that, I did just "git pull" (without any arguments) and it works just fine. What happens in running "git pull"

A: (Note: this answer simplifies. But not by much!)
Consider this situation, looking at two versions of the same branch:
A - B - C - X (remote)

A - B - C - Y (local)

How can these be reconciled? Only one way: by merging. If we merge the remote version into the local version, we get this:
          -- X --
         /       \
A - B - C         M (local)
         \       /
          -- Y --

...where M is a newly created merge commit that combines the contributions from X and Y.
Well, that is what git pull does. It copies the remote version of the branch down to you, and merges it with your local version.
But it is illegal to do that same thing on the remote — by saying git push. You are not permitted to form a merge commit in that way. The reconciliation can only be performed on your computer, locally. You cannot, therefore, push when the remote has commits on this branch that you do not have.
Hence when you attempt to do it, the remote Git refuses. The solution of pull-then-push solves the problem. After you pull, you have all the commits that the remote has, and so the push becomes legal.

Extra information:
Consider the situation after the pull but before the push. Remember, the remote still has:
A - B - C - X (remote)

And you now have:
          -- X --
         /       \
A - B - C         M (local)
         \       /
          -- Y --

When you push, the remote is able to accept these commits just by adding M to the end of its version of the branch, like this:
A - B - C - X - M (remote)
         \     /
          - Y -

It's true that it must also accommodate Y, but the point is that no new merge commit is needed in order to do that. This is called a fast-forward — no new commits are created, but existing pushed commits are just appended to the branch.
So the rule, technically, is that you cannot push unless it is possible to fast-forward on the remote. When we started, that was not possible: somebody must create a true merge commit in order to reconcile these branches, and that somebody is not going to be the remote. By doing a pull first, and allow the non-fast-forward merge to happen on the local, you make it possible to fast-forward on the remote.


text:
Q: Xlib XGetWindowProperty Zero items returned I have problems reading some XWindow ICCCM Properties.
The problem actually is when i try to read _NET_WM_STATUS property.
The function i'm using is:
int get_property_value(Display* display, Window window,char *propname, long max_length,
           unsigned long *nitems_return, unsigned char **prop_return){
    int result;
    Atom property;
    Atom actual_type_return;
    int actual_format_return;
    unsigned long bytes_after_return;
    unsigned char* prop_to_return;
    unsigned long n_items;
    printf("-----GET_PROPERTY_VALUE-------\n");
    printf("\tPropname: %s\n", propname);
    property = XInternAtom(display, propname, True);
    if(property==None){
      printf("\tWrong Atom\n");
      return;
    }

    result = XGetWindowProperty(display, window, property, 0,   /* long_offset */
            (~0L),  /* long_length */
            False,  /* delete */
            AnyPropertyType,    /* req_type */
            &actual_type_return,
            &actual_format_return,
            &n_items, &bytes_after_return, &prop_to_return);
    if (result != Success){
        printf("\tXGetWindowProperty failed\n");
        return (-1);
    }   else {
        printf("\tActual Type: %s\n", XGetAtomName(display,property));
        printf("\tProperty format: %d\n", actual_format_return);
        //printf("Actual property return: %s\n", XGetAtomName(display,actual_type_return));
        printf("\tByte after return: %ld\n", bytes_after_return);
        printf("\tnitems return: %d\n", n_items);
        printf("\tprop return: %s\n", prop_to_return);
    }
    printf("-----END OF GET_PROPERTY_VALUE-------\n");

    return (0);
}

The get_property_value function is called after a ClientMessage is received, and this is the piece of code that handle the Event:
    case ClientMessage:
        printf("ClientMessage\n");
        printf("Message: %s\n", XGetAtomName(display,local_event.xclient.message_type));
        unsigned long nitems_return;
        unsigned char *prop_return;
        get_property_value(display, local_event.xclient.window, XGetAtomName(display,local_event.xclient.message_type), 256, &nitems_return, (unsigned char **)&prop_return);
    break;

But when i read properties sometimes i get a property with no values, is that possible?
The problem mainly is when i'm trying read AtomProperties sent from firefox (i'm trying to read the _NET_WM_STATE value) in ClientMessage Event.
As you can see from the output the property name is correctly read, but then it seems that it doesn't contains any item.
ClientMessage
Message: _NET_WM_STATE
-----GET_PROPERTY_VALUE-------
    Propname: _NET_WM_STATE
    Actual Type: _NET_WM_STATE
    Property format: 0
    Byte after return: 0
    nitems return: 0
    prop return: (null)
-----END OF GET_PROPERTY_VALUE-------

A: I don't have enough rep to comment yet (I'm kind of new to this), but I've been spending some time wrestling Xlib myself and I'll try to see if I can help. I wrote a small program incorporating your code:
#include <X11/Xlib.h>
#include <stdlib.h>
#include <stdio.h>

int get_property_value(Display* display, Window window,char *propname, long max_length,
           unsigned long *nitems_return, unsigned char **prop_return){
    int result;
    Atom property;
    Atom actual_type_return;
    int actual_format_return;
    unsigned long bytes_after_return;
    unsigned char* prop_to_return;
    unsigned long n_items;
    printf("-----GET_PROPERTY_VALUE-------\n");
    printf("\tPropname: %s\n", propname);
    property = XInternAtom(display, propname, True);
    if(property==None){
      printf("\tWrong Atom\n");
      return;
    }

    result = XGetWindowProperty(display, window, property, 0,   /* long_offset */
            (~0L),  /* long_length */
            False,  /* delete */
            AnyPropertyType,    /* req_type */
            &actual_type_return,
            &actual_format_return,
            &n_items, &bytes_after_return, &prop_to_return);
    if (result != Success){
        printf("\tXGetWindowProperty failed\n");
        return (-1);
    }   else {
        printf("\tActual Type: %s\n", XGetAtomName(display,actual_type_return));
        printf("\tProperty format: %d\n", actual_format_return);
        //printf("Actual property return: %s\n", XGetAtomName(display,actual_type_return));
        printf("\tByte after return: %ld\n", bytes_after_return);
        printf("\tnitems return: %d\n", n_items);
        printf("\tprop return: %s %s\n", XGetAtomName(display,*(Atom*)prop_to_return), XGetAtomName(display,((Atom*)prop_to_return)[1]));
    }
    printf("-----END OF GET_PROPERTY_VALUE-------\n");

    return (0);
}

int main(int argc, char** argv) {
    Display* dsp = XOpenDisplay(NULL);
    unsigned long nitems_return;
    unsigned char* prop_return;
    get_property_value(dsp, (Window)atoi(argv[1]), "_NET_WM_STATE", 100000, &nitems_return, &prop_return);
    return 0;
}

I did change some of the output things: I changed the "Actual type" output to print the name of actual_type_return rather than property (since that seemed like a typo) and I changed the "prop return" output to print atom names instead of the binary data. Anyway, I pointed this version of the code at an instance of Firefox running on my computer, and this is what I got:
$ ./xproptest 60817587
-----GET_PROPERTY_VALUE-------
    Propname: _NET_WM_STATE
    Actual Type: ATOM
    Property format: 32
    Byte after return: 0
    nitems return: 2
    prop return: _NET_WM_STATE_MAXIMIZED_VERT _NET_WM_STATE_MAXIMIZED_HORZ
-----END OF GET_PROPERTY_VALUE-------

So, the good news is that your code actually works perfectly on my machine. I'm not sure why it doesn't work on yours, though. Of course, the above output is from when Firefox is maximized; when it is not, the output is this:
$ ./xproptest 60817587
-----GET_PROPERTY_VALUE-------
    Propname: _NET_WM_STATE
    Actual Type: ATOM
    Property format: 32
    Byte after return: 0
    nitems return: 0
    prop return:

…and then a couple errors about how I'm reading invalid Atoms because the code above just assumes there are two. This is the correct output for when a property is empty and has no values; however, notice how my property format is 32 and yours is 0. From reading the manuals, it looks like the only way to get a 0 property format out of a successful call to XGetWindowProperty is to call it on a property that doesn't exist. I'm not sure why your Firefox wouldn't have _NET_WM_STATE set, though.
In summary, my guess is that your code actually functions perfectly (besides the typo on one of the outputs), but that for some reason the property that you're trying to read doesn't exist on the window you're trying to read it from. If I'm right, if you examine the value of actual_type_return after reading the property you should find that it is None. Furthermore, you should be able to (if you haven't already) print the window id you're attempting to read from in your code (window) and use xwininfo and xprop with the -id flag in order to check whether the window you're reading from is the one that you think it is and whether it actually has the property that you're trying to read. Hopefully this will help you to figure out what the actual problem is.


text:
Q: how to get max blocks in thrust in cuda 5.5 The Thrust function below can get the maximum blocks of for a CUDA launch CUDA 5.0, which is used by Sparse Matrix Vector multiplication(SpMV) in CUSP, and it is a technique for setting up execution for persistent threads. The first line is the header file.
#include <thrust/detail/backend/cuda/arch.h>

thrust::detail::backend::cuda::arch::max_active_blocks(kernel<float,int,VECTORS_PER_BLOCK,TH    READS_PER_VECTOR>,THREADS_PER_BLOCK,(size_t)0)

But the function is not supported by CUDA 5.5. Was this technique not supported by CUDA 5.5, or should I use some other function instead?

A: There was never any supported way to perform this computation in any version of Thrust. Headers inside thrust/detail and identifiers inside a detail namespace are part of Thrust's implementation -- they are not public features. Using them will break your code.
That said, there's some standalone code implementing the occupancy calculator in this repository:
https://github.com/jaredhoberock/cuda_launch_config


text:
Q: Latex Output When I compile a latex file, it produces also a .txt, .bbl, .aux files. They are not useful as I can delete them without harm. My question is what are these files for and how can I opte not to generate them when I compile the .tex file?

A: Those files are useful and represent the output of the multiple-pass typesetting process.  If you delete them, you'll need to rerun LaTeX to regenerate them.  Quite often, you'll see a LaTeX workflow that looks something like this:

*

*Run LaTeX (finds all the bibliographical references, figure entries, etc.)

*Run BibTeX (creates an initial set of text for the bibliographic entries)

*Run LaTeX (populates the document with bibliography, figure references)

*Run LaTeX (general good luck: there are some corner cases when references need two passes to fully populate)

That said, once you have a printable document (.dvi, .pdf, .ps, etc.), you can delete those temporary files until you need to edit the LaTeX source again.
This answer to another question breaks down what each pass is doing (from the point of a bibliography).

A: From bluesky.com
"The .aux (auxiliary) file is where LaTeX stores all the information about the counters (like section numbers), footnotes, bibliography entries, reference marks, and anything else that LaTeX may need to keep track of. This file is written over whenever a file is typeset by LaTeX. Whenever a document is typeset LaTeX reads this file to get the information it need, and writes to it after typesetting is completed. This is why changes in the counters will not take effect until LaTeX is run twice, because the .aux file is not up to date the first time. The .bib file is where all the bibliography information is kept. You can either make this file yourself, or you can use BibTeX to create the file. The .toc file contains all the information needed to create the Table of Contents. This file is created when LaTeX sees the command \tableofcontents, and the section names, numbers and page numbers are all read from the .aux file."