text:
Q: How do I connect a Mixer with an AUGraph I want to create an AUGraph that has the following AudioUnits:

*

*1 * 440HZ sine wave generator

*1 * 880HZ sine wave generator

*1 * Mixer

*1 * Output

If I connect my sine wave generators to my mixer, then the mixer to the output I get no sound.
If I connect a sine wave generator directly to the output I do get sound, probably because the Output unit connects to the sine wave generator callback.
Is there something I'm missing with how this should be connected?
Full code sample, Connect 1 * Joins 1 is not working, comment these out and run Connect 2 and Joins 2 to hear the sine wave working
    //
//  main.c
//  TestAudioUnit
//
//  Created by Chris Davis on 25/08/2013.
//  Copyright (c) 2013 Chris Davis. All rights reserved.
//

#include <CoreFoundation/CoreFoundation.h>
#import <AudioToolbox/AudioToolbox.h>

typedef struct MyAUGraphPlayer
{
    AudioStreamBasicDescription streamFormat;

    AUGraph graph;
    AUNode output;
    AUNode mixer;
    AUNode sine;
    AudioUnit audioUnits[3];

    AudioBufferList *inputBuffer;

    Float64 firstInputSampleTime;
    Float64 firstOutputSampleTime;
    Float64 inToOutSampleTimeOffset;
} MyAUGraphPlayer;

OSStatus SineWaveRenderCallback(void * inRefCon,
                                AudioUnitRenderActionFlags * ioActionFlags,
                                const AudioTimeStamp * inTimeStamp,
                                UInt32 inBusNumber,
                                UInt32 inNumberFrames,
                                AudioBufferList * ioData)
{
    // inRefCon is the context pointer we passed in earlier when setting the render callback
    double currentPhase = *((double *)inRefCon);
    // ioData is where we're supposed to put the audio samples we've created
    Float32 * outputBuffer = (Float32 *)ioData->mBuffers[0].mData;
    const double frequency = 880.0;
    const double phaseStep = (frequency / 44100.) * (M_PI * 2.);

    for(int i = 0; i < inNumberFrames; i++) {
        outputBuffer[i] = sin(currentPhase);
        currentPhase += phaseStep;
    }

    // If we were doing stereo (or more), this would copy our sine wave samples
    // to all of the remaining channels
    for(int i = 1; i < ioData->mNumberBuffers; i++) {
        memcpy(ioData->mBuffers[i].mData, outputBuffer, ioData->mBuffers[i].mDataByteSize);
    }

    // writing the current phase back to inRefCon so we can use it on the next call
    *((double *)inRefCon) = currentPhase;
    return noErr;
}

int main(int argc, const char * argv[])
{

    MyAUGraphPlayer *player = {0};
    MyAUGraphPlayer p = {0};
    player=&p;

    NewAUGraph(&player->graph);

    //Output
    {
    AudioComponentDescription description = {
        .componentType = kAudioUnitType_Output,
        .componentSubType = kAudioUnitSubType_DefaultOutput,
        .componentManufacturer = kAudioUnitManufacturer_Apple
    };
    AUGraphAddNode(player->graph, &description, &player->output);
    AudioComponent comp = AudioComponentFindNext(NULL, &description);
    AudioComponentInstanceNew(comp, &player->audioUnits[0]);
    AudioUnitInitialize(player->audioUnits[0]);
    AudioStreamBasicDescription ASBD = {
        .mSampleRate       = 44100,
        .mFormatID         = kAudioFormatLinearPCM,
        .mFormatFlags      = kAudioFormatFlagsNativeFloatPacked,
        .mChannelsPerFrame = 1,
        .mFramesPerPacket  = 1,
        .mBitsPerChannel   = sizeof(Float32) * 8,
        .mBytesPerPacket   = sizeof(Float32),
        .mBytesPerFrame    = sizeof(Float32)
    };
    AudioUnitSetProperty(player->audioUnits[0],
                         kAudioUnitProperty_StreamFormat,
                         kAudioUnitScope_Global,
                         0,
                         &ASBD,
                         sizeof(ASBD));
    }

    //Mixer
    {
        AudioComponentDescription description = {
            .componentType = kAudioUnitType_Mixer,
            .componentSubType = kAudioUnitSubType_StereoMixer,
            .componentManufacturer = kAudioUnitManufacturer_Apple
        };
        AUGraphAddNode(player->graph, &description, &player->mixer);
        AudioComponent comp = AudioComponentFindNext(NULL, &description);
        AudioComponentInstanceNew(comp, &player->audioUnits[1]);
        AudioUnitInitialize(player->audioUnits[1]);

    }

    //Sine
    {
        AudioComponentDescription description = {
            .componentType = kAudioUnitType_Generator,
            .componentSubType = kAudioUnitSubType_ScheduledSoundPlayer,
            .componentManufacturer = kAudioUnitManufacturer_Apple
        };
        AUGraphAddNode(player->graph, &description, &player->sine);
        AudioComponent comp = AudioComponentFindNext(NULL, &description);
        AudioComponentInstanceNew(comp, &player->audioUnits[2]);
        AudioUnitInitialize(player->audioUnits[2]);

    }

    //Connect 1
    {
        AURenderCallbackStruct callbackInfo = {
            .inputProc       = SineWaveRenderCallback,
            .inputProcRefCon = player
        };

        AudioUnitSetProperty(player->audioUnits[1],
                                        kAudioUnitProperty_SetRenderCallback,
                                        kAudioUnitScope_Global,
                                        0,
                                        &callbackInfo,
                             sizeof(callbackInfo));

    }

    //Joins 1 - sine to mixer to outout
    {
        AUGraphConnectNodeInput(player->graph,
                                player->sine,
                                0,
                                player->mixer,
                                0);

        AUGraphConnectNodeInput(player->graph,
                                player->mixer,
                                0,
                                player->output,
                                0);

    }

    //connect 2
    /*{
        AURenderCallbackStruct callbackInfo = {
            .inputProc       = SineWaveRenderCallback,
            .inputProcRefCon = player
        };

        AudioUnitSetProperty(player->audioUnits[0],
                             kAudioUnitProperty_SetRenderCallback,
                             kAudioUnitScope_Global,
                             0,
                             &callbackInfo,
                             sizeof(callbackInfo));

    }

    //Joins 2 - sine direct to output
    {
        AUGraphConnectNodeInput(player->graph,
                                player->sine,
                                0,
                                player->output,
                                0);
    }*/

    AUGraphInitialize(player->graph);
    player->firstOutputSampleTime = -1;
    AudioOutputUnitStart(player->audioUnits[0]);
    AUGraphStart(player->graph);

    printf("enter key to stop\n");
    getchar();

    return 0;
}

A: This code correctly plays the sine wave, however, I get lots of errors from CoreAudio during setup:
    //
//  main.c
//  TestAudioUnit
//
//  Created by Chris Davis on 25/08/2013.
//  Copyright (c) 2013 Chris Davis. All rights reserved.
//

#include <CoreFoundation/CoreFoundation.h>
#import <AudioToolbox/AudioToolbox.h>

typedef struct MyAUGraphPlayer
{
    AudioStreamBasicDescription streamFormat;

    AUGraph graph;
    AUNode output;
    AUNode mixer;
    AUNode sine;
    AudioUnit audioUnits[3];

    AudioBufferList *inputBuffer;

    Float64 firstInputSampleTime;
    Float64 firstOutputSampleTime;
    Float64 inToOutSampleTimeOffset;
} MyAUGraphPlayer;

OSStatus SineWaveRenderCallback(void * inRefCon,
                                AudioUnitRenderActionFlags * ioActionFlags,
                                const AudioTimeStamp * inTimeStamp,
                                UInt32 inBusNumber,
                                UInt32 inNumberFrames,
                                AudioBufferList * ioData)
{
    // inRefCon is the context pointer we passed in earlier when setting the render callback
    double currentPhase = *((double *)inRefCon);
    // ioData is where we're supposed to put the audio samples we've created
    Float32 * outputBuffer = (Float32 *)ioData->mBuffers[0].mData;
    const double frequency = 880.0;
    const double phaseStep = (frequency / 44100.) * (M_PI * 2.);

    for(int i = 0; i < inNumberFrames; i++) {
        outputBuffer[i] = sin(currentPhase);
        currentPhase += phaseStep;
    }

    // If we were doing stereo (or more), this would copy our sine wave samples
    // to all of the remaining channels
    for(int i = 1; i < ioData->mNumberBuffers; i++) {
        memcpy(ioData->mBuffers[i].mData, outputBuffer, ioData->mBuffers[i].mDataByteSize);
    }

    // writing the current phase back to inRefCon so we can use it on the next call
    *((double *)inRefCon) = currentPhase;
    return noErr;
}

int main(int argc, const char * argv[])
{

    MyAUGraphPlayer *player = {0};
    MyAUGraphPlayer p = {0};
    player=&p;

    NewAUGraph(&player->graph);

    OSStatus result = 0;

    AudioStreamBasicDescription ASBD = {
        .mSampleRate       = 44100,
        .mFormatID         = kAudioFormatLinearPCM,
        .mFormatFlags      = kAudioFormatFlagsNativeFloatPacked,
        .mChannelsPerFrame = 2,
        .mFramesPerPacket  = 1,
        .mBitsPerChannel   = sizeof(Float32) * 8,
        .mBytesPerPacket   = sizeof(Float32),
        .mBytesPerFrame    = sizeof(Float32)
    };

    //Output
    {
        AudioComponentDescription description = {
            .componentType = kAudioUnitType_Output,
            .componentSubType = kAudioUnitSubType_DefaultOutput,
            .componentManufacturer = kAudioUnitManufacturer_Apple
        };
        result = AUGraphAddNode(player->graph, &description, &player->output);
        printf("err: %d\n", result);
        AudioComponent comp = AudioComponentFindNext(NULL, &description);
        result = AudioComponentInstanceNew(comp, &player->audioUnits[0]);
        printf("err: %d\n", result);
        result = AudioUnitInitialize(player->audioUnits[0]);
        printf("err: %d\n", result);

    }

    //Mixer
    {
        AudioComponentDescription description = {
            .componentType = kAudioUnitType_Mixer,
            .componentSubType = kAudioUnitSubType_StereoMixer,
            .componentManufacturer = kAudioUnitManufacturer_Apple
        };
        result = AUGraphAddNode(player->graph, &description, &player->mixer);
        printf("err: %d\n", result);
        AudioComponent comp = AudioComponentFindNext(NULL, &description);
        result = AudioComponentInstanceNew(comp, &player->audioUnits[1]);
        printf("err: %d\n", result);

    }

    //Sine
    {
        AudioComponentDescription description = {
            .componentType = kAudioUnitType_Generator,
            .componentSubType = kAudioUnitSubType_ScheduledSoundPlayer,
            .componentManufacturer = kAudioUnitManufacturer_Apple
        };
        result = AUGraphAddNode(player->graph, &description, &player->sine);
        printf("err: %d\n", result);
        AudioComponent comp = AudioComponentFindNext(NULL, &description);
        result = AudioComponentInstanceNew(comp, &player->audioUnits[2]);
        printf("err: %d\n", result);
        result = AudioUnitInitialize(player->audioUnits[2]);
        printf("err: %d\n", result);

    }

    result = AUGraphConnectNodeInput(player->graph,
                            player->sine,
                            0,
                            player->mixer,
                            0);
    printf("err: %d\n", result);

    result = AUGraphConnectNodeInput(player->graph,
                            player->mixer,
                            0,
                            player->output,
                            0);
    printf("err: %d\n", result);

    result = AUGraphOpen(player->graph);
    printf("err: %d\n", result);

    UInt32 numbuses = 1;

    result = AudioUnitSetProperty(player->audioUnits[1], kAudioUnitProperty_ElementCount, kAudioUnitScope_Input, 0, &numbuses, sizeof(numbuses));
    printf("err: %d\n", result);

    for (UInt32 i = 0; i <= numbuses; ++i) {
        // setup render callback struct
        AURenderCallbackStruct rcbs;
        rcbs.inputProc = &SineWaveRenderCallback;
        rcbs.inputProcRefCon = &player;

        printf("set AUGraphSetNodeInputCallback\n");

        // set a callback for the specified node's specified input
        result = AUGraphSetNodeInputCallback(player->graph, player->mixer, i, &rcbs);
        printf("AUGraphSetNodeInputCallback err: %d\n", result);

        printf("set input bus %d, client kAudioUnitProperty_StreamFormat\n", (unsigned int)i);

        // set the input stream format, this is the format of the audio for mixer input
        result = AudioUnitSetProperty(player->audioUnits[1], kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, i, &ASBD, sizeof(ASBD));
        printf("err: %d\n", result);
    }

    result = AudioUnitSetProperty(player->audioUnits[1], kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 0, &ASBD, sizeof(ASBD));
    printf("err: %d\n", result);

    OSStatus status = AUGraphInitialize(player->graph);
    printf("err: %d\n", status);

    player->firstOutputSampleTime = -1;
    AudioOutputUnitStart(player->audioUnits[0]);
    AUGraphStart(player->graph);

    printf("enter key to stop\n");
    getchar();

    return 0;
}


text:
Q: Scoring system xcode 5 sprite Kit I have an array of asteroids flying across the screen to the left towards my character. If they hit my character game over. If it doesn't hit my character and reaches to the end of the screen I want a score system to increment the score by one when this happens. I am using xcode 5. How can i achieve this. This code shows the movement of the asteroids
 double curTime = CACurrentMediaTime();
      if (curTime > _nextAsteroidSpawn) {
    //NSLog(@"spawning new asteroid");
    float randSecs = [self randomValueBetween:0.20 andValue:1.0];
    _nextAsteroidSpawn = randSecs + curTime;

    float randY = [self randomValueBetween:0.0 andValue:self.frame.size.height];
    float randDuration = [self randomValueBetween:2.0 andValue:10.0];

    SKSpriteNode *asteroid = [_asteroids objectAtIndex:_nextAsteroid];
    _nextAsteroid++;

    if (_nextAsteroid >= _asteroids.count) {
        _nextAsteroid = 0;
    }

    [asteroid removeAllActions];
    asteroid.position = CGPointMake(self.frame.size.width+asteroid.size.width/2, randY);
    asteroid.hidden = NO;

    CGPoint location = CGPointMake(-self.frame.size.width-asteroid.size.width, randY);

    SKAction *moveAction = [SKAction moveTo:location duration:randDuration];
    SKAction *doneAction = [SKAction runBlock:(dispatch_block_t)^() {
        //NSLog(@"Animation Completed");
        asteroid.hidden = YES;

    }];

    SKAction *moveAsteroidActionWithDone = [SKAction sequence:@[moveAction, doneAction ]];
    [asteroid runAction:moveAsteroidActionWithDone withKey:@"asteroidMoving"];

A: Just change your done action completion block:
SKAction *doneAction = [SKAction runBlock:(dispatch_block_t)^() {
    //NSLog(@"Animation Completed");
    asteroid.hidden = YES;
    ++myAwesomeScore;
}];

I can't see how you're destroying the asteroids when they collide with the player, but if you're just hiding them and not completely deleting them (and therefore still hitting that runBlock. Then just modify it to something along the lines of:
SKAction *doneAction = [SKAction runBlock:(dispatch_block_t)^() {
    //NSLog(@"Animation Completed");
    asteroid.hidden = YES;
    if (asteroid.isNotDead) ++myAwesomeScore;
}];

redpajama_set_name: RedPajamaStackExchange


text:
Q: Prove that ${\left(\frac{x+1}{2}\right)}^{x+1} \leq x^x$ I want to prove that for each real number $x>0$, the statement
$${\left(\frac{x+1 } {2}\right)}^{\!x+1} \leq x^x$$
is correct.
I've tried using mathematical induction methods, but haven't found a solution. Although, using any method is appreciated.

A: I'll try to prove this by induction itself.
For $n=1$;
$$P(1):={\left(\frac{1+1 } {2}\right)}^{\!1+1} \leq 1^1$$
$$1^2 \leq 1^1$$
This holds true. Let it be true for $P(k)$ as well.
$$P(k):={\left(\frac{k+1 } {2}\right)}^{\!k+1} \leq k^k\tag{Ineq. 01}\label{1}$$
And for $P(k+1)$;
$$P(k+1):={\left(\frac{k+2 } {2}\right)}^{\!k+2} \leq (k+1)^{k+1}\tag{Ineq. 02}\label{2}$$
By Ineq. $01$; we know that;
$$(k+1)^{k+1} \leq 2^{k+1}k^k$$
Substituting that with Ineq. $02$;
$$(k+2)^{k+2} \leq 2^{k+2}2^{k+1}k^k$$
$$(k+2)^{k+2} \leq 8(4k)^k$$
$$\frac{(k+2)^{k+2}}{(4k)^k} \leq 8$$
$$\left(\frac{1}{4}+\frac{1}{2k}\right)^k(k+2)^2 \leq 8$$
$$\left(\frac{1}{4}+\frac{1}{2k}\right)^k \leq \frac{8}{k^2}+2(1+\frac{2}{k})$$
We know that $\left(\frac{1}{4}+\frac{1}{2k}\right)^k<1$
Hence, this is true. And The claim is true for all $n ∈ N$

A: You can show your inequality using the concavity of the logarithm:

*

*$(\star)$: For $p \in [0,1]$ and $x,y>0$ you have
$$p\log x + (1-p) \log y \leq \log (px+(1-p)y)$$
Hence,
$${\left(\frac{x+1 } {2}\right)}^{\!x+1} \le x^x \Leftrightarrow \left(\frac{x+1}{x}\right)^x(x+1)\leq 2^{x+1}$$
$$\Leftrightarrow x\log \left(\frac{x+1}{x}\right) + \log (x+1)\leq (x+1)\log 2$$
$$\stackrel{(\star)}{\Leftrightarrow} \frac{x}{x+1}\log \left(\frac{x+1}{x}\right) + \frac{1}{x+1}\log (x+1)$$ $$\stackrel{(\star)}{\leq} \log \left(\frac{x}{x+1}\cdot \frac{x+1}{x} + \frac{1}{x+1}\cdot (x+1) \right) = \log 2$$
The last inequality is true because of $(\star)$.

A: We need to prove that
$$x\ln{x}\geq(x+1)\ln\frac{x+1}{2}$$ or
$$\frac{x\ln{x}+1\ln1}{2}\geq\frac{x+1}{2}\ln\frac{x+1}{2},$$ which is true by Jensen for a convex function $f(x)=x\ln{x}.$

A: you can use functions for that: lets assume $$f(x)= x^x - (\frac{x+1}{2})^{x+1}$$. then, its derviative (after simplification) is: $$f'(x)= −(x+1)^{x+1}⋅2^{−x−1}(\ln(x+1)+1)+x^x(\ln(x)+1)+\ln(2)(x+1)^{x+1}⋅2^{−x−1}$$.
you can check that $f(0)=\frac{1}{2}$, $f(1)=0$, and the value of $f'(x)>0$ for all $x>1$, and $f'(x)<0$ for all $0<x<1$.
there for the function is always equal or above the x-axis and therefore the inequality stands


text:
Q: How to debug react-native-web with Expo and vscode? I am trying to find how react-native-web apps (specifically using Expo and  vscode) can be debugged.
I found guidance neither in the web, nor in the react-native-web's own site.
The debug configuration that comes with the React Native Tools aims to run within the Expo application, but my intention is to use the browser to debug/test the react-native-web behaviour.
{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Debug in Exponent",
            "request": "launch",
            "type": "reactnative",
            "cwd": "${workspaceFolder}",
            "platform": "exponent",
            "expoHostType": "local"
        }
    ]
}

A: I could have found the method. For all who are stuck the method is as follows.

*

*Go to the debug pane.

*If previously not chosen choose "Run and Debug"

*Choose add configuration.

*Choose Chrome: Launch (we would like to launch a chrome browser when we start debugging, you may have alternative browsers, or you may choose to have the attach approach also). (We will come back to here after step 5.)

It will add a configuration like:
        {
            "name": "Launch Chrome",
            "request": "launch",
            "type": "chrome",
            "url": "http://localhost:8080", // This line should be modified at step 6
            "webRoot": "${workspaceFolder}"
        },

*Open the vscode's terminal and run expo start --web and you should see your server and related port. (Below, in my case it is port 19006.)

*Modify the configuration.

        {
            "name": "Launch Chrome 19006", // Modified as 19006
            "request": "launch",
            "type": "chrome",
            "url": "http://localhost:19006", // Modified as 19006
            "webRoot": "${workspaceFolder}"
        },

*Confirm that expo start --web is running then go to the debug pane and launch a browser by the debug start button, with "Launch Chrome 19006" value:

After these 6 steps you should be able to debug Expo applications that use react-native-web through the vscode.


text:
Q: How to use a map key in EL which is a concatenation of static string and EL variable I have a <p:dataTable var="object"> with a <p:commandLink> inside. In my bean I have a Map whose value I want to display in <p:commandLink value> . I need to pass a key to this map which is a concatenation of "someString" and #{object.firstName}. I would something like this to work:
value="#{bean.map['someString'+object.firstName]}"

How can I achieve this?

A: You can concatenate strings in EL by creating a new EL variable with the string and EL expression just inlined. You can use <c:set> for that.
<c:set var="key" value="someString#{object.firstName}" />
<p:commandLink value="#{bean.map[key]}" ... />

Alternatively, if you're on EL 2.2 already which supports invoking direct methods, then you can just directly make use of String#concat() method.
<p:commandLink value="#{bean.map['someString'.concat(object.firstName)]}" ... />

If you're not on EL 2.2 yet, but are using EL 2.1, then you can always install JBoss EL to have the same feature.

A: Mr AC_1985 didn't respond but for information I have some working code along these lines.
                            <h:panelGrid columns="1" cellpadding="5" style="width:100%">
                                <p:inputTextarea id="factsText" style="width:100%; height:100%;" rows="18" cols="100"
                                value="#{property.model.property.facts[property.model.factsLanguage.code]}"
                                counter="display" maxlength="2000" counterTemplate="{0} characters remaining." autoResize="false" />
                                <h:outputText id="display" />
                            </h:panelGrid>

Here I have a combo box where I can select a language. Then the text is retrieved from the Map for the language selected.
Thanks My BalusC for your invaluable help, as always.
Allan


text:
Q: wkhtmltopdf compilation on Ubuntu I am trying to compile wkhtmltopdf from the latest source. I am on Ubuntu 12.10 x64 server edition.
I used the instructions from here and here.
For the wkhtmltopdf-qt compilation, as mentioned by the author, the new Git repo is at gitorious.org/~antialize/qt/antializes-qt.git on the 4.8.2 branch. So, that is what I used as well.
Everything went fine. The compilation of both (qt and wkhtmltopdf) completed successfully. But I was able to use wkhtmltopdf only as root (using sudo). When I ran it as any other user, I got the following error.
error while loading shared libraries: libQtWebKit.so.4: cannot open shared object file: No such file or directory.

I had done all the compilations as root, with the files inside the root user's home directory (/root). I guessed that the wkhtmltopdf program needs to read the wkqt directory, where the compiled qt resides (and the libQtWebKit.so.4 file). This directory was inside the root user's home directory as well, thus preventing other users from running wkhtmltopdf.
So, I decided to start from scratch again. This time, I put all the source files (wkhtmltopdf-qt and wkhtmltopdf) in /usr/wkhtmltopdf. But during the compilation of qt, I get an error with the compiler trying to access qmake at the previous (old) location where qt source was present (/root/wkhtmltopdf-qt).
Error below:
ln -s libQtDeclarative.so.4.8.2 libQtDeclarative.so
ln -s libQtDeclarative.so.4.8.2 libQtDeclarative.so.4
ln -s libQtDeclarative.so.4.8.2 libQtDeclarative.so.4.8
rm -f ../../lib/libQtDeclarative.so.4.8.2
rm -f ../../lib/libQtDeclarative.so
rm -f ../../lib/libQtDeclarative.so.4
rm -f ../../lib/libQtDeclarative.so.4.8
mv -f libQtDeclarative.so.4.8.2 libQtDeclarative.so libQtDeclarative.so.4 libQtDeclarative.so.4.8 ../../lib/
make[1]: Leaving directory `/usr/wkhtmltopdf/wkhtmltopdf-qt/src/declarative'
cd src/3rdparty/webkit/Source/ && make -f Makefile.WebKit
make[1]: Entering directory `/usr/wkhtmltopdf/wkhtmltopdf-qt/src/3rdparty/webkit/Source'
/root/wkhtmltopdf-qt/bin/qmake -spec ../../../../mkspecs/linux-g++-64 -o Makefile.WebKit WebKit.pro
make[1]: /root/wkhtmltopdf-qt/bin/qmake: Command not found
make[1]: *** [Makefile.WebKit] Error 127
make[1]: Leaving directory `/usr/wkhtmltopdf/wkhtmltopdf-qt/src/3rdparty/webkit/Source'
make: *** [sub-webkit-make_default-ordered] Error 2

I don't understand how this is possible when I am starting with absolutely fresh source code.
Is there some way in which I can completely remove (uninstall) the previously installed wkhtmltopdf-qt and wkhtmltopdf?
I would appreciate some help. Thanks.

A: Okay, I figured it out.
Apparently, the source code was not as fresh as I thought.
I was cleaning the untracked and modified files in the Git working copy of the QT source directory. Running git status showed no modified files. But what I missed was that there were a lot of git-ignored folders and files, which still had the info about the previous compilation. These files and folders were not showing up in git status.
So, I temporarily moved the .gitignore file outside the repo and ran git clean -fd. That cleaned out all unnecessary files. Then I moved the .gitignore file back. For safety, I also ran git checkout -- . to get the latest versions of all the files from HEAD.
Compilation worked after that.


text:
Q: Handling PyLint Warning of Inconsistent Return Statement I'm running PyLint on some code and I'm getting the warning of "Either all return statements in a function should return an expression or none of them should. (inconsistent-return-statements)."
Here is the code I have:
def determine_operand_count(opcode_form, opcode_byte):
  if opcode_form == OP_FORM.VARIABLE:
    if opcode_byte & 0b00100000 = 0b00100000:
      return OP_COUNT.VAR

    return OP_COUNT.OP2

  if opcode_form == OP_FORM.SHORT:
    if opcode_byte & 0b00110000 == 0b00110000:
      return OP_COUNT.OP0

    return OP_COUNT.OP1

  if opcode_form == OP_FORM.LONG:
    return OP_COUNT.OP2

Here "OP_FORM" and "OP_COUNT" are Enums defined earlier in the code.
To me, that code is very readable code and I guess I'm curious what the warning from PyLint is complaining about. In every condition that I have, an "OP_COUNT" type is returned. In fact, if any of these conditionals weren't returning an OP_COUNT, my code would be failing entirely.
This seems to be a warning about my "return statements", suggesting that some aren't returning any sort of expression. But that's clearly not true (so far as I can see) as each return statement is returning something. So I'm guessing this has to do with implied returns?
But to that point, in my original code I actually held "else" clauses for my internal if statements. But when I did that, PyLint gave me another warning: "Unnecessary 'else' after 'return' (no-else-return)."
I did see the following: "How to fix inconsistent return statement in python?", but that didn't seem to reflect the situation in my code.
So it's unclear to me how to satisfy PyLint in this case since the code clearly works and seems to be doing what the warning suggests I need to be doing. Given that, I suspect I'm missing something obvious but that I currently lack the intuition for spotting. Any help to get me spotting what I'm missing would be appreciated.

A: Pylint complains about what is happening when you reach the very end of the function.  What should happen at the end of the function?  (added a return and the warning goes away)
def determine_operand_count(opcode_form, opcode_byte):
    if opcode_form == OP_FORM.VARIABLE:
        if opcode_byte & 0b00100000 == 0b00100000:
            return OP_COUNT.VAR
        return OP_COUNT.OP2

    if opcode_form == OP_FORM.SHORT:
        if opcode_byte & 0b00110000 == 0b00110000:
            return OP_COUNT.OP0
        return OP_COUNT.OP1

    if opcode_form == OP_FORM.LONG:
        return OP_COUNT.OP2

    return OP_COUNT.UNKNOWN

This code should work, but in my experience is kind of fragile over time because of the indentation.  An alternative is to write it as:
def determine_operand_count_v2(opcode_form, opcode_byte):
    def variable_form(opcode_byte):
        if opcode_byte & 0b00100000 == 0b00100000:
            return OP_COUNT.VAR
        return OP_COUNT.OP2

    def short_form(opcode_byte):
        if opcode_byte & 0b00110000 == 0b00110000:
            return OP_COUNT.OP0
        return OP_COUNT.OP1

    def long_form(_):
        return OP_COUNT.OP2

    opfcn = {OP_FORM.VARIABLE: variable_form,
             OP_FORM.SHORT: short_form,
             OP_FORM.LONG: long_form}

    return opfcn[opcode_form](opcode_byte)

A: In your case, it might happen for 2 reasons:
1) Your variable name case is for some reason inconsistent: opcode_Form (with uppercase "F") in first if statement (probably you just have mistyped it, since you also have = instead of == at the very same place) and opcode_form (with a lowercase "f") in all other places.
2) More likely, since opcode_form is not type-hinted as being an OP_FORM enum instance, it actually can be of any value, and the final else (for the case when opcode_form is neither OP_FORM.VARIABLE nor OP_FORM.SHORT or OP_FORM.LONG) is missing. So, for example, if opcode_form is some string "string", the function will actually return nothing.


text:
Q: Proveedor de Twitter en la clase AuthUI de Firebase Android Hola estoy implementando la autenticación con Firebase UI en mi app.
Intento llamar al proveedor de Twitter pero estoy observando que mi clase AuthUI no contiene este proveedor, solamente contiene:
public static final String EMAIL_PROVIDER = "email";

/**
 * Provider identifier for Google, for use with {@link SignInIntentBuilder#setProviders}.
 */
public static final String GOOGLE_PROVIDER = "google";

/**
 * Provider identifier for Facebook, for use with {@link SignInIntentBuilder#setProviders}.
 */
public static final String FACEBOOK_PROVIDER = "facebook";

Cómo puedo hacer para que mi clase AuthUI implemente el proveedor de Twitter?
Gracias

A: RESUELTO: el problema estaba en la versión de la dependencia 'com.firebaseui:firebase-ui-auth:1.1.1' anteriormente tenía la versión 0.4.1.
La 1.1.1 requiere
maven {
            url 'https://maven.fabric.io/public'
        }
en el gradle del proyecto


text:
Q: Elementary derivation for the minima of the interference pattern in the case of a thin wire without referring to the Babinet principle For the single slit there is a well known elementary derivation along the following line:

*

*If the path difference $\delta$ between the elementary waves coming from the borders of the slit is one wave length $\lambda$ you imagine say 100 elementary waves evenly distributed starting from the slit. Then the path difference between the 1. and 51. wave is $\lambda/2$ so they interfere destructively, the same path difference occurs between the 2. and 52. wave, the 3. and 53, and so on. So you get a interference minimum for $\delta = \lambda$.

*If $\delta = k\lambda$ ($k \in \{1,2,3,\dots\}$) you just devide the ray bundle into $k$ bundles, where in each bundle the path difference between the "boundary rays" is $\lambda$ and you can argue as in 1. So for each bundle you get complete destructive interference.

*From geometry it follows then that you get minima for
$$
\sin(\alpha) = \frac{k\lambda}{b}
$$
where $b$ is the width of the slit.

From Babinets principle it follows that the same formula should apply for the interference pattern of a opaque thin wire of thickness $b$.
Is there any direct elementary derivation (like that one for the single slit as sketched out above) for the case of the thin wire?

A: For interference( just like thin wire)
Minima is at $y =m\lambda D/d$
For diffraction ,
Maxima is at $y= m\lambda D/d$
Add the two and you, get maxima + minima =  all light is passed as if no object is there.
Apply this at each fringe..
As for intensity, If you look at centre, since in diffraction intensity I was divided in each fringe, centre had less light, calculate that, and in double slit intereference, light was added at centre ,which was otherwise dark.
Both these contribute to make a centre of normal intensity as if there was no slit or wire.
Intensity at distance from object wont matter as they wont show any diffraction..
Note: I cant find formula for intensities, so, I cant help with math part....


text:
Q: Counting the number of rows from multiple tables I'm trying to do something very basic but can't quite figure this one out. I'm using PHP and MySQLi (OOP) rather than MySQL. I could use multiple single select statements then put the count from each number into a variable, but I think it's inefficient.
Okay, there are a few tables;
TABLE NAME: UCC_STAFF
id
email
username
password
status

TABLE NAME: UCC_TEMP_STAFF
id
email
username
password
status

TABLE NAME: UCC_TEMP_STUDENTS
id
email
username
password
status

TABLE NAME: UCC_VISITORS
id
email
username
password
status

What I'm trying to do is count the number of rows from each table, each row represents a user. As I've explained; It's easy enough to do with one table but I'd like to combine results with a single request into a an array rather than multiple statements into multiple variables.
An example of the desired result would be;
$a = results('UCC_STAFF' => '35',
            'UCC_TEMP_STAFF' => '12',
            'UCC_STUDENTS' => '543',
            'UCC_VISITORS'  => '6',);

What I would imagine this to look like would be;
$db_host = "dbhost";
$db_username = "username";
$db_pass = "password";
$db_name = "dbname";

$mysqli = new mysqli("$db_host", "$db_username", "$db_pass", "$db_name");

if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}

$query  = "SELECT * FROM UCC_STAFF;";
$query .= "SELECT * FROM UCC_TEMP_STAFF;";
$query .= "SELECT * FROM UCC_STUDENTS;";
$query .= "SELECT * FROM UCC_VISITORS";

if ($mysqli->multi_query($query)) {

// Results into $results
// How do I do this, what goes here?

    }

// Print Array
print_r ($results);

A: You could do something like that to count data from multiple tables with one query.
$query  = "SELECT ";
$query .= "(SELECT COUNT(*) FROM UCC_STAFF) AS count_staff, ";
$query .= "(SELECT COUNT(*) FROM UCC_TEMP_STAFF) AS count_temp_staff, ";
$query .= "(SELECT COUNT(*) FROM UCC_TEMP_STUDENTS) AS count_students, ";
$query .= "(SELECT COUNT(*) FROM UCC_VISITORS) AS count_visitors";

A: Create one table
TABLE NAME: UCC_PEOPLE
id
email
username
password
status
type <-- use this field to distinguish different types

Run one query to get the count of records, not records themselves
SELECT type, count(*) cnt, FROM UCC_PEOPLE GROUP BY type

A: i think you looking for something like this with UNION
 $query  =(  (SELECT CONCAT('UCC_STAFF', '')as UCC_STAFF ,count(*)as count from UCC_STAFF )

              UNION ALL
              (SELECT CONCAT('UCC_TEMP_STAFF', '')as UCC_TEMP_STAFF ,count(*) from UCC_TEMP_STAFF )

              UNION ALL
              (SELECT CONCAT('UCC_TEMP_STUDENTS', '')as UCC_TEMP_STUDENTS ,count(*) from  UCC_TEMP_STUDENTS )

              UNION ALL
              (SELECT CONCAT('UCC_VISITORS', '')as UCC_VISITORS ,count(*) from UCC_VISITORS ) );

DEMO SQLFIDDLE HERE


text:
Q: Where is the difference between those 2 convolutional layers in keras? I was following 2 different tutorials about basic CNNs and keras (Tensorflow backend) Conv2D layers.
When i swap one layer with an (in my opinion) identical one, with a different notation my model completely fails and goes from ~95% accuracy to under 20%.
Obviously there must be a major difference that i did not spot!
This is my working model, that works as expected:

    model = Sequential()

    model.add(Conv2D(64, kernel_size = 3, activation='relu', input_shape=(28,28,1)))

    model.add(Conv2D(32, kernel_size = 3, activation='relu'))

    model.add(Flatten())

    model.add(Dense(10, activation='softmax'))

If i replace the second layer
    model.add(Conv2D(32, kernel_size = 3, activation='relu'))

with

    model.add(Conv2D(32, (3, 3), strides=(1, 1), activation='relu'))

I've read that the kernel size can also be defined like (3, 3) this in a tupel and that the default stride size is 1x1.
Why would this replacement result in any different result at all ?


text:
Q: Correct usage of Entity AND DTO to provide Json in Restful web service There are many articles stating that using DTOs is not necessary with JPA/hibernate
Use the open session in view pattern, or a disciplined assembly phase to avoid problems with unfetched data.Hibernate frees the developer from writing tedious Data Transfer Objects (DTO)...
The above lines are from https://docs.jboss.org/hibernate/orm/3.5/reference/en/html/best-practices.html
Also In an article by a SO member Bohzo I read DTO's are rarely required
Even in articles against exposing entities state that there is no need of having a DTO when Entities do not have any behavior (when they are POJOs) as in the anemic domain model
Let's Say there is an Entity class
class Department{
    List<Employee> employees //lazily loaded collection

Each object in the collection contains another lazily loaded collection
 class Employee{
    List<Account> accounts

There is a getDepartment() method
which is used by a restful service to provide Json information of the Department.
The possible solutions are
Solution 1) As per hibernate documentation opening and closing the hibernate session per request (that is the uppermost method in controller is transactional?) or better using Spring's  OpenSessionInViewFilter as per this SO post
Why can't hibernate re-open a session and fetch the lazily loaded object instead of throwing an exception?Is there a way to configure this with JPA/hibernate?
Solution 2) Again as in hibernate doc another way is to have an assembly phase.What exactly does it mean ?
Break down the getDepartment API into different API's of the DAO ?
Solution 3)Use DTO's Even with DTO's how can the persistence layer know whether view needs a fully loaded Department or not.This
leads to breaking the API into getDepartmentOnly() getDepartmentWithEmployees() and others saying whether to get 100% of the department object or a part of it
One API broke down into many and one entity mapped to many DTO's
Solution 4) As in bohzo's article with paginated views avoid lazy loading and have queries to fetch limited results
Please correct Solution 2 and explain what is intended in the hibernate documentation?

A: Assembly phase in the Hibernate documentation means:
public Department getDepartmentWithEmployees(Long departmentId) {
   Department result = em.find(Department.class, departmentId);
   Hibernate.initialize(result.getEmployees());
   return result;
}

Or:
public Department getDepartmentWithEmployees(Long departmentId) {
   String query = "select d from Department d join fetch d.employees where d.id = :departmentId";
   ...
}

Or ...
Basically, it's up to you to fetch the necessary data to provide the balance between code readability and maintainability vs performance (the number of different APIs vs the amount of data fetched).
This is not a JPA/Hibernate specific issue; you would need to consider this with any other persistence framework (or with direct JDBC) as well.


text:
Q: Why isn't my loop working? Only goes up to first print out I can't seem to figure out why my program is running? Can someone help steer me to the right direction?
import java.util.*;

public class EasyLoops
{
    public static void main (String [] args)
    {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter Number:");
        int n = input.nextInt();

        while ( n > 0 );
        {
            System.out.println("Hello World");
            n = n - 1;
        }
    }
}

A: Remove the ; here:
while ( n > 0 );

That would mean the "content" of the loop is nothing,
and the {} after it are just for fun (valid, but needless)...
It would loop forever (if n>0) because nothing in n changes.

A: Remove the ; in the while loop otherwise while loop terminates
while ( n > 0 );<- here

A: Reomove the ";" the end of while statement. ";" is set only do while Loop not while Loop
while (n > 0)
{
    System.out.println("Hello World");
    n = n - 1;

}

Thank you

A:         while ( n > 0 );

Notice the semicolon. The syntax of a while loop is
while (condition) statement;

or
while (condition) { block }

You wrote the first syntax, and included no statement, so if n is greater than zero you will get an infinite loop (since n will never decrement).  If n is less than or equal to zero then the while will not execute and the block below will execute exactly once.

A: you terminate your loop with ;
 while(n>0); // your mistake
{
  //your code
}

try this
public static void main (String [] args)
{
    Scanner input = new Scanner(System.in);
    System.out.print("Enter Number:");
    int n = input.nextInt();
        while ( n > 0 )
    {
        System.out.println("Hello World");
        n = n - 1;
    }
}


text:
Q: запутался в строках на с++ Всем привет!
У меня есть программа, которая выводит из строки количество в ней цифер.
Допустим строчка "qwrtt56hhbb055ghjj". Соответственно программа выводит "5 цифр".
А как мне теперь найти их сумму? То есть 5+6+0+5+5?

A: Думаю, здесь проще всего использовать обычные циклы.
Вот демонстрационная программа, которая показывает два подхода в зависимости от того, где  хранится строка.
#include <iostream>
#include <string>

int main()
{
{
    const char *s = "qwrtt56hhbb055ghjj";
    unsigned int sum = 0;

    for ( const char *t = s; *t; ++t )
    {
        if ( *t >= '0' && *t <= '9' ) sum += *t - '0';
    }

    std::cout <<  "sum = " << sum << std::endl;
}
{
    std::string s( "qwrtt56hhbb055ghjj" );

    unsigned sum = 0;

    for ( char c : s )
    {
        if ( c >= '0' && c <= '9' ) sum += c - '0';
    }

    std::cout <<  "sum = " << sum << std::endl;
}

    return 0;
}

В обоих случаях вывод на консоль будет
sum = 21
sum = 21


text:
Q: stuck at 92% "Launching: starting virtual machine" on eclipse java program very often when I try to compile and run a java program on eclipse it gets stuck at 92 percent and when I click on the bottom right corner it says "Launching: Starting virtual machine" so I close eclipse and when I reopen the program it works once but then when I try to launch it a second time I get the same problem, I'm using the windows 10 technical preview so it could be a problem with that and not eclipse. but I'm not sure can somebody please help.

A: It might help to increase your heap size:
https://wiki.eclipse.org/FAQ_How_do_I_increase_the_heap_size_available_to_Eclipse


text:
Q: Como tener acceso a una serie de elementos (tipo gridpane en mi caso) almacenados en un ObservableList Tengo 5 GridPane que necesito hacer visible/invisible dependiendo de ciertas circunstancias. He intentado almacenarlos en un ObservableList pero al intentar acceder a ellos para aplicarle el método .setVisible da error, ya que al acceder al índice devuelve null en lugar del gridpane en cuestión. Ayuda Porfa :(

@FXML
private GridPane fila1;
@FXML
private GridPane fila2;
@FXML
private GridPane fila3;
@FXML
private GridPane fila4;
@FXML
private GridPane fila5;

@FXML
ObservableList<GridPane> mesas = FXCollections.observableArrayList(fila1,fila2,fila3,fila4,fila5);

for(int i=0;i<temp.getEmpleados().size();i++) {
    mesas.get(i).setDisable(false);
    }

A: Los elementos de la colección son perfectamente accesibles. Posiblemente tu error se deba a que intentas acceder con un índice fuera de rango, es decir, una 'i' superior a la cantidad de GridPane de la ObservableList. No sé que es temp.getEmpleados() así que yo lo llamaré 'elemento'. El bucle for sería algo así:
mesas.stream().forEach((elemento) -> {
    elemento.setDisable(false);
        });


text:
Q: SharePoint strange behavior? I have a strange Behaviour issue with Sharepoint.
I'm testing some javascript in the content editor web part and ran accross this issue.
When Creating DOM Elements dynamically in a normal HTML Page as shown below, I am able to  retrieve the values from the created Element.
When I however try this in a Sharepoint Content Editor web part, I get the JS error back from the SharePoint Page stating : "0.value1" is null or not an object.
Any idea why this is happening?

<input id="Button1" type="button" value="button" onclick="WriteElements();"/>

A: I can't tell you exactly what the problem is.  My guess is that IE isn't reparsing the DOM soon enough, so document.getElementsByName fails.
This works for me:

<input id="Button1" type="button" value="button" onclick="WriteElements();"/>

A: In fact, even if you create a "normal" html page with the code you posted above; It doesn't work.
value1 is not a property of the object of type "input", it is an attribute and it's retrieved in a different fashion.


text:
Q: For the $U(1)$ problem, is the Kugo and Ojima Goldstone quartet wrong? On page 96 in "Local Covariant Operator Formalism of Non-Abelian Gauge Theories and Quark Confinement Problem", Prog. Theor. Phys. Suppl. 66 (1979) 1, KO state the following:

Finally we should comment on the current belief that the $U(1)$ problem
  was resolved by instanton. It is not correct; namely:, the instanton
  by itself cannot assure the unphysicalness of the $U(1)$ Goldstone boson
  $\chi$ which is contained in $J^{\mu}_5 $ because of the chiral $U(1)$ Ward
  identity ($ 7 \cdot 4$ ).No one has
  ever proved in the framework of "instanton physics" in a satisfactory manner
  that the $\chi$ really contained in the gauge-variant current $J^{\mu}_5$is not contained
  in the gauge-invariant one, $j^{\mu}_5$, although this problem has been discussed by
  many authors.

Are Kugo and Ojima correct? I thought 't Hooft proved that the instantons solved the $U(1)$ problem.

A: The expectation of the axial current divergence in a $\theta$  shifted $QCD$ vacuum is given by
$\partial_{\mu} \langle  J^{\mu5}_{\mathrm{inv}} \rangle_{\theta}  =  2m_q \langle \bar{q}i\gamma^5q \rangle_{\theta} +  \langle \Xi \rangle_\theta,$
where the first term on the right hand side is the explicit breaking term due to the quark masses and the second term,
$ \Xi =  \frac{2 g^2N_f}{32\pi^2}\ F_{\mu\nu }^a F^{\mu\nu a},$
comes from the contribution added to the current to make it gauge invariant. The volume density of this term is called the topological susceptibility.
According to 't Hooft, the expectation value in the second term is nonvanishing, since it is proportional to the expectation of the fluctuation of the index in the presence of instantons:
$\langle \Xi \rangle_\theta = \langle(N_+-N_-)^2\rangle_{\theta}.$
There is strong evidence from lattice QCD that this contribution is nonvanishing. This means that the $U(1)$ axial symmetry  is explicitly broken even in the absence of quark masses, therefore  the $\eta^{\prime}$  is not a Goldstone which is a possible explanation of its large mass compared to the "Goldstone Octet"
Kugo argues that if we use the gauge variant current which is the true Noether current instead of the gauge invariant one we get the usual current conservation broken only due to the quark masses, thus naively $\eta^{\prime}$   could be a Goldstone. However, he argues that this gauge variant Goldstone field belongs to a quarted obtained by the action on it by the BRST operator thus experiences quartet decoupling from the physical spectrum just as the temporal, longitudinal gluon polarizations and ghosts in the Kugo-Ojima theory.

A: I think 't Hooft and Kugo are solving different problems.
't Hooft addresses the issue that the anomaly involves a topological term. As a result, in perturbation theory there is no theta dependence and the anomaly equation by itself does not solve the $U(1)$ problem. He shows that topological objects (semi-classically, instantons) generate theta dependence. He also shows that instanton zero modes provide a microscopic mechanism for chirality non-conservation, and that instantons generate an effective vertex that can give a mass to the $\eta'$.
Kugo addresses the issue that the anomaly involves a total divergence. As a result I can define a gauge dependent current which is conserved, and therefore has a Goldstone pole. This means that I should show that this pole does not couple to any gauge invariant currents. Kugo provides a mechanism (BRST quartet), by which this can happen.


text:
Q: How to get the value of Loaction present in Response Header in Angular Js? I'm using Restful webserivce(Jersey),I need to get the value of Location present in the Response Header
$http({
        method : "POST",
        url : ' http://localhost:8084/leasing-management/customers/',
        headers : {
            'Content-type' : 'application/json'
        },
        data :  $scope.customer
    })
    .success(function(dataFromServlet,status, headers) {
        console.log(status);
        if(status==201){
             alert( headers('Location') );
            console.log(headers('Content-Type'));
            showToasterBox("success","Customer Created Successfully ","Success");
            /*$location.path("customers/headers('Location')");*/
        }
        else{
            showToasterBox("error","Status : " + status + " - Application Error","Try Again");
        }
    })
    .error(function(dataFromServlet,status, headers) {
        showToasterBox("error","Status : " + status + " - Application Error","Try Again");
    });

If I  put alert for Loaction it says null.
Response Header:
Access-Control-Allow-Headers:Origin, X-Requested-With, Content-Type, Accept
Access-Control-Allow-Methods:POST, GET, OPTIONS, DELETE
Access-Control-Allow-Origin:*
Access-Control-Expose-Headers:custom-header
Content-Length:0
Content-Type:application/json
Date:Thu, 20 Aug 2015 07:28:04 GMT
Location:http://localhost:8084/leasing-management/customers/10081
Server:Apache-Coyote/1.1

A: Have you tried $location servcie?
https://docs.angularjs.org/api/ng/service/$location
Or you can use window.localtion?


text:
Q: how to prevent keep getting duplicated result from API with Flatlist react native? im trying to get repos in order of stars from the API, but as i scroll, i keep getting random duplicates :
export default function App() {
  const [repos, setRepos] = useState([]);
  const [page, setPage] = useState(1);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const getUsers = async () => {
      const res = await axios.get(
        `https://api.github.com/search/repositories?q=created:>2020-01-01&sort=stars&order=desc&page=${page}`
      );
      const data = await res.data;
      // setRepos([...repos, ...data.items]);
      setRepos([...repos, ...data.items]);
      setLoading(false);
      };
      getUsers();
    }, [page]);

    const scrollToEnd = () => {
      if (loading === false) {
        setPage(page + 1);
        setLoading(true);
      }

      console.log("page", page);
    };

    const renderItem = ({ item }) => (
      <Text className="boxed">
        Stars: {item.stargazers_count} Id: {item.id}
      </Text>
    );

    return (
      <SafeAreaView style={styles.screen}>
        <View style={styles.container}>
          <FlatList
            data={repos}
            renderItem={renderItem}
            keyExtractor={(item) => item.id}
            onEndReached={scrollToEnd}
            showsVerticalScrollIndicator={false}
          />

          {loading && <Text className="loading">...loading</Text>}
        </View>

        <StatusBar style="auto" />
      </SafeAreaView>
    );
  }

A: I think you got too much going on in your useEffect function, maybe missing a closing }. Try this:
function App() {
  const [repos, setRepos] = useState([]);
  const [page, setPage] = useState(1);
  const [loading, setLoading] = useState(true);

  // This will trigger when page changes:
  useEffect(() => {
    getUsers();
  }, [page]);

  const getUsers = async () => {
    const res = await axios.get(
      `https://api.github.com/search/repositories?q=created:>2020-01-01&sort=stars&order=desc&page=${page}`
    );
    const data = await res.data;
    // setRepos([...repos, ...data.items]);
    setRepos([...repos, ...data.items]);
    setLoading(false);
  };

  const scrollToEnd = () => {
    if (loading === false) {
      setPage(page + 1);
      setLoading(true);
    }

    console.log("page", page);
  };

  const renderItem = ({ item }) => (
    <Text className="boxed">
      Stars: {item.stargazers_count} Id: {item.id}
    </Text>
  );

  return (
    <SafeAreaView style={styles.screen}>
      <View style={styles.container}>
        <FlatList
          data={repos}
          renderItem={renderItem}
          keyExtractor={(item) => item.id}
          onEndReached={scrollToEnd}
          showsVerticalScrollIndicator={false}
        />

        {loading && <Text className="loading">...loading</Text>}
      </View>

      <StatusBar style="auto" />
    </SafeAreaView>
  );
}

export default App;

A: You should avoid duplicate data before set it to state, update your getUsers function with this,
useEffect(() => {
const getUsers = async () => {
  const res = await Axios.get(
    `https://api.github.com/search/repositories?q=created:>2020-01-01&sort=stars&order=desc&page=${page}`,
  );
  const data = await res.data;
  let arrRepos = [...repos, ...data.items];
  let uniq = new Set(arrRepos.map((objRepo) => JSON.stringify(objRepo)));
  arrRepos = Array.from(uniq).map((objRepo) => JSON.parse(objRepo));
  setRepos(arrRepos);
  setLoading(false);
};
getUsers();
}, [page]);


text:
Q: Cannot invoke extension Java method from XSLT in SaxonEE9-9-1-4J I have following simple XSLT example:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="3.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:fn="http://www.w3.org/2005/xpath-functions"
                xmlns:eg="http://example.com/saxon-extension"
                xmlns:eks="ekstern"
                xmlns:dmp="http://arealinformation.miljoeportal.dk/gis/services/distribution/MapServer/WFSServer"
                exclude-result-prefixes="eg">
    <xsl:output method="xml" version="1.0" encoding="utf-8" indent="yes"/>
    <xsl:template match="/">
        <xsl:copy>
            <xsl:sequence select="eg:shift-left(1,2)"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

and I have this basic "ShiftLeft" class which I took from a Saxon example: https://www.saxonica.com/html/documentation/extensibility/integratedfunctions/ext-full-J.html
package diadem.base.plugin.helpers;

import net.sf.saxon.lib.ExtensionFunctionCall;
import net.sf.saxon.lib.ExtensionFunctionDefinition;
import net.sf.saxon.om.Sequence;
import net.sf.saxon.om.StructuredQName;
import net.sf.saxon.trans.XPathException;
import net.sf.saxon.expr.XPathContext;
import net.sf.saxon.value.SequenceType;
import net.sf.saxon.value.IntegerValue;
import net.sf.saxon.value.Int64Value;

public class ShiftLeft extends ExtensionFunctionDefinition {
    @Override
    public StructuredQName getFunctionQName() {
        return new StructuredQName("eg", "http://example.com/saxon-extension", "shift-left");
    }

    @Override
    public SequenceType[] getArgumentTypes() {
        return new SequenceType[]{SequenceType.SINGLE_INTEGER, SequenceType.SINGLE_INTEGER};
    }

    @Override
    public SequenceType getResultType(SequenceType[] suppliedArgumentTypes) {
        return SequenceType.SINGLE_INTEGER;
    }

    @Override
    public ExtensionFunctionCall makeCallExpression() {
        return new ExtensionFunctionCall() {
            @Override
            public Sequence call(XPathContext context, Sequence[] arguments) throws XPathException {
                long v0 = ((IntegerValue)arguments[0]).longValue();
                long v1 = ((IntegerValue)arguments[1]).longValue();
                long result = v0<<v1;
                return Int64Value.makeIntegerValue(result);
            }
        };
    }
}

I am for some reason facing following errormessage in XSLT:
Static error in {eg:shift-left(1,2)} in expression in xsl:sequence/@select on line 12 column 56 of conflictsTestTransform.xslt:
  XPST0017: Cannot find a 2-argument function named Q{http://example.com/saxon-extension}shift-left()

I don't actually know why it cannot invoke the "Call"-method in the Java extension function. The code I am using for transformation:
 private static Document transform(Document inputDoc, File xsltFile) throws XSLTransformException {
        JDOMSource source = new JDOMSource(inputDoc, null)
        JDOMResult result = new JDOMResult()
        try {
            TransformerFactory tFactory = TransformerFactory.newInstance("com.saxonica.config.EnterpriseTransformerFactory", null)
            tFactory.setURIResolver(new XsltUriResolver())
            if(tFactory instanceof TransformerFactoryImpl) {
                TransformerFactoryImpl tFactoryImpl = (TransformerFactoryImpl) tFactory;
                Configuration saxonConfig = tFactoryImpl.getConfiguration();
                saxonConfig.registerExtensionFunction(new ShiftLeft());
            }

            Templates templates = TransformerFactory.newInstance("com.saxonica.config.EnterpriseTransformerFactory", null).newTemplates(new StreamSource(xsltFile))
            Transformer transformer = templates.newTransformer()
            result.setFactory(null)  // null ok
            try {
                transformer.transform(source, result)
                return result.getDocument()
            }
            catch (TransformerException e) {
                throw new XSLTransformException("Could not perform transformation", e)
            }
        } catch (TransformerConfigurationException tce) {
            // Error generated by the parser
            // log.warn("Transformer Factory error", tce)
        } catch (SAXException sxe) {
            // Error generated by this application
            // (or a parser-initialization error)
            // log.warn("SAXException", sxe)
        } catch (ParserConfigurationException pce) {
            // Parser with specified options can't be built
            // log.warn("Parser build error", pce)
        } catch (IOException ioe) {
            // I/O error
            // log.warn("IO error", ioe)
        }

        return null
    }

A: You have two TransformerFactories, and two Saxon Configurations; you have registered the extension function with one of them, and you are trying to use it in the other.


text:
Q: Python Curve Smoothing using Savitzky_Golay - issue Input File CSV data link.  My Python code is as pasted beneath. The curve smoothing technique does not really seem to be working. As I plot the smoothed curve upon the parent data, they overlap exactly. Could someone please help me in resolving the issue please. The code uses the Savitzky_Golay algorithm.The code extracts the x,y axis data from a csv file and is formulated to suite the required data type needed for the Savitzky_Golay function call

    import numpy as np
    import csv
    from math import factorial
    import itertools
    import matplotlib.pyplot as plt
    from matplotlib.ticker import FormatStrFormatter
    #from scipy.interpolate import spline
    #import openpyxl
    #import pandas as pd
    #from scipy.interpolate import interp1d

    def savitzky_golay(y, window_size, order, deriv=0, rate=1):
        r"""Smooth (and optionally differentiate) data with a Savitzky-Golay filter.
        The Savitzky-Golay filter removes high frequency noise from data.
        It has the advantage of preserving the original shape and
        features of the signal better than other types of filtering
        approaches, such as moving averages techniques.
        Parameters
        ----------
        y : array_like, shape (N,)
          the values of the time history of the signal.
        window_size : int
          the length of the window. Must be an odd integer number.
        order : int
          the order of the polynomial used in the filtering.
          Must be less then `window_size` - 1.
        deriv: int
          the order of the derivative to compute (default = 0 means only smoothing)
        Returns
        -------
        ys : ndarray, shape (N)
          the smoothed signal (or it's n-th derivative).
        Notes
        -----
        The Savitzky-Golay is a type of low-pass filter, particularly
        suited for smoothing noisy data. The main idea behind this
        approach is to make for each point a least-square fit with a
        polynomial of high order over a odd-sized window centered at
        the point.
        Examples
        --------
        t = np.linspace(-4, 4, 500)
        y = np.exp( -t**2 ) + np.random.normal(0, 0.05, t.shape)
        ysg = savitzky_golay(y, window_size=31, order=4)
        import matplotlib.pyplot as plt
        plt.plot(t, y, label='Noisy signal')
        plt.plot(t, np.exp(-t**2), 'k', lw=1.5, label='Original signal')
        plt.plot(t, ysg, 'r', label='Filtered signal')
        plt.legend()
        plt.show()
        References
        ----------
        .. [1] A. Savitzky, M. J. E. Golay, Smoothing and Differentiation of
         Data by Simplified Least Squares Procedures. Analytical
         Chemistry, 1964, 36 (8), pp 1627-1639.
        .. [2] Numerical Recipes 3rd Edition: The Art of Scientific Computing
         W.H. Press, S.A. Teukolsky, W.T. Vetterling, B.P. Flannery
         Cambridge University Press ISBN-13: 9780521880688
        """

        try:
          window_size = np.abs(np.int(window_size))
          order = np.abs(np.int(order))
        except ValueError, msg:
          raise ValueError("window_size and order have to be of type int")
        if window_size % 2 != 1 or window_size < 1:
          raise TypeError("window_size size must be a positive odd number")
        if window_size < order + 2:
          raise TypeError("window_size is too small for the polynomials order")
        order_range = range(order+1)
        half_window = (window_size -1) // 2
        # precompute coefficients
        b = np.mat([[k**i for i in order_range] for k in range(-half_window, half_window+1)])
        m = np.linalg.pinv(b).A[deriv] * rate**deriv * factorial(deriv)
        # pad the signal at the extremes with
        # values taken from the signal itself
        firstvals = y[0] - np.abs( y[1:half_window+1][::-1] - y[0] )
        lastvals = y[-1] + np.abs(y[-half_window-1:-1][::-1] - y[-1])
        y = np.concatenate((firstvals, y, lastvals))
        return np.convolve( m[::-1], y, mode='valid')

    CurveName_1 = "Actual"
    ind1, ind2 = 0,0
    check = 0
    for line in open('C:\Users\XYZ\Documents\FileTransfers\Vicky.csv'):
        csv_row = line.split(",")
        csv_row = map(str.strip, csv_row)
        csv_row = [i.replace('"', '') for i in csv_row]
        if CurveName_1 in csv_row:
            ind1 = csv_row.index(CurveName_1)
            check += 1
        if check > 1:
            break

    x = []
    y = []
    with open( 'C:\Users\XYZ\Documents\FileTransfers\Vicky.csv', "r") as file:
        reader = csv.reader(file)
        for idx,line in enumerate(reader):
            if idx>3:
                x.append(float(line[ind1]))
                y.append(float(line[0]))
                #t=line[ind1],line[ind2]
                #print t

    print len(x)
    print len(y)

    xm = np.array(x)
    ym = np.array(y)

    #ym = np.array(ym)
    yhat = savitzky_golay(ym, 51, 3) # window size 51, polynomial order 3

    plt.grid(True)
    plt.minorticks_on()
    # Customize the major grid
    plt.grid(which='major', linestyle='-', linewidth='0.5', color='red')
    # Customize the minor grid
    plt.grid(which='minor', linestyle=':', linewidth='0.5', color='black')
    axes = plt.subplot(111)
    axes.xaxis.set_minor_formatter(FormatStrFormatter("%.2f"))
    axes.yaxis.set_minor_formatter(FormatStrFormatter("%.2f"))
    plt.plot(yhat, xm)
    plt.plot(ym,xm, color='red')
    plt.show()

A: Maybe a little late, and maybe not the exact answer to your question, but for a very similar application I use pandas.read_excel to import the data and scipy.signal.savgol_filter for filtering: the less I implement, the more chances it has of working properly...


text:
Q: Display image exported as byte array in JasperReports I am trying to export image(byte array) and display in PDF using iReport. Groovy code:
        InvoiceVO invoiceVO = new InvoiceVO()
        invoiceVO.kms = 5
         ..............
        invoiceVO.image = currentUser.profile.image // byte array

In iReport I am using:
    <image>
        <reportElement x="2" y="7" width="143" height="32" uuid="df5cd1ab-e7a2-41a1-920d-6045db41cfc9"/>
        <imageExpression><![CDATA[net.sf.jasperreports.engine.util.JRImageLoader.loadImage($F{image})]]></imageExpression>
    </image>

but its not working. Field image is of type "java.lang.object" also tried "java.lang.byte". Image expression place-holder displays blank.

A: The method net.sf.jasperreports.engine.util.JRImageLoader.loadImage(byte[]) is absent (obsolete) in JasperReports API 6.x.
You should pass java.awt.Image object to the report.
Converting byte[] to java.awt.Image can be done in a chain.
Java code:
try (InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("images/smile.png")) {
    params.put("smileImage", ImageIO.read(new ByteArrayInputStream(JRLoader.loadBytes(inputStream))));
} catch (JRException | IOException e) {
    throw new RuntimeException("Failed to load image", e);
}

The jrxml file:
<parameter name="logo" class="java.awt.Image"/>
<summary>
    <band height="150">
        <image >
            <reportElement x="20" y="20" width="50" height="50"/>
            <imageExpression><![CDATA[$P{smileImage}]]></imageExpression>
        </image>


text:
Q: Comparing 2 lists and return difference in a 3rd list .net 4.0 I am trying compare 2 lists and output the differences in another list.Comparing each property Value based on the CustomerNo.I know this has been asked many times but I cannot seem to find what exactly
I am looking for ,so please do not rush to say it's a duplicate.
My issue are
1) How can I convert to a hashset to improve perfomance (tried convert to hashset but does not return the same result as the list.
2) how can I return a list of "Differences" .By Difference I mean if a customerNo in 1 list has multiple properties that are different that these should be added to the list
Any suggestions
This is what I have done
    class Program
        {
            static void Main()
            {
                Customer[] oldCustomersSet =
                {
                    new Customer { CustomerNo="1", Name = "Joe", Surname = "Bloggs", City = "London"},
                    new Customer {CustomerNo="2",Name = "Mark", Surname = "Smith", City = "Manchester"},
                    new Customer {CustomerNo="3",Name = "Emily", Surname = "Blunt", City = "Liverpool"},
                    new Customer {CustomerNo="4",Name = "George", Surname = "William", City = "Exter"},
                    new Customer {CustomerNo="5",Name = "aaa", Surname = "bbb", City = "Exter"},
                    new Customer {CustomerNo="6",Name = "ccc", Surname = "ddd", City = "Exter"},
                    new Customer {CustomerNo="7",Name = "Jane", Surname = "Wonder", City = "Exter"},
                };
                Customer[] newCustomersSet =
                {
                    new Customer {CustomerNo="1",Name = "Joe", Surname = "Bloggs", City = "London"},
                    new Customer {CustomerNo="2",Name = "Mark", Surname = "WrongSurname", City = "Manchester"},
                    new Customer {CustomerNo="3",Name = "Emily", Surname = "Blunt", City = "Liverpool"},
                    new Customer {CustomerNo="4",Name = "George", Surname = "William", City = "WrongCity"},
                    new Customer {CustomerNo="5",Name = "aaa", Surname = "bbb", City = "Exter"},
                    new Customer {CustomerNo="6",Name = "ccc", Surname = "ddd", City = "Exter"},
                    new Customer {CustomerNo="7",Name = "Jane", Surname = "Wonder", City = "ExterMistake"},
                };

                 var firstSet = oldCustomersSet.Except(newCustomersSet);
        var secondSet = newCustomersSet.Except(oldCustomersSet);

                //This returns 6 items (3 old and 3 new)
                var result = firstSet.Union(secondSet).ToList();

                //now find all the differences.How do I match it based on customerNo and write to the difference List?
                List<Difference>diffList=new List<Difference>();

            }
        }

    }

    public class Difference
    {
        public string PropertyName { get; set; }
        public string OldValue { get; set; }
        public string NewValue { get; set; }
    }
    public class Customer : IEquatable<Customer>
    {

        public string CustomerNo { get; set; }
        public string Name { get; set; }
        public string Surname { get; set; }
        public string City { get; set; }

        public bool Equals(Customer other)
        {
            if (ReferenceEquals(null, other)) return false;
            if (ReferenceEquals(this, other)) return true;
            return string.Equals(City, other.City)
                && string.Equals(CustomerNo, other.CustomerNo)
                && string.Equals(Name, other.Name)
                && string.Equals(Surname, other.Surname);
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            if (obj.GetType() != this.GetType()) return false;
            return Equals((Customer)obj);
        }

        public override int GetHashCode()
        {
            unchecked
            {
                var hashCode = (City != null ? City.GetHashCode() : 0);
                hashCode = (hashCode * 397) ^ (CustomerNo != null ? CustomerNo.GetHashCode() : 0);
                hashCode = (hashCode * 397) ^ (Name != null ? Name.GetHashCode() : 0);
                hashCode = (hashCode * 397) ^ (Surname != null ? Surname.GetHashCode() : 0);
                return hashCode;
            }
        }

        public static bool operator ==(Customer left, Customer right)
        {
            return Equals(left, right);
        }

        public static bool operator !=(Customer left, Customer right)
        {
            return !Equals(left, right);
        }

A: You have to join the two arrays, so you can use the Join extension method.
To actually produce the list of "Differences", create a method that compares the properties of the matching new and old customer.
Here's a quick and dirty example:
public IEnumerable<Difference> GetDifferences(Customer oldOne, Customer newOne)
{
    var props = typeof(Customer).GetProperties();

    foreach (var prop in props)
    {
        var oldvalue = prop.GetValue(oldOne);
        var newvalue = prop.GetValue(newOne);
        if(oldvalue != newvalue)
            yield return new Difference { CustomerNo = oldOne.CustomerNo, PropertyName = prop.Name, OldValue = oldvalue.ToString(), NewValue = newvalue.ToString() };
    }
}

Used like this (adjust as necessary):
var result = oldCustomersSet.Join(newCustomersSet,
                                  o => o.CustomerNo,
                                  i => i.CustomerNo,
                                  GetDifferences)
                            .Where(d => d.Any())
                            .ToLookup(d => d.First().CustomerNo);

produces this result:

(Note I added a CustomerNo property to Difference)

If both of your lists/arrays are sorted and each element at a certain index in the first list corresponds to the same customer at the same indexin the second list, you could also use a simple for loop instead.
var diffs = new List<Tuple<string, List<Difference>>>();
for(int i = 0; i < oldCustomersSet.Length; i++)
{
    var curDiffs = GetDifferences(oldCustomersSet[i], newCustomersSet[i]).ToList();
    if(curDiffs.Any())
        diffs.Add(Tuple.Create(oldCustomersSet[i].CustomerNo, curDiffs));
}

But to know if this is really faster, you'll have to actually test it.


text:
Q: System.ServiceModel.MessageHeaderException: Multiple headers with name 'Action' and namespace ... found I have implemented an interface to an erp-system with WCF. The interface works fine nearly all the time. Every 2-3 weaks in the erp-system a deadlock occurs and then I get a System.ServiceModel.MessageHeaderException when I try to read the answer. Somehow I get a success and a failure message from the erp-system an I can't read this. I have not enabled logging for the wcf right now.
How can I prevent this error? Can I interpret messages with multiple headers?
Complete error:
System.ServiceModel.MessageHeaderException: Multiple headers with name 'Action' and namespace 'http://www.w3.org/2005/08/addressing' found.

A: I too faced encountered same error while working on aif services which is basically based on top of dotnet wcf services. My Service operation was returning a List DataContract of a type which itself  having a List DataContract as DataMember.
There was a problem in the code which resulted in corrupted response header

Here is complete metadata
<HMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContractHMPackageItemDefaultsContract: Dynamics.Ax.Application.HMPackageItemDefaultsContract>}

Items were not seperated by commas (,). due to a code glitch
contract = new HMPackageItemDefaultsContract();
switch (line.HMProductType)
{
    case HMInventType::Laboratory:

        hmLaboratoryDefault = HMLaboratoryDefault::findByPackageDefinitionLine(line);
        while select hmLaboratoryDefault
        {
            contract.parmCollectionDate(hmLaboratoryDefault.CollectionDate);
            contract.parmInstructionstoPatient(hmLaboratoryDefault.Instructions);
            contract.parmNotestoPharmacy(hmLaboratoryDefault.Notes);
            contract.parmSpecimenSource(hmLaboratoryDefault.HMSpecimenSource);

            list.addEnd(contract);
        }

    break;

contract was not being instantiated on each while iteration to add it to list.
Took me 3 hour to figure it out after doing compilation, cleaning up XPPIL and doing full cil.
I just figured out there is one more scenario where it fails, when you have DataMemberberContract returning enum type with a fixed set of items with their corresponding integer values and you returning an enum integer value out of bound.
WCF doesn't give any error message specific to the actual error, it just fails with below message
Multiple headers with name 'Action' and namespace 'http://www.w3.org/2005/08/addressing' found.

Hope it help folks out there who encounter such concealed exceptions.


text:
Q: search multiple fields django I'm trying to build a search system, and I want to search by multiple fieldsname, state, city, in my django models. I wrote the below code, yet I've been unable to figure out how to go about it. I use Q but it seems not working:
views.py:
def data_consulting(request):
    if request.method == 'POST':
          form = FilterForm(request.POST)
          if form.is_valid():
                conditions = [('toBuy', form.cleaned_data['toBuy']), ('name__contains', form.cleaned_data['searchName']),(('price__gte', form.cleaned_data['searchPriceBegin']), ('price__lte',form.cleaned_data['searchPriceEnd'])),(('calories__gte', form.cleaned_data['searchCalorieBegin']), ('calories__lte', form.cleaned_data['searchCalorieEnd'])), (('date__gte',form.cleaned_data['DateBegin']), ('date__lte', form.cleaned_data['DateEnd']))]
                all_products = Product.objects.filter(reduce(operator.or_, [Q(condition) for condition in conditions]))
                send = True
                all_products = Product.objects.filter(reduce(operator.or_, [Q(condition) for condition in conditions]))
           else:
                form = FilterForm()
                all_products = Product.objects.all()
    return render(request, 'mealManager/data_consulting.html', locals())

A: Have a think about what
reduce(operator.or_, [Q(condition) for condition in conditions])

becomes with e.g. [('toBuy', 'bread'), ('name__contains', 'bread')]. It becomes
Q(('toBuy', 'bread')) | Q(('name_contains', 'bread'))

which is obviously wrong syntax, since Q rather needs kwargs than a tuple:
Q(toBuy='bread') | Q(name__contains='bread')

that's where the ** operator comes to the rescue. If you get data like this:
[{'toBuy': 'bread'}, {'name__contains': 'bread'}]

which may be accomplished by simply changing the conditions assignment you can then do
reduce(operator.or_, [Q(**condition) for condition in conditions])

which translates in the particular case to
Q(toBuy='bread') | Q(name__contains='bread')

which is exactly what we need.


text:
Q: Mongo C# IMongoCollection Design I am using an interface as a collection type when initializing an IMongoCollection. I am using an interface class as the collection so that it can be better for testing.
public IMongoCollection<IEmployee> Employees => Database.GetCollection<IEmployee>("employee");

public interface IEmployee
{
  [BsonId]
  ObjectId Id { get; set; }
  string Name { get; set; }
}

[BsonDiscriminator(Required = true)]
[BsonKnownTypes(typeof(Employee))]
public class Employee : IEmployee
{
  public ObjectId { get; set; }
  public string Name { get; set; }
}

I have a database class of Employee which implements IEmployee. When storing to the database, I have to store a type of Employee because I can't declare a new instance of IEmployee.
var emp = new Employee
{
   Id = ObjectId.GenerateNewId();
   Name = "Wayne Rooney";
};

// Insert into the Employees collection
await Employees.InsertOneAsync(emp);

When I want to replace/update that document, I can't because I am querying from a lower layer class of IEmployee.
await Employees.FindOneAndReplaceAsync(f => f.Id.ToString() == context.Id, g);

context in this case is the parameter of type Employee that I am passing in. g is the update document of type Employee. f in this case is type IEmployee. When I do a replace, I get a [document].Id.ToString() is not supported error.
So the question is, I'm able to insert and retrieve them, but not able to update/replace/delete a document. Any suggestions?

A: First, a few heads ups.
When inserting to the database, if you have specified an ObjectId as your BsonId then there is no need to manually set it.
So set the BsonId-attribute on your Id.
public class Employee : IEmployee
{
    [BsonId]
    public ObjectId Id { get; set; }
    public string Name { get; set; }
}

And then insert as such:
var emp = new Employee
{
   Name = "Wayne Rooney";
};

// Insert into the Employees collection
await Employees.InsertOneAsync(emp);

A unique ObjectId will be set by itself upon inserting.

The problem itself most likely lies in the ToString()-part of your Linq-query. I'm not sure it translates well into a mongo-query. A quick work-around would be to just use something like:
var id = new ObjectId(context.Id);

await Employees.ReplaceOneAsync(f => f.Id == id, g);

This eliminates the ToString()-call and compares ObjectId's directly.
The support of Linq-queries are somewhat limited in the driver. I would advise against using them (there is also some overhead here).
The suggested, and most direct route is to use the built-in filters.
For instance:
var filter = Builders<IEmployee>.Filter
    .Eq(nameof(Employee.Id), new ObjectId(context.Id));

await Employees.ReplaceOneAsync(filter, g);

nameof(Employee.Id) is C# 6, and will return "Id". If you do not have support for C# 6 then simply use "Id" instead.


text:
Q: Threadsafe logging I want to implement a simple class for logging from multiple threads. The idea there is, that each object that wants to log stuff, receives an ostream-object that it can write messages to using the usual operators. The desired behaviour is, that the messages are added to the log when the stream is flushed. This way, messages will not get interrupted by messages from other threads. I want to avoid using a temporary stringstream to store the message, as that would make most messages at least twoliners. As I see it, the standard way of achieving this would be to implement my own streambuffer, but this seems very cumbersome and error-prone. Is there a simpler way to do this? If not, do you know a good article/howto/guide on custom streambufs?
Thanks in advance,
Space_C0wbo0y
UPDATE:
Since it seems to work I added my own answer.

A: Take a look at log4cpp; they have a multi-thread support. It may save your time.

A: So, I took a look at Boost.IOstreams and here's what I've come up with:
class TestSink : public boost::iostreams::sink {
public:
    std::streamsize write( const char * s, std::streamsize n ) {
        std::string message( s, n );
            /* This would add a message to the log instead of cout.
               The log implementation is threadsafe. */
        std::cout << message << std::endl;
        return n;
    }
};

TestSink can be used to create a stream-buffer (see stream_buffer-template). Every thread will receive it's own instance of TestSink, but all TestSinks will write to the same log. TestSink is used as follows:
TestSink sink;
boost::iostreams::stream_buffer< TestSink > testbuf( sink, 50000 );
std::ostream out( &testbuf );

for ( int i = 0; i < 10000; i++ )
    out << "test" << i;

out << std::endl;

The important fact here is, that TestSink.write is only called when the stream is flushed (std::endl or std::flush), or when the internal buffer of the stream_buffer instance is full (the default buffer size cannot hold 40000 chars, so I initalize it to 50000). In this program, TestSink.write is called exactly once (the output is too long to post here). This way I can write logmessage using normal formatted stream-IO without any temporary variables and be sure, that the message is posted to the log in one piece when I flush the stream.
I will leave the question open another day, in case there are different suggestions/problems I have not considered.

A: You think log4cpp is too heavy and you reach for Boost.IOStreams instead?  Huh?
You may wish to consider logog.  It's thread-safe for POSIX, Win32 and Win64.

A: Re. your own response.  If you are using this for error logging and you program crashes before flushing your stream then you logging is a bit useless isn't it?


text:
Q: C# Graphics redrawing I'm writing a little game using C#. In fact, it just have to draw corolful circles every time user moves a mouse (or just every n milliseconds) according to the mouse location. The problem is, i have to redraw the whole pictureBox every single period of time. I know there are .Invalidate() and .Refresh() options for that, but it seems like I need to re-create Graphics object every single time I need to redraw something, that happens every second.
private void redrawCircles(int distance)
{
            prevdist = distance / 5;
            g = Graphics.FromImage(pictureBox1.Image);
            for (int i = 0; i < n - 1; i++)
            {
                brushes[i] = brushes[i + 1];
            }
            brushes[n - 1] = BrushFromDistance(distance);
            for (int i = 0; i < n; ++i)
            {
                g.FillEllipse(brushes[i], startX + i * rad, startY + i * rad, 2 * diag - 2 * i * rad, 2 * diag - 2 * i * rad);
            }
            g.Dispose();

            pictureBox1.Refresh();
}

where g is:
    public static System.Drawing.Graphics g;
redrawCircles is called in the MouseMove event handler, and i'm planning to cal it in Timer.Tick event handler. So it's called very often. Re-creating Graphics object seems not effective.
Do I really need re-creating Graphics object in that situation or there is an easier way?


text:
Q: how to check UIControl class orientation? In my app i have created one custom class with superclass UIControl.and add that class view to  window.Now my problem is my custom class view cannot identify the orientation.when i rotate the device custom class view doesnt rotate.
Is there any method to rotate a custom class or is there any way to rotate that custom view?
here is my code:
          - (void) showForView:(UIView *)forView
     {
        NSLog(@"window frame=%@",forView.window);
          if(self.hidden || hiding || !view.superview) {
                     UIWindow *viewWindow=[[UIWindow alloc]init];

               viewWindow = forView.window;

    [[NSNotificationCenter defaultCenter] postNotificationName:CustomKeyboardWillShowNotification object:self];

    // remove from old view and add to new view (if necessary)
    if(view.superview && (view.superview != viewWindow)) {
        [view removeFromSuperview];
    }
    if(!view.superview) {
        CGFloat x;

             x = view.bounds.size.width / 2;

                   y = viewWindow.frame.size.height/2.5 + (view.frame.size.height/2);

        self.hiddenCenter = CGPointMake(x, y);
        view.center = hiddenCenter;

    self.view.transform=CGAffineTransformMakeRotation(-(M_PI/2));

        [viewWindow addSubview:view];
            self.autoHideWhenInactive = [[NSUserDefaults standardUserDefaults] boolForKey:kKeyboardAutoHideKey];
    }
}

Please guide me or suggest me the way to do this.
Thank you

A: you need to add your custom view to a view controller.view, not to Window:
windows don't rotate...

A: Tried this?.[UIApplication sharedApplication].statusBarOrientation


text:
Q: Do iPhones come with recently used emojis? Do iPhones come with emojis already in the "recently used" area? Like preset in that area?

A: As per your question, it seems you are interested with the most frequently used emoji. In your keyboard when you toggle the emoji button, the very first tab called "frequently used", shows all the frequently used emoji.

A: Yep. When you tap the emoji which you use often, it will be shown in your keyboard which called "frequently used".


text:
Q: How to fix duplicated model name with using gem I try to use a gem which is ging/mailboxer in my rails application.
In the gem, "Receipt" class is used in model.
But I already use "Receipt" class in my application.
In this case, model and table name is duplicated.
so what is the best way to fix duplicated model name ?
I think the below:

*

*Way1: To rename the model/table name in the gem

*Way2: To rename the model/table name in my application

I didn't find any clew to adopt the Way1.
If I adopt the Way2, I will rename table name then rename model name in my whole application. If possible, I'd like to avoid this way because I've already used "Receipt" in many places.
Do I have to adopt the Way2, or are there any other good way to fix duplicated model name ?

A: As you said, since they are ActiveRecord classes, they have the same table and they will collide in the namespace of your application.
You can use Modules to avoid the name class collision, or you can update either the gem or your code to use a different name for the class.
If you choose to put your classes within a Module, for the table son the database, you can use set_table_name to use a different name for that class instead of the default one expected by ActiveRecord.


text:
Q: How to train and test nlu model in RASA inside Docker? Having issues with trainig RASA inside Docker.
I enter it:
docker run -it -v C:\Users\User\Documents:/app --entrypoint=/bin/bash rasa/rasa
Then I provide a command line to train with exact path to traning_data (it exists!)
rasa train --data %cd%\data\split_train\train_data.md nlu
But every time I got this
2019-12-16 17:35:39 WARNING  rasa.cli.utils  - '%cd%datasplit_traintrain_data.md' does not exist. Using default value 'data' instead.
2019-12-16 17:35:39 WARNING  rasa.cli.utils  - 'nlu' does not exist. Using default value 'data' instead.

What should I do to finally be able totrain and test my utterances in C:\Users\User\Documents\data\split_train\training_data.md?

A: You need to execute rasa train inside the running docker container.
check your running containers by executing:
docker ps

now execute rasa train inside the container with your model :
docker exec <container-name> rasa train <arguments>

test if the model was trained:
docker exec -it <container-name> rasa shell <arguments>

Reference to docker exec in the Docker Docs.
See also the Rasa Docs Running Rasa with Docker.


text:
Q: Improving analysis skills I am a software engineer with a couple of years of experience. However I feel my problem solving skills need to be improved. To put in crude terms given facts A and fact B I have difficulty in reaching conclusion X ? Some people seem to have the ability to reach conclusion X given facts A and B and and also remembering to take facts C,D in account.
What techniques do you use to improve your problem solving and analysis skills ?

A: Generally when I'm solving problems via analysis I do the following:

*

*locate in a system, the sub-components that are the focus of the problem

*State the initial assumptions for the components state

*given a set of initial state(s), predict what you believe will be the outcome.

*If the prediction(s) fail, remove each state assumption one at a time, and confirm that the state is what you assumed it to be.

*If the states are all correct, then the issue is one of logic.

*To solve a set of Logical issues, start off with a set of "Logical Transform" assumptions

*Repeat the above method but for "Logical Transforms" example: "assume (1) when condition X -> x transforms to y"

That's loosely how I work through problems.

A: There is a book called Analysis Patterns by Marin Fowler. It is about object models and not about any algorithmic analysis, but learning about this patterns, helped me recognizing patterns in various domains and thus being able to analyze it more thoroughly.


text:
Q: extract a linguistic structure based on POS tagged sentence using Stanford nlp in JAVA I am new in Natural Language Processing (NLP), I want to do part-of-speech tagging (POS) and then do find a specific structure within a text. I could manage POS tagging using Stanford-NLP but, I do not know how to extract this structure:

NN/NNS + IN + DT + NN/NNS/NNP/NNPS

public static void main(String args[]) throws Exception{
    //input File
    String contentFilePath = "";
    //outputFile
    String triplesFilePath = contentFilePath.substring(0, contentFilePath.length()-4)+"_postagg.txt";

    //document to POS tagging
    String content = getFileContent(contentFilePath);

    Properties props = new Properties();

    props.setProperty("annotators","tokenize, ssplit, pos");
    StanfordCoreNLP pipeline = new StanfordCoreNLP(props);
    // Annotate the document.
    Annotation doc = new Annotation(content);
    pipeline.annotate(doc);

    // Annotate the document.
    List<CoreMap> sentences = doc.get(CoreAnnotations.SentencesAnnotation.class);
    for (CoreMap sentence : sentences) {
        for (CoreLabel token: sentence.get(CoreAnnotations.TokensAnnotation.class)) {
            String word = token.get(CoreAnnotations.TextAnnotation.class);
            // this is the POS tag of the token
            String pos = token.get(CoreAnnotations.PartOfSpeechAnnotation.class);
            System.out.println(word + "/" + pos);
        } }}}

A: You can simply iterate over your sentence and check for the POS tags. If they match your requirements, you can extract this structure. The code for that could look like this:
for (CoreMap sentence : doc.get(CoreAnnotations.SentencesAnnotation.class)) {
    List<CoreLabel> tokens = sentence.get(TokensAnnotation.class);
    for(int i = 0; i < tokens.size() - 3; i++) {
        String pos = tokens.get(i).get(PartOfSpeechAnnotation.class);
        if(pos.equals("NN") || pos.equals("NNS")) {
            pos = tokens.get(i + 1).getString(PartOfSpeechAnnotation.class);
            if(pos.equals("IN")) {
                pos = tokens.get(i + 2).getString(PartOfSpeechAnnotation.class);
                if(pos.equals("DT")) {
                    pos = tokens.get(i + 3).getString(PartOfSpeechAnnotation.class);
                    if(pos.contains("NN")) {
                        //We have a match starting at index i and ending at index i + 3
                        String word1 = tokens.get(i).getString(TextAnnotation.class);
                        String word2 = tokens.get(i + 1).getString(TextAnnotation.class);
                        String word3 = tokens.get(i + 2).getString(TextAnnotation.class);
                        String word4 = tokens.get(i + 3).getString(TextAnnotation.class);
                        System.out.println(word1 + " " + word2 + " " + word3 + " " + word4);
                    }
                }
            }
        }
    }
}


text:
Q: A HTML link redirects to correct URL but page doesn't load and shows 403 error. The page loads fine once the page is refreshed I have a web application hosted on Apache Tomcat which is installed on XAMPP (XAMPP is an app. like citrix/vmware). On clicking a particular link on the homepage, among many others that work absolutely fine, I'll be redirected to the required URL but the page doesn't load and shows 403 error. However, the page loads fine once the page is refreshed. Also, this error happens only when accessed from XAMPP(where it is hosted; using 'localhost'). This error does not occur when accessed outside XAMPP(using application url). All other links on the homepage works fine in both the cases
ScreenShot of error
Can someone help fix this, please? Any support is much appreciated.