text:
Q: Emulate super in javascript Basically is there a good elegant mechanism to emulate super with syntax that is as simple as one of the following

*

*this.$super.prop()

*this.$super.prop.apply(this, arguments);
Criteria to uphold are :

*

*this.$super must be a reference to the prototype. i.e. if I change the super prototype at run-time this change will be reflected. This basically means it the parent has a new property then this should be shown at run-time on all children through super just like a hard coded reference to the parent would reflect changes

*this.$super.f.apply(this, arguments); must work for recursive calls. For any chained set of inheritance where multiple super calls are made as you go up the inheritance chain, you must not hit the recursive problem.

*You must not hardcode references to super objects in your children. I.e. Base.prototype.f.apply(this, arguments); defeats the point.

*You must not use a X to JavaScript compiler or JavaScript preprocessor.

*Must be ES5 compliant

The naive implementation would be something like this.
var injectSuper = function (parent, child) {
  child.prototype.$super = parent.prototype;
};

But this breaks condition 2.
The most elegant mechanism I've seen to date is IvoWetzel's eval hack, which is pretty much a JavaScript preprocessor and thus fails criteria 4.

A: John Resig posted an ineherence mechanism with simple but great super support.
The only difference is that super points to the base method from where you are calling it.
Take a look at http://ejohn.org/blog/simple-javascript-inheritance/.

A: Note that for the following implementation, when you are inside a method that is invoked via $super, access to properties while working in the parent class never resolve to the child class's methods or variables, unless you access a member that is stored directly on the object itself (as opposed to attached to the prototype). This avoids a slew of confusion (read as subtle bugs).
Update:
Here is an implementation that works without __proto__. The catch is that using $super is linear in the number of properties the parent object has.
function extend (Child, prototype, /*optional*/Parent) {
    if (!Parent) {
        Parent = Object;
    }
    Child.prototype = Object.create(Parent.prototype);
    Child.prototype.constructor = Child;
    for (var x in prototype) {
        if (prototype.hasOwnProperty(x)) {
            Child.prototype[x] = prototype[x];
        }
    }
    Child.prototype.$super = function (propName) {
        var prop = Parent.prototype[propName];
        if (typeof prop !== "function") {
            return prop;
        }
        var self = this;
        return function () {
            var selfPrototype = self.constructor.prototype;
            var pp = Parent.prototype;
            for (var x in pp) {
                self[x] = pp[x];
            }
            try {
                return prop.apply(self, arguments);
            }
            finally {
                for (var x in selfPrototype) {
                    self[x] = selfPrototype[x];
                }
            }
        };
    };
}

The following implementation is for browsers that support the __proto__ property:
function extend (Child, prototype, /*optional*/Parent) {
    if (!Parent) {
        Parent = Object;
    }
    Child.prototype = Object.create(Parent.prototype);
    Child.prototype.constructor = Child;
    for (var x in prototype) {
        if (prototype.hasOwnProperty(x)) {
            Child.prototype[x] = prototype[x];
        }
    }
    Child.prototype.$super = function (propName) {
        var prop = Parent.prototype[propName];
        if (typeof prop !== "function") {
            return prop;
        }
        var self = this;
        return function (/*arg1, arg2, ...*/) {
            var selfProto = self.__proto__;
            self.__proto__ = Parent.prototype;
            try {
                return prop.apply(self, arguments);
            }
            finally {
                self.__proto__ = selfProto;
            }
        };
    };
}

Example:
function A () {}
extend(A, {
    foo: function () {
        return "A1";
    }
});

function B () {}
extend(B, {
    foo: function () {
        return this.$super("foo")() + "_B1";
    }
}, A);

function C () {}
extend(C, {
    foo: function () {
        return this.$super("foo")() + "_C1";
    }
}, B);

var c = new C();
var res1 = c.foo();
B.prototype.foo = function () {
    return this.$super("foo")() + "_B2";
};
var res2 = c.foo();

alert(res1 + "\n" + res2);

A: The main difficulty with super is that you need to find what I call here: the object that contains the method that makes the super reference. That is absolutely necessary to get the semantics right. Obviously, having the prototype of here is just as good, but that doesn't make much of a difference. The following is a static solution:
// Simulated static super references (as proposed by Allen Wirfs-Brock)
// http://wiki.ecmascript.org/doku.php?id=harmony:object_initialiser_super

//------------------ Library

function addSuperReferencesTo(obj) {
    Object.getOwnPropertyNames(obj).forEach(function(key) {
        var value = obj[key];
        if (typeof value === "function" && value.name === "me") {
            value.super = Object.getPrototypeOf(obj);
        }
    });
}

function copyOwnFrom(target, source) {
    Object.getOwnPropertyNames(source).forEach(function(propName) {
        Object.defineProperty(target, propName,
            Object.getOwnPropertyDescriptor(source, propName));
    });
    return target;
};

function extends(subC, superC) {
    var subProto = Object.create(superC.prototype);
    // At the very least, we keep the "constructor" property
    // At most, we preserve additions that have already been made
    copyOwnFrom(subProto, subC.prototype);
    addSuperReferencesTo(subProto);
    subC.prototype = subProto;
};

//------------------ Example

function A(name) {
    this.name = name;
}
A.prototype.method = function () {
    return "A:"+this.name;
}

function B(name) {
    A.call(this, name);
}
// A named function expression allows a function to refer to itself
B.prototype.method = function me() {
    return "B"+me.super.method.call(this);
}
extends(B, A);

var b = new B("hello");
console.log(b.method()); // BA:hello

A: I don't think there is a "free" way out of the "recursive super" problem you mention.
We can't mess with the this because doing so would either force us to change prototypes in a nonstandard way, or move us up the proto chain, losing instance variables. Therefore the "current class" and "super class" must be known when we do the super-ing, without passing that responsibility to this or one of its properties.
There are many some things we could try doing but all I can think have some undesireable consequences:

*

*Add super info to the functions at creation time, access it using arguments.calee or similar evilness.

*Add extra info when calling the super method
$super(CurrentClass).method.call(this, 1,2,3)

This forces us to duplicate the current class name (so we can look up its superclass in some super dictionary) but at least it isn't as bad as having to duplicate the superclass name, (since coupling against the inheritance relationships if worse then the inner coupling with a class' own name)
//Normal Javascript needs the superclass name
SuperClass.prototype.method.call(this, 1,2,3);

While this is far from ideal, there is at least some historical precedent from 2.x Python. (They "fixed" super for 3.0 so it doesn't require arguments anymore, but I am not sure how much magic that involved and how portable it would be to JS)

Edit: Working fiddle
var superPairs = [];
// An association list of baseClass -> parentClass

var injectSuper = function (parent, child) {
    superPairs.push({
        parent: parent,
        child: child
    });
};

function $super(baseClass, obj){
    for(var i=0; i < superPairs.length; i++){
        var p = superPairs[i];
        if(p.child === baseClass){
            return p.parent;
        }
    }
}

A: JsFiddle:
What is wrong with this?
'use strict';

function Class() {}
Class.extend = function (constructor, definition) {
    var key, hasOwn = {}.hasOwnProperty, proto = this.prototype, temp, Extended;

    if (typeof constructor !== 'function') {
        temp = constructor;
        constructor = definition || function () {};
        definition = temp;
    }
    definition = definition || {};

    Extended = constructor;
    Extended.prototype = new this();

    for (key in definition) {
        if (hasOwn.call(definition, key)) {
            Extended.prototype[key] = definition[key];
        }
    }

    Extended.prototype.constructor = Extended;

    for (key in this) {
        if (hasOwn.call(this, key)) {
            Extended[key] = this[key];
        }
    }

    Extended.$super = proto;
    return Extended;
};

Usage:
var A = Class.extend(function A () {}, {
    foo: function (n) { return n;}
});
var B = A.extend(function B () {}, {
    foo: function (n) {
        if (n > 100) return -1;
        return B.$super.foo.call(this, n+1);
    }
});
var C = B.extend(function C () {}, {
    foo: function (n) {
        return C.$super.foo.call(this, n+2);
    }
});

var c = new C();
document.write(c.foo(0) + '
'); //3
A.prototype.foo = function(n) { return -n; };
document.write(c.foo(0)); //-3

Example usage with privileged methods instead of public methods.
var A2 = Class.extend(function A2 () {
    this.foo = function (n) {
        return n;
    };
});
var B2 = A2.extend(function B2 () {
    B2.$super.constructor();
    this.foo = function (n) {
        if (n > 100) return -1;
        return B2.$super.foo.call(this, n+1);
    };
});
var C2 = B2.extend(function C2 () {
    C2.$super.constructor();
    this.foo = function (n) {
        return C2.$super.foo.call(this, n+2);
    };
});

//you must remember to constructor chain
//if you don't then C2.$super.foo === A2.prototype.foo

var c = new C2();
document.write(c.foo(0) + '
'); //3

A: In the spirit of completeness (also thank you everyone for this thread it has been an excellent point of reference!) I wanted to toss in this implementation.
If we are admitting that there is no good way of meeting all of the above criteria, then I think this is  a valiant effort by the Salsify team (I just found it) found here. This is the only implementation I've seen that avoids the recursion problem but also lets .super be a reference to the correct prototype, without pre-compilation.
So instead of breaking criteria 1, we break 5.
the technique hinges on using Function.caller (not es5 compliant, though it is extensively supported in browsers and es6 removes future need), but it gives really elegant solution to all the other issues (I think). .caller lets us get the method reference which lets us locate where we are in the prototype chain, and uses a getter to return the correct prototype. Its not perfect but it is widely different solution than what I've seen in this space
var Base = function() {};

Base.extend = function(props) {
  var parent = this, Subclass = function(){ parent.apply(this, arguments) };

    Subclass.prototype = Object.create(parent.prototype);

    for(var k in props) {
        if( props.hasOwnProperty(k) ){
            Subclass.prototype[k] = props[k]
            if(typeof props[k] === 'function')
                Subclass.prototype[k]._name = k
        }
    }

    for(var k in parent)
        if( parent.hasOwnProperty(k)) Subclass[k] = parent[k]

    Subclass.prototype.constructor = Subclass
    return Subclass;
};

Object.defineProperty(Base.prototype, "super", {
  get: function get() {
    var impl = get.caller,
        name = impl._name,
        foundImpl = this[name] === impl,
        proto = this;

    while (proto = Object.getPrototypeOf(proto)) {
      if (!proto[name]) break;
      else if (proto[name] === impl) foundImpl = true;
      else if (foundImpl)            return proto;
    }

    if (!foundImpl) throw "`super` may not be called outside a method implementation";
  }
});

var Parent = Base.extend({
  greet: function(x) {
    return x + " 2";
  }
})

var Child = Parent.extend({
  greet: function(x) {
    return this.super.greet.call(this, x + " 1" );
  }
});

var c = new Child
c.greet('start ') // => 'start 1 2'

you can also adjust this to return the correct method (as in the original post) or you can remove the need to annotate each method with the name, by passing in the name to a super function (instead of using a getter)
here is a working fiddle demonstrating the technique: jsfiddle

A: For those who do not understand the recursion problem the OP presents, here is an example:
function A () {}
A.prototype.foo = function (n) {
    return n;
};

function B () {}
B.prototype = new A();
B.prototype.constructor = B;
B.prototype.$super = A.prototype;
B.prototype.foo = function (n) {
    if (n > 100) return -1;
    return this.$super.foo.call(this, n+1);
};

function C () {}
C.prototype = new B();
C.prototype.constructor = C;
C.prototype.$super = B.prototype;
C.prototype.foo = function (n) {
    return this.$super.foo.call(this, n+2);
};

alert(new C().foo(0)); // alerts -1, not 3

The reason: this in Javascript is dynamically bound.

A: Have a look at the Classy library; it provides classes and inheritance and access to an overridden method using this.$super

A: I came up with a way that will allow you to use a pseudo keyword Super by changing the execution context (A way I have yet to see be presented on here.) The drawback that I found that I'm not happy with at all is that it cannot add the "Super" variable to the method's execution context, but instead replaces it the entire execution context, this means that any private methods defined with the method become unavailable...
This method is very similar to the "eval hack" OP presented however it doesn't do any processing on the function's source string, just redeclares the function using eval in the current execution context. Making it a bit better as both of the methods have the same aforementioned drawback.
Very simple method:
function extend(child, parent){

    var superify = function(/* Super */){
        // Make MakeClass scope unavailable.
        var child = undefined,
            parent = undefined,
            superify = null,
            parentSuper = undefined,
            oldProto = undefined,
            keys = undefined,
            i = undefined,
            len = undefined;

        // Make Super available to returned func.
        var Super = arguments[0];
        return function(/* func */){
            /* This redefines the function with the current execution context.
             * Meaning that when the returned function is called it will have all of the current scopes variables available to it, which right here is just "Super"
             * This has the unfortunate side effect of ripping the old execution context away from the method meaning that no private methods that may have been defined in the original scope are available to it.
             */
            return eval("("+ arguments[0] +")");
        };
    };

    var parentSuper = superify(parent.prototype);

    var oldProto = child.prototype;
    var keys = Object.getOwnPropertyNames(oldProto);
    child.prototype = Object.create(parent.prototype);
    Object.defineProperty(child.prototype, "constructor", {enumerable: false, value: child});

    for(var i = 0, len = keys.length; i<len; i++)
        if("function" === typeof oldProto[keys[i]])
            child.prototype[keys[i]] = parentSuper(oldProto[keys[i]]);
}

An example of making a class
function P(){}
P.prototype.logSomething = function(){console.log("Bro.");};

function C(){}
C.prototype.logSomething = function(){console.log("Cool story"); Super.logSomething.call(this);}

extend(C, P);

var test = new C();
test.logSomething(); // "Cool story" "Bro."

An example of the drawback mentioned earlier.
(function(){
    function privateMethod(){console.log("In a private method");}

    function P(){};

    window.C = function C(){};
    C.prototype.privilagedMethod = function(){
        // This throws an error because when we call extend on this class this function gets redefined in a new scope where privateMethod is not available.
        privateMethod();
    }

    extend(C, P);
})()

var test = new C();
test.privilagedMethod(); // throws error

Also note that this method isn't "superifying" the child constructor meaning that Super isn't available to it. I just wanted to explain the concept, not make a working library :)
Also, just realized that I met all of OP's conditions! (Although there really should be a condition about execution context)

A: Here's my version: lowclass
And here's the super spaghetti soup example from the test.js file (EDIT: made into running example):

var SomeClass = Class((public, protected, private) => ({

    // default access is public, like C++ structs
    publicMethod() {
        console.log('base class publicMethod')
        protected(this).protectedMethod()
    },

    checkPrivateProp() {
        console.assert( private(this).lorem === 'foo' )
    },

    protected: {
        protectedMethod() {
            console.log('base class protectedMethod:', private(this).lorem)
            private(this).lorem = 'foo'
        },
    },

    private: {
        lorem: 'blah',
    },
}))

var SubClass = SomeClass.subclass((public, protected, private, _super) => ({

    publicMethod() {
        _super(this).publicMethod()
        console.log('extended a public method')
        private(this).lorem = 'baaaaz'
        this.checkPrivateProp()
    },

    checkPrivateProp() {
        _super(this).checkPrivateProp()
        console.assert( private(this).lorem === 'baaaaz' )
    },

    protected: {

        protectedMethod() {
            _super(this).protectedMethod()
            console.log('extended a protected method')
        },

    },

    private: {
        lorem: 'bar',
    },
}))

var GrandChildClass = SubClass.subclass((public, protected, private, _super) => ({

    test() {
        private(this).begin()
    },

    reallyBegin() {
        protected(this).reallyReallyBegin()
    },

    protected: {
        reallyReallyBegin() {
            _super(public(this)).publicMethod()
        },
    },

    private: {
        begin() {
            public(this).reallyBegin()
        },
    },
}))

var o = new GrandChildClass
o.test()

console.assert( typeof o.test === 'function' )
console.assert( o.reallyReallyBegin === undefined )
console.assert( o.begin === undefined )

Trying invalid member access or invalid use of _super will throw an error.
About the requirements:

*

*this.$super must be a reference to the prototype. i.e. if I change the super prototype at run-time this change will be reflected. This basically means it the parent has a new property then this should be shown at run-time on all children through super just like a hard coded reference to the parent would reflect changes
No, the _super helper doesn't return the prototype, only an object with copied descriptors to avoid modification of the protected and private prototypes. Furthermore, the prototype from which the descriptors are copied from is held in the scope of the Class/subclass call. It would be neat to have this. FWIW, native classes behave the same.

*this.$super.f.apply(this, arguments); must work for recursive calls. For any chained set of inheritance where multiple super calls are made as you go up the inheritance chain, you must not hit the recursive problem.
yep, no problem.

*You must not hardcode references to super objects in your children. I.e. Base.prototype.f.apply(this, arguments); defeats the point.
yep

*You must not use a X to JavaScript compiler or JavaScript preprocessor.
yep, all runtime

*Must be ES5 compliant
Yes, it includes a Babel-based build step (f.e. lowclass uses WeakMap, which is compiled to a non-leaky ES5 form). I don't think this defeats requirement 4, it just allows me to write ES6+ but it should still work in ES5. Admittedly I haven't done much testing of this in ES5, but if you'd like to try it, we can definitely iron out any builds issues on my end, and from your end you should be able to consume it without any build steps.
The only requirement not met is 1. It would be nice. But maybe it is bad practice to be swapping out prototypes. But actually, I do have uses where I would like to swap out prototypes in order to achieve meta stuff. 'Twould be nice to have this feature with native super (which is static :( ), let alone in this implementation.
To double check requirement 2, I added the basic recursive test to my test.js, which works (EDIT: made into running example):

const A = Class((public, protected, private) => ({
    foo: function (n) { return n }
}))

const B = A.subclass((public, protected, private, _super) => ({
    foo: function (n) {
        if (n > 100) return -1;
        return _super(this).foo(n+1);
    }
}))

const C = B.subclass((public, protected, private, _super) => ({
    foo: function (n) {
        return _super(this).foo(n+2);
    }
}))

var c = new C();
console.log( c.foo(0) === 3 )

(the class header is a bit long for these little classes. I have a couple ideas to make it possible to reduce that if not all the helpers are needed up front)

A: I think I have a more simple way....
function Father(){
  this.word = "I'm the Father";

  this.say = function(){
     return this.word; // I'm the Father;
  }
}

function Sun(){
  Father.call(this); // Extend the Father

  this.word = "I'm the sun"; // Override I'm the Father;

  this.say = function(){ // Override I'm the Father;
    this.word = "I was changed"; // Change the word;
    return new Father().say.apply(this); // Call the super.say()
  }
}

var a = new Father();
var b = new Sun();

a.say() // I'm the father
b.ay() // I'm the sun
b.say() // I was changed


text:
Q: How can i add elements to a PriorityQueue of Java Collections that are of different type? I want to add string and integer elements into a Priority Queue. However,after adding string elements and then integer, the program breaks and gives me error as following:
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
Is it not allowed to have values of multiple types in a single PriorityQueue?
What could be the other way around?
My PriorityQueue looks like this:
PriorityQueue queue = new PriorityQueue();

Element to add is as following:
public void addElementToQueue(Object obj) {
        queue.add(obj);
}

A: I don't know know what logic do you want to follow but it will look like the following code:
 public static void main(String[] args) {
    PriorityQueue<Object> priorityQueue = new PriorityQueue<>(new Comparator<Object>() {

        @Override
        public int compare(Object o1, Object o2) {
            //Your own comparison logic
            return 0;
        }
    });
    priorityQueue.add("Bar");
    priorityQueue.add(2);
    priorityQueue.add(1);
    priorityQueue.add(3);
    priorityQueue.add(4);
    priorityQueue.add("Foo");
    System.out.println(priorityQueue);
}

Please let me know if you need more details.
Thanks

redpajama_set_name: RedPajamaStackExchange


text:
Q: RxJS Combine 2 Subscriptions I have a service that outputs 2 observables. 1 is for just getting the currently authenticated user and the other is for getting all of the active users. On the main screen I want to call both of these observables to use, this will be done (currently) by subscribing to both of these observables, however the first observable does not always run. I am looking for a solution for both observables to emit a value before anything errors our or loads on the page. I have tried forkjoin in my examble below but it does not work, i suspect this is because forkjoin expects something to emit but nothing emits, but subscribing to both observables does output the data I need. here  is what I have tried:
    const tt =  Observable.forkJoin(
        this.auth.getActiveUsers().map((res) => res = res  ),
        this.auth.user.map((res) => res = res ),
    );
    console.log("running" );
    tt.subscribe( (data) => {
      console.log("data ", data );
        console.log("data[0] ", data[0] );
        console.log("data[1] ", data[1] );
      },
      err => console.error(err),
      () => console.error("complete"),
    );

and here is how the subscriptions are laid out in my service.ts file:
    Filename: Service.ts

    ...

    // first Observable
    constructor( private afAuth: AngularFireAuth,
                private db: AngularFirestore ) {

        this.user = this.afAuth.authState.switchMap(user => {
            if (user) {
                return this.db.doc<iUser>(`users/${user.uid}`).valueChanges()
            } else {
                return Observable.of(null)
            }
            })

    }

    ...

    // second Observable
    getActiveUsers(): Observable<iUser[]> {
    return this.db.collection<iUser>('users').valueChanges().catch(this.catchError);
    }

    ...

A: forkJoin expects an array, so I think that's why it didn't work in your code:
 const tt = Observable.forkJoin([
                this.auth.getActiveUsers(),
                this.auth.user
            ]);
 // ...

A: I guess your auth.user observable is a hot one (not complete when the value is emitted) while forkJoin emits only when all passed observables are complete. Not emit a value but complete.
If my guess is correct what you can do in this case is just passing auth.user.first() which will create a complete observable from the original observable and your forkJoin will work as expected

A: Use mergeMap + forkJoin:
import { mergeMap } from 'rxjs/operators';
import { forkJoin, of } from 'rxjs';

const myPromise = val =>
  new Promise(resolve =>
    setTimeout(() => resolve(`Promise Resolved: ${val}`), 5000)
  );

const source = of([1, 2, 3, 4, 5]);
const example = source.pipe(mergeMap(q => forkJoin(...q.map(myPromise))));
/*
  output:
  [
   "Promise Resolved: 1",
   "Promise Resolved: 2",
   "Promise Resolved: 3",
   "Promise Resolved: 4",
   "Promise Resolved: 5"
  ]
*/
const subscribe = example.subscribe(val => console.log(val));

Full example


text:
Q: Is multiple named query file possible I always see a single file being used for named query. I have never seen multiple file for queries, but can it be done?

A: Yes. You can add as many as you want.
It's actually a mapping file, but hibernate doesn't care if there isn't a class mapping definition in there.
See the docs here, so you should add a
<mapping resource="path/to/your/Mapping-or-query-file.hbm.xml"/>


text:
Q: Spring JTA transaction with JPA and jndi datasource for Websphere I am having multiple datasource and one one database configured with JPA. I am using websphere 7. I want all these datasouces to be configured as global transactions. I am using below spring configurations but the transactions are not working as expected global transaction. If one db is failing then the other db is getting commited which is not expected as single global transactions. Can you please help me where i m doing incorrect,
I am having 2 datasouce one as configured below with id="us_icfs_datasource" and another using JPA
<jee:jndi-lookup id="entityManagerFactory" jndi-name="persistence/persistenceUnit"/>
    <bean id="pabpp" class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>

<bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager" />

<!-- Needed for @Transactional annotation -->
    <tx:annotation-driven/>

<jee:jndi-lookup id="US_ICFS_DATASORCE"
        jndi-name="jdbc/financing_tools_docgen_txtmgr"
        cache="true"
        resource-ref="true"
        proxy-interface="javax.sql.DataSource" />

also I have added below code in web.xml
 <persistence-unit-ref>
    <persistence-unit-ref-name>persistence/persistenceUnit</persistence-unit-ref-name>
    <persistence-unit-name>persistenceUnit</persistence-unit-name>
  </persistence-unit-ref>

  <persistence-context-ref>
    <persistence-context-ref-name>persistence/persistenceUnit</persistence-context-ref-name>
    <persistence-unit-name>persistenceUnit</persistence-unit-name>
  </persistence-context-ref>

below is my code where i m using transaction
> @Transactional    public TemplateMapping addTemplateMapping(User user,
> TemplateMapping templateMapping)          throws
> TemplateMappingServiceException {         .... }

A: On Websphere you should use this bean to hook into the Websphere transaction manager:
<bean id="transactionManager"
     class="org.springframework.transaction.jta.WebSphereUowTransactionManager"/>

See also this article
EDIT:
In order to use 2-phase commit (i.e. ensuring consistency across multiple resources), you will need to use XA data sources.  See this article for details.

A: First of all your data sources that participate in global transaction must be of javax.sql.XADataSource type.
You also have to set transaction type in your persistence unit to JTA (not RESOURCE_LOCAL).
And you need to inform your JPA implementation that you want to do global transactions.


text:
Q: jboss 5 changing default port I am trying to change the default port on my jboss server to port 80.
i have had a look around the web and i have had suggestions of editing this file jboss5\server\default\deploy\jbossweb.sar\server.xml which is fine. changing this file alone still does not fix the issue.
There have also been suggestion to also change this file: jboss5\server\default\conf\bootstrap\bindings.xml Only problem is that i cant find this binding.xml
Is the binding.xml file a standard in JBoss 5? Or has it been renamed or changes location in JBoss 5.
Does anyone have any clear steps on changing the the default port from 8080 to 80.

A: ${JBOSS_HOME}\server\default\deploy\jbossweb.sar\server.xml
For example, locate in the path:
D:\jboss-5.0.0.CR2-jdk6\jboss-5.0.0.CR2\server\default\deploy\jbossweb.sar,
search for the section:
<Connector protocol="HTTP/1.1" port="8080" address="${jboss.bind.address}"
       connectionTimeout="20000" redirectPort="8443" />

Then, change the port number to the one you choose, for example: from: "8080" to "8090" as follows:
<Connector protocol="HTTP/1.1" port="8090" address="${jboss.bind.address}"
       connectionTimeout="20000" redirectPort="8443" />

I hope this would help you.

A: This works on jboss-5.1.0.GA :
Edit the file ${JBOSS_HOME}/server/default/conf/bindingservice.beans/META-INF/bindings-jboss-beans.xml as follows ->
Change ${jboss.service.binding.set:ports-default} to
${jboss.service.binding.set:ports-01}
This will change all defalt to default+100 port.
HTTP - > 8180 and so on.

A: Can you try changing in ${JBOSS_HOME}/server/default/conf/bindingservice.beans/META-INF/bindings-jboss-beans.xml

A: It´s posible configure the ports as explained by peers in the next two files:
${JBOSS_HOME}/server/default/conf/bindingservice.beans/META-INF/bindings-jboss-beans.xml

${JBOSS_HOME}/server/default/deploy/jboss-web.deployer/server.xml

When the two configurations coexist Jboss works for the highest port, for example:
jbossweb.sar
Connector protocol="HTTP/1.1" port="8980" address="${jboss.bind.address}"
       connectionTimeout="20000" redirectPort="8443"

bindings-jboss-beans.xml
*${jboss.service.binding.set:ports-01}*

Jboss will run in port 8980

A: another part could be

Blockquote

D:\jboss-4.2.3.GA\server\default\deploy\jboss-web.deployer\server.xml

Blockquote

There
   *<Connector port=**"9090"** address="${jboss.bind.address}"
     maxThreads="250" maxHttpHeaderSize="8192"
     emptySessionPath="true" protocol="HTTP/1.1"
     enableLookups="false" redirectPort="8443" acceptCount="100"
     connectionTimeout="20000" disableUploadTimeout="true" />*

change the port above

A: Just change the port number in the file
jboss-5.0.0.GA\server\default\deploy\jbossweb.sar\server.xml
  <Connector protocol="HTTP/1.1" port="7070" address="${jboss.bind.address}"
           connectionTimeout="20000" redirectPort="8443" />

In the above i have changed to 7070.

A: Change the port number in the file ${JBOSS_HOME}/server/default/conf/bindingservice.beans/META-INF/bindings-jboss-beans.xml. For example to 6060
  <Connector protocol="HTTP/1.1" port="6060" address="${jboss.bind.address}"
           connectionTimeout="20000" redirectPort="8443" />

If for any reason dont works also change this another too. To the same port.
jboss-5.0.0.GA\server\default\deploy\jbossweb.sar\server.xml


text:
Q: JPA 2.0 LEFT JOIN induces INNER JOIN I have a ClassRoom class with a name field, and a Student class with a ClassRoom field. Not all students have a classroom.
I want a list of all students with their classroom name (or an empty string if no classroom). Using this JPQL query :
Select s.name, s.classRoom.name from Student s LEFT JOIN s.classRoom

The problem is that this returns only students with a classroom. The right generated SQL should be
Select s.name, c.name from student s left join classroom c on c.id=s.classroomid

Which returns all students, but the s.classRoom.name construct seems to force an inner join in the generated SQL.

A: Using a chained expression like s.classRoom.name generates an inner join. You need to assign an alias to the left joined entity and use that alias:
select s.name, c.name from Student s left join s.classRoom c


text:
Q: EWS: Can't update item body since it contains control characters (ASCII 29, 30) I tried to update body of an item using EWS, however, I get the following error:
Exception calling "Update" with "1" argument(s): "The invalid value '' was specified for the 'Body' element."
FullyQualifiedErrorId : ServiceXmlSerializationException

Steps to reproduce problem:
$item.Body.Text = 30 -as [char]
$item.Update("AlwaysOverwrite")

Cause of error is usage of control characters  (File, Group, Record, and Unit: FS, GS, RS and US).


text:
Q: Reduction Algorithm for Dot Product of Two 1D Vectors I've been trying to work out an algorithm to get the dot product of two vectors within a CUDA program via reduction and seem to be stuck :/
In essence, I'm trying to write this code in CUDA:
for (int i = 0; i < n; i++)
    h_h += h_a[i] * h_b[i];

Where h_a and h_b are arrays of floats and h_h sums up the dot product.
I'm trying to use reduction here - so far I've got this...
__global__ void dot_product(int n, float * d_a, float * d_b){

     int i = threadIdx.x;

     for (int stride = 1; i + stride < n; stride <<= 1) {
         if (i % (2 * stride) == 0){
             d_a[i] += d_a[i + stride] * d_b[i + stride];
         }
         __syncthreads();
     }
}

If I change the main line to d_a[i] += d_a[i + stride];, it sums up the array just fine. I seem to be running into a parallel issue here from what I gather. Can someone point out my issue?
My kernel call is:
dot_product<<<1, n>>>(n, d_a, d_b);, where n is the size of each array.

A: There are two problems here:

*

*As pointed out in comments, you never calculate the product of the first elements (this is a minor issue)

*Your dot product calculation is incorrect. The parallel reduction should be performing a sum of the individual products of corresponding elements. Your code performs the product at every stage of the parallel reduction, so that products are getting multiplied again as they as are summed. That is incorrect.

You want to do something like this:
__global__ void dot_product(int n, float * d_a, float * d_b){

     int i = threadIdx.x;

     d_a[i] = d_a[i] * d_b[i]; // d_a now contains products
     __syncthreads();

     for (int stride = 1; i + stride < n; stride <<= 1) {
         if (i % (2 * stride) == 0){
             d_a[i] += d_a[i + stride]; // which are summed by reduction
         }
         __syncthreads();
     }
}

[disclaimer: written in browser, never compiled or test, use at own risk]


text:
Q: Multisite - Parent site with Polylang with different domains for each language A client wants a Wordpress multisite installation where they will have over 100 child sites. The child sites will either have its own domain or use the subdomain. This is all fine and good but now he's requesting that the parent site to have both English and French using Polylang plugin and have a different domain for each.
Example: http://ParentSite.com and http://ParentSiteFrench.com will both go the the main site of the network but ParentSiteFrench.com will show only the FR pages from Polylang.
Is this possible?
Thanks in advanced!

A: Looking at the plugin description, this should be possible:

you can use one different subdomain or domain per language

You would need to activate the plugin on the main site only. It is best to test the whole thing on some testing multisite environment.


text:
Q: Есть ли библиотека для работы с RDP на уровне TCP? Без окон Ищу библиотеку, которая позволила бы общаться с удаленным компьютером по протоколу RDP, но без окон. Мне не нужно управление. По сути мне надо лишь проверять доступность множества серверов по RDP.
Пока видел:
 1. ActiveX компонент с wrapper'ом. Но он требует окно, что логично. Но мне не подходит.
 2. Смотрел спецификацию протокола. Там все не просто. Много структур. Для всего, вроде есть описание и возможно придется обходиться этим.
Есть мысли?

A: *

*Идём в менеджер Nuget-пакетов и ищем что-нибудь по слову RDP

*Находим там FreeRDP-Sharp.

*Устанавливаем, смотрим что в нём есть через Class View. Замечаем пространство имён Core, в нём класс RDP, делаем предположение что это то, что нам нужно.

*Для проверки пишем простой код:
    var rdp = new FreeRDP.Core.RDP();
    rdp.Connect("192.168.0.10", "", "user", "password");
    Console.WriteLine(rdp.Connected);
    Console.ReadKey();

Всё, проверка пройдена - мы присоединились к серверу по RDP и получили статус соединения.
Если нужны детали реализации - идём на гитхаб и смотрим исходники проекта. По сути, это просто обёртка над unsafe-библиотекой FreeRDP, в которой можно (при наличии должных знаний C++) посмотреть детали реализации.


text:
Q: Apache James TLS Woes I am trying to set up a small email server using Apache James v2.3.2.1.  My Java version for this installation is jre1.8.0_131.  My server is running CentOS 6.9.  I have the server running, but I cannot get clients to properly connect via TLS.
First, I generated a key like this:
keytool -genkey -alias james -keyalg RSA -keystore ./keystore

For the common name of the subject, I provided the FQDN of the server as I will be using it, henceforth "a.b.c"
I then updated the James config.xml server-sockets section to load from said keystore:
<factory name="ssl" class="org.apache.avalon.cornerstone.blocks.sockets.TLSServerSocketFactory">
    <ssl-factory>
           <keystore>
              <file>conf/keystore</file>
              <password>?</password>
              <key-password>?</key-password>
              <type>JKS</type>
              <protocol>TLS</protocol>
              <algorithm>SunX509</algorithm>
              <authenticate-client>false</authenticate-client>
           </keystore>
        </ssl-factory>
     </factory>

The server starts properly, and with debug output turned on, I can see that it is reading the keystore:
Running Phoenix:

Phoenix 4.2

***
found key for : james
chain [0] = [
[
  Version: V3
  Subject: CN=a.b.c, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=US
  Signature Algorithm: SHA256withRSA, OID = 1.2.840.113549.1.1.11

  Key:  Sun RSA public key, 2048 bits
  modulus: ...
  public exponent: ...
  Validity: [From: Thu Apr 20 13:11:08 EDT 2017,
               To: Wed Jul 19 13:11:08 EDT 2017]
  Issuer: CN=a.b.c, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=US
  SerialNumber: [    51a402ba]

...

adding as trusted cert:
  Subject: CN=a.b.c, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=US
  Issuer: CN=a.b.c, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=US
  Algorithm: RSA; Serial number: 0x51a402ba
  Valid from Thu Apr 20 13:11:08 EDT 2017 until Wed Jul 19 13:11:08 EDT 2017

However, I also receive a large number (100+) of unavailable cipher messages, which seems excessive:
....
Ignoring unavailable cipher suite: TLS_ECDH_RSA_WITH_AES_256_CBC_SHA
Ignoring unavailable cipher suite: TLS_ECDH_anon_WITH_AES_128_CBC_SHA
Ignoring unavailable cipher suite: TLS_ECDH_ECDSA_WITH_RC4_128_SHA
Ignoring unavailable cipher suite: TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA
Ignoring unavailable cipher suite: TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384
Ignoring unavailable cipher suite: TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA
Ignoring unavailable cipher suite: TLS_ECDH_ECDSA_WITH_NULL_SHA
Ignoring unavailable cipher suite: TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256
Ignoring unavailable cipher suite: TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA
Ignoring unavailable cipher suite: TLS_ECDH_RSA_WITH_RC4_128_SHA
Ignoring unavailable cipher suite: TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA
Ignoring unavailable cipher suite: TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384
Ignoring unavailable cipher suite: TLS_ECDHE_RSA_WITH_RC4_128_SHA
Ignoring unavailable cipher suite: TLS_DHE_RSA_WITH_AES_256_CBC_SHA256
Ignoring unavailable cipher suite: TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA
Ignoring unavailable cipher suite: TLS_DHE_DSS_WITH_AES_256_CBC_SHA256
Ignoring unavailable cipher suite: TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256
...

I have tried two different ways to connect the server.  The primary has been via Mozilla Thunderbird as a baseline email client.  It indicates that it cannot connect to the server with no helpful additional information.  However, over in the server console output (with Java SSL debug output enabled), I see:
Allow unsafe renegotiation: true
Allow legacy hello messages: true
Is initial handshake: true
Is secure renegotiation: false
default Worker #2, setSoTimeout(300000) called
Ignoring unsupported cipher suite: TLS_RSA_WITH_AES_128_CBC_SHA256 for TLSv1
Ignoring unsupported cipher suite: TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 for TLSv1
Ignoring unsupported cipher suite: TLS_DHE_DSS_WITH_AES_128_CBC_SHA256 for TLSv1
Ignoring unsupported cipher suite: TLS_RSA_WITH_AES_128_CBC_SHA256 for TLSv1.1
Ignoring unsupported cipher suite: TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 for TLSv1.1
Ignoring unsupported cipher suite: TLS_DHE_DSS_WITH_AES_128_CBC_SHA256 for TLSv1.1
default Worker #6, READ: TLSv1 Handshake, length = 181
*** ClientHello, TLSv1.2
RandomCookie:  GMT: ... bytes = { ... }
Session ID:  {}
Cipher Suites: [TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, Unknown 0xcc:0xa9, Unknown 0xcc:0xa8, TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_RSA_WITH_AES_256_CBC_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_RSA_WITH_AES_256_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA]
Compression Methods:  { 0 }
Extension server_name, server_name: [type=host_name (0), value=a.b.c]
Unsupported extension type_23, data:
Extension renegotiation_info, renegotiated_connection: <empty>
Extension elliptic_curves, curve names: {unknown curve 29, secp256r1, secp384r1, secp521r1}
Extension ec_point_formats, formats: [uncompressed]
Unsupported extension type_35, data:
Unsupported extension status_request, data: 01:00:00:00:00
Unsupported extension type_18, data:
Unsupported extension type_65283, data:
Extension signature_algorithms, signature_algorithms: SHA256withECDSA, SHA384withECDSA, SHA512withECDSA, Unknown (hash:0x8, signature:0x4), Unknown (hash:0x8, signature:0x5), Unknown (hash:0x8, signature:0x6), SHA256withRSA, SHA384withRSA, SHA512withRSA, SHA1withECDSA, SHA1withRSA
***
%% Initialized:  [Session-2, SSL_NULL_WITH_NULL_NULL]
default Worker #6, handling exception: java.lang.RuntimeException: Could not generate DH keypair
%% Invalidated:  [Session-2, SSL_NULL_WITH_NULL_NULL]

And in the POP3 log, an impressive stack trace:
20/04/17 14:41:27 ERROR pop3server: Exception during connection from x.x.x.x (x.x.x.x) : Connection has been shutdown: javax.net.ssl.SSLException: java.lang.RuntimeException: Could not generate DH keypair
javax.net.ssl.SSLException: Connection has been shutdown: javax.net.ssl.SSLException: java.lang.RuntimeException: Could not generate DH keypair
        at sun.security.ssl.SSLSocketImpl.checkEOF(SSLSocketImpl.java:1541)
        at sun.security.ssl.AppInputStream.read(AppInputStream.java:95)
        at java.io.BufferedInputStream.fill(BufferedInputStream.java:246)
        at java.io.BufferedInputStream.read(BufferedInputStream.java:265)
        at org.apache.james.util.CRLFTerminatedReader.read(CRLFTerminatedReader.java:153)
        at org.apache.james.util.CRLFTerminatedReader.readLine(CRLFTerminatedReader.java:113)
        at org.apache.james.pop3server.POP3Handler.readCommandLine(POP3Handler.java:424)
        at org.apache.james.pop3server.POP3Handler.handleConnection(POP3Handler.java:277)
        at org.apache.james.util.connection.ServerConnection$ClientConnectionRunner.run(ServerConnection.java:432)
        at org.apache.excalibur.thread.impl.ExecutableRunnable.execute(ExecutableRunnable.java:55)
        at org.apache.excalibur.thread.impl.WorkerThread.run(WorkerThread.java:116)
Caused by: javax.net.ssl.SSLException: java.lang.RuntimeException: Could not generate DH keypair
        at sun.security.ssl.Alerts.getSSLException(Alerts.java:208)
        at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1949)
        at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1906)
        at sun.security.ssl.SSLSocketImpl.handleException(SSLSocketImpl.java:1889)
        at sun.security.ssl.SSLSocketImpl.handleException(SSLSocketImpl.java:1815)
        at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:128)
        at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:82)
        at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:140)
        at sun.nio.cs.StreamEncoder.implFlush(StreamEncoder.java:297)
        at sun.nio.cs.StreamEncoder.flush(StreamEncoder.java:141)
        at java.io.OutputStreamWriter.flush(OutputStreamWriter.java:229)
        at java.io.BufferedWriter.flush(BufferedWriter.java:254)
        at java.io.PrintWriter.flush(PrintWriter.java:320)
        at org.apache.james.util.InternetPrintWriter.println(InternetPrintWriter.java:92)
        at org.apache.james.util.InternetPrintWriter.println(InternetPrintWriter.java:189)
        at org.apache.james.pop3server.POP3Handler.handleConnection(POP3Handler.java:274)
        ... 3 more
Caused by: java.lang.RuntimeException: Could not generate DH keypair
        at sun.security.ssl.DHCrypt.<init>(DHCrypt.java:142)
        at sun.security.ssl.DHCrypt.<init>(DHCrypt.java:103)
        at sun.security.ssl.ServerHandshaker.setupEphemeralDHKeys(ServerHandshaker.java:1416)
        at sun.security.ssl.ServerHandshaker.trySetCipherSuite(ServerHandshaker.java:1206)
        at sun.security.ssl.ServerHandshaker.chooseCipherSuite(ServerHandshaker.java:1026)
        at sun.security.ssl.ServerHandshaker.clientHello(ServerHandshaker.java:741)
        at sun.security.ssl.ServerHandshaker.processMessage(ServerHandshaker.java:224)
        at sun.security.ssl.Handshaker.processLoop(Handshaker.java:1026)
        at sun.security.ssl.Handshaker.process_record(Handshaker.java:961)
        at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1062)
        at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1375)
        at sun.security.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:747)
        at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:123)
        ... 13 more
Caused by: java.security.NoSuchAlgorithmException: DiffieHellman KeyPairGenerator not available
        at java.security.KeyPairGenerator.getInstance(KeyPairGenerator.java:218)
        at sun.security.ssl.JsseJce.getKeyPairGenerator(JsseJce.java:260)
        at sun.security.ssl.DHCrypt.<init>(DHCrypt.java:126)
        ... 25 more

The second test I did was to just try to verify the TLS layer via an openssl (OpenSSL 1.0.1e-fips 11 Feb 2013) client call:
[user@host ~]$ openssl s_client -msg -connect a.b.c:995 -msg -debug
CONNECTED(00000003)
write to ...
0000 - ...
0010 - ...
0020 - ...
0030 - ...
0040 - ...
0050 - ...
0060 - ...
0070 - ...
0080 - ...
0090 - ...
00a0 - ...
00b0 - ...
00c0 - ...
00d0 - ...
00e0 - ...
00f0 - ...
>>> TLS 1.2 Handshake [length 00f2], ClientHello
    ...
read from ...
0000 - ...
<<< TLS 1.2 Alert [length 0002], fatal internal_error
    02 50
140124392265544:error:14077438:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1 alert internal error:s23_clnt.c:744:
---
no peer certificate available
---
No client certificate CA names sent
---
SSL handshake has read 7 bytes and written 247 bytes
---
New, (NONE), Cipher is (NONE)
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
---

The same errors/stack traces occur at the James end here.
Googling the Exception chain within James' POP3 log produces suggestions that the JVM may not be able to handle the proper key size, BUT they are all much older and refer to problems in the Java5/6 timeframe, indicating that 6+ has that problem fixed.  The fact that the base Exception claims that DH exchange is not available seemed significant, but other sources I found online indicated that that is actually a catch-all handshake failure Exception, and that singling out that cause might be unproductive.
Surely this is something simple that I've overlooked or fat fingered?

A: I still have no answer to the question but I have solved the problem:  I set up James to accept only local, insecure connections, and then used stunnel to set up an external-facing TLS proxy.  Email is now flowing, securely!


text:
Q: Javafx Table stops responding to binding updates I have the following callback for a column in a JavaFx TableView
public class CuePreWaitCallback implements Callback<TableColumn.CellDataFeatures<cObj,String>, ObservableValue<String>> {

    @Override
    public ObservableValue<String> call(final CellDataFeatures<cObj, String> param) {
        final Timeline preWait = param.getValue().getCTimeline().getPreWait();
        return new StringBinding() {
            {
                super.bind(param.getValue().getCTimeline().getPreWait().playhead());
                super.bind(param.getValue().getCTimeline().getPreWait().waitTime());
            }

            @Override
            protected String computeValue() {
                System.out.println("Value Called---------------------------------------------->");
                return preWait.getAbsoluteDuration().subtract(preWait.getPlayhead()).toString();
            }
        };
    }

}

Notice the giant print statement in the middle. All of the sudden, the GUI stops updating when the values change. Note that the values change very rapidly (if that matters). About every 3-5 milliseconds (It's displaying a time).
About the Timeline class: The getAbsoluteDuration() method returns a TimeElapsed object, which subtracts the preWait.getPlayhead() TimeElapsed object to create a new TimeElapsed object of their difference. The TimeElapsed toString() method is then called.


text:
Q: Remove index.php and subdirectory in url string Joomla I am trying to remove the subdirectory name and the index.php from a website running Joomla.
I have the following setup:
../public_html/.htaccess
../public_html/subdir/htaccess.txt
I have looked through several articles such as this one that have helped me a little but I can't quite get there. I have also studied a little about the .htaccess file from articles such as this one and this one to help me with this.
The setup that works but displays the subdirectory and index.php looks like this:
cat /../public_html/.htaccess
 RewriteEngine on
    RewriteCond %{HTTP_HOST} ^(www\.)?domain\.co\.uk$
    RewriteCond %{REQUEST_URI} !^/subdir/
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ /subdir/$1
    RewriteCond %{HTTP_HOST} ^(www\.)?domainn\.co\.uk$
    RewriteRule ^(/)?$ subdir/index.php [L]

    # Use PHP5.4 as default
    AddHandler application/x-httpd-php54 .php

cat /../public_html/subdir/htaccess.txt    (Joomla default)
##
# @package    Joomla
# @copyright  Copyright (C) 2005 - 2015 Open Source Matters. All rights reserved.
# @license    GNU General Public License version 2 or later; see LICENSE.txt
##

##
# READ THIS COMPLETELY IF YOU CHOOSE TO USE THIS FILE!
#
# The line just below this section: 'Options +FollowSymLinks' may cause problems
# with some server configurations.  It is required for use of mod_rewrite, but may already
# be set by your server administrator in a way that disallows changing it in
# your .htaccess file.  If using it causes your server to error out, comment it out (add # to
# beginning of line), reload your site in your browser and test your sef url's.  If they work,
# it has been set by your server administrator and you do not need it set here.
##

## No directory listings
IndexIgnore *

## Can be commented out if causes errors, see notes above.
Options +FollowSymlinks
Options -Indexes

## Mod_rewrite in use.

RewriteEngine On

## Begin - Rewrite rules to block out some common exploits.
# If you experience problems on your site block out the operations listed below
# This attempts to block the most common type of exploit `attempts` to Joomla!
#
# Block out any script trying to base64_encode data within the URL.
RewriteCond %{QUERY_STRING} base64_encode[^(]*\([^)]*\) [OR]
# Block out any script that includes a <script> tag in URL.
RewriteCond %{QUERY_STRING} (<|%3C)([^s]*s)+cript.*(>|%3E) [NC,OR]
# Block out any script trying to set a PHP GLOBALS variable via URL.
RewriteCond %{QUERY_STRING} GLOBALS(=|\[|\%[0-9A-Z]{0,2}) [OR]
# Block out any script trying to modify a _REQUEST variable via URL.
RewriteCond %{QUERY_STRING} _REQUEST(=|\[|\%[0-9A-Z]{0,2})
# Return 403 Forbidden header and show the content of the root homepage
RewriteRule .* index.php [F]
#
## End - Rewrite rules to block out some common exploits.

## Begin - Custom redirects
#
# If you need to redirect some pages, or set a canonical non-www to
# www redirect (or vice versa), place that code here. Ensure those
# redirects use the correct RewriteRule syntax and the [R=301,L] flags.
#
## End - Custom redirects

##
# Uncomment following line if your webserver's URL
# is not directly related to physical file paths.
# Update Your Joomla! Directory (just / for root).
##

# RewriteBase /

## Begin - Joomla! core SEF Section.
#
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
#
# If the requested path and file is not /index.php and the request
# has not already been internally rewritten to the index.php script
RewriteCond %{REQUEST_URI} !^/index\.php
# and the requested path and file doesn't directly match a physical file
RewriteCond %{REQUEST_FILENAME} !-f
# and the requested path and file doesn't directly match a physical folder
RewriteCond %{REQUEST_FILENAME} !-d
# internally rewrite the request to the index.php script
RewriteRule .* index.php [L]
#
## End - Joomla! core SEF Section.

I have tried to follow the suggestions of the article mentioned above and got the files to look like this:
cat /../public_html/.htaccess.try
RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www\.)?domain\.co\.uk$ [NC]
RewriteRule ^(.*)$ http://domain/$1 [R=301,L]
RewriteCond %{HTTP_HOST} ^(www\.)?domain\.co\.uk$
RewriteRule ^(.*)$ /subdir/$1 [PT,L,QSA]
#RewriteRule ^(/)?$ subdir/index.php [L]

# Use PHP5.4 as default
AddHandler application/x-httpd-php54 .php

cat /../public_html/subdir/htaccess.txt.try
.
.
.
# RewriteBase /
## Begin - Joomla! core SEF Section.
#
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
#
# If the requested path and file is not /index.php and the request
# has not already been internally rewritten to the index.php script
RewriteCond %{REQUEST_URI} !^/index\.php
# and the requested path and file doesn't directly match a physical file
RewriteCond %{REQUEST_FILENAME} !-f
# and the requested path and file doesn't directly match a physical folder
RewriteCond %{REQUEST_FILENAME} !-d
# internally rewrite the request to the index.php script
RewriteRule ^(.*)$ /$1 [L]

RewriteRule ^subdir/index.php?(.*)$ /$1 [L]
#
## End - Joomla! core SEF Section.

With the two .try files saved instead of the originals, I am getting a redirection loop, as printed out by the browser:
This webpage has a redirect loop

ERR_TOO_MANY_REDIRECTS

I have also tried modifying the files myself but most of them lead to "internal server error" probably meaning the syntax written is not correct, or they overrule each other?
Any idea how the two files should look like?

A: regarding public_html/subdir/htaccess.txt
# RewriteBase /

*

*this should be uncommented and edited to match your current subfolder, like this:

RewriteBase /subdir/

*

*public_html/subdir/htaccess.txt must be renamed to public_html/subdir/.htaccess in order for it to be processed by apache;

*finally, enable SEF in your admin panel global settings


text:
Q: Server Error in Application My SharePoint 2013 site stopped working today and cannot find the source of the issue. I wonder if anybody has the expertise to work out what the error below means or how I can go about trouble-shooting the issue.
The windows server was installing updates at the time but this may just be a coincidence and can not find any updates that may have caused a problem. Tried restarting services/iis/application pools but no luck. Central admin also does not load
Thanks

Server Error in '/' Application
Derived method 'RequiresWebPartClientScript' in type
  'Microsoft.SharePoint.Taxonomy.TermProperty' from assembly
  'Microsoft.SharePoint.Taxonomy, Version=15.0.0.0, Culture=neutral,
  PublicKeyToken=71e9bce111e9429c' cannot reduce access
[TypeLoadException: Derived method 'RequiresWebPartClientScript' in
  type 'Microsoft.SharePoint.Taxonomy.TermProperty' from assembly
  'Microsoft.SharePoint.Taxonomy, Version=15.0.0.0, Culture=neutral,
  PublicKeyToken=71e9bce111e9429c' cannot reduce access.]
  Microsoft.SharePoint.Publishing.Navigation.TaxonomyNavigationContext.EnsureCallbackInitialized()
  +0
[TargetInvocationException: Exception has been thrown by the target of
  an invocation.]    System.RuntimeTypeHandle.CreateInstance(RuntimeType
  type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached,
  RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
  System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean
  skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +159
  System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly,
  Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
  +256    System.Activator.CreateInstance(Type type, Boolean nonPublic) +127    System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture,
  Object[] activationAttributes, StackCrawlMark& stackMark) +14297981
  System.Activator.CreateInstance(Type type, BindingFlags bindingAttr,
  Binder binder, Object[] args, CultureInfo culture, Object[]
  activationAttributes) +198    System.Activator.CreateInstance(Type
  type, BindingFlags bindingAttr, Binder binder, Object[] args,
  CultureInfo culture) +28
  System.Web.HttpRuntime.CreateNonPublicInstance(Type type, Object[]
  args) +66
  System.Web.HttpApplication.BuildIntegratedModuleCollection(List`1
  moduleList) +309
  System.Web.HttpApplication.GetModuleCollection(IntPtr appContext)
  +1227    System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr
  appContext, HttpContext context, MethodInfo[] handlers) +139
  System.Web.HttpApplication.InitSpecial(HttpApplicationState state,
  MethodInfo[] handlers, IntPtr appContext, HttpContext context) +322
  System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr
  appContext, HttpContext context) +384
  System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr
  appContext) +397
[HttpException (0x80004005): Exception has been thrown by the target
  of an invocation.]
  System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +646
  System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context)
  +159    System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest
  wr, HttpContext context) +779

A: Run the Configuration Wizard.
This should be the last step after updates have been installed.
(This should be done after hours as this does require IIS resets)
Install a software update (SharePoint 2013)
Should also help get you back into Central Admin

A: Go to the "/_admin/FarmServer.aspx" page from the central administration and if we have multi severs farm – check the upgrade status for each server in the farm like the below screen:

Notes:

*

*In this page for all servers in the farm should be upgrade is not required.

*If the upgrade is required, please upgrade them one by one.

*If it showed upgrade blocked, we must upgrade all servers in the farm, otherwise, none of the sites will gent opened.

*Before running the Wizard, make sure to take all necessary backups.

For more details - please refer the below article:
SharePoint Server Error:


text:
Q: Scheme: Loop Function in Racket Write a recursive function that, given a positive integer k, computes the product (1-1/2)(1-1/3)...(1-1/k).
I have tried to make a loop, but don't know where to start.
Any ideas?

A: Sure! This example fits the pattern of section 9.3 (Natural Numbers) from How To Design Programs, v2e. You should find a lot of helpful guidance there.


text:
Q: HP UX max stack size limit What is the max stack size limit of 32 bit process in HP-UX B.11.31 or what is the max stack size that can be alloacted to a 32 bit process in HP -UX

A: MAX STACK SIZE LIMIT
Default
      32 bit: 0x800000 (8MB)
  64 bit: 0x10000000 (256MB)

Allowed values
  32 bit minimum: 0x40000

  32 bit maximum: 0x17F00000

  64 bit minimum: 0x40000

  64 bit maximum: 0x80000000


text:
Q: How do I write chinese charactes in ZipEntry? I want to export a string(chinese text) to CSV file inside a zip file. Where do I need to set the encoding to UTF-8? Or what approach should I take (based on the code below) to display chinese characters in the exported CSV file?
This is the code I currently have.
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ZipOutputStream zipOut = new ZipOutputStream(out, StandardCharsets.UTF_8)
        try {
            ZipEntry entry = new ZipEntry("chinese.csv");
            zipOut.putNextEntry(entry);
            zipOut.write("类型".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            zipOut.close();
            out.close();
        }

Instead of "类型", I get "类型" in the CSV file.

A: The getBytes() method is one culprit, without an explicit charset it takes the default character set of your machine. As of the Java String documentation:

getBytes()
  Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.
getBytes(string charsetName)
  Encodes this String into a sequence of bytes using the given charset, storing the result into a new byte array.

Furthermore, as @Slaw pointed out, make sure that you compile (javac -encoding <encoding>) your files with the same encoding the files are in:

-encoding Set the source file encoding name, such as EUC-JP and UTF-8. If -encoding is not specified, the platform default converter is used.

A call to closeEntry() was missing in the OP btw. I stripped the snippet down to what I found necessary to achieve the desired funcitonality.
    try (FileOutputStream fileOut = new FileOutputStream("out.zip");
         ZipOutputStream zipOut = new ZipOutputStream(fileOut)) {
        zipOut.putNextEntry(new ZipEntry("chinese.csv"));
        zipOut.write("类型".getBytes("UTF-8"));
        zipOut.closeEntry();
    }

Finally, as @MichaelGantman pointed out, you might want to check what is in which encoding using a tool like a hex-editor for example, also to rule out that the editor you view the result file in displays correct utf-8 in a wrong way. "类" in utf-8 is (hex) e7 b1 bb in utf-16 (the java default encoding) it is 7c 7b

A: First, you definitely need to change zipOut.write("类型".getBytes()); to zipOut.write("类型".getBytes(StandardCharsets.UTF_8)); Also, when you open your resultant CSV file, the editor might not be aware that the content is encoded in UTF-8. You may need to tell your editor that it is UTF-8 encoding. For instance, in Notepad, you can save your file with "Save As" option and change encoding to UTF-8. Also, your issue might be just wrong display issue rather than actual encoding. There is an Open Source Java library that has a utility that converts any String to Unicode Sequence and vice-versa. This utility helped me many times when I was working on diagnosing various charset related issues. Here is the sample what the code does
result = "Hello World";
result = StringUnicodeEncoderDecoder.encodeStringToUnicodeSequence(result);
System.out.println(result);
result = StringUnicodeEncoderDecoder.decodeUnicodeSequenceToString(result);
System.out.println(result);

The output of this code is:
\u0048\u0065\u006c\u006c\u006f\u0020\u0057\u006f\u0072\u006c\u0064
Hello World

The library can be found at Maven Central or at Github It comes as maven artifact and with sources and javadoc
Here is javadoc for the class StringUnicodeEncoderDecoder
I tried your inputs and got this:
System.out.println(StringUnicodeEncoderDecoder.encodeStringToUnicodeSequence("类型"));
System.out.println(StringUnicodeEncoderDecoder.encodeStringToUnicodeSequence("类型"));

And the output was:
\u7c7b\u578b
\u00e7\u00b1\u00bb\u00e5\u017e\u2039

So it looks like you did lose the info, and it is not just a display issue


text:
Q: rmarkdown - embed sparkline into a bootstrap popover I'm trying to display a sparkline in a popover. I'm using rmarkdown to create my html document.
Here is my attempt:
---
title: "test_embed_popup"
author: "me"
date: "16 June 2017"
output: html_document
---

```{r}
library(sparkline)
library(htmltools)
library(bsplus)

bsplus::use_bs_popover()

button_content <-
  spk_chr(c(1:5))

tags$button(type = "button", class = "btn btn-default", "A button") %>%
  bs_embed_popover(title = "I'm a popover", content = button_content, html = "true") %>%
  sparkline::spk_add_deps()
```

when i knit this document, the button with the popover appears however no sparkline is in the popover. I would like to display the sparkline in the popover.
Any help much appreciated.

A: I have fiddled with this a bit - I think that the underlying problem is that the JavaScript is not being executed. This is discussed here:
Execute JS inside of a Bootstrap popover
I think the proposed solution is probably out of scope (at least for now) for bsplus - but I've made an issue to remind myself.


text:
Q: Is there a way to know that a pathos/multiprocessing worker is finished? I'd like to know when workers finish so that I can free up resources as the last action any worker. Alternatively I can also free up these resources on the main process, but I need to free these up after each worker one by one (in contrast to freeing them up once after all of the workers finish).
I'm running my workers as below, tracking progress and PIDs used:
from pathos.multiprocessing import ProcessingPool
pool = ProcessingPool(num_workers)
pool.restart(force=True)
# Loading PIDs of workers with my get_pid() function:
pids = pool.map(get_pid, xrange(num_workers))
try:
    results = pool.amap(
        exec_func,
        exec_args,
    )
    counter = 0
    while not results.ready():
        sleep(2)
        if counter % 60 == 0:
            log.info('Waiting for children running in pool.amap() with PIDs: {}'.format(pids))
        counter += 1
    results = results.get()
    # Attempting to close pool...
    pool.close()
    # The purpose of join() is to ensure that a child process has completed
    # before the main process does anything.
    # Attempting to join pool...
    pool.join()
except:
    # Try to terminate the pool in case some worker PIDs still run:
    cls.hard_kill_pool(pids, pool)
    raise

Because of load balancing, it is hard to know which job will be the last on a worker. Is there any way to know that some workers are already inactive?
I'm using pathos version 0.2.0.

A: I'm the pathos author.  If you need to free up resources after each worker in a Pool is is done running, I'd suggest you not use a Pool.  A Pool is meant to allocate resources, and keep using them until all jobs are done.  What I'd suggest is to use a for loop that spawns a Process and then ensures that the spawned Process is joined when you are done with it.  If you need to do this within pathos, the Process class is at the horribly named: pathos.helpers.mp.Process (or much more directly at multiprocess.Process from the multiprocess package).


text:
Q: Sphere-plane collision resolve I want to write a c++ program that will calculate collision between sphere and plane.
The rule is that the angle of the falling object equals to angle of reflection.
What do I have for sphere:
//sphere coordinates and radius
float x;
float y;
float z;
float r;
//sphere velocity vector projections
float vx;
float vy;
float vz;

Plane is described by plane equation coefficients:
float A;
float B;
float C;
float D;

With sphere-plane collision detection I have no problem. But how to find velocity after collision?

What did I find:

So, ultimately I need to calculate updated values for vx vy vz.

A: @Beta's answer on c++:
float wl = sqrt(plane->A*plane->A+plane->B*plane->B+plane->C+plane->C); // "W" vector length

float nx = plane->A/wl; //Normal components
float ny = plane->B/wl;
float nz = plane->C/wl;

float scope = (sphere->vx*nx + sphere->vy*ny + sphere->vz*nz)*2; // 2(V . n)

nx = nx*scope; // 2(V . n)n
ny = ny*scope;
nz = nz*scope;

sphere->vx -= nx; // V' = V - 2(V . n)n
sphere->vy -= ny;
sphere->vz -= nz;

A: The equation defining the plane is
Ax + By + Cz + D = 0

So the vector normal to the plane is
W = (A, B, C)

Normalize it:
n = W/|W|

Now take the velocity vector:
V = (vx, vy, vz)

Its component normal to the plane is
Vn = (V . n) n

and the rest of it, the part parallel to the plane is
Vp = V - Vn

We want to reverse the normal component and leave the parallel component unchanged:
V' = -Vn + Vp

which works out to
V' = V - 2(V . n)n


text:
Q: Merging Personal Geodatabase (MDB) data into ArcSDE using FME? Im a novice in FME and I have a MDB file that i want to write/insert to an SDE database using FME. I created a simple translation that generally reads the data from the MDB file and writes it to the SDE database, although the translation is successful and it prints out the number of written rows, when i checked the SDE database, it wasn't able to right any data on it.
i then checked the log and i found this specific warning:

MS SQL Server (Spatial) Writer: Attribute data ' too large to fit in
  specified data type for columnSHAPE'

The shape column holds the geometry data in the MDB file. FME sets the SHAPE datatype to 'oleobject' in the Reader and I noticed that the SHAPE column in the writer was automatically converted to 'text' datatype.
Is there anything else i need to configure to make this work?
UPDATE: I am using FME Database Edition 2014 (20140120 - Build 14235 - WIN64)
Here are some screenshots of my FME translation:

A: FME's MDB Reader is only a reader for pure tabular data (without geometry). It interpretes the shape column as some kind of binary data, but doesn't know that it contains geometry actually. Therefore the content then neither doesn't fit into the datatype FME initially uses for that  nor does it know how to store any geometry into the SDE layer (again, because it haven't read any geometry).
If the MDB File is a ESRI personal Geodatabase use the ESRI Geodatabase reader instead.
Use the format Identifier GEODATABASE_MDB to define, that it is a Geodatabase stored in a mdb file, as there is also the option to store it in a RDBMS (enterprise geodatabase based on SDE) or in a directory (File Geodatabase).
If you use it correctly, you will see, that FME never ever presents the column containing the geometry as a mappable field (as "shape" with the MDB reader) because it only presents attribute fields. Geometries are handled in the background.
When you have defined your SDE writer, you can right click your Geodatabase reader feature type and select "duplicate on writer" to define a 1:1 copy of your feature type schema in SDE.
In the writer feature types properties you can select how the feature class should be updated, i.e.:

*

*Should it drop and recreate the feature class with every run of the workbench

*Should it only truncate the table and append the features then

*Should it only append

With "Bulk insert" set to Yes (see screenshot) you can speed up writing up from 6 to 10 times.There aren't any situations where this could really cause a problem, except when you want to update small sets of data and can't proof the validity before appending them to your destination table.
Screenshot via @Mapperz using FME 2014 (SP1 build 14287)


text:
Q: A good sorting algorithm for mostly-sorted data that doesn't all fit into memory? In case you are given:

*

*certain amount of data

*memory with size half of the data size

*part of the data is sorted

*you do not know the size of the sorted data.

Which sorting algorithm would you choose?
I am debating between insertion and quicksort. I know that the best case for insertion sort is O(n), but the worst case is O(n2). Also, considering the fact the memory is limited, I would divide the data in two parts, and on each of them do quicksort, then merge everything together. It will take O(n) time to split the data, O(n) to merge the data, and O(n log n) to sort the data using quicksort, for a net runtime of O(n log n).
Does anyone have any suggestions on how to improve this?

A: Your mergesort-like approach seems very reasonable.  More generally, this type of sorting algorithm is called an external sorting algorithm.  These algorithms often work as you've described - load some subset of the data into memory, sort it, then write it back out to disk.  At the end, use a merging algorithm to merge everything back together.  The choice of how much to load in and what sorting algorithm to use are usually the dominant concerns.  I'll focus mostly on the sorting algorithm choice.
Your concerns about quicksort's worst-case behavior are generally speaking nothing to worry about, since if you choose the pivot randomly the probability that you get a really bad runtime is low.  The random pivot strategy also works well even if the data is already sorted, as it has no worst-case inputs (unless someone knows your random number generator and the seed).  You could also use a quicksort variant like introsort, which doesn't have the worst-case behavior, as your sorting algorithm in order to avoid this worst-case.
That said, since you know that the data is already partially sorted, you may want to look into an adaptive sorting algorithm for your sorting step.  You've mentioned insertion sort for this, but there are much better adaptive algorithms out there.  If memory is scarce (as you've described), you might want to try looking into the smoothsort algorithm, which has best-case runtime O(n), worst-case runtime O(n log n), and uses only O(1) memory.   It's not as adaptive as some other algorithms (like Python's timsort, natural mergesort, or  Cartesian tree sort), but it has lower memory usage.  It's also not as fast as a good quicksort, but if the data really is mostly sorted it can do pretty well.
Hope this helps!

A: On the face of it, I would divide & conquer with quicksort and call it a day. Many algorithms problems are over-thought.
Now, if you do have have test data to work with and really want a grasp on that, stick an abstract class in the middle and benchmark. We can hem and haw over things all day, but knowing that the data is already partially sorted, you'll have to test. Sorted data brings about worst-case performance in most quicksort implementations.
Consider that there are many sorting algorithms and some are suited better to sorted sets. Also, when you know a set is sorted, you can merge it with another set in n time. Thus, identifying chunks of sorted data first might save you a lot of time when you compare adding a single (n) pass and greatly reducing the chance of quicksort going to (n2) time.


text:
Q: Lost connection to MySQL server during query - Python, MySql I am trying to send INSERT statements to mysql from Python using pymysql. Based on some conditions if I find a particular file, I insert it's contents to it's corresponding table in database. Currently I have two tables CACCT and PAUTH. I have separate functions for table specific INSERTs. The functions are:
 1. load_json_sql_CACCT()
 2. load_json_sql_PAUTH()

My main function is recon().
mysql_conn_dev = mysql.connect(host="xxxx",
                     user="xxx",
                     db="xxx")

cur = mysql_conn_dev.cursor(mysql.cursors.DictCursor)

tables = ["CACCT", "PAUTH"]

def recon():
    global unzipped_flg
    unzipped_flg = ''
    for item in tables:
        name_pattern = item + '_' + recon_date + '.*'
        for subdir, dirs, files in os.walk(src):
            for file in files:
                filepath = subdir + os.sep + file
                if fnmatch.fnmatch(file, name_pattern) and os.stat(filepath).st_size != 0:
                    if not result_match.empty:

                        if item == 'PAUTH':
                            load_json_sql_PAUTH(item, src + item + '_MISSING_RECORDS_' + recon_date + '.json')
                        elif item == 'CACCT':
                            load_json_sql_CACCT(item, src + item + '_MISSING_RECORDS_' + recon_date + '.json')
                    else:
                        print('No mismatch for ' + item)

def load_json_sql_CACCT(item, json_file):
    missing_record_list = []
    with open(json_file) as f:
        for json_obj in f:
            data_dict = json.loads(json_obj)
            missing_record_list.append(data_dict)
    print(json_file)
    for record in missing_record_list:
        print(record)

        if item == 'CACCT':
            with mysql_conn_dev.cursor() as cursor:
                cur.execute(
                r"INSERT INTO sayyed_sandpit.CACCT_UNI (instanceNumber,classNumber,parentClassNumber,subLevel,subId,edition,oid,u_acct_no,u_astatus,u_cust_no,u_myGlobal,u_preferred,u_status) "
                r"VALUES ("
                r"CAST(substring_index(substring_index(%s, '.', 2), '.', -1) as unsigned integer)"
                r",substring_index(%s, '.', 1)"
                r",0"
                r",0"
                r",0"
                r",%s"
                r",CONCAT(%s, '.0.0.0')"
                r",%s"
                r",%s"
                r",%s"
                r",CASE WHEN %s is not null then CONCAT(TRIM(LEADING '[' FROM TRIM(TRAILING ']' FROM %s)), '.0.0.0') end"
                r",%s"
                r",%s)",
                (record["OID"], record["OID"], record["edition"], record["OID"], record["acct_no"],
                 record["astatus"], record["cust_no"], record["myGlobal"], record["myGlobal"], record["preferred"], record["status"]))
            mysql_conn_dev.commit()
            print("CACCT inserted")

def load_json_sql_PAUTH(item, json_file):
    missing_record_list = []
    with open(json_file) as f:
        for json_obj in f:
            data_dict = json.loads(json_obj)
            missing_record_list.append(data_dict)

    for record in missing_record_list:
        print(record)
        with mysql_conn_dev.cursor() as cursor:
            cursor.execute(
                r"INSERT INTO sayyed_sandpit.PAUTH_UNI (instanceNumber, classNumber, parentClassNumber, subLevel, subId, edition,...) "
                r"VALUES ()",
                (record["OID"], record["OID"], record["edition"], record["OID"],...))

        mysql_conn_dev.commit()

if __name__ == '__main__':
    recon()
    #load_json_sql_PAUTH()

    mysql_conn.close()

For some reason it has been failing only for:
load_json_sql_PAUTH()

If I execute load_json_sql_PAUTH() separately own it's own, it works perfectly but when I put it in the conditional logic in recon(), it fails by as loosing connection as soon as it hits the INSERT statement.
Below is the error message:
    load_json_sql_PAUTH(item, src + item + '_MISSING_RECORDS_' + recon_date + '.json')
  File "C:/Users/Shahsa/PycharmProjects/mymisc/recon_json.py", line 370, in load_json_sql_test
    cursor.execute(
  File "C:\Users\Shahsa\PycharmProjects\mymisc\venv\lib\site-packages\pymysql\cursors.py", line 170, in execute
    result = self._query(query)
  File "C:\Users\Shahsa\PycharmProjects\mymisc\venv\lib\site-packages\pymysql\cursors.py", line 328, in _query
    conn.query(q)
  File "C:\Users\Shahsa\PycharmProjects\mymisc\venv\lib\site-packages\pymysql\connections.py", line 517, in query
    self._affected_rows = self._read_query_result(unbuffered=unbuffered)
  File "C:\Users\Shahsa\PycharmProjects\mymisc\venv\lib\site-packages\pymysql\connections.py", line 732, in _read_query_result
    result.read()
  File "C:\Users\Shahsa\PycharmProjects\mymisc\venv\lib\site-packages\pymysql\connections.py", line 1075, in read
    first_packet = self.connection._read_packet()
  File "C:\Users\Shahsa\PycharmProjects\mymisc\venv\lib\site-packages\pymysql\connections.py", line 657, in _read_packet
    packet_header = self._read_bytes(4)
  File "C:\Users\Shahsa\PycharmProjects\mymisc\venv\lib\site-packages\pymysql\connections.py", line 706, in _read_bytes
    raise err.OperationalError(
pymysql.err.OperationalError: (2013, 'Lost connection to MySQL server during query')

A: I fixed the problem by creating separate connections in each of the functions.
Something similar is mentioned by @xvga in this question


text:
Q: SQL row number partitioned by a repeated value I am looking for a way to flag and reset a row number on rows that repeated before in the table, but only to have one row as the basis of comparison. In the example below, the first row (vertex ID 1) should be the base row for comparison until it finds a match based on the ObjID, Lat, Lon columns (vertex ID 4). Then the next row (vertex ID 5) is the basis for comparison until the next match (vertex ID 8).

ObjID
VertexID
Lat
Lon
Reader Notes

1
1
30.1
-100.1
Polygon 1 st.

1
2
30.2
-100.2

1
3
30.3
-100.2

1
4
30.1
-100.1
Polygon 1 end

1
5
30.4
-100.4
Polygon 2 st.

1
6
30.5
-100.4

1
7
30.5
-100.5

1
8
30.4
-100.4
Polygon 2 end

Ideally, I would have another column that counts 1...4 for the first polygon and 1...4 for the second as well. I already have the SQL to count off polygon numbers (e.g. four 1s and four 2s).
As you might infer from the example, I have a list of all the points in a multipolygon but without any indicator on when the vertices start and end for each of the multipolygon shapes start other than the fact that the first and last vertices must be the same.

A: You can do it with a recursion . For the sample data I assume VertexID is unique and it is a continues series of integers. Otherwise first row_number() data accordingly.
with poly as (
   select ObjID, VertexID, Lat, Lon, polyN=1, flag=0, sObjID=ObjID, sLat=Lat, sLon=Lon
   from tbl
   where VertexID =1

   union all

   select  t.ObjID, t.VertexID, t.Lat, t.Lon, polyN + flag,
      case when t.ObjID = p.sObjID and t.Lat = p.sLat and t.Lon = p.sLon then 1 else 0 end,
      case flag when 1 then t.ObjID else sObjID end,
      case flag when 1 then t.Lat else sLat end,
      case flag when 1 then t.Lon else sLon end

   from poly p
   join tbl t on t.VertexID = p.VertexID + 1
)
select ObjID, VertexID, Lat, Lon, polyN
from poly


text:
Q: printpreview not showing properly in vb.net I have a form clicking the print preview button showing as a preview of the form but it's displaying like screenshot.because it's showing background gray color background and textview boxes also displaying.
[In the below preview it's looks like a screenshot and don't want to show textboxes only want to show values]
Private Sub Button4_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
        PrintDialog1.Document = PrintDocument1
        PrintDialog1.PrinterSettings = PrintDocument1.PrinterSettings
        PrintDialog1.AllowSomePages = True
        If PrintDialog1.ShowDialog = DialogResult.OK Then
            PrintDocument1.PrinterSettings = PrintDialog1.PrinterSettings

            PrintDocument1.Print()
        End If
    End Sub

    Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
        PrintForm1.PrintAction = Printing.PrintAction.PrintToPreview

        Button4.Visible = False
        Button5.Visible = False
        Button1.Visible = False
        Button2.Visible = False
        PrintForm1.Print()

    End Sub


text:
Q: Exporting a textured image from Blender and using with React Three FIber (shaders?) I'm still pretty new to 3d with blender (and coding in 3d), but I'm trying to create and export a material using nodes (instead of a jpg image):

In React, I'm coding as follows:
export default function Ring({ ...props }: JSX.IntrinsicElements['group']) {
  const group = useRef<THREE.Group>(null)
  const { nodes, materials } = useGLTF('../assets/ring.glb', 'https://www.gstatic.com/draco/versioned/decoders/1.4.1/') as GLTFResult
  return (
    <group ref={group} {...props} dispose={null}>
      <mesh castShadow receiveShadow geometry={nodes.ring.geometry} material={materials['Material.001']} />
    </group>
  )
}

However, in the browser I am getting this result:

I'm trying to figure out if the issue is:

*

*a. There is nothing to reflect, and therefore no color (I added <Sky .. /> and <Environment .. /> tags hoping this would solve it.

*b. The code needs some extra code to pull in other parameters which are part of the object itself:

*

*c. I need to add extra shaders or something because of 'unknown unknowns' in the way I'm using things.

*d. I've exported it wrongly - which might be the case because I've tried importing here: https://3dviewer.net/ and it is still white. (I tried using 'apply modifiers' when exporting).

Either way, I need to figure out if this is an exporting issue, or a coding issue. If it is an issue with the way I'm using Blender, I'll close this question and re-ask it on https://blender.stackexchange.com.
Thanks for the help.


text:
Q: Time complexity of Tsp using DP this is the recursion formula for problem :
C(i,S) = min { d(i,j) + C(j,S-{j}) }
In fact, when I tried to implement it as a code, the following code came to my mind:
int TSP(i, S){
    if(S.size == 0)
    return dist(start_vertex,i)
min = inf
cost = inf
  for(int j=0;j<S.size;j++)
     {
      cost = dist(i,S[j])+TSP(j,S-{j});
      if(cost < min)
       min = cost;
      }
global_cost+=min;
return min;
}

Because this for compares n times to find the minimum, it means its recursion as:
T(n) = nT(n-1)+n ==> T(n) = O(n!)

Because each step we compare to find the minimum size of size S is, of course, the code is factorial. So what does it have to do with the subset and
So why the complexity of time in the form of (n^2*2^n)? And what is the proof of its time complexity?


text:
Q: Does Go sanitize URLs for web requests? I was implementing a simple web server in Go. As I have no experience in web development, this striked as a serious question for me.
Let's say I'm serving web pages with a modified loadPage function from here
func loadPage(title string) []byte {
    filename := title
    body, _ := ioutil.ReadFile(filename)
    return body
}

func handler(w http.ResponseWriter, req *http.Request) {
    content := loadPage(req.URL.Path[1:])
    fmt.Fprintf(w, "%s", content)
}

Technically this allows me to write a request in a form of
 http://example.com/../../etc/passwd

and the code would happily serve the /etc/passwd file, but it does not. Does this mean that there is some sort of protection against ../ in the Go http package or http protocol itself, or am I just doing something wrong and it is a security hole?

A: net/http does this in its HTTP request multiplexer, ServeMux:

ServeMux also takes care of sanitizing the URL request path, redirecting any request containing . or .. elements to an equivalent .- and ..-free URL.

The relevant function is the private func cleanPath(p string) string, which calls path.Clean:
1415        np := path.Clean(p)

path.Clean does the appropriate removals:
 97         case path[r] == '.' && path[r+1] == '.' && (r+2 == n || path[r+2] == '/'):
 98             // .. element: remove to last /
 99             r += 2
100             switch {
101             case out.w > dotdot:
102                 // can backtrack
103                 out.w--
104                 for out.w > dotdot && out.index(out.w) != '/' {
105                     out.w--
106                 }

There's an additional case if the path isn't rooted, but cleanPath above ensures it is so, by prepending a forward-slash to the path to be cleaned if there isn't one already.


text:
Q: Ajax call type POST showing undefined index error I have a table where I'm displaying files uploaded

A: You are need to pass object to data, not int/string. So the code will be
$.ajax({
  type: 'POST',
  data: {key: key}
  ...
})

A: You need to pass data .
 $.ajax({
    type: "POST",
    url: 'abc.php',
    data: {"key":"value"},
    success: function(data){
        alert(data.value1);
    }
 });


text:
Q: Deploying to Wildfly 8.2.0 I'm trying to deploy a GWT Errai application to Jboss Wildfly 8.2.0 Final, however, I am getting the following deployment error.
Caused by: java.lang.ClassNotFoundException: org.apache.catalina.core.ApplicationContextFacade from [Module "deployment.app.ui-1.8.2.war:main" from Service Module Loader]
    at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:213) [jboss-modules.jar:1.3.3.Final]
    at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:459) [jboss-modules.jar:1.3.3.Final]
    at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:408) [jboss-modules.jar:1.3.3.Final]
    at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:389) [jboss-modules.jar:1.3.3.Final]
    at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:134) [jboss-modules.jar:1.3.3.Final]
    ... 13 more

2015-03-25 13:05:39,466 ERROR [org.jboss.as.controller.management-operation] (management-handler-thread - 1) JBAS014613: Operation ("deploy") failed - address: ([("deployment" => "app.ui-1.8.2.war")]) - failure description: {"JBAS014671: Failed services" => {"jboss.undertow.deployment.default-server.default-host./" => "org.jboss.msc.service.StartException in service jboss.undertow.deployment.default-server.default-host./: Failed to start service
    Caused by: java.lang.NoClassDefFoundError: org/apache/catalina/core/ApplicationContextFacade
    Caused by: java.lang.ClassNotFoundException: org.apache.catalina.core.ApplicationContextFacade from [Module \"deployment.app.ui-1.8.2.war:main\" from Service Module Loader]"}}
2015-03-25 13:05:39,468 ERROR [org.jboss.as.server] (management-handler-thread - 1) JBAS015870: Deploy of deployment "app.ui-1.8.2.war" was rolled back with the following failure message:
{"JBAS014671: Failed services" => {"jboss.undertow.deployment.default-server.default-host./" => "org.jboss.msc.service.StartException in service jboss.undertow.deployment.default-server.default-host./: Failed to start service
    Caused by: java.lang.NoClassDefFoundError: org/apache/catalina/core/ApplicationContextFacade
    Caused by: java.lang.ClassNotFoundException: org.apache.catalina.core.ApplicationContextFacade from [Module \"deployment.app.ui-1.8.2.war:main\" from Service Module Loader]"}}

It appears as if Weld incorrectly detects the application server as Tomcat.
Any ideas as to what might be wrong?

A: You should not deploy Weld as part of your application. It is already part of the application server. You should exclude Weld artifacts from your dependencies, especially weld-servlet.

A: This is a late post but your project requires class org.apache.catalina.core.ApplicationContextFacade which the ClassLoader fails to find.
I am not too familiar with GWT so my knowledge on that domain is useless. Either you add a JAR containing the class mentioned above in your CLASSPATH or in your WEB-INF/lib folder or find a best way to deploy GWT application on Wildfly.


text:
Q: Upper-bound on second moment of martingale I have a sequence of independent random variables $(X_n,n\geq 1)$ such that $X_n\sim \mathcal{E}(n)$. More precisely, $P(\{X_n\leq t\}) = 1-e^{-nt}$. From this I build the following process $(S_n,n\geq 1)$ where $S_0=0, S_n=X_1+\ldots+X_n$.
In the end I have the process $M_n=S_n-E(S_n)$. I was able to show that this is a martingale, since $E(X_i)= \frac{1}{i}$,
$$ E(S_{n+1}-E(S_{n+1})\mid \mathcal{F}_n)= S_n + E(X_{n+1}) - E(S_{n}) - E(X_{n+1}) = S_n - E(S_n)$$
And I have that $E(S_n)=\sum_{j=1}^n \frac{1}{j}$ and that $Var(S_n)=\sum_{j=1}^{n} \frac{1}{j^2}$ thanks to independence.
I am trying to compute whether there exists a r.v. $M_{\infty}$ such that:

*

*$M_n\to M_{\infty}$ a.s.

*$M_n = E(M_{\infty}\mid\mathcal{F}_n)$

In order to do this I need to upper-bound $\sup_n E(M_n^2)$ or $\sup_n E(|M_n|)$ but I do not know how to proceed...any hints?

A: Note that the martingale $M_n := S_n-\mathbb{E}(S_n)$ satisfies
$$\mathbb{E}(M_n^2) = \text{var}(S_n) = \sum_{j=1}^n \text{var}(X_j) = \sum_{j=1}^n \frac{1}{j^2}$$
and therefore
$$\sup_{n \in \mathbb{N}} \mathbb{E}(M_n^2)<\infty,$$
i.e. $(M_n)_{n \in \mathbb{N}}$ is an $L^2$-bounded martingale. Applying a standard convergence theorem for martingales we find that there exists $M_{\infty} \in L^2$ such that $M_n \to M_{\infty}$ almost surely and in $L^2$. In particular, $M_n \to M_{\infty} \in L^1$ and from this it is not difficult to see that
$$M_n = \mathbb{E}(M_{\infty} \mid \mathcal{F}_n)$$
for all $n \in \mathbb{N}$.


text:
Q: Python/Gensim - What is the meaning of syn0 and syn0norm? I know that in gensims KeyedVectors-model, one can access the embedding matrix by the attribute model.syn0. There is also a syn0norm, which doesn't seem to work for the glove model I recently loaded. I think I also have seen syn1 somewhere previously.
I haven't found a doc-string for this and I'm just wondering what's the logic behind this?
So if syn0 is the embedding matrix, what is syn0norm? What would then syn1 be and generally, what does syn stand for?

A: These names were inherited from the original Google word2vec.c implementation, upon which the gensim Word2Vec class was based. (I believe syn0 only exists in recent versions for backward-compatbility.)
The syn0 array essentially holds raw word-vectors. From the perspective of the neural-network used to train word-vectors, these vectors are a 'projection layer' that can convert a one-hot encoding of a word into a dense embedding-vector of the right dimensionality.
Similarity operations tend to be done on the unit-normalized versions of the word-vectors. That is, vectors that have all been scaled to have a magnitude of 1.0. (This makes the cosine-similarity calculation easier.) The syn0norm array is filled with these unit-normalized vectors, the first time they're needed.
This syn0norm will be empty until either you do an operation (like most_similar()) that requires it, or you explicitly do an init_sims() call. If you explicitly do an init_sims(replace=True) call, you'll actually clobber the raw vectors, in-place, with the unit-normed vectors. This saves the memory that storing both vectors for every word would otherwise require. (However, some word-vector uses may still be interested in the original raw vectors of varying magnitudes, so only do this when you're sure most_similar() cosine-similarity operations are all you'll need.)
The syn1 (or syn1neg in the more common case of negative-sampling training) properties, when they exist on a full model (and not for a plain KeyedVectors object of only word-vectors), are the model neural network's internal 'hidden' weights leading to the output nodes. They're needed during model training, but not a part of the typical word-vectors collected after training.
I believe the syn prefix is just a convention from neural-network variable-naming, likely derived from 'synapse'.


text:
Q: The best way of preventing paragraphs from "pushing" other divs in a hover/float? I'm trying to make a 50%-50% (half-half) webpage that when the user hovers over one side, it expands and vice versa.
How do I prevent the words from the
 ("This is the container") from moving and pushing down the
 everytime I hover over it?  I'm trying to make the words go "under side" of panel1.  My code is below:

#container {
  background-color: yellow;
  min-height: 100%;
  box-sizing: border-box;
  float: left;
  min-width: 100%;
  }

#panel1 {
  background-color: red;
  min-height: 100%;
  box-sizing: border-box;
  padding: 20px;
  width: 50%;
  float: right;
  }

#panel2 {
  background-color: blue;
  min-height:100%;
  box-sizing: border-box;
  padding: 20px;
  width: 100px;
  height: 200px
  }

#container:hover #panel1 {width:30%; transition: 0.5s;}

#container:hover #panel1:hover {width: 70%; transition: 0.5s;}

  This is the container (hover over me.). Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris ac magna eget magna laoreet convallis ut et libero. "How do I prevent this paragraph from pushing down Panel 1 yet still be able to put words "under" the panel one?""....

This is panel one.(hover over me.)

This is panel two.


text:
Q: Qual o melhor tipo para armazenar área, volume e perímetro? Decimal, Numeric ou Float, qual a melhor opção para armazenar área ou volume?
Eu usaria o Decimal, mas gostaria de ver a opinião de outros também.
Parece que não, mas o tipo certo ou o mais próximo disso faz toda a diferença, até porque apanhei com um banco com tipos REAL e não quero perder tempo com tipos errados. Usei c# pois nela irei mapear os tipos do banco pelo C#.

A: De forma geral o decimal é o mais correto. Mesmo que não precise da exatidão dele se interagir com outras unidades que precisam, a ruim contamina a boa e tudo fica errado.
De forma geral eu vejo zero vantagens em usar um tipo de ponto flutuante binário. Sim, pode ter mais performance e deve ocupar menos memória, mas o risco é muito grande, principalmente na mão de programadores que não são muito afiados em desenvolvimento de software e façam tudo com muita minúcia, com profundo entendimento de todas as consequências. E tudo seja absurdamente bem documentado, o que nunca acontece.
Veja mais em Qual a forma correta de usar os tipos float, double e decimal?.

A: É pouco difundido mas existe os tipos espaciais no C#. Claro que é possível trabalhar com qualquer tipo de dado com ponto flutuante, mas além de armazenar certamente você vai querer fazer cálculos com estes pontos.
Já precisei para um trabalho acadêmico e foi uma mão na roda.
https://docs.microsoft.com/pt-br/ef/core/modeling/spatial