text:
Q: Not able to connect to the redis instance created with docker I have created a docker container for redis but I am not able to connect the same instance with a redis client.
docker command i used to bring up my redis isntance
docker run --name localredis -p 6379:6379 -d redis
please find below my docker inspect of the container
[
    {
        "Id": "ea6adada84602054f1057dded66c474231fcfdabcb3b0797fd82da0ff558cd6c",
        "Created": "2021-01-26T16:07:13.477202002Z",
        "Path": "docker-entrypoint.sh",
        "Args": [
            "redis-server"
        ],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 2675,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2021-01-26T16:07:13.834485936Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        },
        "Image": "sha256:621ceef7494adfcbe0e523593639f6625795cc0dc91a750629367a8c7b3ccebb",
        "ResolvConfPath": "/var/lib/docker/containers/ea6adada84602054f1057dded66c474231fcfdabcb3b0797fd82da0ff558cd6c/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/ea6adada84602054f1057dded66c474231fcfdabcb3b0797fd82da0ff558cd6c/hostname",
        "HostsPath": "/var/lib/docker/containers/ea6adada84602054f1057dded66c474231fcfdabcb3b0797fd82da0ff558cd6c/hosts",
        "LogPath": "/var/lib/docker/containers/ea6adada84602054f1057dded66c474231fcfdabcb3b0797fd82da0ff558cd6c/ea6adada84602054f1057dded66c474231fcfdabcb3b0797fd82da0ff558cd6c-json.log",
        "Name": "/localredis",
        "RestartCount": 0,
        "Driver": "overlay2",
        "Platform": "linux",
        "MountLabel": "",
        "ProcessLabel": "",
        "AppArmorProfile": "",
        "ExecIDs": [
            "66947da6a117e75cbbe696fad9e4cebd623d0209c94b63bdfb22d25ca723c074"
        ],
        "HostConfig": {
            "Binds": null,
            "ContainerIDFile": "",
            "LogConfig": {
                "Type": "json-file",
                "Config": {}
            },
            "NetworkMode": "default",
            "PortBindings": {
                "6379/tcp": [
                    {
                        "HostIp": "",
                        "HostPort": "6379"
                    }
                ]
            },
            "RestartPolicy": {
                "Name": "no",
                "MaximumRetryCount": 0
            },
            "AutoRemove": false,
            "VolumeDriver": "",
            "VolumesFrom": null,
            "CapAdd": null,
            "CapDrop": null,
            "Capabilities": null,
            "Dns": [],
            "DnsOptions": [],
            "DnsSearch": [],
            "ExtraHosts": null,
            "GroupAdd": null,
            "IpcMode": "private",
            "Cgroup": "",
            "Links": null,
            "OomScoreAdj": 0,
            "PidMode": "",
            "Privileged": false,
            "PublishAllPorts": false,
            "ReadonlyRootfs": false,
            "SecurityOpt": null,
            "UTSMode": "",
            "UsernsMode": "",
            "ShmSize": 67108864,
            "Runtime": "runc",
            "ConsoleSize": [
                0,
                0
            ],
            "Isolation": "",
            "CpuShares": 0,
            "Memory": 0,
            "NanoCpus": 0,
            "CgroupParent": "",
            "BlkioWeight": 0,
            "BlkioWeightDevice": [],
            "BlkioDeviceReadBps": null,
            "BlkioDeviceWriteBps": null,
            "BlkioDeviceReadIOps": null,
            "BlkioDeviceWriteIOps": null,
            "CpuPeriod": 0,
            "CpuQuota": 0,
            "CpuRealtimePeriod": 0,
            "CpuRealtimeRuntime": 0,
            "CpusetCpus": "",
            "CpusetMems": "",
            "Devices": [],
            "DeviceCgroupRules": null,
            "DeviceRequests": null,
            "KernelMemory": 0,
            "KernelMemoryTCP": 0,
            "MemoryReservation": 0,
            "MemorySwap": 0,
            "MemorySwappiness": null,
            "OomKillDisable": false,
            "PidsLimit": null,
            "Ulimits": null,
            "CpuCount": 0,
            "CpuPercent": 0,
            "IOMaximumIOps": 0,
            "IOMaximumBandwidth": 0,
            "MaskedPaths": [
                "/proc/asound",
                "/proc/acpi",
                "/proc/kcore",
                "/proc/keys",
                "/proc/latency_stats",
                "/proc/timer_list",
                "/proc/timer_stats",
                "/proc/sched_debug",
                "/proc/scsi",
                "/sys/firmware"
            ],
            "ReadonlyPaths": [
                "/proc/bus",
                "/proc/fs",
                "/proc/irq",
                "/proc/sys",
                "/proc/sysrq-trigger"
            ]
        },
        "GraphDriver": {
            "Data": {
                "LowerDir": "/var/lib/docker/overlay2/f89d87a8018ce297dc6b204fff66b5da39212bc8a063be3e14fbb43813a377ad-init/diff:/var/lib/docker/overlay2/74014cbeac95ded3e80f5ec0ba64aafc252846b7c7517d5f1e00ca0ae8436e0e/diff:/var/lib/docker/overlay2/7f220239171723472e6e62802bb1f6a3341e1f3003414bb6f5f35ac8fef326a7/diff:/var/lib/docker/overlay2/5ebf1767ac29a0f344fc2134218365426f354e90e60e4ab51f09f9d571ac073f/diff:/var/lib/docker/overlay2/39eb79b70bd7680a7153eea515f4478d24733a67687a853643f87ff718566259/diff:/var/lib/docker/overlay2/6f9e7e2d91dcd0fa1f8d0ca68b600230b724c8add6bfa4102f8da12e667a5a31/diff:/var/lib/docker/overlay2/b8782f485b043e4168304f049982cb78c1039b09dae95eaed596ce61eb9ffd12/diff",
                "MergedDir": "/var/lib/docker/overlay2/f89d87a8018ce297dc6b204fff66b5da39212bc8a063be3e14fbb43813a377ad/merged",
                "UpperDir": "/var/lib/docker/overlay2/f89d87a8018ce297dc6b204fff66b5da39212bc8a063be3e14fbb43813a377ad/diff",
                "WorkDir": "/var/lib/docker/overlay2/f89d87a8018ce297dc6b204fff66b5da39212bc8a063be3e14fbb43813a377ad/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [
            {
                "Type": "volume",
                "Name": "1bb68817383777a30df146c139e4e8d97ef7ceb3d72e2eeaba5e45bed472df05",
                "Source": "/var/lib/docker/volumes/1bb68817383777a30df146c139e4e8d97ef7ceb3d72e2eeaba5e45bed472df05/_data",
                "Destination": "/data",
                "Driver": "local",
                "Mode": "",
                "RW": true,
                "Propagation": ""
            }
        ],
        "Config": {
            "Hostname": "ea6adada8460",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "ExposedPorts": {
                "6379/tcp": {}
            },
            "Tty": false,
            "OpenStdin": false,
            "StdinOnce": false,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
                "GOSU_VERSION=1.12",
                "REDIS_VERSION=6.0.10",
                "REDIS_DOWNLOAD_URL=http://download.redis.io/releases/redis-6.0.10.tar.gz",
                "REDIS_DOWNLOAD_SHA=79bbb894f9dceb33ca699ee3ca4a4e1228be7fb5547aeb2f99d921e86c1285bd"
            ],
            "Cmd": [
                "redis-server"
            ],
            "Image": "redis",
            "Volumes": {
                "/data": {}
            },
            "WorkingDir": "/data",
            "Entrypoint": [
                "docker-entrypoint.sh"
            ],
            "OnBuild": null,
            "Labels": {}
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "62f19eea272849065d5dd21104f6fa7c7e385ed9cf8fbb518c59088bc48f5fdc",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {
                "6379/tcp": [
                    {
                        "HostIp": "0.0.0.0",
                        "HostPort": "6379"
                    }
                ]
            },
            "SandboxKey": "/var/run/docker/netns/62f19eea2728",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "f0d51b78c34b598b27fef608c824974407bdf235a4d289e23f935aa87d906ef9",
            "Gateway": "172.17.0.1",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "172.17.0.3",
            "IPPrefixLen": 16,
            "IPv6Gateway": "",
            "MacAddress": "02:42:ac:11:00:03",
            "Networks": {
                "bridge": {
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": null,
                    "NetworkID": "b3c2da1a7455de3deac167a7759678f293f5e9a8e886375867b7c64c30e12935",
                    "EndpointID": "f0d51b78c34b598b27fef608c824974407bdf235a4d289e23f935aa87d906ef9",
                    "Gateway": "172.17.0.1",
                    "IPAddress": "172.17.0.3",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "02:42:ac:11:00:03",
                    "DriverOpts": null
                }
            }
        }
    }
]

I am trying to add this instance as below but getting error

Any help on this would be appreciated.


text:
Q: write records from many files to one file I have three files. File1 has record like
abc|123
bcd|234
cde|345

and File2 has records like
12
13

and File3 has records like
Add|xyz.txt|04
Add|str.txt|05
Del|uyt.txt|99

Here i'm trying to put records of all files into one file.So output(final.txt) will look like
abc|123|12|Add|xyz.txt|04
bcd|234|13|Add|str.txt|05
cde|345|  |Del|uyt.txt|99

A: How about using paste:-
paste -d'|' file1 file2 file3
abc|123|12|Add|xyz.txt|04
bcd|234|13|Add|str.txt|05
cde|345||Del|uyt.txt|99

A: With an extra effort to preserve spaces for better alignment, also consider to use column
paste -d'|' file1 file2 file3 | column -tns '|'

abc  123  12  Add  xyz.txt  04
bcd  234  13  Add  str.txt  05
cde  345      Del  uyt.txt  99

You can replace the delimiter back through sed
paste -d'|' file1 file2 file3 | column -tns '|' | sed 's/\([^ ]\)  /\1|/g;s/  \([^ ]\)/|\1/g'

abc|123|12|Add|xyz.txt|04
bcd|234|13|Add|str.txt|05
cde|345|  |Del|uyt.txt|99

redpajama_set_name: RedPajamaStackExchange


text:
Q: which they were Which of the following is correct:
1) They were accused of breaking the law, which they were doing.
2) They were accused of breaking the law, which they were.
3) They were accused of breaking the law, which they had done.
4) They were accused of breaking the law, which they had.

A: I find all four of them acceptable, with 2) and 4) a little bit more natural than the others.
The difference between the first two and the last two is the temporal focus of the utterance - 1 & 2 focus on the time when they were breaking the law, and 3 & 4 on a time afterwards (probably when the accusation was made).
As is common with choices about the perfect in English, the difference reflects how the speaker is viewing the events, not any objective difference in the events that occurred.


text:
Q: Trigger static_assert even when function signature is invalid Suppose I'm designing a library that provides some types and a template function that I expect users to instantiate on those types. The signature of the template function depends on nested typedefs within the template parameter, and I want to use static_assert to give a nice error message if the template is instantiated with an incompatible type:
// library.h
#include <type_traits>

struct compatible_with_f {};

struct foo : compatible_with_f {
  using some_type = int;
};

struct bar : compatible_with_f {
  using some_type = float;
};

template <typename T>
void f(typename T::some_type param) {
  static_assert(std::is_base_of<compatible_with_f, T>::value,
                "the template parameter to f should be `foo` or `bar`");
  // some code, which also uses the type T itself directly
}

// main.cc

int main() {
  f<foo>(0); // works
  f<bar>(0.f); // works
  f<int>(0); // error: no matching function for call to 'f'
}

This doesn't work as I hope: my friendly error message doesn't get printed, because the signature of f doesn't make sense, so the compiler bails out before it even reaches the static_assert in the body of the function.
Is there a way to achieve what I want in a good way? Here is the best I could come up with:
// library.h
#include <type_traits>

struct compatible_with_f {};

struct foo : compatible_with_f {
  using some_type = int;
};

struct anything {
  template <typename T>
  anything(T&&) {}
};

template <typename, typename = void>
struct get_some_type {
  using type = anything;
};

template <typename T>
struct get_some_type<T, typename std::enable_if<std::is_base_of<compatible_with_f, T>::value>::type> {
  using type = typename T::some_type;
};

template <typename T>
void f(typename get_some_type<T>::type param) {
  static_assert(std::is_base_of<compatible_with_f, T>::value,
                "the template parameter to f should be `foo` or `bar`");
  // some code, which also uses the type T itself directly
}

// main.cc

int main() {
  f<foo>(0); // works
  f<int>(0); // error: the template parameter to f should be `foo` or `bar`
}

I use SFINAE to provide a default some_type which is convertible from anything. Now the signature always makes sense, so the compiler instantiates the body of the function and I get the nice error message. But I don't like this solution: it seems overly complicated, and it has the big disadvantage that the signature of f is now much less clear - before it took T::some_type, which was obvious, now it takes some weird trait magic. Is there a better way?

A: You could write a forwarding function to do the check before passing it to the actual implementation:
template <typename T>
void f_impl(typename T::some_type param) {
  // some code, which also uses the type T itself directly
}

template<typename U, typename T>
void f(T&& t)
{
  static_assert(std::is_base_of<compatible_with_f, U>::value,
                "the template parameter to f should be `foo` or `bar`");
  f_impl<U>(std::forward<T>(t));
}

LIVE
EDIT:
Alternatively, you could add a less specialized overload for f:
template <typename T>
void f(T param) {
  static_assert(std::is_base_of<compatible_with_f, T>::value,
                "the template parameter to f should be `foo` or `bar`");
}

template <typename T>
void f(typename T::some_type param) {
  static_assert(std::is_base_of<compatible_with_f, T>::value,
                "the template parameter to f should be `foo` or `bar`");
  // some code, which also uses the type T itself directly
}

LIVE


text:
Q: Page Layout and PickList for Custom Object Let's say I have a custom object with 2 picklist fields. I've added this fields into page layout but i cannot see that ones. Wham am I doing wrong?

A: Check your Field Level Security on those picklist fields and make sure the fields are visible to the appropriate profiles.


text:
Q: Put background image behind ionic ion-content and ion-header Is it possible to have a background image for a page in an ionic 2 App that extends across the entire page including the <ion-header> and <ion-content?
I can get a background image for the content and another background image for the header but I can't get one image to cover the entire page behind both the content and the header.

A: *

*Add a div first then add ion-header and ion-content.

*Add background-image for a particular page.

*Add property
ion-content {
    position: initial;
}


text:
Q: Add a number of cells that only have a 1 in them Is there any way for me to add a bunch of cells that only have a 1 in them? If they have a 0 in them, then this should not be added to the total. This should also work if the list is filtered too.

A: I think that you mean that you want to count the number of cells with 1 in them?
=COUNTIF(A:A,">0")

Will give you a count of the number of cells in column A containing a number greater than zero, change the test to =1 to be more specific.

A: Yes. Just add them all since 0 will not affect the value?


text:
Q: In regression, if the residuals are correlated with X then what assumption has most likely been violated?
*

*independence

*homoscedasticity

This question is from an online quiz with one "correct" answer, but I'm not sure I agree. I understand that the answer is homoscedasticity, but isn't independence violated here as well? Since heteroskedasticity indicates that residuals are correlated with X, then there is a dependency with x. Therefore, independence is also violated.
Could someone please explain?

A: As both @AlecosPapadopoulos and @Glen_b note, there is a problem with the question.  Since they said the answer was 2 (heteroscedasticity), I wonder if they meant to ask: 'In regression, if the [standard deviation of the] residuals are correlated with X then what assumption has most likely been violated?'  However, that would be an awkward way to get at that idea (certainly not the question I would ask to probe that issue) and "are" should be "is" to maintain proper number agreement.
An alternative interpretation would be 'In regression, if the residuals are correlated with X then [themselves,] what assumption has most likely been violated?'  This would make your choice of 1 (independence) correct.  A variable correlated with itself (at some lag) is autocorrelated, which @Stat discusses.  This can happen when the functional form of the variable is misspecified.  For example, if the relationship between $X$ and $Y$ is curvilinear, but a straight line is fit, then you may have, say, several negative residuals in a row, followed by several positive residuals in a row, followed by several negative residuals in a row again.
In sum, the question is flawed.  Without more information from the asker, it is impossible to say exactly what the deal is.


text:
Q: SDL_mixer function Mix_LoadMUS_RW causes Access Violation I have a problem in loading music from memory with SDL_mixer.
The following "minimal" example including a bit of error checking will always crash with an access violation in Music::play.
#include <SDL\SDL_mixer.h>
#include <SDL\SDL.h>
#include <vector>
#include <iostream>
#include <string>
#include <fstream>

class Music {
public:
    void play(int loops = 1);
    SDL_RWops* m_rw;
    std::vector<unsigned char> m_file;
    Mix_Music * m_music = nullptr;
};

void Music::play(int loops) {
    if (Mix_PlayMusic(m_music, loops) == -1)
        std::cout << "Error playing music " + std::string(Mix_GetError()) + " ...\n";
}

void readFileToBuffer(std::vector<unsigned char>& buffer, std::string filePath) {
    std::ifstream file(filePath, std::ios::binary);

    file.seekg(0, std::ios::end);
    int fileSize = file.tellg();
    file.seekg(0, std::ios::beg);
    fileSize -= file.tellg();

    buffer.resize(fileSize);
    file.read((char *)&(buffer[0]), fileSize);

    file.close();
}

void writeFileToBuffer(std::vector<unsigned char>& buffer, std::string filePath) {
    std::ofstream file(filePath, std::ios::out | std::ios::binary);
    for (size_t i = 0; i < buffer.size(); i++)
        file << buffer[i];
    file.close();
}

Music loadMusic(std::string filePath) {
    Music music;

    readFileToBuffer(music.m_file, filePath);
    music.m_rw = SDL_RWFromMem(&music.m_file[0], music.m_file.size());

    // Uncommenting the next block runs without problems
    /*
    writeFileToBuffer(music.m_file, filePath);
    music.m_rw = SDL_RWFromFile(filePath.c_str(), "r");
    */

    if (music.m_rw == nullptr)
        std::cout << "Error creating RW " + std::string(Mix_GetError()) + " ...\n";

    music.m_music = Mix_LoadMUSType_RW(music.m_rw, Mix_MusicType::MUS_OGG, SDL_FALSE);

    if (music.m_music == nullptr)
        std::cout << "Error creating music " + std::string(Mix_GetError()) + " ...\n";

    return music;
}

int main(int argc, char** argv) {
    SDL_Init(SDL_INIT_AUDIO);
    Mix_Init(MIX_INIT_MP3 | MIX_INIT_OGG);
    Mix_OpenAudio(MIX_DEFAULT_FREQUENCY, MIX_DEFAULT_FORMAT, MIX_DEFAULT_CHANNELS, 1024);

    Music music = loadMusic("Sound/music/XYZ.ogg");

    music.play();

    std::cin.ignore();

    return 0;
}

My ArchiveManager works for sure, which can also be seen because ucommenting the block that writes the buffer to a file and creating an SDL_RW from this will run just fine.
The music file I load is just assumed to be an ogg file, which it is in this case, hence creating an SDL_RW from the file works fine. Meaning nothing crashes and the music plays properly start to end.
The music class is from my understanding much too big. I am just keeping the buffer m_file around, as well as the SDL_RW to make sure that the problem does not come from that data being freed. Running Mix_LoadMUS_RW with SDL_FALSE should also make sure that the RW is not freed.
Notably a similar example loading a wav file from the same archive using Mix_LoadWAV_RW works just fine:
Mix_Chunk * chunk;
std::vector<unsigned char> fileBuf = ArchiveManager::loadFileFromArchive(filePath);
chunk = Mix_LoadWAV_RW(SDL_RWFromConstMem(&fileBuf[0], fileBuf.size()), SDL_TRUE);

And here I am not even keeping the buffer around until calling the Mix_PlayCannel. Also here I am calling the load function with SDL_TRUE because I am not creating an explicit SDL_RW. Trying the similar thing for loading the music will not make a difference.
I studied the SDL_mixer source code, but it didn't help me. Maybe my knowledge is not sufficient or maybe I missed something crucial.
To get to the point: Where does that access violation come from and how can I prevent it?
EDIT: Changed the example code so it is straightforward for anyone to reproduce it. So no ArchiveManager or anything like that, just reading an ogg directly into memory. The crucial parts are just the few lines in loadMusic.

A: Music music = loadMusic("Sound/music/XYZ.ogg");
music.play();

The first line will copy the object of type class Music on the right into the new one called music. This will result in the vector m_file being copied, including the data in it. The data for the vector of our new object music will obviously be stored at a different memory location than that of the vector of the object returned by loadMusic. Then the object returned by loadMusic will be deleted from the stack and the data of it's vector will be freed thus invalidating the previously created Mix_Music object and causing an access violation on the second line.
This can be remedied by only ever creating one Music object, for example by creating it via new on the heap and having loadMusic return a pointer to that object.
Music* music = loadMusic("Sound/music/XYZ.ogg");
music->play();

It might anyway be the better choice to allocate the memory for a whole file on the heap instead of on the stack, though I would guess that vectors do this internally.
So short version, it was (what I consider) an rookie mistake and I was too fixated on blaming SDL_Mixer. Bad idea.


text:
Q: java.lang.NoSuchMethodError: org.codehaus.jackson.map.AnnotationIntrospector.pair I am trying to wrok with JAX RS service. I have added few dependencies in my pom .xml. Here is the pom.
    <properties>
    <jersey.version>1.19</jersey.version>
</properties>
<dependencies>
    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-servlet</artifactId>
        <version>${jersey.version}</version>
    </dependency>

    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-json</artifactId>
        <version>${jersey.version}</version>
    </dependency>
    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-client</artifactId>
        <version>${jersey.version}</version>
    </dependency>

    <dependency>
        <groupId>org.mvel</groupId>
        <artifactId>mvel2</artifactId>
        <version>2.2.1.Final</version>
    </dependency>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
        <version>3.0</version>
    </dependency>
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.2.4</version>
    </dependency>

    <dependency>
        <groupId>org.apache.drill.exec</groupId>
        <artifactId>drill-jdbc-all</artifactId>
        <version>1.1.0</version>
    </dependency>

</dependencies>

when i add this dependency <dependency>
            <groupId>org.apache.drill.exec</groupId>
            <artifactId>drill-jdbc-all</artifactId>
            <version>1.1.0</version>
        </dependency>
it fails with elow mentioned exception. I need the above mentioned dependecy for apache drill. On removing and running it works smooth.
The excpetion i am getting is:
java.lang.NoSuchMethodError: org.codehaus.jackson.map.AnnotationIntrospector.pair(Lorg/codehaus/jackson/map/AnnotationIn
trospector;Lorg/codehaus/jackson/map/AnnotationIntrospector;)Lorg/codehaus/jackson/map/AnnotationIntrospector;
    at org.codehaus.jackson.jaxrs.MapperConfigurator._resolveIntrospectors(MapperConfigurator.java:155)
    at org.codehaus.jackson.jaxrs.MapperConfigurator._setAnnotations(MapperConfigurator.java:133)
    at org.codehaus.jackson.jaxrs.MapperConfigurator.getDefaultMapper(MapperConfigurator.java:70)
    at org.codehaus.jackson.jaxrs.JacksonJsonProvider.locateMapper(JacksonJsonProvider.java:648)
    at org.codehaus.jackson.jaxrs.JacksonJsonProvider.writeTo(JacksonJsonProvider.java:500)
    at com.sun.jersey.json.impl.provider.entity.JacksonProviderProxy.writeTo(JacksonProviderProxy.java:160)
    at com.sun.jersey.spi.container.ContainerResponse.write(ContainerResponse.java:302)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1510)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1419)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1409)
    at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:409)
    at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:558)
    at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:733)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291).

Can some one please help as in why on adding the particular dependency it fails with the above exception.
tried running mvn dependency tree to check the conflict in jars.

Building JAXRS-JSON Maven Webapp 0.0.1-SNAPSHOT
------------------------------------------------------------------------

 --- maven-dependency-plugin:2.8:tree (default-cli) @ JAXRS-JSON ---
 com.java.codegeeks.example:JAXRS-JSON:war:0.0.1-SNAPSHOT
 +- com.sun.jersey:jersey-servlet:jar:1.19:compile
 |  \- com.sun.jersey:jersey-server:jar:1.19:compile
 +- com.sun.jersey:jersey-json:jar:1.19:compile
 |  +- org.codehaus.jettison:jettison:jar:1.1:compile
 |  +- com.sun.xml.bind:jaxb-impl:jar:2.2.3-1:compile
 |  |  \- javax.xml.bind:jaxb-api:jar:2.2.2:compile
 |  |     +- javax.xml.stream:stax-api:jar:1.0-2:compile
 |  |     \- javax.activation:activation:jar:1.1:compile
 |  +- org.codehaus.jackson:jackson-core-asl:jar:1.9.2:compile
 |  +- org.codehaus.jackson:jackson-mapper-asl:jar:1.9.2:compile
 |  +- org.codehaus.jackson:jackson-jaxrs:jar:1.9.2:compile
 |  +- org.codehaus.jackson:jackson-xc:jar:1.9.2:compile
 |  \- com.sun.jersey:jersey-core:jar:1.19:compile
 |     \- javax.ws.rs:jsr311-api:jar:1.1.1:compile
 +- com.sun.jersey:jersey-client:jar:1.19:compile
 +- junit:junit:jar:3.8.1:test
 \- org.apache.drill.exec:drill-jdbc-all:jar:1.1.0:compile
 ------------------------------------------------------------------------
 BUILD SUCCESS

A: drill contains too many packages inside it and it collides with other jars in app. I too encountered similar problem but with com.google.common.collect and org.apache.zookeeper packages of drill jar. In my case the version drill is using for these packages are older and so, I just removed those.
zip -d drill-jdbc-all-1.1.0.jar com/google/common/collect/*
zip -d drill-jdbc-all-1.1.0.jar org/apache/zookeeper/*

Now it is working fine. I am not sure how to handle all these using maven only and so opted to delete. It would be better if maven can handle that.


text:
Q: Paginated query from Database I have to do paginated query to return the list to frontend. And this query should be sorted in descending order of their timestamp of transaction i.e. most recent recent transaction should be the 1st element in the list and oldest transaction should be the last element in the list. But I am facing an issue :
Scenario :
Total no of records : 41
Page Size : 5
Query1 :
        R1,R2,R3,R4,R5
Query2 :
        R6,R7,R8,R9,R10

I have served the top 10 records in two pages and now I have to return the next set of results for
3rd page and parallely a new transaction has been done. So the total no of records is 42 now, and
I will do sorting as per timestamp, and will end up in returning R10 again in page no 3, as now there will
be a new record in the top. Also I won't be able to show the newest record as I have already served the
1st page.

How to solve this scenario? The DB is MySQL/MongoDB. Sometimes I need to serve this from ElasticSearch as well.


text:
Q: Mongoose Error: Schema hasn't been registered I got an error that Schema hasn't been registered for model "student".

Here is my code of schema and services respectively.
import { IsString, IsInt } from 'class-validator'

export class studentdto{
  @IsString()
  name:string

  @IsInt()
  rollno:number

  @IsString()
  section:string
}

import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { studentdto } from './student.dto';

@Injectable()
export class CrudService {
  constructor(
    @InjectModel('student') private readonly studentdto
  ) {}

 async insert(name, rollno, section) {
   const add_stu=await this.studentdto({name,rollno,section})
   return await add_stu.save()
   return "data saved"
 }
}

Here is the code of module file of my app
import { Module } from '@nestjs/common';
import { CrudController } from './crud.controller';
import { CrudService } from './crud.service';
import { MongooseModule } from '@nestjs/mongoose';
import { studentdto } from './student.dto';

@Module({
  imports: [
    CrudModule,
    MongooseModule.forFeature([
      { name: 'student', schema:"studentdto", collection: 'data' },
    ]),
  ],
  controllers: [CrudController],
  providers: [CrudService],
})
export class CrudModule {}


text:
Q: email scraper using python beautiful soup or html module Currently, I am trying to gather data from my realtor from the listings she sends me. It always comes through a link from the main site "http://v3.torontomls.net" I think only realtors can go into this site and filter on houses, but when she sends it to me I can see a list of houses.
I am wondering if it is possible to create a python script that:)
1) opens Gmail
2) filter's on her emails
3) opens one of her emails
4) clicks on the link
5) Scrapes the house data into a CSV format
I am not sure about the feasibility of this, I have never used python to scrape web pages. I can see step 5 is doable, but how do I go about step 1 to 4?

A: Yes, this is possible, but you need to do some requirements gathering beforehand to determine which parts of the process can be eliminated. For instance, if your realtor is sending you the same link each time, you can just target that web address directly. If the link changes but is parameterized by month, for instance, you can just adjust the web address each month when you want to process the results.
To make the requests, I would suggest using the requests package along with bs4 (BeautifulSoup 4) to target elements. For creating CSV files, you may choose to use csv, but there are many alternatives if you require something that's more specific to your use case.


text:
Q: Regularization and scaling feature matrix with weights When using L1 or L2 regularization in a glm it is necessary to standardize the features to be variance 1. When applying weights to the glm, should the feature matrix be standardized so that it has a weighted variance of 1?
According to the glmnet paper
https://web.stanford.edu/~hastie/Papers/glmnet.pdf
There is no mention of standardizing to have weighted variance 1. Furthermore, there is a simplification in the unweighted case that's made in equation 8 where the authors took advantage of the fact that column j had variance 1. When they describe the weighted case, they do not make any simplification taking advantage of column j having weighted variance 1. This makes it sound like standardization always happens without weights.
When I went through the source code of ElasticNet in sklearn I was unable to find references to weights
https://github.com/scikit-learn/scikit-learn/blob/14031f6/sklearn/linear_model/coordinate_descent.py#L503
This doesn't seem to be correct. If I have a data frame with 2 identical rows, they will contribute twice to the mean and variance. This can be equivalently represented as one row with a weight of 2, but if weights are ignored in standardization the algorithm will have a different result


text:
Q: PHP statment not working on an include I have a PHP statement on a sidebar, the sidebar is included on all pages.
In the sidebar I want hide content on the results page, so I'm using this:
<?php
if ($page!='results')
{?>

THE MAIN SIDEBAR CONTENT

SOME CONTENT

<?php }  ?>

The problem is that it looks like its not recognising the page as having
$page='results';

at the top of it. Maybe because the code is in a included page but I thought it would just get read as one page?
If I add
$page='results';

to the start of the above script, it works (just to verify I have written the code correctly.
I have also checked that results.php has
$page='results';

right at the very top of it.
Can I not use this code on an include or am I missing something?
As per navnav's request, here is the code for the include and the actual page. NOTE I am not actually using '$results' I'd just used that as an example for my post. In the real code below, you'll see I am using '$getvaluation'
Code for sidebar....

Property Search

      <?php
            $page = $_SERVER['REQUEST_URI'];
            $page = explode('/', $page);
        if (isset($_POST['bed']) && $_POST['bed'] != '' && $page[2] == 'test.php'){
            $url = 'http://www.vebra.com/home/quick/PFrefine.asp';
            $target = 'target="hello"';
            $js_submit = true;

            $bed = $_POST['bed'];
            $min = $_POST['lop'];
            $max = $_POST['hip'];
            $area1 = $_POST['cou1'];
            $area2 = $_POST['cou2'];
            $area3 = $_POST['cou3'];
            // Hidden Fields
            $hidden1 = $_POST['slo'];
            $hidden2 = $_POST['fid'];
            $hidden3 = $_POST['bid'];
            $hidden4 = $_POST['dbt'];
            $hidden5 = $_POST['nre'];
            $hidden6 = $_POST['thu'];
            $hidden7 = $_POST['vto'];
            $hidden8 = $_POST['ord'];
            $hidden9 = $_POST['nba'];

        } else {

            $url = 'test.php';
            $target = '';
            $js_submit = false;
        }

      ?>

      <form method="post" action="<?php echo $url; ?>" name="searchform" id="searchform" <?php echo $target; ?> >

Bedrooms

<select name="bed" class="type1 Selectrooms">
                  <option <?php if($bed == '0'){ echo 'selected="selected"';} ?> value="0">0</option>
                  <option <?php if($bed == '1'){ echo 'selected="selected"';} ?> value="1">1</option>
                  <option <?php if($bed == '2'){ echo 'selected="selected"';} ?> value="2">2</option>
                  <option <?php if($bed == '3'){ echo 'selected="selected"';} ?> value="3">3</option>
                  <option <?php if($bed == '4'){ echo 'selected="selected"';} ?> value="4">4</option>
                  <option <?php if($bed == '5'){ echo 'selected="selected"';} ?> value="5">5+</option>
              </select>

Minimum Price

<select class="type2 SelectPrices" name="lop">
                <option <?php if ($min == '0'){ echo 'selected="selected"';} ?> value="0">£0</option>
                <option <?php if ($min == '25000'){ echo 'selected="selected"';} ?> value="25000">£25,000</option>
                <option <?php if ($min == '50000'){ echo 'selected="selected"';} ?> value="50000">£50,000</option>
                <option <?php if ($min == '75000'){ echo 'selected="selected"';} ?> value="75000">£75,000</option>
                <option <?php if ($min == '100000'){ echo 'selected="selected"';} ?> value="100000">£100,000</option>
                <option <?php if ($min == '125000'){ echo 'selected="selected"';} ?> value="125000">£125,000</option>
                <option <?php if ($min == '150000'){ echo 'selected="selected"';} ?> value="150000">£150,000</option>
                <option <?php if ($min == '175000'){ echo 'selected="selected"';} ?> value="175000">£175,000</option>
                <option <?php if ($min == '200000'){ echo 'selected="selected"';} ?> value="200000">£200,000</option>
                <option <?php if ($min == '225000'){ echo 'selected="selected"';} ?> value="225000">£225,000</option>
                <option <?php if ($min == '250000'){ echo 'selected="selected"';} ?> value="250000">£250,000</option>
                <option <?php if ($min == '275000'){ echo 'selected="selected"';} ?> value="275000">£275,000</option>
                <option <?php if ($min == '300000'){ echo 'selected="selected"';} ?> value="300000">£300,000</option>
                <option <?php if ($min == '325000'){ echo 'selected="selected"';} ?> value="325000">£325,000</option>
                <option <?php if ($min == '350000'){ echo 'selected="selected"';} ?> value="350000">£350,000</option>
                <option <?php if ($min == '375000'){ echo 'selected="selected"';} ?> value="375000">£375,000</option>
                <option <?php if ($min == '400000'){ echo 'selected="selected"';} ?> value="400000">£400,000</option>
                <option <?php if ($min == '500000'){ echo 'selected="selected"';} ?> value="500000">£500,000</option>
                <option <?php if ($min == '600000'){ echo 'selected="selected"';} ?> value="600000">£600,000</option>
                <option <?php if ($min == '700000'){ echo 'selected="selected"';} ?> value="700000">£700,000</option>
                <option <?php if ($min == '800000'){ echo 'selected="selected"';} ?> value="800000">£800,000</option>
                <option <?php if ($min == '900000'){ echo 'selected="selected"';} ?> value="900000">£900,000</option>
                <option <?php if ($min == '1000000'){ echo 'selected="selected"';} ?> value="1000000">£1,000,000</option>
                <option <?php if ($min == '2000000'){ echo 'selected="selected"';} ?> value="2000000">£2,000,000</option>
                <option <?php if ($min == '3000000'){ echo 'selected="selected"';} ?> value="3000000">£3,000,000</option>
                <option <?php if ($min == '4000000'){ echo 'selected="selected"';} ?> value="4000000">£4,000,000</option>
                <option <?php if ($min == '5000000'){ echo 'selected="selected"';} ?> value="5000000">£5,000,000</option>
                <option <?php if ($min == '6000000'){ echo 'selected="selected"';} ?> value="6000000">£6,000,000</option>
              </select>

Maximum Price

<select name="hip" class="type3 SelectPrices">
                <option <?php if ($max == '25000'){ echo 'selected="selected"';} ?> value="25000"> £25,000</option>
                <option <?php if ($max == '50000'){ echo 'selected="selected"';} ?> value="50000">£50,000</option>
                <option <?php if ($max == '75000'){ echo 'selected="selected"';} ?> value="75000">£75,000</option>
                <option <?php if ($max == '100000'){ echo 'selected="selected"';} ?> value="100000">£100,000</option>
                <option <?php if ($max == '125000'){ echo 'selected="selected"';} ?> value="125000">£125,000</option>
                <option <?php if ($max == '150000'){ echo 'selected="selected"';} ?> value="150000">£150,000</option>
                <option <?php if ($max == '175000'){ echo 'selected="selected"';} ?> value="175000">£175,000</option>
                <option <?php if ($max == '200000'){ echo 'selected="selected"';} ?> value="200000">£200,000</option>
                <option <?php if ($max == '225000'){ echo 'selected="selected"';} ?> value="225000">£225,000</option>
                <option <?php if ($max == '250000'){ echo 'selected="selected"';} ?> value="250000">£250,000</option>
                <option <?php if ($max == '275000'){ echo 'selected="selected"';} ?> value="275000">£275,000</option>
                <option <?php if ($max == '300000'){ echo 'selected="selected"';} ?> value="300000">£300,000</option>
                <option <?php if ($max == '325000'){ echo 'selected="selected"';} ?> value="325000">£325,000</option>
                <option <?php if ($max == '350000'){ echo 'selected="selected"';} ?> value="350000">£350,000</option>
                <option <?php if ($max == '375000'){ echo 'selected="selected"';} ?> value="375000">£375,000</option>
                <option <?php if ($max == '400000'){ echo 'selected="selected"';} ?> value="400000">£400,000</option>
                <option <?php if ($max == '500000'){ echo 'selected="selected"';} ?> value="500000">£500,000</option>
                <option <?php if ($max == '600000'){ echo 'selected="selected"';} ?> value="600000">£600,000</option>
                <option <?php if ($max == '700000'){ echo 'selected="selected"';} ?> value="700000">£700,000</option>
                <option <?php if ($max == '800000'){ echo 'selected="selected"';} ?> value="800000">£800,000</option>
                <option <?php if ($max == '900000'){ echo 'selected="selected"';} ?> value="900000">£900,000</option>
                <option <?php if ($max == '1000000'){ echo 'selected="selected"';} ?> value="1000000">£1,000,000</option>
                <option <?php if ($max == '2000000'){ echo 'selected="selected"';} ?> value="2000000">£2,000,000</option>
                <option <?php if ($max == '3000000'){ echo 'selected="selected"';} ?> value="3000000">£3,000,000</option>
                <option <?php if ($max == '4000000'){ echo 'selected="selected"';} ?> value="4000000">£4,000,000</option>
                <option <?php if ($max == '5000000'){ echo 'selected="selected"';} ?> value="5000000">£5,000,000</option>
                <option <?php if ($max == '6000000'){ echo 'selected="selected"';} ?> value="6000000">£6,000,000+</option>
              </select>

Regions

<input <?php if( $area1 == '43' ){ echo 'checked="checked"';} ?> type="checkbox" name="cou1" id="couHertfordshire" value="43" />

Hertfordshire

<input <?php if( $area2 == '126' ){ echo 'checked="checked"';} ?> type="checkbox" name="cou2" id="couLondonNorth" value="126" />

London, North

<input <?php if( $area3 == '127' ){ echo 'checked="checked"';} ?> type="checkbox" name="cou3" id="couLondonNorthWest" value="127" />

London, North West

            <input type="hidden" name="cou" id="couHertfordshire_hide" value="<?php if ( $area1 == '43' ) { echo '43';} ?>" />
            <input type="hidden" name="cou" id="couLondonNorth_hide" value="<?php if ( $area2 == '126' ) { echo '126';} ?>" />
            <input type="hidden" name="cou" id="couLondonNorthWest_hide" value="<?php if ( $area3 == '127' ) { echo '127';} ?>" />

            <input type="hidden" name="slo" value="undefined" />
            <input type="hidden" name="fid" value="894" />
            <input type="hidden" name="bid" value="0" />
            <input type="hidden" name="dbt" value="1" />
            <input type="hidden" name="nre" value="undefined" />
            <input type="hidden" name="thu" value="undefined" />
            <input type="hidden" name="vto" value="undefined" />
            <input type="hidden" name="ord" value="undefined"/>
            <input type="hidden" name="nba" value="undefined" />

<input type="submit" class="search_now" value="Find Property" />

      </form>

      <?php if($js_submit){ ?>

        <?php } ?>

        <?php
        if ($page!='getvaluation')
       { ?>

Featured Property

      <?php perch_content('Featured Property Image');?>

<?php perch_content('Featured Property Title'); ?>

     <?php perch_content('Featured Property Description'); ?>

     <?php }  ?>

Code for Valuation Page
<?php
$page='getvaluation';
include('perch/runtime.php'); ?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1    /DTD/xhtml1-transitional.dtd">

<title>Squires Estates - Independent Estate Agent, London</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE9" />
<meta name="description" content="" />
<meta name="keywords" content="" />
<link href="css/screen.css" rel="stylesheet" type="text/css" />

<link rel="stylesheet" href="slider/themes/default/default.css" type="text/css" media="screen" />
<link rel="stylesheet" href="slider/nivo-slider.css" type="text/css" media="screen" />

<?php include("header.php"); ?>

Please use the form below to arrange a free valuation

      <?php
      // Text Section
      //perch_content('form');?>
      <?php perch_content('Form Text');?>

    <?php
    include('sidebar.php');
    include('footer.php');
    ?>

A: Make sure you're including the file that assigns result to $page before you do the comparing.
So,
This is bad:
<?php
if ($page!='results')
{?>

THE MAIN SIDEBAR CONTENT

SOME CONTENT

<?php }
include("the-file-here-that-defines-$page");//The include line is AFTER the comparing here...which means the $page value will not be changed until after the comparing...
?>

This is good:
<?php
include("the-file-here-that-defines-$page");//the include line is BEFORE the comparing, so $page will change before, and it should all work well..
if ($page!='results')
{?>

THE MAIN SIDEBAR CONTENT

SOME CONTENT

<?php }

?>

EDIT:
I've taken a look at your edit, and my original suggestion is causing the issue. In your sidebar.php you have $page = explode('/', $page); which is executed after you do $page='getvaluation'; but, you're also doing your comparing in sidebar.php which you also re-define $page in.
A quick fix for this would be to simply use another variable to represent 'getvaluation':
So, in your sidebar.php:
if($getValuation===true){$page='getvaluation';}//check if $getValuation is true (which will will be defined in your valuation page)
        if ($page!='getvaluation')
       { ?>

Featured Property

      <?php perch_content('Featured Property Image');?>

<?php perch_content('Featured Property Title'); ?>

     <?php perch_content('Featured Property Description'); ?>

     <?php }  ?>

And now, in your valuation page:
Instead of:
<?php
$page='getvaluation';

do this:
<?php
$getValuation=true;

and on other pages (pages where you would like the side bar to show), simply do not define $getValuation or assign it to false:


text:
Q: Delayed Differential Equations using Desolve I am trying to set up an "interface model for dosage adjustment connects hematotoxicity to pharmacokinetics". In this model there is a feedback loop and the influx must not only be amplified but also be delayed. Is there any good starting point to implement such models
Image and equations Shown below.

dCc <- -k12 * c_central + k21 * r * c_peripheral - k10 * c_central
dCp <- k12 / r * c_central - k21 * c_peripheral
dy=-alphaexp[-beta(y)]*y+[c_central -gamma]*H[c_central -gamma] ; Y(0)=0
dg=kskww0*phi[w,param]*m[y,u]-{ks+n[y,v]}*g
dw=g*(time-delay)-kw*w
m[y(t),u]=exp(-uy(t)]
n[y(t),v]=vy(t)
initial condition
phi[w(t),param]=[w(t)/W0]^-param
H <- function(x) {
  ifelse(x < 0, 0, 1)
}
diffeq <- function(t, state, params) {
  with(as.list(c(state, params)), {
    dCc <- -k12 * c_central + k21  * c_peripheral - k10 * c_central
    dCp <- k12  * c_central - k21 * c_peripheral
    dy <- -alpha * exp(-beta * y) * y + (c_central - gamma) *H(c_central - gamma)
    ds <- ks*kw*((w/w0)^-0.2)*(1-exp(-u*y))- ks * s
    dw <- -kw * w + (t-k) * s
    return(list(c(ds, dw, dCc, dCp,dy)))
  })
}

# Set the initial conditions and parameter values
y0<-0
s0 <- 10
w0 <- 3
c_central0 <- 500/5
c_peripheral0 <- 0
params <- c(Rs = 1, d = 0.1, k = 1.65, kw = 1, ks = 0.5, theta = 1, W = 100, K = 100,
            alpha = 0.85, beta = 1.5*10-4, gamma = 0.2,u=5.6*10-4,
            k12 =1.263*10-1, k21 = 3.547*10-1, k10 = 9.461*10-2, r = 10000/42000)

# Solve the differential-delay equation using an ODE solver
result <- ode(y = c(y = y0,s = s0, w = w0, c_central = c_central0, c_peripheral = c_peripheral0),
              times = seq(0, 40, by = 0.1), func = diffeq, parms = params)

# Plot the solution
plot(result[, "time"], result[, "c_central"], type = "l", xlab = "Time (t)", ylab = "Neutrophil Progenitor Cells (s(t))")

lines(result[, "time"], result[, "s"], col = "red")
lines(result[, "time"], result[, "c_central"], col = "blue")
lines(result[, "time"], result[, "c_peripheral"], col = "green")


text:
Q: Hiding the ticks on the x-axes clips the chart (Chart.JS) I am trying to hide the ticks on the x-axis of a bubble chart.
I tried using "display: false" within the ticks property.
It does remove the ticks however the chart is now being clipped.
Is there a way I can hide these ticks without affecting the appearance of the chart or to maybe add some padding so the chart's appearance isn't affected?
Appearance before the ticks are removed
Clipping once the ticks are removed with "display: false"
You can see the code for the chart I have created below:
xAxes : [
    {
        id : 'first-x-axis',
        ticks : {
            display : false,
            min :  <  ? php echo $min ?  > , // Controls where axis starts
            max :  <  ? php echo $max ?  > , // Controls where axis finishes
            stepSize :  <  ? php echo $step ?  > // Control the gap between the first x-axis value and the last x-axis value
        },
        gridLines : {
            display : false,
            lineWidth : 7 // Width of bottom line
        }
    }
]

I appreciate any help or suggestions ^_^

A: I figured it out!
You can adjust the height/length of the tick marks by using "tickMarkLength" within "gridlines"
You can see the code for the solution below:
xAxes: [
    {
        id: 'first-x-axis',
        ticks: {
            display: false,
            min: <?php echo $min ?>, // Controls where axis starts
            max: <?php echo $max ?>, // Controls where axis finishes
            stepSize: <?php echo $step ?> // Control the gap between the first x-axis value and the last x-axis value
        },
        gridLines: {
            display: false,
            lineWidth: 7,
            tickMarkLength: 30// Adjusts the height for the tick marks area
        }
    }
]

I hope this helps!


text:
Q: How to get multiple SLD files of the same shapefile? I need to get multiple SLD files for the same shapefile. Geometry is polygons, and they need to be colored by one attribute column.  What is the best solution? I'm working with ArcMap2SLD or ArcMap to SLD Converter.

A: The simplest way to do this is to create the first SLD file using which ever tool you like. The copy it and edit it using a text editor to change the filter to point to the next column and change the colour as required.
Though from you description you should be able to have one SLD file with all the criteria in it, unless an object can have a 1 in multiple columns.


text:
Q: Let {$x_n$} be such that $\lim \inf_{n \to \infty }|x_n|=0$. Prove that there exists a {$x_{n_{k}}$} where $\sum_{k=1}^{\infty}x_{n_{k}}$ converges.
Problem: Let $\{x_n\}$ be such that $\displaystyle\lim \inf_{n \to \infty }|x_n|=0$. Prove that $\exists$ a subsequence $\{x_{n_{k}}\}$ where the subseries $\displaystyle\sum_{k=1}^{\infty}x_{n_{k}}$ converges.

I know that $\displaystyle\lim\inf_{n \to \infty } |x_n| = \sup_{n \geqslant 1} \inf_{k\geqslant n} |x_k|=0$.
However, I am confused as to how to take this to the limit of a series, and conclude that infinite series converges. Any help would be appreciated!

A: Let $\displaystyle a_n=\inf_{j\geq n} |x_j|$. By hypothesis, $a_n \to 0$ as $n\to\infty$. Let $\{b_k\}$ be a positive sequence such that $\sum_{k=1}^\infty b_k <\infty.$ Obviously, $b_k \to 0$. Since $a_n \to 0$, for each $k$, there exists $n_k$ such that $a_{n_k}<b_k$. By definition, $b_k$ is not a lower bound for the set $A_{n_k}=\{|x_m| : m\geq n_k\}$. Hence, there exists $|x_{m(n_k)}|\in A_{n_k}$ such that $a_{n_k}\leq |x_{m(n_k)}|<b_k$.
Finally, by comparison, $\displaystyle \sum_{k=1}^\infty |x_{m(n_k)}|<\sum_{k=1}^\infty b_k<\infty,$ so the convergence follows (absolutely).


text:
Q: Loading new cells added from Parse data class I'm creating an app for clothing shop and I'm using parse cloud to upload and retrieve data from it. But when I add a new item to the data class, it loads at the bottom of the tableview.
How can I make the new items or the new cells load from the top of the table view like at the first cell?
I'm using PFQueryTableView from Parse instead of the original tableView.

A: If you are using PFQuery then you can trial & error using:
– orderByAscending:
OR
– orderByDescending: - right after you update the data source.
Also, you might want to check out This Discussion.
Let me know, if it works for you.


text:
Q: Break out certain time within a timeframe in excel I am paying salaries for some workers and they have different salary depending on what time of the day they work. E.g. if they work between 06:00-22:00 they earn X and if they work between 22:00-06:00 they earn Y. The time extracted from my software take the total time worked, e.g. between 21:15-06:15, i.e. the staff will get paid differently during the time of this shift. How do I break the time out so I can chose to pay different between the different time slots. I've attached a gsheet with some example data and with two columns where the output should be:
https://docs.google.com/spreadsheets/d/1nRrxn6tTtiNXCrssMJwRyWL2jj5TXBFVmNhKPJ_BbVg/edit#gid=0

A: To detect 6-22 use below formula. Check your sheet.
=IF(AND(A4>TIME(5,30,),A4<TIME(6,30,0)),"X","")

To detect 22-6 use below formula
=IF(AND(A4>TIME(21,30,),A4<TIME(22,30,0)),"Y","")

Then change X and Y as your need. You can also change time frame to detect start time. I have used 1 hour to detect shift.

A: Here is a fairly general one based on the overlap formula
For hours worked 06:00-22:00
=max(min(B4+(B4<A4),time(22,0,0))-max(A4,0.25),0)+max(min(B4+(B4<A4),1+TIME(22,0,0))-max(A4,1.25),0)

For hours worked 22:00-06:00
=max(min(B4,0.25)-max(A4,0),0)+max(min(B4+(B4<A4),1.25)-max(A4,time(22,0,0)),0)


text:
Q: encrypt file with php and public key I generated a key pair (public and private), and from console by:
openssl smime -encrypt -aes256 -in backup.sql -binary -DEM -out outform backup_encrypted.sql public_key.pem
I encrypt the file correctly. Sql, as I can do this with php? I've tried several and nothing Functions
Here I leave one of them.
$data=file_get_contents("backup.sql");
$key=file_get_contents("public_key.pem");
openssl_public_encrypt($data,$output,$key);
echo $output;

$output returns nothing ..
Thank you.

A: Please take a look at the manual, you have to give the path of the public key:
$data=file_get_contents("backup.sql");
$key="file://path/to/public_key.pem";
openssl_public_encrypt($data,$output,$key);
echo $output;

A: you can you file_get_contents(), as example:
$data=file_get_contents("backup.sql");
$key= file_get_contents('public_key.pem');
openssl_public_encrypt($data,$output,$key);
echo $output;

I checked this snippets and its working.


text:
Q: Dreamweaver CS5.5 Mac OS X main CONFIGURATION folder deleted So I had a problem with Dreamweaver telling me that there is something wrong with a file so I went to Google to fix my problem but instead of deleting the configuration folder inside the en_US folder, I deleted the main one (which is important and should never be deleted) so now Dreamweaver is telling me "Dreamweaver is unable to locate the menus.xml file and cannot rebuilt it from backup. You may need to reinstall Dreamweaver" is there a solution for my problem? I am trying to recover my deleted folders from the trash. And btw before deleting the configuration folder I placed a copy of it on my desktop but somehow it turned out to be empty!

A: Well - as it says, you should reinstall Dreamweaver. You might also be able to copy the files from another PC where Dreamweaver is installed.
You might want to try data recovery software, but the question would be if it would be worth the work. Reinstalling will be faster and more reliable to actually work.


text:
Q: Google Visualization Animation when chart loads for the first time I would like to know if I can apply an animation to the charts on the first time it draws?
And not only when a change of data happens?
THanks!

A: The Chart should be rendered before you can apply your animation which is showing transition from one state to another. You can either change the data or change the chart options to create the transition and its animation.
To be able to show animation on the first time, you can simply create an empty (no data) chart, and then add your data to the chart, to show the data animation.
var options = {
  animation:{
    duration: 1000,
    easing: 'out',
  }
};
var data = new google.visualization.DataTable();
data.addColumn('string', 'N');
data.addColumn('number', 'Value');
var chart = new google.visualization.ColumnChart...
chart.draw(data, options);
// Adding data
data.addRow(['V', 200]);

A: Try something like this http://jsfiddle.net/h7mSQ/163/. The way to do this is to render chart with zero values and then set values as required and draw chart again. Don't forget to set minimal and maximal value for (in this example) vertical axis.
function drawChart() {
  var option = {title:"Yearly Coffee Consumption in our company",
               width:600, height:400,
               animation: {duration: 1000, easing: 'out',},
               vAxis: {title: "Cups of coffee", minValue:0, maxValue:500},
               hAxis: {title: "Year"}};
  var data = new google.visualization.DataTable();
  data.addColumn('string', 'N');
  data.addColumn('number', 'Value');
  data.addRow(['2003', 0]);
  data.addRow(['2004', 0]);
  data.addRow(['2005', 0]);
  // Create and draw the visualization.
  var chart = new google.visualization.ColumnChart(document.getElementById('chart'));
  chart.draw(data, option);
  data.setValue(0, 1, 400);
  data.setValue(1, 1, 300);
  data.setValue(2, 1, 400);
  chart.draw(data, option);

}

google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);

A: UPDATED ANSWER
Google has updated chart options and added the option to animate the chart on the first time it draws.
So the only thing you have to do is psecify it in the options like that:
var options = {
            animation: {
                duration: 1500,
                startup: true //This is the new option
            }
        };

So you dont have to load an empty chart on the beggining or to do any other hack.
DEMO


text:
Q: sort columns based in names R I need to sort the following data.frame in R based on its columns name:
L1 L10 L11 L12           L13       L14 L15        L16          L17 L18 L19 L2 L20 L21        L22 L23 L24         L25
1  1.00000000   0   0   0  0.000000e+00 0.0000000   0 0.00000000 0.000000e+00   0   0  0   0   0 0.00000000   0   0 0.000000000

The ordered columns must look like:
L1 L2 L10 L11 L12 L13 L14 L15 L16 L17 L18 L19 L20 L21 L22 L23 L24 L25

A: You could do sort(names(df)) but the issue is that L2 comes after L10 (lexicographical sorting for strings).
One thing we could do is adding a white space (left padding) in front of the strings length 2 which makes sure they come before when sorted.
df[order(sprintf("%*s", 3, names(df)))]

  L1 L2 L10 L11 L12 L13 L14 L15 L16 L17 L18 L19 L20 L21 L22 L23 L24 L25
1  1  0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0

A stringr alternative:
df[order(stringr::str_pad(names(df), 3, side = "left", pad = " "))]

PS.
If you have longer variable names, 3 should be replace by max(nchar(names(df)).


text:
Q: Mock private field with mockito shows no such field exception I am trying to follow this blog https://newbedev.com/mockito-mock-private-field-initialization
and a lot of stackoverflow questions to mock a private field of a class which is basically another class.
    public class Class1 {
 @Inject private Class2 class2;

When I use
Class2 mockedClass2 = Mockito.mock(Class2.class);
Class1 mockedClass1 = Mockito.mock(Class1.class);
Whitebox.setInternalState(Class1.class, "class2", mockedClass2);

Or if I use
ReflectionTestUtils.setField(class1, "class2", mockedClass2);

Or
FieldSetter.setField(class1,  class1.getClass().getDeclaredField("class2")
        , mockedClass2)

I get the same error that  java.lang.NoSuchFieldException
Does the class have to be static that I am trying to mock? Can anyone suggest what's going wrong. working for the first time with powermockito.


text:
Q: SimpleDateFormat - day, month, time are incorrect This code converts a vendor proprietary timestamp in hex (radix16) format to a Unix time.  I know from the Java docs that the SimpleDateFormat is zero-based month (Jan=0), however, when converting from a Unix timestamp to a human readable format using the format string, neither the month, day nor time is correct (see the results in the comments near the end).
Expected:
Yr 2010 Mo 1 Da 4 Time 13513407 (03:45:13:407).

Results:
HR:20100205_032123239.

The month is 02 instead of 01 (as expected), but the day is 05 instead of 04.  The hour (03) is correct, but the mins, secs, and millis are not.
I've included the pass "text" value used for testing in the comments.
public static long parseUnsignedHex(String text) {
    // text = "07DA010400CE32BF"
    long bsUnixTs = 0;
    if (text.length() == 16) {
        String bsYr = text.substring(1, 4);
        String bsMo = text.substring(5,6);
        String bsDa = text.substring(7,8);
        String bsTime = text.substring(9,16);
        try {
            long bsYrL = Long.decode("0x" + bsYr);
            long bsMoL = Long.decode("0x" + bsMo);
            long bsDaL = Long.decode("0x" + bsDa);
            long bsTimeL = Long.decode("0x" + bsTime);
            Calendar bsCal = Calendar.getInstance();
            bsCal.set((int)bsYrL, (int)bsMoL, (int)bsDaL);
            bsCal.setTimeInMillis(bsCal.getTimeInMillis() + bsTimeL);
            bsUnixTs = bsCal.getTimeInMillis();
            System.out.printf("Yr %d Mo %d Da %d Time %d%n", bsYrL, bsMoL, bsDaL, bsTimeL);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        } catch (Throwable e){
            e.printStackTrace();
        }
    }
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmssSSS");
    // convert unix into yyyyMMdd_HHmmssSSS Human Readable (HR) format
    String[][] arTimeString = new String[1][2];
    for(int i=0; i<arTimeString.length; i++){
        arTimeString[i][0] = Long.toString(bsUnixTs);
        arTimeString[i][1] = sdf.format(bsUnixTs);
        try {
                System.out.format("Unix:" + arTimeString[i][0] + " HR:" + arTimeString[i][1]);
                System.out.println();
                // result:
                // SimpleDateFormat - month is zero-based
                //                    the day of month may be incremented because the time is 03:45:13:407
                // Yr 2010 Mo 1 Da 4 Time 13513407
                // Unix:1265358083239 HR:20100205_032123239
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    return bsUnixTs;
}

A: Basically, change...
Calendar bsCal = Calendar.getInstance();
bsCal.set((int)bsYrL, (int)bsMoL, (int)bsDaL);
bsCal.setTimeInMillis(bsCal.getTimeInMillis() + bsTimeL);

To
Calendar bsCal = Calendar.getInstance();
bsCal.set((int) bsYrL, (int) bsMoL - 1, (int) bsDaL, 0, 0);
bsCal.set(Calendar.SECOND, 0);
bsCal.set(Calendar.MILLISECOND, 0);

This will result in the output
Yr 2010 Mo 1 Da 4 Time 13513407
Unix:1262537113407 HR:20100104_034513407

Calendar uses 0 based months, not SimpleDateFormat, also, when using Calendar#set it will only affect the fields you supply, leaving the hour, minute and second and millisconds unchanged from the time the Calendar was created (which is a snapshot of that time/date value)
So what your original code was doing was capturing a snapshot of the current date AND time, resetting the year, month and day values, the adding an additional time value to the CURRENT time...


text:
Q: What to do with a question that was based on a wrong assumptions? I asked a question based on a wrong assumption. As it later turned out, my problem had nothing to do with what was assumed in the question. The answer to my question, however, is based on that wrong assumption.
My question now would be what to do with that question? As it cannot be altered without rendering the answers useless and wrong, should it be deleted?
It'm talking about this question: How would I address QWidgets Ui when working with namespaces?

A: The long term objective of a stack exchange question is to be useful to a number of people (only the first of which is the question author). It is from that perspective that you should make your decision, I think this question could be of use to others and so should stay.
The question is of course moot as you can't delete it anyway as it has upvoted answers

A: Just leave the question.  If it's a valid question with an answer that may well be helpful to future visitors then the site is serving it's purpose.  It may not have helped you, but that doesn't mean it can't help anyone else.  In any case, the post has an answer with a positive score, so you couldn't delete it even if you wanted to.
If you still have a problem that you need help with then just ask a new question, given that trying to edit this one would be too much of a radical change that would invalidate existing answers.


text:
Q: Google Photos API - media items without albums I like Google Photos but I've noticed that it is lacking some basic metrics like how many media items are in my account. Also I wanted to see which of my media items are not included in any of my albums. I ended up creating a simple console app using Google Photos REST API. It uses GET /albums, then POST /mediaItems:search?albumId={id} to get each album's media items and then cross references them with a full list of media items returned by GET /mediaItems.
It worked reasonably well however I've noticed a problem with the shared items. For a shared album owned by account A, if a media item is added from another account B then its id won't be found in the list of the media items of the account A (which is not unreasonable). If such a shared media item is saved in account A its id won't match the id of the original shared media item added to the shared album (returned by POST /mediaItems:search?albumId={id}). W/out an indicator of some sort to identify if a media item belongs to another account it's challenging to filter them out. I expected to see the contributorInfo as part of the MediaItem but that attribute is not returned.
If I try to add a saved copy of the same shared item into an album using UI I get a notification message that it's already there so obviously Google Photos UI does have that info. Does anyone have any clever ideas on how to  match a saved copy of a shared media item with the original? The code is available at https://github.com/pavelfomin/gphoto-manager

A: I ended up using ignore media items list in https://github.com/pavelfomin/gphoto-manager that I populate locally with the media items I want to ignore:
Usage: com.droidablebee.gphoto.GooglePhotoApplication [options] -token=<access token> [-Dsuppress-warnings] [-Dignore-media-items-file=<file with media items to ignore>]
            --albums           list all albums, sorted by name
            --album-items      list all items per album (use with care for large number of media items)
            --items            list all items (use with care for large number of media items)
            --items-no-album   list all items not included in any album
            <access token>     OAuth 2 Access Token can be obtained from https://developers.google.com/oauthplayground
                               use 'https://www.googleapis.com/auth/photoslibrary.readonly' as the requested scope
            suppress-warnings  suppress all warnings, including album media count / items mismatch

Ideally, I'd use Google Photos REST API to filter out the shared items but that does not seem to be possible at the moment.


text:
Q: Postfix not receiving email from gmail but it does recieve from hotmail I got Zentyal SOGo installed. I can send emails from SOGo and both the gmail and hotmail accounts receive the emails.
I reply the email from hotmail and SOGo receives the email.
I reply the email from gmail and the email does not arrives.
Any Ideas? Where should i look? Any documentation recommended to read?


text:
Q: how to make Numbering rows in a query I have a simple select statement:
Get numbering of rows from Product table in the following order: a name of the manufacturer in
--decreasing order of quantity of models produced by it (when there is identical quantity of models
--for a number of manufacturers, their names should follow in increasing alphabetic order), model (increasing order).
--Output: number in accordance with the above order, a name of the manufacturer (maker), model
RESULT SHOULD BE -
no  maker   model
1   A   1232
10  E   2112
11  E   2113
12  B   1121
13  B   1750
14  D   1288
15  D   1433
16  C   1321
2   A   1233
3   A   1276
4   A   1298
5   A   1401
6   A   1408
7   A   1752
8   E   1260
9   E   1434

MY QUERY :
with result as
(select *, count(*) over (partition by maker) as ModelsCount from Product)
select row_number() over (order by ModelsCount desc,model) AS No, Maker, Model
from result

MY RESULT:
no  maker   model
1   A   1232
10  E   2112
11  E   2113
12  B   1121
13  D   1288
14  D   1433
15  B   1750
16  C   1321
2   A   1233
3   A   1276
4   A   1298
5   A   1401
6   A   1408
7   A   1752
8   E   1260
9   E   1434


text:
Q: UIScrollView doesn't zoom UIView after applying affine transformation to the latter I'm struggling with this issues since two days now and I couldn't find a solution yet. My setup is pretty basic: I've got a UIScrollView, a UIView inside it, return the latter at viewForZoomingInScrollView and there's really nothing more than that. Actually, it works as expected. The issue comes when I add this line at viewDidLoad of my view controller:
viewForZooming.transform = CGAffineTransformMakeRotation(M_PI/2);

Then the scroll view doesn't zoom anymore.
Is this related to the frame getting invalidated after transforming the view? Is there any workaround?
Thanks.


text:
Q: Parsefloat give output in scientific format in golang i am trying to parse this string "7046260" using Parsefloat function in golang , but i am getting  output in scientific format 7.04626e+06. i want the output in the format 7046260. how to get this?
package main

import (
    "fmt"
    "strconv"
)

func main() {

    Value := "7046260"
    Fval, err := strconv.ParseFloat(Value, 64)

    if err == nil {
        fmt.Println(Fval)
    }

}

ouput :- 7.04626e+06

A:
Parsefloat give output in scientific format in golang
i am trying to parse this string "7046260" using Parsefloat function in golang , but i am getting output in scientific format 7.04626e+06. i want the output in the format 7046260

*

*You're confusing the floating-point value's (default) formatted output with its internal representation.

*ParseFloat is working fine.

*You just need to specify an output format:

*

*See the fmt package documentation.

*Use Printf to specify a format-string.

*Use the format %.0f to instruct Go to print the value as-follows:

*

*% marks the start of a placeholder.

*. denotes default width (i.e. don't add leading or trailing zeroes).

*0 denotes zero radix precision (i.e. don't print any decimal places, even if the value has them)

*f denotes the end of the placeholder, and that the placeholder is for a floating-point value.

I have a few other recommendations:

*

*Local variables in Go should use camelCase, not PascalCase. Go does not encourage the use of snake_case.

*You should check err != nil after each nil-returning function returns and either fail-fast (if appropriate), pass the error up (and optionally log it), or handle it gracefully.

*When working with floating-point numbers, you should be aware of NaN's special status. The IsNaN function is the only way to correctly check for NaN values (because ( aNaNValue1 == math.NaN ) == false).

*

*The same applies in all languages that implement IEEE-754, including Java, JavaScript, C, C#.NET and Go.

Like so:
package main

import (
    "fmt"
    "strconv"
    "math"
    "log"
)

func main() {

    numberText := "7046260"
    numberFloat, err := strconv.ParseFloat(numberText, 64)
    if err != nil {
        log.Fatal(err)
    }

    if math.IsNaN(numberFloat) {
        log.Fatal("NaN value encountered")
    }

    fmt.Printf("%.0f",numberFloat)
    fmt.Println()

}


text:
Q: Interpreting Results of Multivariable Regression / how to transform variables to improve results I am working on a project that predicts the Market Cap (value) of different crypto-currencies. My data is very small (51 observations) and I initially have 18 X-variables. I was hoping to get feedback on my modeling approach and results, and suggestions on improving the model (particularly by transforming variables / with a non-linear regression) technique. I will do my best to keep the post clear and brief, and hope it can be helpful to others working on a similar analysis. The post may seem long, but a lot of it is images. Also, I am doing this in R, and can share any code on request.
1.) My first action was to log-transform the Market Cap (Y-variable) into log(Market Cap). Here are 2 graphs, of Market Cap and of log(Market Cap) of my 50 observations:

...the outlier point, with a $190B market cap, is bitcoin, and the model badly overfit to this data point if I did not log-transform. For this reason, I think this first action of log-transforming the Market Cap is a good action.
2.) 12 of the 50 observations were missing values for 6 of the X-variables. Rather than throwing these observations away, I predict missing values for these 6 X-variables by fitting, for each of these 6 X-variables, a simple linear regression between the (a) the X-variable with missing values, and (b) one of the remaining 12 X-variables with no missing values. For (b), I chose the X-variable with the highest pearson correlation to the missing-value-X-variable. I use this simple linear regression to predict missing values.
3.) I then fit an initial linear model with all 18 variables. However, since 18 variables will almost certainly overfit to 50 data points, and because there is some multicollinearity to the X-variables, I then use stepwise regression with backward elimination to fit a model with fewer variables. The R summary output of the model returned using backward elimination, with 9 variables, is here:

and the R diagnostics plots from this model are:

4.) Lastly, here is a grid with variable distributions and correlations for these 9 predictor variables + the log(Market Cap):

as well as a table of Variance Inflation Factors

My thoughts on next steps are to fix the remaining multicollinearity issue by removing additional variables, and also remove some outlier data points indicated in the Residuals vs. Leverage graph. I also plan to test the model on a test data-set (I did a 40 / 10 split), 5 times using 5-fold cross validation.
I am interested in anyone's thoughts on transforming the X-variables, which I currently do none of. The grid of histograms / correlations / scatter plots shows that many variables are right-skewed. Additionally, I have graphed the simple linear regression fit between log(Market Cap) and each of the 9 remaining variables, and received these plots (for 4 of the 9):

And noticed for the most part that none of the X-variables seem to have a great linear-fit with log(Market Cap).
Any thoughts on next-steps on my model building would be greatly, greatly appreicated. Apologies again for the long post, but I felt that thorough / lots of images / plots would be helpful here. Thanks!

A: just some quick thoughts:
re Q2: there is a large literature on imputation; i guess you're familiar with it and you have followed some standard. The proportion of missing is quite high however (20% for some variables?) and thus any approach will feel dubious. The estimates should account somehow for the uncertainty of the imputed values.
re Q3: i personally do not like those stepwise methods, they are data-depedendent and your result may be an artefact of that particular dataset. Selection of variables, if possible, could be informed by an understanding of things. Unless of course the purpose of the analysis is to identify key predictors, then selecting a priori may be tautologous
re Q4: i wouldn't transform the X variables. If a large no. of values are clustered at 0 (as in one of your plots) then it is not a great loss of info to categorise this variable, especially if it is meaningful and aids interpretation of the results to do so. So much depends on the context and the purpose of the analysis, and the type of data you're handling is unfamiliar to me
frank harrell has a great stats blog and is an expert on these things: http://www.fharrell.com/ Where he contradicts what i have said: believe him


text:
Q: Entity Framework 6 Code First: specific model design implementation I have a little model but i have a doubt on how to design.
My idea is to have three classes: JobReport/Customer/Project.
The scope is to populate reports choosing Customer and then Project that is bound to its customer (plus other payloads).
My design is:

MODEL:
public class EFDBContext : DbContext
{
    public DbSet<JobReport> JobReport { get; set; }
}

When i scaffold JobReport View and use its model i find difficoult to bind Customer entity, since it is directly bound to Project and not to JobReport.
Another solution is to put both CustomerID and ProjectID into JobReport, but it seems to me it's redundant.

I have in my mind two possibilities:
1- keep the first model and create a ViewModel with JobReport and Customer separately
2- Use the second model so i have all the IDs.
What do you think about it?
How would you implement this case?
Thanks very much!!
Max

A: A couple of observations:

*

*Design 1 seems appropriate, unless one JobReport should be able to reference multiple projects belonging to different customers.

*The ProjectID property doesn't belong in the Customer type, right? The Projects collection is rightfully there, though.

*The Project type should have a JobReports collection that lists all reports belonging to a specific object.

This is a problem that is closely related to discussions about identifying aggregates in Domain Driven Design. It seems that your Customer entity is a natural aggregate root, which means that all interactions with objects inside the aggregate must go through the customer.
This would mean that the DbContext should look like this instead:
public class EFDBContext : DbContext
{
    public DbSet<Customer> Customers { get; set; }
}

And to get sub-items belonging to a customer, you use LINQ to traverse the relations:
public IEnumerable<JobReport> GetReportsByCustomer(int customerId)
{
    using (var context = new EFDBContext())
    {
        return context.Customers.Where(x => x.CustomerID.Equals(customerId))
            .SelectMany(x => x.Projects)
            .SelectMany(x => x.JobReports)
            .OrderBy(x => x.Timestamp);
    }
}

You can also select to always use the Customer as base for your edit actions, since it's the aggregate root. This would involve pulling the Customer out of the database and make sure that all detail data is included:
public IEnumerable<Customer> GetCustomer(int customerId)
{
    using (var context = new EFDBContext())
    {
        return context.Customers
            .Include(x => x.Projects.Select(y => y.JobReports))
            .FirstOrDefault(x => x.CustomerID.Equals(customerId));
    }
}

You would need to manually add using System.Data.Entity; at the top of your class file for the above code to work.


text:
Q: NodeJS flush function streams not working I have this main file, with the goal to output the sum of profits for a country
const { createReadStream } = require("fs");
const parse = require("csv-parse");
const csv = require("csvtojson");
const { filterByCountry } = require("./filter-by-country");
const { sumProfit } = require("./sum-profit.js");

const csvParser = csv();

createReadStream("data.csv") // (1)
  .pipe(csvParser) // (2)
  .pipe(filterByCountry("Italy"))
  .pipe(sumProfit())
  .pipe(process.stdout);

csvparser works, filterByCountry works but once it goes through sumProfit() I am unable to output just 1 TOTAL for the profit.
sumProfit function:
const { Transform } = require("stream");
const { EOL } = require("os");
let TOTAL = 0;

const sumProfit = () => {
  return new Transform({
    objectMode: true,
    transform: (chunk, encoding, done) => {
      const parsedObj = JSON.parse(chunk);
      TOTAL += Math.floor(parseFloat(parsedObj["profit"]));
      done(null);
    },
    //flush function ??
    function(done) {
      done(null, String(TOTAL) + EOL);
    },
  });
};

module.exports = { sumProfit };

If I remove the flush function I have tried to implement and replace the done(null) with done(null, String(TOTAL)) It logs everytime the total is added...

A: I figured it out, Fixed the sumProfit functions to:
const { Transform } = require("stream");
const { EOL } = require("os");

let TOTAL = 0;

const sumProfit = () => {
  return new Transform({
    objectMode: true,
    transform: (chunk, encoding, done) => {
      const parsedObj = JSON.parse(chunk);
      TOTAL += Math.floor(parseFloat(parsedObj["profit"]));
      done(null);
    },
    flush: (done) => {
      done(null, String(TOTAL) + EOL);
    },
  });
};

module.exports = { sumProfit };

Silly mistake I am used to using through2


text:
Q: var_dump return a value but JSONP not I have an API based on Php Slim Framework and want to generate JSONP for my website. When I call the website on: 'http://api.mysite.com/users?callback=JSON_CALLBACK'. It returns a blank page with JSON CALLBACK() write on it. When logged to the console it is undefined.
API's index.php
<?php
require 'vendor/autoload.php';

$app = new \Slim\Slim();
$app->contentType('application/json');
$app->get('/users', 'getUsers');
$app->run();

function getConnection() {
$dbhost="localhost";
$dbuser="";
$dbpass="";
$dbname="";
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

return $dbh;
}

function getUsers() {
$sql = "select * FROM manga";
try {
$db = getConnection();
$stmt = $db->query($sql);
$users = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo $_GET['callback'] . '('.json_encode($users).')';
}
catch(PDOException $e) {
echo $_GET['callback'] . '('.json_encode($e->getMessage()).')';
}
}

var_dump($users), Call on http://api.mysite.com/users and result is:
function getUsers() {
$sql = "select * FROM manga";
$db = getConnection();
$stmt = $db->query($sql);
$users = $stmt->fetchAll(PDO::FETCH_OBJ);
var_dump($users);
}

Result:
array(2) {
[0]=>
object(stdClass)#35 (10) {
["id"]=>
string(1) "1"
["ad"]=>
string(6) "Naruto"
["yazar"]=>
string(17) "Masashi KISHIMOTO"
["icerik"]=>
string(28) "Ninja, Dövü?, Aksiyon, Drama"
["tarih"]=>
string(4) "1999"
["tur"]=>
string(5) "Manga"
["durum"]=>
string(9) "Sona Erdi"
["konu"]=>
string(560) "Yondaime Hokage, gizli bir ninja kasabas? olan Konohagakure'ye sald?ran cehennemin iblislerinden Kyuubi'yi durdurmak için, Onu yeni do?mu? bir çocuk olan Naruto'nun içine mühürler. Böylece kahram?n?m?z Naruto ortaya ç?km?? olur. ?çine mühürlenen korkunç iblis sebebiyle kasaba halk?n?n nefretini kazanan Naruto daha bebekken yetim kalm?? biridir. Kasaba halk?n?nda kendini d??lamas?ylada oldukça yaramaz ve haylaz biri çocuk olur. Fakat ninja akademisinden mezun olaca?? gün, hayat?nda ilk defa olarak arkada? edinmesi Naruto'nun hayat?n? bütünüyle de?i?tirir."
["kapak"]=>
string(10) "naruto.jpg"
["son"]=>
string(3) "300"
}
[1]=>
object(stdClass)#36 (10) {
["id"]=>
string(1) "2"
["ad"]=>
string(9) "One Piece"
["yazar"]=>
string(12) "Eiichiro ODA"
["icerik"]=>
string(32) "Macera, Komedi, Dövü?, Fantastik"
["tarih"]=>
string(4) "1997"
["tur"]=>
string(5) "Manga"
["durum"]=>
string(12) "Devam Ediyor"
["konu"]=>
string(881) "Korsan Kral Gold Roger, bu dünyadaki her?eyi elde eder ve idam edilirken, tüm servetinin Grand Line'da oldu?unu, onu aray?p bulmalar? gerekti?ini söyler. Bu olaydan sonra herkes Grand Line'a gider. Ancak Grand Line'a girmek çok zor, Grand Line'da canl? kalabilmek imkans?zd?r.

Kahraman?m?z Monkey D. Luffy'nin rüyas?, Korsan Kral olmak ve One Piece denen kimsenin bilmedi?i, görmedi?i hazineyi ele geçirmektir. Küçük ya?lardan beri hep korsan olmak isteyen Luffy, kazara bir ?eytan meyvas? (Akuma No Mi) yemi?tir. 3 farkl? ?eytan meyvas? vard?r ve bu meyvalar yiyenlere çok üstün güçler sa?lamaktad?r ancak bu güçlerin bedeli asla yüzememektir. Luffy'nin yedi?i meyva onu bir lastik çocu?a çevirir. Bu olaydan y?llar sonra Luffy denize aç?l?r. Yolculu?u s?ras?nda ekibini toplayacak ve One Piece'i bulmak için Grand Line'da birbirinden tehlikeli ve komik maceralara at?lacakt?r."
["kapak"]=>
string(13) "one_piece.jpg"
["son"]=>
string(3) "788"
}
}

A: No where in your HTTP response are you defining a javascript function to handle the JSONP response. I assume this function is then defined in another JavaScript resource (inline or script) in your web app.  Therefore an undefined error would be caused by your javascript elsewhere and not from this segment of code.
To test this, load up your web app and launch the console.  You can manually run:
myCallbackFunction({field:"value"}); // some test JSON document
to determine if the callback function exists.
However.
IMHO JSONP is generally a terrible idea, and best described by jQuery's page on the topic.

JSONP is essentially a consensual cross-site scripting hack

It opens your client side application to easier MITM attacks, here's a SO question on this very issue.
Since you are ultimately just returning the JSON data and not custom logic, I would recommend trying the following:

*

*Return the JSON encoded response with header('Content-Type: application/json);.  You're very close to doing this already with your existing code.

*Have the same callback function in JavaScript, i.e. it doesn't need to be passed as part of your HTTP request and the function name wouldn't need to differ.

*Handle the JSON in almost exactly the same way client side. You'll need to make minimal changes to the JavaScript since all you're doing is passing the JSON object into the function as it is.


text:
Q: Can i use _source field inside aggregations? I have documents with some many fields, i want to find the count of documents that are inserted after certain hour which can be done by using range query but among all documents fields i want the only Timestamp field should be displayed .
I used the following query
 {
      "_source": [
        "fields.Timestamp"
      ],
      "aggs": {
        "last_5_mins": {
          "filter": {
            "range": {
              "fields.Timestamp": {
                "gt": "2017-02-10T10:07:04.4367673Z"
              }
            }
          }
        }
      }
    }

When i saw the output i didnt get the Timestamp for the matched documents rather i got for the documents that are not matched with my query.
MY output:
"hits": {
    "total": 6,
    "max_score": 1,
    "hits": [
      {
        "_index": "matrix",
        "_type": "neo",
        "_id": "5",
        "_score": 1,
        "_source": {

        }
      },
      {
        "_index": "matrix",
        "_type": "neo",
        "_id": "2",
        "_score": 1,
        "_source": {
          "fields": {
            "Timestamp": "2017-02-10T10:07:04.4367673Z"
          }
        }
      },
      {
        "_index": "matrix",
        "_type": "neo",
        "_id": "4",
        "_score": 1,
        "_source": {
          "fields": {
            "Timestamp": "2017-02-10T10:07:04.4836472Z"
          }
        }
      },
      {
        "_index": "matrix",
        "_type": "neo",
        "_id": "6",
        "_score": 1,
        "_source": {

        }
      },
      {
        "_index": "matrix",
        "_type": "neo",
        "_id": "1",
        "_score": 1,
        "_source": {
          "fields": {
            "Timestamp": "2017-02-10T10:07:04.4367673Z"
          }
        }
      },
      {
        "_index": "matrix",
        "_type": "neo",
        "_id": "3",
        "_score": 1,
        "_source": {
          "fields": {
            "Timestamp": "2017-02-10T10:07:12.1147415Z"
          }
        }
      }
    ]
  },
  "aggregations": {
    "last_5_mins": {
      "doc_count": 2
    }
  }
}

How can i get the timestamp for the matched documents?
Thanks..

A: You don't need to use an aggregation for that, simply move your range query in the query section and you're good:
{
   "_source": [
      "fields.Timestamp"
   ],
   "query": {
      "bool": {
         "filter": {
            "range": {
               "fields.Timestamp": {
                  "gt": "2017-02-10T10:07:04.4367673Z"
               }
            }
         }
      }
   }
}


text:
Q: Sufficiently high power of a function is smooth Assume $f(x)$ is a positive, continuous and bounded function. Is it true that the $k$-th power of $f$ is, say, $C^2$ (i.e. bounded first and second derivatives) for some $k$ big enough? I feel like higher powers should "smooth" the function, but I'm having trouble showing this.

A: I think this function is a counter-example:
$$f(x) = \begin{cases}
2 & x \leq -1 \\
\sqrt{|x|} + 1 & -1 < x \leq 1 \\
2 & x > 1
\end{cases} $$


text:
Q: Azure CDN Worldwide vs China I've been trying to find an alternative for my current CDN (Rocket CDN), because they don't deliver content well in China. For instance, various partners contacted me last month that our images are no longer visible when visiting our site in China.
Since Azure offers a CDN option for China, I'm looking into their services. I've also looked to Cloudflare, but they seem more expensive when using their 'China Network Acces'. My current website has 1k visitor from china weekly, and 2k from other regions in the world, and we use around 50 gig of data. So I'm not sure what CDN from Azure could solve my problem, because they have one CDN-service focused on China, and one for the rest of the world.
Has anyone faced similar problems? And how did you solve this? My current concerns are: if I chose Azure CDN Worldwide would I still face similar problems; or if I would chose Azure CDN China would other countries face a slow(er) website; or is there an option to combine both services? Or is there another good and affordable service, which I should look in to?
Thank you in advance for tips / help / comment.


text:
Q: How to call a function from the App class in the cppwinrt template project from MainPage I am working within the Visual Studio template project for a cppWinRT Blank App.
What I would like to do is make a call to a function defined in MainPage from the OnLaunched function inside the App class.
So far my theory is that I need is something along those lines:
MainPage* mainPageImpl = from_abi<BlankApp1::implementation::MainPage>(/*somehow get a pointer to the MainPage instance*/);
mainPageImpl->myFunction();

However I am not sure if this is the correct approach.

A: Use get_self to convert projection class to implementation class.
MainPage* mainPageImpl = get_self<MainPage>(Window::Current().Content().try_as<Frame>().Content().try_as<BlankApp1::MainPage>());
mainPageImpl->myFunction();


text:
Q: UISegmentController not visible in a popover on iOS 8 I have a UISegmentController that is being presented in a navigation bar in a `UIPopoverController'. The segmented control is build in the xib file right above table view.
This seems to work on iOS 7, but on iOS 8 the segment controller is not even showing up in a popover. Why would that be?
Any help is appreciated.


text:
Q: Using the same view component with different route, but with different props I have a view component, ViewDeal, that I want to reuse for different routes /housedeal/1 and /cardeal/1.
I'm using Vue Router and it's working nice, except I must know in the view component what route was used.
So this is my component:
const ViewDeal = {
  props: ['id'],
  template: '
Is this a car deal view or a house deal view? What route was used?
'
}

And in vue router I have this:
const router = new VueRouter({
  routes: [
    { path: '/housedeal/:id', component: ViewDeal, props: true },
    { path: '/cardeal/:id', component: ViewDeal, props: true },
  ]
})

I read about Object mode in Vue Router which means I can add a prop to housedeal route eg. {isHousedeal: true}, but then the :id param wont be passed in.
This thread didn't have any answers to combine url props with object ones.

A: This should work :
const router = new VueRouter({
  routes: [
    { path: '/housedeal/:id', component: ViewDeal, props: {isHousedeal: true} },
    { path: '/cardeal/:id', component: ViewDeal, props: {isHousedeal: false} },
  ]
})

Then to retrieve the id, you can use {{ $route.params.id }} in your component.
const ViewDeal = {
  props: ['isHousedeal'],
  template: '
Is this house deal? {{isHousedeal}}. ID : {{$route.params.id}}
'
}


text:
Q: 'No matching tab was found with the following properties: Title=Demo Web Shop*' when running testcase in Jenkins for a tosca testcase I have integrated Tosca with jenkins to run in local .The test runs successfully on jenkins .However I see below error in result.xml file .The tests run fine in Tosca its only in Jenkins that I see this error .What do I do?
This is the result.xml output
<testcase name="Shipping Costs" time="12.7" timestamp="2022-10-07T16:04:47.1086587+05:30" log="- Failed Shipping Costs {LogInfo='Execution will be continued with the next TestCase, because there was an error in the current TestCase.'} + Passed Open Web Shop - Failed Navigate to Log In Page {LogInfo='No matching tab was found with the following properties: Title=Demo Web Shop*'} ">

- Failed Shipping Costs {LogInfo='Execution will be continued with the next TestCase, because there was an error in the current TestCase.'} + Passed Open Web Shop - Failed Navigate to Log In Page {LogInfo='No matching tab was found with the following properties: Title=Demo Web Shop*'}