Q: Root redirect with Tomcat 7 and Apache reverse proxy Expected behavior: Requests to example.com should redirect to example.com/.
Problem: Requests in a browser (Firefox) to example.com succeed. Requests in a browser to example.com/ redirect to example.com, which is backwards. With curl, neither request redirects and both serve the same content.
$ curl -D - example.com
HTTP/1.1 200 OK
Date: Sun, 23 Oct 2011 05:54:28 GMT
Content-Type: text/plain;charset=ISO-8859-1
Content-Length: 27
Connection: close

Servlet handling request: /index.html

$ curl -D - example.com/
HTTP/1.1 200 OK
Date: Sun, 23 Oct 2011 06:01:24 GMT
Content-Type: text/plain;charset=ISO-8859-1
Content-Length: 27
Connection: close

Servlet handling request: /index.html

Direct requests to Tomcat behave as expected.
$ curl -D - localhost:8080/myapp
HTTP/1.1 302 Moved Temporarily
Server: Apache-Coyote/1.1
Location: http://localhost:8080/myapp/
Transfer-Encoding: chunked
Date: Sun, 23 Oct 2011 05:50:20 GMT

Redirecting to http://localhost:8080/myapp/

I believe the problem is with my reverse proxy configuration. (I'm serving static content by Apache from the /a directory in the webapp.)
<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /usr/share/tomcat7/webapps/myapp

    RewriteEngine On
    RewriteCond %{REQUEST_URI} !^/a/
    RewriteRule (.*) ajp://localhost:8009/myapp$1 [P]

    <Directory /usr/share/tomcat7/webapps/myapp/a>
        Order deny,allow
        Allow from all
    </Directory>

    <Directory /usr/share/tomcat7/webapps/myapp>
        Order deny,allow
        Deny from all
    </Directory>
</VirtualHost>

A: http://example.com/ is absolutely same as http://example.com - both are requests to www.example.com path /. Path can't be empty: "If the abs_path is not present in the URL, it MUST be given as "/" when used as a Request-URI for a resource". So, there are no redirects for /, it's probably just a different behavior of different UI's.
But, it is different with /myapp: /myapp/ and /myapp is two different URL's and here you can do redirects, serve different pages and so on.


Q: Why my text box's border color doesn't grow? I have a textbox as follow.

                    Repeat Password
                    <input type="password" class="form-control" required="" name="passwordr" value="">
                    Type the password again. Passwords must match.

I am expecting to have a textbox with a glowing colour when the user click the textbox.
But it doesn't happen now.
Please see it here.
I have another setting, it works here.
I think pretty much the same.
The second one has rounded corner and the light grows.
Why the first one doesn't have rounded corner and the light doesn't glow?
EDIT:

A: !imporant for apply css forcefully and effects same as bootstrap.
.form-control:focus{
 box-shadow: 0 0 5px rgba(81, 203, 238, 1) !important;
   border: 1px solid rgba(81, 203, 238, 1) !important;

}

Working Fiddle

A: If you want an input to have a different/special appearance once selected, use the :focus CSS pseudo-class.
A simple example:
#myInput:focus {
    border: 1px solid red;
}

PS. I assume you mean "glow", not "grow", and certainly not "blow" :-)


Q: list of numbers to a stack back to a list Imagine four railroad cars positioned on the input side of the track in the figure above, numbered 1, 2, 3, and 4, respectively. Suppose we perform the following sequence of operations (which is compatible with the direction of the arrows in the diagram and does not require cars to "jump over" other cars):
As a result of these operations the original order of the cars, 1234, has been changed into 2431.
The operations above can be more concisely described by the code SSXSSXXX, where S stands for move a car from the input into the stack, and X stands for move a car from the stack into the output. Some sequences of S's and X's specify meaningless operations, since there may be no cars available on the specified track; for example, the sequence SXXSSXXS cannot be carried out. (Try it to see why.)
Write and test a function that emulates the train car switching:
    # [import statements]
    import q2_fun
# [constants]

# [rest of program code]
cars = [1, 2, 3, 4]
s_x = input("enter a code with s's and x's to move one stack to another")
list1 = q2_fun.train_swicth(cars, s_x)
print(list1)

from stack_array import Stack

def train_swicth(cars, s_x):

    s = Stack()
    list1 = []

    for i in range(len(s_x)):
        if s_x[i] == "s":
            a = s_x.append()
            s.push(a)
        elif s_x[i] == "x":
            b = s.pop()
            list1.append(b)

    return list1

I keep getting [] as the return and it should be 2431 with ssxssxxx. Can I get some help?

A: if I understood you right you could do:
def train_swicth(cars, s_x):
    i=0
    s=[]
    out=[]
    for c in s_x:
        if c=="s":
            s.append(cars[i])
            i+=1
        elif c=="x":
            out.append(s.pop())
    return out

as lists can be used as stacks with append as push-operation


Q: ImageProcessing in WPF (Fant BitmapScalingMode) My application presents an image that can be scaled to a certain size. I'm using the Image WPF control with the scaling method of FANT.
However, there is no documentation how this scaling algorithm works.
Can anyone reference me to the relevant link for this algorithm description?
Nir

A: Avery Lee of VirtualDub states that it's a box filter for downscaling and linear for upscaling. If I'm not mistaken, "box filter" here means basically that each output pixel is a "flat" average of several input pixels.
In practice, it's a lot more blurry for downscaling than GDI's cubic downscaling, so the theory about averaging sounds about right.

A: I know what it is, but I couldn't find much on Google either :(
http://ieeexplore.ieee.org/xpl/freeabs_all.jsp?arnumber=4056711 is the appropriate paper I think; behind a pay-wall.
You don't need to understand the algorithm to use it.  You should explicitly make the choice each time you create a bitmap control that is scaled whether you want it high-quality scaled or low quality scaled.


Q: My jQuery script makes always the first  look like focused when not Thing is, no matter which <select> I'm clicking, it always looks like the first one gets focused when actually the second one isn't.
The code works, but I want to implement the $(this) thing so the button I press is the one who must look focused, and I can't figure how to do it.
Here's my jsfiddle: http://jsfiddle.net/Arkl1te/TeNaf/

A: You have all <div>s with the same ID. You should not duplicate the IDs. They should be unique. And also, a <label> cannot have a <div> inside it.
Since you are using $("#select"), it selects only the first <div>. Make sure your IDs are unique and try it. This code works for you:
$(document).ready( function(){
    $('select').focus( function(){
        $(this).closest("div").addClass('selected');
    });
    $('select').focusout( function(){
        $(this).closest("div").removeClass('selected');
    });
});

Fiddle: http://jsfiddle.net/praveenscience/TeNaf/2/


Q: How to align two figures with different labels? These are two figures in my paper. Apparently, the two axes are not in alignment. How can I make sure that two figures generated independently align with each other? The problem is that the two figures have different labels and different ticklabels. That makes the positions of the axes different.

A: For each subplot, find the x/y/width/height. Then adjust the second (or both) to be the same height and the same "y"
get(gca,'position')
set(gca, 'position', [0.1300    0.15    0.3347  0.3412]) %x y width height, dummy numbers


Q: NSIS "Bad text encoding" compilation error from _EndSwitch macro We've been using NSIS 2.50 for some time now and I'm trying to update to the newest 3.0x version. I'm using Unicode true. I've ran into an issue, which I'm failing to understand. We use a switch for mapping native language names to language IDs, more or less like this:
${Switch} "${LANGNAME}"
    ${Case} "${LANGFILE_ALBANIAN_NAME}"
        StrCpy $0 "${LANG_ALBANIAN}"
        ${Break}
    ${Case} "${LANGFILE_ARABIC_NAME}"
        StrCpy $0 "${LANG_ARABIC}"
        ${Break}
    ; Other cases
${EndSwitch}

The error I'm getting from compilation:
Bad text encoding: C:\Users\me\AppData\Local\Temp\nst9352.tmp:9
!include: error in script: "C:\Users\me\AppData\Local\Temp\nst9352.tmp" on line 9
Error in macro _EndSwitch on macroline 9

The temporary file is apparently created by LogicLib, which then tries to include it. The file really doesn't have any valid Unicode encoding (I'm posting just a snippet from the file):
!insertmacro _== `$2` `Shqip` _LogicLib_Label_433 ""
!insertmacro _== `$2` `???????` _LogicLib_Label_434 ""
!insertmacro _== `$2` `Catal�` _LogicLib_Label_441 ""

The strings with invalid UTF-8 characters seem to be encoded in various ANSI encodings (some seem to be Western European, some Central European etc.), while the question marks are saved as real question marks (0x3F). ${LANGFILE_NLFID_NAME} is defined in language files as native name using the LANGFILE macro from LangFile.nsh. I looked at the language files and they are encoded in UTF-8 BOM and look all right. So it looks like the native name is re-encoded to ANSI or something for ${LANGFILE_NLFID_NAME}?
I'm pretty sure I'm making some stupid mistake, but I can't really figure out what it is.

A: Looks like a bug, it will be fixed in the next release.
Since you are not using the fall-through Switch feature you can just use Select or If/ElseIf instead:
${Select} "${LANGNAME}"
    ${Case} "${LANGFILE_ALBANIAN_NAME}"
        DetailPrint LANG_ALBANIAN
    ${Case} "${LANGFILE_ARABIC_NAME}"
        DetailPrint LANG_ARABIC
${EndSelect}


Q: Recursively get every nth element from array Javascript I have an array of colors that I need to recursively get every nth element to generate a legend. The colors array might look something like this:
[
'red',
'dark_red',
'dark_dark_red',
'green',
'dark_green',
'dark_dark_green',
'blue',
'dark_blue',
'dark_dark_blue'
]

I have a variable amount of legend items that I want to generate colors for. I want to be able to generate the colors based off of the index when looping through the legend items in a pattern like so:
1 - green
2 - blue
3 - dark_red
4 - dark_green
5 - dark_blue
6 - etc...

How might I go about this? I tried using modulus and a double-loop statement but was not able to generate the colors properly.

A: To get the nthItems:

function nthItems(array, n){
  const r = [];
  for(let i=n-1,l=array.length; i<l; i+=n){
    r.push(array[i]);
  }
  return r;
}
const a = [
  'red',
  'dark_red',
  'dark_dark_red',
  'green',
  'dark_green',
  'dark_dark_green',
  'blue',
  'dark_blue',
  'dark_dark_blue'
];
console.log(nthItems(a, 2));
console.log(nthItems(a, 3));

A: StackSlave's answer is the most efficient way but if you want a recursive way you could do

const a = [
  'red',
  'dark_red',
  'dark_dark_red',
  'green',
  'dark_green',
  'dark_dark_green',
  'blue',
  'dark_blue',
  'dark_dark_blue'
];

const nthItems = (array, n) => {
  const results = [];
  const addItem = index => {
    if (index < array.length) {
      results.push(array[index]);
      addItem(index + n);
    }
  };
  addItem(0);
  return results;
};

console.log(nthItems(a, 2));
console.log(nthItems(a, 3));

But this is recursive purely for the sake of recursion, it adds values to the stack unnecessarily when a for loop will do.


Q: rxjava StackOverflowError exception in long chain I build very long rxjava chain (with retrofit request) with a lot of operators: doOnNext, doOnError, switchIfEmpty, onErrorResumeNext, flatMap
On some devices (Android 4.1 for example) it throws StackOverflowError exception when chain go by the longest route.
Are there some ways or best practices to optimize chains or prevent StackOverflowError?
Now I see only one way  - break chain, and call second part from first onComplete(OnNext), but it is not reactive way, I think.
Yet another way - change threads with .subscribeOn(Schedulers.newThread()); operator. Seems not the best solution too.
My code:
1) code with subscribing
fastSearch(keyphrase)
    .onErrorResumeNext(throwable -> {
        return correctKeyphraseAndSearch(keyphrase);
    })
    .doOnNext(resultsDao -> {...})
    .subscribe(...)

2) helper methods
public static Observable<SearchResultsDao> fastSearch(final String keyphrase) {
    String SRD = "true";
    final HttpQueryParams params = new HttpQueryParams();
    //read from cache chain
    Observable<SearchResultsDao> cacheChain = getCache().fastSearch(keyphrase, SRD)
            .doOnNext(...)
            .doOnError(...)
            .onErrorResumeNext(new HandleNoCacheEntry<SearchResultsDao>(params)); //save some data to "params", and return Observable.empty
    //network request chain
    Observable<SearchResultsDao> networkChain = getApi().fastSearch(keyphrase, SRD)
            .retryWhen(new OnNewSessionRequired())
            .doOnNext(new WriteToCacheAction<SearchResultsDao>(params)); //save to cache
    //combine cache+network chains
    return cacheChain
            .switchIfEmpty(networkChain)
            .doOnNext(resultsDao -> resultsDao.setKeyphrase(keyphrase));
}

public static Observable<SearchResultsDao> correctKeyphraseAndSearch(final String keyphrase) {
    return mainDiv()
            .flatMap(str -> syntax(str, keyphrase, true))
            .flatMap(syntaxDao -> {
                //get corrected keyphrase from server
                StringBuilder newKeyphrase = ... ;
                //repeat search request with new keyphrase
                return fastSearch(newKeyphrase.toString());
            });
}

3) some comments:
mainDiv() and syntax() methods identical to fastSearch() method, but doing another requests to server
getCache().fastSearch() - create observable that reads data from own cache (retrofit-like: getCache() implements retrofit Api methods interface)
Stacktrace:
Uncaught Exception
java.lang.IllegalStateException: Fatal Exception thrown on Scheduler.Worker thread.
at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:62)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:442)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:150)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:264)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
Caused by: java.lang.StackOverflowError
okhttp3.HttpUrl.newBuilder (HttpUrl.java:633)
retrofit2.RequestBuilder.addQueryParam (RequestBuilder.java:144)
retrofit2.ParameterHandler$Query.apply (ParameterHandler.java:109)
retrofit2.ServiceMethod.toRequest (ServiceMethod.java:108)
retrofit2.OkHttpCall.createRawCall (OkHttpCall.java:178)
retrofit2.OkHttpCall.execute (OkHttpCall.java:162)
retrofit2.adapter.rxjava.RxJavaCallAdapterFactory$RequestArbiter.request (RxJavaCallAdapterFactory.java:171)
rx.internal.producers.ProducerArbiter.setProducer (ProducerArbiter.java:126)
rx.internal.operators.OnSubscribeRedo$2$1.setProducer (OnSubscribeRedo.java:272)
rx.Subscriber.setProducer (Subscriber.java:205)
retrofit2.adapter.rxjava.RxJavaCallAdapterFactory$CallOnSubscribe.call (RxJavaCallAdapterFactory.java:152)
retrofit2.adapter.rxjava.RxJavaCallAdapterFactory$CallOnSubscribe.call (RxJavaCallAdapterFactory.java:138)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable.unsafeSubscribe (Observable.java:8314)
rx.internal.operators.OnSubscribeRedo$2.call (OnSubscribeRedo.java:278)
rx.schedulers.TrampolineScheduler$InnerCurrentThreadScheduler.enqueue (TrampolineScheduler.java:80)
rx.schedulers.TrampolineScheduler$InnerCurrentThreadScheduler.schedule (TrampolineScheduler.java:59)
rx.internal.operators.OnSubscribeRedo$5.request (OnSubscribeRedo.java:366)
rx.internal.producers.ProducerArbiter.setProducer (ProducerArbiter.java:126)
rx.internal.operators.OperatorSwitchIfEmpty$AlternateSubscriber.setProducer (OperatorSwitchIfEmpty.java:106)
rx.Subscriber.setProducer (Subscriber.java:205)
rx.internal.operators.OnSubscribeRedo.call (OnSubscribeRedo.java:358)
rx.internal.operators.OnSubscribeRedo.call (OnSubscribeRedo.java:55)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable.unsafeSubscribe (Observable.java:8314)
rx.internal.operators.OperatorSwitchIfEmpty$ParentSubscriber.subscribeToAlternate (OperatorSwitchIfEmpty.java:78)
rx.internal.operators.OperatorSwitchIfEmpty$ParentSubscriber.onCompleted (OperatorSwitchIfEmpty.java:71)
rx.internal.operators.OperatorOnErrorResumeNextViaFunction$4$1.onCompleted (OperatorOnErrorResumeNextViaFunction.java:125)
rx.Observable$EmptyHolder$1.call (Observable.java:1123)
rx.Observable$EmptyHolder$1.call (Observable.java:1120)
rx.Observable.unsafeSubscribe (Observable.java:8314)
rx.internal.operators.OperatorOnErrorResumeNextViaFunction$4.onError (OperatorOnErrorResumeNextViaFunction.java:141)
rx.internal.operators.OperatorDoOnEach$1.onError (OperatorDoOnEach.java:71)
rx.internal.operators.OperatorDoOnEach$1.onError (OperatorDoOnEach.java:71)
com.testrx.app.retrofit.api.CacheHelper$1.call (CacheHelper.java:56)
com.testrx.app.retrofit.api.CacheHelper$1.call (CacheHelper.java:46)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable.unsafeSubscribe (Observable.java:8314)
rx.internal.operators.OperatorMerge$MergeSubscriber.onNext (OperatorMerge.java:235)
rx.internal.operators.OperatorMerge$MergeSubscriber.onNext (OperatorMerge.java:145)
rx.internal.operators.OperatorMap$1.onNext (OperatorMap.java:54)
rx.internal.operators.OperatorMerge$MergeSubscriber.emitScalar (OperatorMerge.java:368)
rx.internal.operators.OperatorMerge$MergeSubscriber.tryEmit (OperatorMerge.java:330)
rx.internal.operators.OperatorMerge$InnerSubscriber.onNext (OperatorMerge.java:807)
rx.internal.operators.OperatorSwitchIfEmpty$ParentSubscriber.onNext (OperatorSwitchIfEmpty.java:89)
rx.internal.operators.OperatorOnErrorResumeNextViaFunction$4.onNext (OperatorOnErrorResumeNextViaFunction.java:153)
rx.internal.operators.OperatorDoOnEach$1.onNext (OperatorDoOnEach.java:85)
rx.internal.operators.OperatorDoOnEach$1.onNext (OperatorDoOnEach.java:85)
com.testrx.app.retrofit.api.CacheHelper$1.call (CacheHelper.java:53)
com.testrx.retrofit.api.CacheHelper$1.call (CacheHelper.java:46)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable.unsafeSubscribe (Observable.java:8314)
rx.internal.operators.OperatorMerge$MergeSubscriber.onNext (OperatorMerge.java:235)
rx.internal.operators.OperatorMerge$MergeSubscriber.onNext (OperatorMerge.java:145)
rx.internal.operators.OperatorMap$1.onNext (OperatorMap.java:54)
rx.internal.operators.OperatorSwitchIfEmpty$ParentSubscriber.onNext (OperatorSwitchIfEmpty.java:89)
rx.internal.operators.OperatorOnErrorResumeNextViaFunction$4.onNext (OperatorOnErrorResumeNextViaFunction.java:153)
rx.internal.operators.OperatorDoOnEach$1.onNext (OperatorDoOnEach.java:85)
rx.internal.operators.OperatorDoOnEach$1.onNext (OperatorDoOnEach.java:85)
com.testrx.app.retrofit.api.CacheHelper$1.call (CacheHelper.java:53)
com.testrx.app.retrofit.api.CacheHelper$1.call (CacheHelper.java:46)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable.unsafeSubscribe (Observable.java:8314)
rx.internal.operators.OperatorOnErrorResumeNextViaFunction$4.onError (OperatorOnErrorResumeNextViaFunction.java:141)
rx.internal.operators.OperatorDoOnEach$1.onError (OperatorDoOnEach.java:71)
rx.internal.operators.OperatorSwitchIfEmpty$AlternateSubscriber.onError (OperatorSwitchIfEmpty.java:116)
rx.internal.operators.OperatorDoOnEach$1.onError (OperatorDoOnEach.java:71)
rx.internal.operators.OnSubscribeRedo$4$1.onError (OnSubscribeRedo.java:331)
rx.internal.operators.OperatorMerge$MergeSubscriber.reportError (OperatorMerge.java:243)
rx.internal.operators.OperatorMerge$MergeSubscriber.checkTerminate (OperatorMerge.java:779)
rx.internal.operators.OperatorMerge$MergeSubscriber.emitLoop (OperatorMerge.java:540)
rx.internal.operators.OperatorMerge$MergeSubscriber.emit (OperatorMerge.java:529)
rx.internal.operators.OperatorMerge$InnerSubscriber.onError (OperatorMerge.java:813)
rx.Observable$ThrowObservable$1.call (Observable.java:10200)
rx.Observable$ThrowObservable$1.call (Observable.java:10190)
rx.Observable.unsafeSubscribe (Observable.java:8314)
rx.internal.operators.OperatorMerge$MergeSubscriber.onNext (OperatorMerge.java:235)
rx.internal.operators.OperatorMerge$MergeSubscriber.onNext (OperatorMerge.java:145)
rx.internal.operators.OperatorMap$1.onNext (OperatorMap.java:54)
rx.internal.operators.OperatorMap$1.onNext (OperatorMap.java:54)
rx.internal.operators.OnSubscribeRedo$3$1.onNext (OnSubscribeRedo.java:307)
rx.internal.operators.OnSubscribeRedo$3$1.onNext (OnSubscribeRedo.java:289)
rx.internal.operators.NotificationLite.accept (NotificationLite.java:150)
rx.subjects.SubjectSubscriptionManager$SubjectObserver.emitNext (SubjectSubscriptionManager.java:253)
rx.subjects.BehaviorSubject.onNext (BehaviorSubject.java:160)
rx.internal.operators.OnSubscribeRedo$2$1.onError (OnSubscribeRedo.java:242)
retrofit2.adapter.rxjava.OperatorMapResponseToBodyOrError$1.onNext (OperatorMapResponseToBodyOrError.java:43)
retrofit2.adapter.rxjava.OperatorMapResponseToBodyOrError$1.onNext (OperatorMapResponseToBodyOrError.java:38)
retrofit2.adapter.rxjava.RxJavaCallAdapterFactory$RequestArbiter.request (RxJavaCallAdapterFactory.java:173)
rx.internal.producers.ProducerArbiter.setProducer (ProducerArbiter.java:126)
rx.internal.operators.OnSubscribeRedo$2$1.setProducer (OnSubscribeRedo.java:272)
rx.Subscriber.setProducer (Subscriber.java:205)
retrofit2.adapter.rxjava.RxJavaCallAdapterFactory$CallOnSubscribe.call (RxJavaCallAdapterFactory.java:152)
retrofit2.adapter.rxjava.RxJavaCallAdapterFactory$CallOnSubscribe.call (RxJavaCallAdapterFactory.java:138)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable.unsafeSubscribe (Observable.java:8314)
rx.internal.operators.OnSubscribeRedo$2.call (OnSubscribeRedo.java:278)
rx.schedulers.TrampolineScheduler$InnerCurrentThreadScheduler.enqueue (TrampolineScheduler.java:80)
rx.schedulers.TrampolineScheduler$InnerCurrentThreadScheduler.schedule (TrampolineScheduler.java:59)
rx.internal.operators.OnSubscribeRedo$5.request (OnSubscribeRedo.java:366)
rx.internal.producers.ProducerArbiter.setProducer (ProducerArbiter.java:126)
rx.internal.operators.OperatorSwitchIfEmpty$AlternateSubscriber.setProducer (OperatorSwitchIfEmpty.java:106)
rx.Subscriber.setProducer (Subscriber.java:205)
rx.internal.operators.OnSubscribeRedo.call (OnSubscribeRedo.java:358)
rx.internal.operators.OnSubscribeRedo.call (OnSubscribeRedo.java:55)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable.unsafeSubscribe (Observable.java:8314)
rx.internal.operators.OperatorSwitchIfEmpty$ParentSubscriber.subscribeToAlternate (OperatorSwitchIfEmpty.java:78)
rx.internal.operators.OperatorSwitchIfEmpty$ParentSubscriber.onCompleted (OperatorSwitchIfEmpty.java:71)
rx.internal.operators.OperatorOnErrorResumeNextViaFunction$4$1.onCompleted (OperatorOnErrorResumeNextViaFunction.java:125)
rx.Observable$EmptyHolder$1.call (Observable.java:1123)
rx.Observable$EmptyHolder$1.call (Observable.java:1120)
rx.Observable.unsafeSubscribe (Observable.java:8314)
rx.internal.operators.OperatorOnErrorResumeNextViaFunction$4.onError (OperatorOnErrorResumeNextViaFunction.java:141)
rx.internal.operators.OperatorDoOnEach$1.onError (OperatorDoOnEach.java:71)
rx.internal.operators.OperatorDoOnEach$1.onError (OperatorDoOnEach.java:71)
com.testrx.app.retrofit.api.CacheHelper$1.call (CacheHelper.java:56)
com.testrx.app.retrofit.api.CacheHelper$1.call (CacheHelper.java:46)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable.unsafeSubscribe (Observable.java:8314)
rx.internal.operators.OperatorSubscribeOn$1.call (OperatorSubscribeOn.java:94)
rx.internal.schedulers.ScheduledAction.run (ScheduledAction.java:55)
java.util.concurrent.Executors$RunnableAdapter.call (Executors.java:442)

A: Stackoverflows rarely happen with typical streams; without code I can't be sure what's wrong.
In earlier versions of RxJava, there were reentrancy problems in some operators that could result in StackOverflows but we haven't received any bug reports like it in some time now. Please make sure you are using the latest RxJava from the 1.x line (the RxAndroid plugin's dependency may need overriding as it is infrequently updated in this regard).
There are a few things you can do:

*

*compact subsequent doOnNext and doOnError calls into doOnEach

*add observeOn(Schedulers.computation()) occasionally

*avoid chaining too many mergeWiths, collect up sources into a List and use merge(Iterable)

*upgrade to RxJava 2.x which should have less stack depth (have not verified)

Edit:
Based on the stacktrace, my undestanding is that you have too many empty sequences and switchIfEmpty keeps deepening the stack when switching from one empty sequence to the next. As you found out, subscribeOn helps "restart" the stack. I'll investigate possible resolutions within RxJava itself.

A: The cause of this problem was Jack compiler (https://source.android.com/source/jack.html) which I use in the project for lambdas support. I switched it off and now everything works fine


Q: How to prevent Visual C Compiler from optimizing out "unused" global variable
Possible Duplicate:
Why does const imply internal linkage in C++, when it doesn’t in C?
What is external linkage and internal linkage in C++

I have a two C files that I'm trying to compile to an executable.  One file contains only a single declaration as follows (simplifed).
const char *foo[2] = {"thing1", "thing2"};

The second c file does this
extern const char *foo[2];
main()
{
 //Code that does stuff with foo
}

When compiling I get a linker error that foo is an unresolved external symbol.  I'm assuming the compiler is optimizing out foo.   Any ideas here?

A: There's nothing wrong with your declarations. The code should compile and link as is, assuming you add explicit int as the return type of your main. The only explanation for the linker error I can come up with is that you are forgetting to supply all required object files to the linker.
The answers that attempt to explain this issue through the fact that in C++ const objects have internal linkage are misleading and irrelevant. The above object foo is not a const object.


Q: Oracle: Finding the stored procedure that modifies record on a table I've got a C# code that calls stored procedures and UPDATES a table. Can I monitor each operation made on this table by a SID.

A: Yes, you can do this at the database level using Oracle auditing.  See here for good writeup and examples of its use.


Q: creating new variables in sas I am trying to create 3 new variables and have used this code however keep getting an error in my log, I am not sure what this issue is:
    Data birthdata
    SET birthdata;

    native=.;
    if race=3 THEN native=1;
    if race=1 THEN native=0;

    aarace=.;
    if race=2 then aarace=1;
    if race=1 then aarace=0;

   nonwhite=.;
   if (1<race=.) then nonwhite=1;
   if race=1 then nonwhite=0;

  label native  = "Maternal race"
  aarace  = "Maternal race"
  nonwhite = "Maternal race";

 FORMAT native native. aarace aarace. nonwhite nonwhite.;

 run;

`

A: You missed ; in first line of data step.


Q: Export data to pdf in Laravel downloading only 2 pages irrespective of data I have huge amount of data in my DB. But when I try to export data to pdf in Laravel only 2 pages are downloading.
 $members = DB::table('members')->where('id_card_issued',0)->get();
 $pdf = PDF::loadView('admin.myPDF', compact('members'));
 return $pdf->download('id_card.pdf');

I want all the data to be downloaded. But now only getting last 2 data in my database table

A: Are you trying to do to download large files from the server, I have changed the below settings in php.ini file in mine to do so :
Upload_max_filesize  - 1500 M
Max_input_time  - 1000
Memory_limit    - 640M
Max_execution_time -  1800
Post_max_size - 2000 M


Q: Javascript unit testing framework that doesn't work in strict mode Is there a way to unit test code from not strict mode. Most of the testing frameworks, mocha, jest, etc are strict mode only. My code involves use of eval that needs non-strict mode scope that I cannot rewrite into strict mode compatible form. Any idea or do I need to write my own unit testing framework.

A: I ended up using Karma with jasmine. Setting it to browser mode means no modules and no strict mode, yay.


Q: Qubo: Energy of of Non Overlapping Constraint in Taillard's Job Shop Problem Suppose we have a set of tasks $T = \{t_1, t_2, \dots, t_n\}$ with durations $\{d(t)| t \in T\}$, that need to be executed on some machine such that their execution times do not overlap.
We can represent the start time of task $t$ as $x(t),\, x \in \mathbb{N}$. We don't care about the execution order.

Regardless whether this problem is trivially solved by just exceuting each task after previous ends, I'd like to encode this constraint as minimizing a polynomial $p: X \times \Xi \to \mathbb{R}$ where $X = \{x(t) : t \in T\}$ and $\Xi$ denotes the set of any extra variables one might need to introduce.
Currently my approach is to use the classic double well in combination with slack variables:
For each pair of tasks $(t_i, t_j)$, we want that $x(t_i) + d(t_i) \leq x(t_j)$ or $x(t_j) + d(t_j) \leq x(t_i)$. Introducing the slack variable $\xi \geq 0$, this translates to
$$x(t_i) + d(t_i) + \xi - x(t_j) = 0 \quad \text{or} \quad x(t_j) + d(t_j) + \xi - x(t_i) = 0$$
Multiplying both options and squaring gives
$$
p_{ij}(x, \xi) = (x(t_i) + d(t_i) + \xi - x(t_j))^2(x(t_j) + d(t_j) + \xi - x(t_i))^2.
$$
It is easy to check that $p_{ij}$ is minimized iff tasks $t_i$ and $t_j$ do not overlap and that $0$ is the global minimum value. Thus summing over all combinations of tasks gives the desired constraint energy for all tasks.
My issue now is that each $p_{ij}$ is of degree 4. Having polynomials of degree $\geq$ 2 adds additional variables and constraints when we compile $p$ down to a QUBO.
Can we encode these non-overlapping constraints with polynomials of degree < 4?

A: For each pair $(t_i, t_j)$ of tasks with $i < j$, introduce a binary variable $z_{ij}\in \lbrace 0,1\rbrace$ which will be 0 if $t_i$ precedes $t_j$ and 1 if $t_j$ precedes $t_i$. The approach is to add a pair of constraints representing those two possibilities, such that for each value of $z_{ij}$ one constraint enforces a particular precedence and the other constraint is vacuous (automatically satisfied). Here you would use the following: $$ x(t_i) + d(t_i) - x(t_j) \le T z_{ij}$$ and $$x(t_j) + d(t_j) - x(t_i) \le T(1-z_{ij}).$$ This is what @RobPratt was getting at.


Q: Clear filter from Table I'm trying to run a macro that replaces data in a table in Excel, when the data might initially be filtered.
The code should remove the filter first, then run the rest of the code.
I tried the "Autofilter" command, but then the normal filter option on the table's range weren't visible, and I had to manually create the filter option again (not a big deal to me, but other people use this file).
Is there a way to clear the filter WITHOUT removing filters from the table?

A: For a Table, you can simply use the ShowAllData method of its Autofilter object:
activesheet.listobjects(1).autofilter.showalldata

Note this won't error even if there is no filter currently applied.

A: This expands on the answer from @Rory (the go-to-answer I look up every time I can't remember the syntax).  It avoids errors that occur when the table doesn't contain an auto-filter.
The section If Not .AutoFilter Is Nothing checks for the AutoFilter object property of the ListObject (table).  If it Is Nothing then that table had it's auto-filter removed.
With Activesheet.Listobjects(1)
    If not .AutoFilter Is Nothing Then .AutoFilter.ShowAllData
End With

A: Hi Guys use this "Worksheets("Sheet1").ListObjects(1).Range.AutoFilter = False" and please note if already filter applied it will remove filter on the other hand if filter not applied before it will apply the filter.

A: I am finding that the "...ClearAllData" method fails.
Sneaky - not hugely elegant solution - that works by field (so cumbersome if you need to do the whole table), but easy if you just have one field (e.g. field 2 in my example) is to use the wildcard:
ActiveSheet.ListObjects(1).Range.AutoFilter Field:=2, Criteria1:="=*"

A: ActiveSheet.ShowAllData

Or
Cells.AutoFilter


Q: "Don't give me with the scruples!" In The Fortune Cookie (1966) Walter Matthau's character, a cunning lawyer, says:

What's the matter? You feel sorry for insurance companies? They got so much money they don't know what to do with it. They've run out of storage space--they have to microfilm it. What's a quarter of a million to them? They take it out of petty cash. So don't give me with the scruples.

"Don't give me with the scruples!" sounds very peculiar to my ear, syntactically. People say "I have no scruples against doing that." But "Don't give me with" is a curious construct, so is "Don't give me with the scruples." Walter Matthau had a very typical New York accent and way of speaking. I wonder if this is his idiolect or something typical of (dated?) NY dialect?
Edit: Jack Lemmon's character later in the same movie says something similar: "Don't give me with that torch."

A: I suspect this is a parallel to "make with the", which is slang for "Produce, Perform".

make with
slang: PRODUCE, PERFORM —usually used with the
Straighten up and walk … make with the feet
[Merriam Webster]

Another example "make with the music" = "Start the music"
Hence "don't give with the scruples" = "don't express your moral doubts to me".

A: I think it could be simply idiosyncratic speech  modelled on "Don't give me that scruples nonsense/trash/crap/…!".


Q: decrypt web.config file for specific project on a local machine I have a project that is running on the server. I want to modify it on a local machine, but connection strings in the web.config file are encrypted using regiis. To decrypt it I tried this article:
http://ryaremchuk.blogspot.com/2012/11/encrypting-and-decrypting-webconfig.html
I copied the project to a folder on the hard desk on my local machine; so its path is C:\project1.
In the prompt interface I reached: C:\windows\Microsoft.NET\Framework\v4.0.30319. Then I used this command with no luck:
aspnet_regiis -pd "connectionStrings" -app "C:\project1"

Is my command wrong? Should the project be in a different path?


Q: Get the detached object from the session in the Hibernate events PostLoadEvent and PostUpdateEvent I have an entity which has transient fields, after the merge / load i loose all the values of these transient fields in the returned managed object.
What i want to do , is to copy the values of the transient fields from the detached object to the managed object.
The solution that i want to follow is based on the events in Hibernate, but i only have access to the detached object (the original entity) in the MergeEventListener and not in the PostUpdateEventListener and PostLoadEventListener .
Do you have any suggestion to find a solution to this issue ?
Thank you


Q: Window 200x200 with circle 200x200 doesn't fit I'm trying to do something very simple. I'm trying to create a window that has a circle in it that fits perfectly. I made the window 200x200 and the circle 200x200 and it looks like this
This is the code I made:
using System.Windows.Forms;
using System.Drawing;

class HalloForm : Form
{
    public HalloForm()
    {
        this.Text = "Hallo";
        this.BackColor = Color.LightGray;
        this.Size = new Size(200, 200);
        this.Paint += this.tekenScherm;
        this.AutoScaleMode = AutoScaleMode.Font;
    }

    void tekenScherm(object obj, PaintEventArgs pea)
    {

        tekenSmiley(pea, 0, 0, 200);
        /*pea.Graphics.DrawString("Hallo!"
                               , new Font("Tahoma", 30)
                               , Brushes.Blue
                               , 10, 10
                               );*/

        //pea.Graphics.DrawArc(Pens.Black, )

        //pea.Graphics.FillEllipse(Brushes.Black, new Rectangle(new Point(x + 40, y + 40), new Size(50, 50)));
        //pea.Graphics.FillEllipse(Brushes.Black, new Rectangle(new Point(x + 110, y + 40), new Size(50, 50)));
        //pea.Graphics.FillPolygon(Brushes.Black, new Point[] { new Point(x + 85, x + 120), new Point(x + 115, y + 120), new Point(x + 100, x + 90) });
    }

    private void tekenSmiley(PaintEventArgs pea, int x, int y, int grootte)
    {
        pea.Graphics.FillEllipse(Brushes.Yellow, new Rectangle(new Point(x, y), new Size(grootte, grootte)));
    }
}

class HalloWin3
{
    static void Main()
    {
        HalloForm scherm;
        scherm = new HalloForm();
        Application.Run(scherm);
    }
}

I tried different auto scale modes and none of them changed anything. Can you help me find out why the circle doesn't fit in the window. I understand that maybe it wouldn't fit vertically because the top bar might be included in the height, but then it should still fit horizontally.

A: As you already mentioned, the Size of the form includes borders, title bars etc. So, try to set the ClientSize which defines the client area of the form:
this.ClientSize = new Size(200, 200);


Q: Why there's no work in adiabatic free expansion? We say that because there is no external force on the system, the work done on the adiabatic free expansion is $0$(If this is wrong, correct me please). But there is a pressure and volume change in the system and if there is no work how can there be pressure and volume changes?
What causes these changes?

A: Suppose we regard our system as all the matter residing within the confines of the rigid container, and we regard the surroundings as the walls of the rigid container and everything outside.  Since the walls of the container is rigid, our system is incapable of doing any work on it; the displacement of the walls is zero.  So the work and the heat are zero (insulated container), and the change in internal energy of our system must be zero.

A: From your comments it seems that free expansion is the confusing part, so let me address that. There are two points to your question, which must be kept distinct.

First: in general, an adiabatic process can occur with or without work being done or received by the system. So, no, when you have an adiabatic process you can't conclude that there's no force applied to the system and no work exchange.
In the specific process of free adiabatic expansion of an ideal gas, it happens that no work is done or received by the system.

Second: Your intuition is right. During the free expansion of a real gas, a small amount of work is always done. From a macroscopic point of view this happens because of surface tension of the gas even when there's no enclosure. From a microscopic point of view this happens because the particles of the gas do work to overcome their mutual attraction. There can be exceptions, though. For a slightly electrified gas the opposite may happen for example: the expansion is favoured by electrostatic repulsion.
An ideal gas is microscopically modelled as a system of non-interacting particles, and therefore they do not do or receive any work during free expansion. However, this system during such a process cannot be described using the thermodynamics of uniform systems – in other words, using just "$(T,V)$" or "$(p,V)$" state variables. Pressure and temperature gradients appear, and if we tried to force a "$(p,V)$ description" we would encounter mathematical singularities. One needs the full thermodynamics of continuous systems to describe such adiabatic expansion.
However, once the free expansion has taken place and the system has gone back to spatially uniform conditions, we can resume our "$(p,V)$ description" and we have that the internal energy is the same as right before the free expansion. (For some real gases a very approximate $(p,V)$ description of free expansion might be possible, in some circumstances).

A good reference on both of these points is

*

*Astarita: Thermodynamics: An Advanced Textbook for Chemical Engineers (Springer 1990)

The question of the free expansion of an ideal gas and its mathematical description is discussed in detail in the Appendix to Chapter 2 and in Problem 2.3, and partly in section 5.1 as well.

A:
how can there be pressure and volume changes?

Although no work may be done, the gas nonetheless expands against a vacuum (increases in volume). When it expands its pressure drops. If it is an ideal gas,
$$\frac{P_{1}V_{1}}{T_{1}}=\frac{P_{2}V_{2}}{T_2}$$
where 1 and 2 denote the initial and final equilibrium states before and after the free expansion.
Since $W=0$ and $Q=0$, from the first law $\Delta U=0$. Also, for an ideal gas internal energy $U$ depends only on temperature so $T_{2}=T_1$. Therefore
$$P_{1}V_{1}=P_{2}V_{2}$$
Hope this helps.


Q: Displaying an image in a jsp from a byte array using struts I can get an image as a byte[] and store it in my database using form.jsp and FormFile.
Now I need to be able to retrieve that byte[] and display it back in the JSP as an image. Is there a way to create a resource and retrieve that image?

A: public ActionForward pageLoad(ActionMapping a,ActionForm b,HttpServletRequest c,HttpServletResponse d){
    b.setImageData(loadImageData());
    return a.findForward("toPage");
}

public ActionForward imageLoad(ActionMapping a,ActionForm b,HttpServletRequest c,HttpServletResponse d){
    byte[] tempByte = b.getImageData();
    d.setContentType("image/jpeg");
    ServletOutputStream stream = d.getOutputStream();
    /*
        Code to write tempByte into stream here.
    */
    return null;
}

Write the tempByte into stream, flush and close it. return null from the action.
now call the action from inside an <img src="yourAction.do">

A:        <%@ page import="java.sql.*" %>
       <%@ page import="java.io.*" %>

        Connection connection =  null;

      String connectionURL = "jdbc:mysql://localhost:3306/Test";
      ResultSet rs = null;

       PreparedStatement psmnt = null;

 InputStream sImage;
 try {

Class.forName("com.mysql.jdbc.Driver").newInstance();

 connection = DriverManager.getConnection(connectionURL, "Admin", "Admin");
psmnt = connection.prepareStatement("SELECT image FROM save_image WHERE id = ?");
psmnt.setString(1, "11"); // here integer number '11' is image id from the table
rs = psmnt.executeQuery();
if(rs.next()) {
byte[] bytearray = new byte[1048576];
int size=0;
sImage = rs.getBinaryStream(1);
response.reset();
response.setContentType("image/jpeg");
while((size=sImage.read(bytearray))!= -1 ){
response.getOutputStream().write(bytearray,0,size);
 }
 }
 }
     catch(Exception ex){
           out.println("error :"+ex);
        }
            finally {
                  rs.close();
                 psmnt.close();
                 connection.close();
         }
                  %>

By this u can retrive Image from Database


Q: Help on Algebra Problem I need help on this problem that 8/9 Grade Math Teacher Assigned me (I'm in 7th Grade). Here's the problem -

Today is Latisha's birthday. Fifty friends have thrown her a surprise party. Before the party, her friends got together and decided to secretly hide several presents in 50 separate boxes numbered 1 to 50.
Latisha is now about to open her gifts, which are arranged in a row in order. Her friends explain that if she follows the instructions below, she will discover which boxes hold a gift.
Latisha wants you to help her figure out which boxes hold presents without actually carrying out their instructions.
Their Instructions:
First, she should go down the line and open every box.
Then, starting with box #2, she should close every other box as she goes down the row.
Starting with box #3, she should change every third box (she opens the box if it is closed and closes it if the box is open)
Starting with box #4, she should change every fourth box.
Starting with box #5, she should change every fifth box.
Continue this process through box #50.

Basically, the boxes at the end that are open are the ones with presents in them. I think that you would have to use a factorial-related-strategy, but I'm not sure. Can anyone help?

A: This is a variation of the Locker Problem. Imagine there are only 10 boxes. If you start with them all open (and if she opens them all, wouldn't she be able to see which ones have gifts?), and close all the even-numbered ones, the boxes that are open are the ones that are not divisible by 2. Now you close boxes 3 and 9 but open box 6 (the multiples of 3). Then you close or open the multiples of 4, and the multiples of 5, etc. etc. The only boxes left are the ones that have an odd number of factors. For example, 10 is divisible by 1, 2, 5, and 10, so it would be closed. However, 9 is divisibly by 1, 3, and 9, so it is open.
I see from a comment made while writing this, that you say

if a number has an odd number of factors, it is closed. If a number has an even number of factors, it is open.

It is actually the opposite, since you must count 1 as a factor.
I hope you can solve this from here, but the only numbers with an odd number of factors are:

 perfect squares

A: A box is flipped once for every divisor its number has and it starts from closed, so it is closed if it has an even number of divisors and open if it has an odd number of divisors.
So this is progress, but it would be good to simplify the answer further. So we need to figure out how to tell whether a number has an even or odd number of divisors other than by counting them. The key here is to note that usually, divisors come in pairs. Say you're look for divisors of $10$. Then you have $1$ and $10,$ and $2$ and $5$... two pairs of divisors for a total of 4. So it seems like this would imply that usually there are an even number of divisors. But there is one situation where the above logic fails and you can have an odd number of divisors.


Q: Using SIFT and OpenCV for object recognition I have an image that is an image of one of a set of objects, and I'd like to use SIFT in Open CV to figure out which object it. I have this code:
Mat pic = imread(...);
vector<KeyPoint> picKP;
Mac picDesc;

Mat obj1 = imread(...);
Mat obj2 = imread(...);
Mat obj3 = imread(...);
vector<KeyPoint> obj1KP;
vector<KeyPoint> obj2KP;
vector<KeyPoint> obj3KP;
Mat obj1Desc;
Mat obj2Desc;
Mat obj3Desc;

SIFT sifter = SIFT();

sifter.detect(pic, picKP);
sifter.detect(obj1, obj1KP);
sifter.detect(obj2, obj2KP);
sifter.detect(obj3, obj3KP);

sifter.compute(pic, picKP, picDesc);
sifter.compute(obj1, obj1KP, obj1Desc);
sifter.compute(obj2, obj2KP, obj1Desc);
sifter.compute(obj3, obj3KP, obj1Desc);

FlannBasedMatcher matcher;
vector<DMatch> matches1;
vector<DMatch> matches2;
vector<DMatch> matches3;

matcher.match(picDesc, obj1Desc, matches1);
matcher.match(picDesc, obj2Desc, matches2);
matcher.match(picDesc, obj3Desc, matches3);

It generates a vector<DMatch> to compare my picture with each potential picture. But I don't know what to do with the 3 vector<DMatch>es to figure out which one is the best match.
Note: I'm doing this mostly to try and learn about SIFT, so even though I know better ways are available for my particular dataset, I still want to try to do it with SIFT.

A: See the API for DMatch data type here:
http://docs.opencv.org/modules/features2d/doc/common_interfaces_of_descriptor_matchers.html#dmatch


Q: Aws lambda java - Implement simple cache to read a file I have a lambda process in java and it reads a json file with a table everytime is triggered. I'd like to implement a kind of cache to have that file in memory and I wonder how to do something simple. I don't want to use elasticchache or redis.
I read something similar to my approach in javascript declaring a global variable with let but not sure how to do it in java, where it should be declared and how to test it. Any idea or example you can provide me? Thanks

A: *

*There are global variables in lambda which can be of help but they have to be used wisely.

*They are usually the variables declared out side of lambda_handler.

*There are pros and cons of using it.

*You can't rely on this behavior but you must be aware it exists. When you call your Lambda function several times, you MIGHT get the same container to optimise run duration and setup delay Use of Global Variables

*At the same time you should be aware of the issues or avoid wrong use of it caching issues

*If you don't want to use ElastiCache/redis then i guess you have very less options left.......may be dynamoDB or S3 that's all i can think of
again connection to dynamoDB or S3 can be cached here. It won't be as fast as ElastiCache though.

A: In Java it's not too hard to do.  Just create your cache outside of the handler:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.amazonaws.services.lambda.runtime.RequestStreamHandler;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class SampleHandler implements RequestStreamHandler {
    private static final Logger logger = LogManager.getLogger(SampleHandler.class);

    private static Map<String, String> theCache = null;

    public SampleHandler() {
        logger.info( "filling cache...");

        theCache = new HashMap<>();

        theCache.put("key1", "value1");
        theCache.put("key2", "value2");
        theCache.put("key3", "value3");
        theCache.put("key4", "value4");
        theCache.put("key5", "value5");
    }

    public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) throws IOException {
        logger.info("handlingRequest");
        LambdaLogger lambdaLogger = context.getLogger();

        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(inputStream);

        String requestedKey = jsonNode.get("requestedKey").asText();

        if( theCache.containsKey( requestedKey )) {
            // read from the cache
            String result = "{\"requestedValue\": \"" + theCache.get(requestedKey) + "\"}";

            outputStream.write(result.getBytes());
        }

       logger.info("done with run, remaining time in ms is " + context.getRemainingTimeInMillis() );
    }
}

(run with the AWS cli with aws lambda invoke --function-name lambda-cache-test --payload '{"requestedKey":"key4"}' out with the output going the the file out)
When this runs with a "cold start" you'll see the "filling cache..." message and then the "handlingRequest" in the CloudWatch log.  As long as the Lambda is kept "warm" you will not see the cache message again.
Note that if you had hundreds of the same Lamda's running they would all have their own independent cache.  Ultimately this does what you want though - it's a lazy load of the cache during a cold start and the cache is reused for warm calls.


Q: How to get the list of all children in Firebase android? I have this model below in Firebase

I am trying to get all the values from child node posts using below code
  databasePostsReference =
  FirebaseDatabase.getInstance().getReference().child("posts");

 final List<UserPostPOJO> list = Collections.EMPTY_LIST;

  databasePostsReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot snapshot : dataSnapshot.getChildren()){
                Log.d(TAG, "onDataChange: entered list adding");
                UserPostPOJO post = snapshot.getValue(UserPostPOJO.class);
                list.add(post);
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

but I am getting error java.lang.UnsupportedOperationException.
in the above scenario i know that error is because list is declared final and i am trying to assign value in onDataChangeMethod so is throwing error but if i am not declaring the list variable final then i cant access list variable from within the onDataChange() method how to solve this
  public class UserPostPOJO {
    String uid;
    Double elevation;
    String uri;
    String feel;

    public UserPostPOJO() {
    }

    public UserPostPOJO(String uid, Double elevation, String uri, String feel) {
        this.uid = uid;
        this.elevation = elevation;
        this.uri = uri;
        this.feel = feel;
    }

    public String getUid() {
        return uid;
    }

    public void setUid(String uid) {
        this.uid = uid;
    }

    public Double getElevation() {
        return elevation;
    }

    public void setElevation(Double elevation) {
        this.elevation = elevation;
    }

    public String getUri() {
        return uri;
    }

    public void setUri(String uri) {
        this.uri = uri;
    }

    public String getFeel() {
        return feel;
    }

    public void setFeel(String feel) {
        this.feel = feel;
    }
    }

Error Log:
  05-08 22:19:49.706 6421-6421/redeyes17.com.abhi.android.iamat
    D/recentfragment: onDataChange: entered list adding
   05-08 22:19:49.726 6421-6421/redeyes17.com.abhi.android.iamat
    E/AndroidRuntime: FATAL EXCEPTION: main

   Process: redeyes17.com.abhi.android.iamat, PID: 6421

   java.lang.UnsupportedOperationException

   at java.util.AbstractList.add(AbstractList.java:404)

   at java.util.AbstractList.add(AbstractList.java:425)

   at redeyes17.com.abhi.android.iamat.UI.tabs
  .RecentFragment$1.onDataChange(RecentFragment.java:78)

  at com.google.android.gms.internal.zzbpx.zza(Unknown Source)

  at com.google.android.gms.internal.zzbqx.zzZT(Unknown Source)

  at com.google.android.gms.internal.zzbra$1.run(Unknown Source)

   at android.os.Handler.handleCallback(Handler.java:739)

  at android.os.Handler.dispatchMessage(Handler.java:95)

  at android.os.Looper.loop(Looper.java:158)

  at android.app.ActivityThread.main(ActivityThread.java:7230)

  at java.lang.reflect.Method.invoke(Native Method)

 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller
 .run(ZygoteInit.java:1230)

 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

A: To get all those values please use this code:
    databasePostsReference = FirebaseDatabase.getInstance().getReference().child("posts").child(postId);
    ValueEventListener eventListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
           List<UserPostPOJO> list = new ArrayList<>();

           String elevation = (String) dataSnapshot.child("elevation").getValue();
           String feel = (String) dataSnapshot.child("feel").getValue();
           String uid = (String) dataSnapshot.child("uid").getValue();
           String uri = (String) dataSnapshot.child("uri").getValue();

          UserPostPOJO userPostPOJO = new UserPostPOJO();
          userPostPOJO.setElevation(elevation);
          userPostPOJO.setFeel(feel);
          userPostPOJO.setUid(uid);
          userPostPOJO.setUri(uri);

          list.add(userPostPOJO);
    }

          @Override
          public void onCancelled(DatabaseError databaseError) {}
};
databasePostsReference.addListenerForSingleValueEvent(eventListener);

In which postId is the unique id generated by the push() method. And notice, that the declaration of your list must be inside the onDataChange() method, otherwise, you'll get null.
Hope it helps.


Q: Emulate mouse click when hitting a key I am trying to emulate left-mouse-down when Home key is down and left-mouse-up when Home key is released.
The reason behind that is my touchpad's buttons are terrible and I like to use the track-point (red nipple) with left mouse click for highlight (copy) text. Instead of using the touchpad's button I want to use the 'Home' key. I am able to emulate the mouse-down part but I don't know how to release the click when the 'Home' key is released.
Here is what I have so for. first I use the xbindkeys tool. I added this entry to the .xbindkeysrc:
"~/bin/mouse-click"
  m:0x0 + c:110

mouse-click is this bash script:
#!/bin/bash
xdotool mousedown 1

The problem is the click is never being released so I need to find a way to detect the release of the 'Home'. Here is the script I am trying to write. The comments describe what I am trying to do:
#!/bin/bash

# not sure how to do that:
exit if Home key is in a pressed state (to avoid more mousedown actions)

xdotool mousedown 1

# not sure how to do that: (if Home key is released, release the mouse click)
while xinput query-state <device name> | grep -Flq 'key[9]=up'
xdotool mouseup 1

So That's what I am trying to figure out:

*

*Query the state of 'Home' key (pressed or not).

*Listen to keyboard events and detect a release of 'Home' key.

If there are better approach to achieve that, I would love to hear about them.
Thanks!
Edit: the solution is one line:  xmodmap -e "keycode 115 = Pointer_Button2"
so now my Home key is doing left click and behave just as if I hit the mouse click and I can keep the key pressed and it highlights (copy) as expected.
I also mapped my End key to be middle click, so I can use it to paste:
xmodmap -e "keycode 110 = Pointer_Button1"

A: The solution is
xmodmap -e "keycode 115 = Pointer_Button2"

Now my Home key is doing left click and behaves just as if I hit the mouse click and I can keep the key pressed and it highlights (copies) as expected.
I also mapped my End key to be middle click, so I can use it to paste:
xmodmap -e "keycode 110 = Pointer_Button1"

Note that it is necessary to have "mousekeys" (mouse emulation using the numeric keypad) enabled for this to work. "mousekeys" can be toggled by pressing Shift+NumLock or set explicitly by running:
dconf write /org/gnome/desktop/a11y/keyboard/mousekeys-enable true
dconf write /org/gnome/desktop/a11y/keyboard/mousekeys-enable false

A: Most desktops have some accessibility settings that will control the mouse with the keyboard already built-in, like XFCE has them in it's All Settings -> Accessibility -> Mouse -> Mouse Emulation, that uses the keyboard number pad so the 5 key does exactly what you're trying to do.
If I recall, gnome, cinnamon and mate have similar features under something like "Accessibility" or assistive technology, etc. Or an installable program/package like mousetweaks ("mouse accessibility enhancements for the GNOME desktop") or keynav (but I couldn't get it to work on xfce).
Or, if your touchpad still works ok (just not the buttons) you could just do a tap for a single click, a tap & then hold for a click & drag, a double-tap = double click... and if they don't work there should be a line or two in the terminal that should get those to work (don't remember them offhand now). I wouldn't want to write my own script when there are a few other options that should work

A: You should use for that an auto clicker program that emulate and automate your mouse clicks (left mouse button in your case).
I recommend for you to use Max Auto Clicker that is available for Ubuntu Linux and other debian like distros.
Available packages format: .deb, .AppImage, .zip


Q: Using an varray type in a select statement I am trying to use an varray-type in a select statement:
CREATE OR REPLACE PROCEDURE ARRAYTEST IS
  type array_t is varray(2) of int;
  array_test array_t := array_t(10,11);
BEGIN
  select * from STATISTIK where abschluss1 in array_test;
END;

But it is giving me an error:
PLS-00428: an INTO clause is expected in this SELECT statement
PLS-00642: local collection types not allowed in SQL statement

The first Exception seems to be misleading, I don't want to select something into a variable I want an aquivalent of:
select * from STATISTIK where abschluss1 in (10,12);

But (10,12) substituted by an array (varray).
Is it possible to convert the varray to be used in a select-statement?

A: It is possible but your type must be global
create type array_t is varray(2) of int;

Then use array as a table (open p for only for compiling)
 declare
    array_test array_t := array_t(10,11);
p sys_refcursor;
    begin
open p for
       select * from STATISTIK where abschluss1 in (select column_value from table(array_test ));
    end;


Q: html5 validate form with required="true" and custom check What I'm looking for: way to have innate html 5 form validation using the required="true", where if the user clicks the "Submit" button, the first thing that happens is the automatic html 5 validation where it checks to see if "username" is provided by the user.  If it's not, then it displays the ugly error bubble.
If it is provided, however, I then have my own custom validation for checking against the db if the username exists.  If it does, then return true (allow submission), false otherwise.  What's happening: the form is getting submitted.  It's like it does not wait for the success callback to return true/false on whether or not it should be submitted.
I hope that's clear enough!  Code below:
html:
<form>
<input type="text" required="true" id="username" />
<button type="submit">Submit</button>
</form>

js:
$("form").submit(function() {
  $.ajax({
      url: 'usernamechecker.php?username=' + $("#username").val(),
      success: function(resp) {
        if (!resp.UsernameExists) {
          return true; // allow form submission
        }
        return false; // do not allow form submission
      }
    });
});

A: You can't return a value through a callback like that. The callback for "success" won't run until the "ajax" call has completed, long after the "submit" handler has already returned.
Instead of that, I'd just do the submit and let it return with an error if there are server-side issues (like "username in use" or whatever).  There's no point making two round-trips. If there are no problems, it can just complete the operation and return whatever results page you want.

A: You need to add "async: false" as a parameter to your ajax call in order to force the call to finish before continuing on with the rest of the code.
$("form").submit(function(event) {
  $.ajax({
      async: false,
      url: 'usernamechecker.php?username=' + $("#username").val(),
      timeout: 1000,
      success: function(resp) {
        if (resp.UsernameExists) {
          event.preventDefault(); // do not allow form submission
        },
      error: function() {
          //fall back code when there's an error or timeout
      },
    });
});


Q: Firebase Google Analytics Console weird behavior. Events are logged but don't show up on User Snapshot I'm using Firebase Analytics and I'm still exploring the Google Analytics Console.
I think there's something wrong with my data, or the way I'm logging it. I have a Single Page App built with React + Firebase.
Since my app is all client side routes, for every page that it renders, I'm firing the following effect to log the screen_view event:
useEffect(() => {
  firebase.analytics().logEvent("screen_view", {
    screen_name: window.location.pathname,
    page_title: "My Page Title"
  });
},[firebase]);

So far, so good. It runs without any errors, and it seems to be logging the event (or at least, I can see the events in some parts of the console).
Here is the test I did that came back with weird results.
Note: I'm monitoring through the Realtime tab over on Google Analytics Console.

I accessed my website, and click on 5 different links. After each page loaded, the screen_view event was fired and I could see this number for total events going from 20 to 25. I.e: my effects were fired and my events were logged!

When you click on "Trending" you open up a window with the count per event type in the last minutes, and I could see the screen_view events going from 12 to 17, which is all correct, so far.

But since this is a new website and I'm currently the only user, I was able to click on "View user snapshot" and see my own activity in the report, and it's supposed to be in real time.

But the weird thing is that my screen_view events don't show up in the snapshot AT ALL. Not on real time and it's not a delay issue. They just don't appear in my user activity.

QUESTION
What is going on here? Am I doing something wrong? Weren't my events supposed to appear in my user's snapshot timeline on Real Time (or even with some delay)? This is getting really difficult to learn and test if I can't see the results of my code logged on screen.
Is there a better way to test this? I mean, I need to update my code and be able to see the changes in the events a user triggers.


Q: InverseSeries slower than it should be I am running into problems with InverseSeries taking far longer than it should. Given (for example)
$$F = q + a_2 q^2 + a_3 q^3 + \ldots + a_{99} q^{99} + O(q^{100}),$$
Computing the inverse series is an easy inductive procedure; you start with $h =q + O(q^2)$; then once you have computed $h = q + b_2 q^2 + \ldots b_{n-1} q^{n-1} + O(q^n)$ you write
$$F(q + \ldots + b_n q^n) = q  +  b_n q^n + (\text{some integer})q^n + O(q^{n+1})$$
and then you immediately solve for $b_n$. The most expensive part of this calculation is substituting a degree $d < 100$ polynomial into another degree $d < 100$ polynomial, which is annoying, but is something that mathematica can do quickly. But somehow whatever the code for InverseSeries does it freezes on examples that I can do faster "by hand", where  "by hand" means repeating the procedure above. What is going wrong, and how can it be fixed?
Here is an example which I can do manually in a few minutes but which Mathematica freezes on: (apologies I just cut and paste and I'm not sure of the correct formatting)
edit: In the original post, I wrote out the explicit form of $F$. As @CarlWoll pointed out, that seems to run in a second or two. So I modified it to give the example below. Here $F$ is first computed from scratch (this is exactly the same $F$ as before), mathematica now hangs --- hopefully others can reproduce this. This now now especially strange, since one could just output $F$ then quit then compute InverseSeries. (Computing $F$ only takes a few seconds.) end edit:
eta[q_] := q^(1/24) Product[(1 - q^n), {n, 1, 101}];
f := f = eta[q^3] eta[q^33]/(eta[q] eta[q^11]) + O[q]^101;
F := F = 1/((-11 + (1 + 3*f)^2*(1/f + 1 + 3*f)));
InverseSeries[F]

A: You are computing way too many series terms with eta[]. Here is my slightly modified code:
eta[k_] := q^(k/24) Product[1-q^n, {n,k,101,k}];
f = eta[3]eta[33]/(eta[1]eta[11]) + O[q]^101;
F = 1/((-11 + (1 + 3*f)^2*(1/f + 1 + 3*f)));
InverseSeries[F]

It should have much better performance than yours.


Q: Electron (Windows) How does manual distribution work? I am trying to follow the instructions on this page: https://electronjs.org/docs/tutorial/application-distribution#manual-distribution however it is very vague and unclear.
I am trying to build an app that is simply an index.html with some static assets (JS, CSS, images.) There are no calls to server-side APIs from the client side.
The docs say to use this layout:
electron/resources/app
- package.json
- main.js
- index.html

But it's not working for me.
What is main.js? I assume this is the electron script that should create the main browser window and set the url to my local index.html, not something that is run within the webview window.
Why does it say index.html has to be there? I would think the URL to index.html is specified in main.js? (I have all client assets in a "public" folder.)
Why does it need a package.json? I have no scripts and don't use any additional npm modules.
I have tried a number of layouts but all that happens when I double-click electron.exe is that it exits immediately without any errors. From what I can tell it never executes my main.js script.
I can't find any additional resources on setting up a simple manual distribution.

A: I got it working after expanding the default_app.asar distributed with the Electron build. The instructions on the page linked above neglected to mention that the package.json should contain something like:
{
  "name": "electron",
  "productName": "Electron",
  "main": "main.js"
}

The only file that needs to be in resources/app is the package.json file. You can set main to the location of your your app's entry point script and you can put any other files wherever you want.


Q: What access modifier to use Suppose I have a base class:
public class A {
    public float someValue;

    <Access Modifier Here> float SomeValue {
        get {
            return someValue;
        }
    }
}

And I want to derive from it:
public class B : A {
    public float SomeProperty {
        get {
            return SomeValue;
        }
    }
}

What access modifier would I use if I want to make the SomeValue property only available to the deriving class and not anywhere else?

A: for only derived classes.. use protected
Protected means that access is limited to the containing class or types derived from the containing class.


Q: How to set hard coded HTML in UWP WebView I have some hard coded html:
string myHtml = "<html>some html</html>"

How can I set it as my WebView source? Something like this:
webView.HtmlSource = myHtml;

A: In general, we use WebView.NavigateToString(htmlstring); to load and display html string. For source of WebView, only apply for Uri parameters. But you can create an attached property like HtmlSource for WebView and when it changes to call NavigateToString to load.
public class MyWebViewExtention
{
    public static readonly DependencyProperty HtmlSourceProperty =
           DependencyProperty.RegisterAttached("HtmlSource", typeof(string), typeof(MyWebViewExtention), new PropertyMetadata("", OnHtmlSourceChanged));
    public static string GetHtmlSource(DependencyObject obj) { return (string)obj.GetValue(HtmlSourceProperty); }
    public static void SetHtmlSource(DependencyObject obj, string value) { obj.SetValue(HtmlSourceProperty, value); }
    private static void OnHtmlSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        WebView webView = d as WebView;
        if (webView != null)
        {
            webView.NavigateToString((string)e.NewValue);
        }
    }
 }

.xaml:
<WebView x:Name="webView" local:MyWebViewExtention.HtmlSource="{x:Bind myHtml,Mode=OneWay}"></WebView>

For more details, you can refer to Binding HTML to a WebView with Attached Properties.


Q: The type arguments for method cannot be inferred from the usage. (c#, lambda) Firstly, I am a complete beginner to advanced level programming. All I have done are tutorials to C++ found on the web. I'm facing this problem at work. I have seen similar queries but nothing has helped me understand.
Please note: I am terrible at terminologies like method, object, interface, etc. So I might have made a mistake somewhere further. I'm slowly learning.
Code Block 1:
public static class DummyClassName
{
    public static T DummyTemplateFunc<T>(DummyInterfaceName aaa1, Func<T> action)
    {
        T DummyVal = action();
        // blah blah code
        // blah blah code

        return val;
    }
}

Code Block 2:
public class ClassName2 : blah1 , blah2, blah3
{
    public void Method1(string DummyString)
     {
         DummyClassName.DummyTemplateFunc(_aaa1, ()=>Function1(_arg1, arg2));
     }
}

I'll try to explain what's happening to the best of my ability. The second bit of code is used over and over in the program with different Functions (or methods?) in place of Function1. (These functions come from a C++ program linked with this one. I don't know how)
If these functions are of any return type EXCEPT void, the program runs fine.
If a void-return-type function is used, I get the error
"The type arguments for method '****.****.DummyClassName.DummyTemplateName<T>
(****.****.DummyInterfaceName, System.Func<T>)' cannot be inferred from the usage.
Try specifying the type arguments explicitly.'

From what I understand, this is because when a void function is passed it takes the place of T in the first block of code and tries returning 'val'. That's why an error is thrown.
Can somebody help me find a workaround to this? I don't mind defining a completely different class/method specifically to handle void functions. I know which functions are of return type void.

A: Create another overload, taking Action instead of Func<T>:
public static class DummyClassName
{
    public static void DummyTemplateFunc(DummyInterfaceName aaa1, Action action)
    {
        // you cannot assign result to variable, because it returns void
        action();

        // I also changed method to return void, so you can't return anything
        // return something;

        // ofc you can make it return something instead
    }
}


Q: Retain Cycle in Class Causing Potential Memory Leak So using the graph debugger tool and instruments I have noticed that there is a memory leak in my app. After many hours I have or the graph debugger has tracked it down to this function.
override func didUpdate(to object: Any) {
    comment = object as? CommentGrabbed
}

Which is contained in this bigger class
import UIKit
import IGListKit
import Foundation
import Firebase

protocol CommentsSectionDelegate: class {
    func CommentSectionUpdared(sectionController: CommentsSectionController)
}
class CommentsSectionController: ListSectionController,CommentCellDelegate {
    weak var delegate: CommentsSectionDelegate? = nil
   weak var comment: CommentGrabbed?
    let userProfileController = ProfileeViewController(collectionViewLayout: UICollectionViewFlowLayout())
    var eventKey: String?
    var dummyCell: CommentCell?
    override init() {
        super.init()
        // supplementaryViewSource = self
        //sets the spacing between items in a specfic section controller
        inset = UIEdgeInsets(top: 5, left: 0, bottom: 0, right: 0)
    }
    // MARK: IGListSectionController Overrides
    override func numberOfItems() -> Int {
        return 1
    }
    override func sizeForItem(at index: Int) -> CGSize {
        let frame = CGRect(x: 0, y: 0, width: collectionContext!.containerSize.width, height: 50)
        dummyCell = CommentCell(frame: frame)
        dummyCell?.comment = comment
        dummyCell?.layoutIfNeeded()
        let targetSize =  CGSize(width: collectionContext!.containerSize.width, height: 55)
        let estimatedSize = dummyCell?.systemLayoutSizeFitting(targetSize)
        let height = max(40+8+8, (estimatedSize?.height)!)
        return  CGSize(width: collectionContext!.containerSize.width, height: height)

    }

    override var minimumLineSpacing: CGFloat {
        get {
            return 0.0
        }
        set {
            self.minimumLineSpacing = 0.0
        }
    }

    override func cellForItem(at index: Int) -> UICollectionViewCell {
        guard let cell = collectionContext?.dequeueReusableCell(of: CommentCell.self, for: self, at: index) as? CommentCell else {
            fatalError()
        }
        //  print(comment)
        cell.comment = comment
        cell.delegate = self
        return cell
    }
    override func didUpdate(to object: Any) {
        comment = object as? CommentGrabbed
    }
    override func didSelectItem(at index: Int){
    }

    func optionsButtonTapped(cell: CommentCell){
        print("like")

        let comment = self.comment
        _ = comment?.uid

        // 3
        let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)

        // 4
        if comment?.uid != User.current.uid {
            let flagAction = UIAlertAction(title: "Report as Inappropriate", style: .default) { _ in
                ChatService.flag(comment!)

                let okAlert = UIAlertController(title: nil, message: "The post has been flagged.", preferredStyle: .alert)
                okAlert.addAction(UIAlertAction(title: "Ok", style: .default))
                self.viewController?.present(okAlert, animated: true, completion: nil)
            }
            let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
            let replyAction = UIAlertAction(title: "Reply to Comment", style: .default, handler: { (_) in
                //do something here later to facilitate reply comment functionality
                print("Attempting to reply to user \(comment?.user.username) comment")

            })
            alertController.addAction(replyAction)
            alertController.addAction(cancelAction)
            alertController.addAction(flagAction)
        }else{
            let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
            let deleteAction = UIAlertAction(title: "Delete Comment", style: .default, handler: { _ in
                ChatService.deleteComment(comment!, (comment?.eventKey)!)
                let okAlert = UIAlertController(title: nil, message: "Comment Has Been Deleted", preferredStyle: .alert)
                okAlert.addAction(UIAlertAction(title: "Ok", style: .default))
                self.viewController?.present(okAlert, animated: true, completion: nil)
                self.onItemDeleted()

            })
            alertController.addAction(cancelAction)
            alertController.addAction(deleteAction)

        }
        self.viewController?.present(alertController, animated: true, completion: nil)

    }
    func onItemDeleted() {
        delegate?.CommentSectionUpdared(sectionController: self)
    }
    func handleProfileTransition(tapGesture: UITapGestureRecognizer){
        userProfileController.user = comment?.user
        if Auth.auth().currentUser?.uid != comment?.uid{
                    self.viewController?.present(userProfileController, animated: true, completion: nil)
        }else{
            //do nothing

        }

    }

    deinit {
        print("CommentSectionController class removed from memory")
    }

}

The CommentGrabbed class looks like this
import Foundation
import  IGListKit

class CommentGrabbed {
    let content: String
    let uid: String
    let user: User
    let creationDate: Date
    var commentID: String? = ""
    let eventKey:String

    init(user: User, dictionary: [String:Any]) {
        self.content = dictionary["content"] as? String ?? ""
        self.uid = dictionary["uid"] as? String ?? ""
        self.eventKey = dictionary["eventKey"] as? String ?? ""
        self.user = user
        let secondsFrom1970 = dictionary["timestamp"] as? Double ?? 0
        self.creationDate = Date(timeIntervalSince1970: secondsFrom1970)
    }

}

extension CommentGrabbed: Equatable{
    static public func  ==(rhs: CommentGrabbed, lhs: CommentGrabbed) ->Bool{
        return rhs.commentID == lhs.commentID
    }
}

extension CommentGrabbed: ListDiffable{
    public func diffIdentifier() -> NSObjectProtocol {
        return commentID! as NSObjectProtocol
    }
    public func isEqual(toDiffableObject object: ListDiffable?) ->Bool{
        guard let object = object as? CommentGrabbed else {
            return false
        }
        return  self.commentID==object.commentID
    }
}

Are there any retain cycles being created here that I don't noice?
This controller is ultimately in control of displaying all the comments and it has a UserService method which works through this code base
static func show(forUID uid: String, completion: @escaping (User?) -> Void) {
    let ref = Database.database().reference().child("users").child(uid)
    ref.observeSingleEvent(of: .value, with: { (snapshot) in
        guard let user = User(snapshot: snapshot) else {
            return completion(nil)

        }

        completion(user)
    })
}

The User model object looks like this
import Foundation
import FirebaseDatabase.FIRDataSnapshot

class User : NSObject {
    //User variables
    let uid : String
    let username : String?
    let profilePic: String?
    var isFollowed = false
    var dictValue: [String : Any] {
        return ["username" : username as Any,
                "profilePic" : profilePic as Any]
    }
    //Standard User init()
    init(uid: String, username: String, profilePic: String) {
        self.uid = uid
        self.username = username
        self.profilePic = profilePic
        super.init()
    }
    //User init using Firebase snapshots
    init?(snapshot: DataSnapshot) {
        guard let dict = snapshot.value as? [String : Any],
            let username = dict["username"] as? String,
            let profilePic = dict["profilePic"] as? String
            else { return nil }
        self.uid = snapshot.key
        self.username = username
        self.profilePic = profilePic
    }
    //UserDefaults
    required init?(coder aDecoder: NSCoder) {
        guard let uid = aDecoder.decodeObject(forKey: "uid") as? String,
            let username = aDecoder.decodeObject(forKey: "username") as? String,
            let profilePic = aDecoder.decodeObject(forKey: "profilePic") as? String            else { return nil }
        self.uid = uid
        self.username = username
        self.profilePic = profilePic
        super.init()
    }
    init?(key: String, postDictionary: [String : Any]) {
        //var dict : [String : Any]
        //print(postDictionary as? [String:])
        let dict = postDictionary
        //print(dict)
        let profilePic = dict["profilePic"] as? String ?? ""
        let username = dict["username"] as? String ?? ""
        self.uid = key
        self.profilePic = profilePic
        self.username = username
    }
    //User singleton for currently logged user
    private static var _current: User?
    static var current: User {
        guard let currentUser = _current else {
            fatalError("Error: current user doesn't exist")
        }
        return currentUser
    }

    class func setCurrent(_ user: User, writeToUserDefaults: Bool = true) {
        //print(user)
       // print("")
        if writeToUserDefaults {
            let data = NSKeyedArchiver.archivedData(withRootObject: user)

            UserDefaults.standard.set(data, forKey: "currentUser")
            UserDefaults.standard.synchronize()
        }
        _current = user
        //print(_current ?? "")
    }
}

extension User: NSCoding {
    func encode(with aCoder: NSCoder) {
        aCoder.encode(uid, forKey: "uid")
        aCoder.encode(username, forKey: "username")
        aCoder.encode(profilePic, forKey: "profilePic")
    }
}

When I change user in commentGrabbed class to weak my code begins to crash if it has to deal with anything related to a user like so
 weak var comment: CommentGrabbed?{
        didSet{
            guard let comment = comment else{
                return
            }
          //  print("apples")
            // textLabel.text = comment.content
            //shawn was also here
            profileImageView.loadImage(urlString: (comment.user?.profilePic!)!)
            //  print(comment.user.username)
            let attributedText = NSMutableAttributedString(string: (comment.user?.username!)!, attributes: [NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 14)])

            attributedText.append(NSAttributedString(string: " " + (comment.content), attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 14)]))

            attributedText.append(NSAttributedString(string: "\n\n", attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 4)]))
            let timeAgoDisplay = comment.creationDate.timeAgoDisplay()
            attributedText.append(NSAttributedString(string: timeAgoDisplay, attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 12), NSAttributedStringKey.foregroundColor: UIColor.gray]))

            textView.attributedText = attributedText

        }
    }

Code block where commentGrabbed is init
 UserService.show(forUID: uid, completion: { [weak self](user) in
                    if let user = user {
                        let commentFetched = CommentGrabbed(user: user, dictionary: commentDictionary)
                        commentFetched.commentID = snapshot.key
                        let filteredArr = self?.comments.filter { (comment) -> Bool in
                            return comment.commentID == commentFetched.commentID
                        }
                        if filteredArr?.count == 0 {
                            self?.comments.append(commentFetched)

                        }
                        self?.adapter.performUpdates(animated: true)
                    }else{
                        print("user is null")

                    }
                    self?.comments.sort(by: { (comment1, comment2) -> Bool in
                        return comment1.creationDate.compare(comment2.creationDate) == .orderedAscending
                    })
                    self?.comments.forEach({ (comments) in
                    })
                })

            })

This is what I see in debugger tool. If I comment out that line nothing loads btw for those who are wondering why not just comment it out

Code for CommentCell as requested
import Foundation
import UIKit
import Firebase

protocol CommentCellDelegate: class {
    func optionsButtonTapped(cell: CommentCell)
    func handleProfileTransition(tapGesture: UITapGestureRecognizer)
}
class CommentCell: UICollectionViewCell {
    weak var delegate: CommentCellDelegate? = nil
    override var reuseIdentifier : String {
        get {
            return "cellID"
        }
        set {
            // nothing, because only red is allowed
        }
    }
    var didTapOptionsButtonForCell: ((CommentCell) -> Void)?

    weak var comment: CommentGrabbed?{
        didSet{
            guard let comment = comment else{
                return
            }
          //  print("apples")
            // textLabel.text = comment.content
            //shawn was also here
            profileImageView.loadImage(urlString: (comment.user?.profilePic!)!)
            //  print(comment.user.username)
            let attributedText = NSMutableAttributedString(string: (comment.user?.username!)!, attributes: [NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 14)])

            attributedText.append(NSAttributedString(string: " " + (comment.content), attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 14)]))

            attributedText.append(NSAttributedString(string: "\n\n", attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 4)]))
            let timeAgoDisplay = comment.creationDate.timeAgoDisplay()
            attributedText.append(NSAttributedString(string: timeAgoDisplay, attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 12), NSAttributedStringKey.foregroundColor: UIColor.gray]))

            textView.attributedText = attributedText

        }
    }

    lazy var textView: UITextView = {
        let textView = UITextView()
        textView.font = UIFont.systemFont(ofSize: 14)
        textView.isScrollEnabled = false
        textView.textContainer.maximumNumberOfLines = 0
        textView.textContainer.lineBreakMode = .byCharWrapping
        textView.isEditable = false
        return textView
    }()

    lazy var profileImageView: CustomImageView = {
        let iv = CustomImageView()
        iv.clipsToBounds = true
        iv.isUserInteractionEnabled = true
        iv.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleProfileTransition)))
        iv.contentMode = .scaleAspectFill
        return iv
    }()

    lazy var flagButton: UIButton = {
        let flagButton = UIButton(type: .system)
        flagButton.setImage(#imageLiteral(resourceName: "icons8-Info-64"), for: .normal)
        flagButton.addTarget(self, action: #selector(optionsButtonTapped), for: .touchUpInside)
        return flagButton
    }()

    @objc func optionsButtonTapped (){
        didTapOptionsButtonForCell?(self)
    }

    @objc func onOptionsTapped() {
        delegate?.optionsButtonTapped(cell: self)
    }
    @objc func handleProfileTransition(tapGesture: UITapGestureRecognizer){
        delegate?.handleProfileTransition(tapGesture: tapGesture)
      //  print("Tapped image")
    }

    override init(frame: CGRect){
        super.init(frame: frame)
        addSubview(textView)
        addSubview(profileImageView)
        addSubview(flagButton)
        textView.anchor(top: topAnchor, left: profileImageView.rightAnchor, bottom: bottomAnchor, right: flagButton.leftAnchor, paddingTop: 4, paddingLeft: 4, paddingBottom: 4, paddingRight: 4, width: 0, height: 0)
        profileImageView.anchor(top: topAnchor, left: leftAnchor, bottom: nil, right: nil, paddingTop: 8, paddingLeft: 8, paddingBottom: 0, paddingRight: 0, width: 40, height: 40)
        profileImageView.layer.cornerRadius = 40/2
        flagButton.anchor(top: topAnchor, left: nil, bottom: nil, right: rightAnchor, paddingTop: 4, paddingLeft: 0, paddingBottom: 0, paddingRight: 4, width: 40, height: 40)
        flagButton.addTarget(self, action: #selector(CommentCell.onOptionsTapped), for: .touchUpInside)

    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

sizeForItem
override func sizeForItem(at index: Int) -> CGSize {
    let frame = CGRect(x: 0, y: 0, width: collectionContext!.containerSize.width, height: 50)
      weak var dummyCell = CommentCell(frame: frame)
    dummyCell?.comment = comment
    dummyCell?.layoutIfNeeded()
    let targetSize =  CGSize(width: collectionContext!.containerSize.width, height: 55)
    let estimatedSize = dummyCell?.systemLayoutSizeFitting(targetSize)
    let height = max(40+8+8, (estimatedSize?.height)!)
    return  CGSize(width: collectionContext!.containerSize.width, height: height)

}


Q: Still having Java install problems Please review my script, all I want to do is check to see if a particular Java Verison is installed (latest version) if it is not installed, then to go to the install command...
Having problems with the For /F command though.
PLease see what I have so far:
@echo On
setlocal ENABLEEXTENSIONS
set KEY_NAME="HKLM\SOFTWARE\JavaSoft\Java Runtime Environment"
set VALUE_NAME="BrowserJavaVersion"

FOR /F "usebackq skip=1 tokens=3" %%A IN (`REG QUERY %KEY_NAME% /v %VALUE_NAME% 2^>nul`) DO (
set ValueValue=%%A
)
if defined ValueValue (
@echo the current Java runtime is %ValueValue%
) else (
@echo %KEY_NAME%\%VALUE_NAME% not found

This is the key I am trying to interrogate from within the Windows Registry (BrowserJavaVersion):
!http://i393.photobucket.com/albums/pp11/Mikoyan_2008/Screenshot.jpg
If the version doesnt match latest Java version to then:
if "%ValueValue%"=="Latest Java Version" ( goto eof ) ELSE ( goto Install )
Can anyone please provide assistance?


Q: How to trace where Xcode program crash I'm getting an error in debugger. In Thread my app crash on line:
0x37265f78:  ldr    r3, [r4, #8]

with:
Thread 1: EXC_BAD_ACCESS (code=1, address=0x50000008)

How to find out where app actually crash? There is a something like "call stack"?

A: http://www.raywenderlich.com/10209/my-app-crashed-now-what-part-1
Best tutorial for trace the error.

A: Run your app under the debugger, then when your app crashes you will have access to the call stack.
Furthermore, if you display the console window, you will get more textual information (including a call stack) at the moment of the crash.
If you are using Xcode 4, have a look at the attached picture.

A: You have to set Exception Breakpoint
Go to the Breakpoints navigator, click the + button at the bottom, and add an Exception Breakpoint.
Now you will know the exact line where any of your exception will occur (e.g. line of crash). best of luck!!


Q: admob impressions is half then request please guide what is the issue also rewarded ads not showing with real id in test is it works Hello I am working with admob but i dont know in my account their is no ads limit but still number of impressions is less then request

Please help me out what is issue why i am getting impressions less then request
second question is in my app rewarded ads are not loading i dont know why in test it works fine but when i put live id its not work and didnot shows ads


Q: Avoid changing the background of Status Bar on iOS in Ionic I'm doing a mobile app using Ionic 6.1.4 and Capacitor 3.5.1.
Android, looks good by default, black background and white icons on any screen.

iOS, always has whatever the background color I have in the ion-content with black icons. Is always like this on any screen. In my app, I have 2 screens with a dark background and the ion-content with the attribute fullscreen.

iOS, as I said, I have two screen with a very dark background, let's replicate it using a black background. See how the icons are not visible anymore?

Component:
<ion-header class="ion-no-border">
  <ion-toolbar>
    <ion-buttons slot="start">
      <ion-menu-button color="white"></ion-menu-button>
    </ion-buttons>
  </ion-toolbar>
</ion-header>

<ion-content [fullscreen]="true">
</ion-content>

Style:
ion-toolbar {
  --background: transparent;
}

ion-content {
  --background: black;
}

How can I change iOS Status Bar to always have a style just like Android?
or even better, how can I leave the Status Bar untouched on iOS (app not modifying the Status Bar at all)?
I have tried:
.ios {

  ion-header {
    margin-top: var(--ion-safe-area-top);
  }

  ion-toolbar {
    margin-top: var(--ion-safe-area-top);
    --padding-top: var(--ion-safe-area-top);
    padding-top: var(--ion-safe-area-top);
  }

}

But this just moves all the content down and Status Bar is keeping the background color of my app.
I was thinking to use the plugin called @capacitor/status-bar to change the Status Bar style just on iOS, but it's not so simple in my case. Since I have 2 screens with dark background, I will need to make the Status Bar Dark when enter, and when onDestroy is called, make it back to Light so my other screens which have white background looks good too. I think this is a tedious process. I think there must be a way to avoid this.
My goal is to keep the Status Bar on iOS always the same and with a color that makes the icons visible. I would prefer leaving the Status Bar untouched just like Android do.

A: Well, I suggest trying one of the followings:

*

*If you are using Cordova, use the cordova-status-bar plugin and try setting the statusBar color in the config.xml:

<preference name="StatusBarBackgroundColor" value="#000000" />
    or
<preference name="StatusBarBackgroundColor" value="#ffffff" />

setting it to a value in hex color, probably you want it black, and then setting the text and icons to light or lightcontent as you did in Android by using:

<preference name="StatusBarStyle" value="lightcontent" />

*If you are using Capacitor, install the Capacitor plugin

npm install @capacitor/status-bar
npx cap sync

and then set the color of the background and text using
import { StatusBar, Style } from '@capacitor/status-bar';

// iOS only
window.addEventListener('statusTap', function () {
  console.log('statusbar tapped');
});

const setStatusBarStyleDark = async () => {
  await StatusBar.setStyle({ style: Style.Dark });
};

*Finally, if none of that works, or you just want to change it on iOS try setting it in the global.scss as you were doing but also changing the backgound color and the color:

.ios {
  ion-header {
    margin-top: var(--ion-safe-area-top);
    background-color: black;
    color: white;
  }

  ion-toolbar {
    margin-top: var(--ion-safe-area-top);
    --padding-top: var(--ion-safe-area-top);
    padding-top: var(--ion-safe-area-top);
    background-color: black;
    color: white;
  }
}

A: I don't know about Capacitor, but I know that on Cordova for iOS, you need to include viewport-fit=cover in the <meta name="viewport" content="..."> tag of your index.html to do this, e.g.
<meta name="viewport" content="initial-scale=1, width=device-width, viewport-fit=cover">

This works for me when using the cordova-plugin-statusbar plugin, anyway.


Q: Qt creator - The process "/usr/bin/make" exited with code 2 default project I installed QT Creator 4.0 on OS X 10.11, when I try to build any project template I get the following: Error output screenshot.
Any idea what causes this issue? Thank you!