text:
Q: How to change the generated filename for App Bundles with Gradle? So to change the generated APK filename inside gradle android I could do something like:
applicationVariants.output.all {
    outputFileName = "the_file_name_that_i_want.apk"
}

Is there a similar thing for the generated App Bundle file? How can I change the generated App Bundle filename?

A: You could use something like this:
defaultConfig {
  applicationId "com.test.app"
  versionCode 1
  versionName "1.0"
  setProperty("archivesBaseName", applicationId + "-v" + versionCode + "(" + versionName + ")")
}

A: Now I've wrote kind of a Exec template for cross-platform CLI execution, no matter what the commandLine is. My RenameTask can detect Linux & Windows, as well as release & debug.
Property archivesBaseName needs to be defined in defaultConfig:
android {
    defaultConfig {
        setProperty("archivesBaseName", "SomeApp_" + "1.0.0")
    }
}

RenameTask extends Exec performs the renaming (not to be confused with type: Rename):
import javax.inject.Inject

/**
 * App Bundle RenameTask
 * @author Martin Zeitler
**/
class RenameTask extends Exec {
    private String buildType
    @Inject RenameTask(String value) {this.setBuildType(value)}
    @Input String getBuildType() {return this.buildType}
    void setBuildType(String value) {this.buildType = value}
    @Override
    @TaskAction
    void exec() {
        def baseName = getProject().getProperty('archivesBaseName')
        def basePath = getProject().getProjectDir().getAbsolutePath()
        def bundlePath = "${basePath}/build/outputs/bundle/${this.getBuildType()}"
        def srcFile = "${bundlePath}/${baseName}-${this.getBuildType()}.aab"
        def dstFile = "${bundlePath}/${baseName}.aab"
        def os = org.gradle.internal.os.OperatingSystem.current()
        if (os.isUnix() || os.isLinux() || os.isMacOsX()) {
            commandLine "mv -v ${srcFile} ${dstFile}".split(" ")
        } else if (os.isWindows()) {
            commandLine "ren ${srcFile} ${dstFile}".split(" ")
        } else {
            throw new GradleException("Cannot move AAB with ${os.getName()}.")
        }
        super.exec()
    }
}

And it finalizes two other tasks:
// it defines tasks :renameBundleRelease & :renameBundleDebug
task renameBundleRelease(type: RenameTask, constructorArgs: ['release'])
task renameBundleDebug(type: RenameTask, constructorArgs: ['debug'])

// it sets finalizedBy for :bundleRelease & :bundleDebug
tasks.whenTaskAdded { task ->
    switch (task.name) {
        case 'bundleRelease': task.finalizedBy renameBundleRelease; break
        case   'bundleDebug': task.finalizedBy renameBundleDebug; break
    }
}

The advance is, that it leaves nothing behind and one can move the files wherever one wants.

A: Why no one is using existing gradle tasks for this?
There is a gradle task with the type FinalizeBundleTask and it is called as the last step of bundle generation and it is doing two things:

*

*Signing generated AAB package

*Move and rename AAB package where was requested

All You need to do is just to change the "output" of this task to any that You want. This task contains a property finalBundleFile - full path to the final AAB package.
I'm using it something like that:
    applicationVariants.all {
        outputs.all {
            // AAB file name that You want. Falvor name also can be accessed here.
            val aabPackageName = "$App-v$versionName($versionCode).aab"
            // Get final bundle task name for this variant
            val bundleFinalizeTaskName = StringBuilder("sign").run {
                // Add each flavor dimension for this variant here
                productFlavors.forEach {
                    append(it.name.capitalizeAsciiOnly())
                }
                // Add build type of this variant
                append(buildType.name.capitalizeAsciiOnly())
                append("Bundle")
                toString()
            }
            tasks.named(bundleFinalizeTaskName, FinalizeBundleTask::class.java) {
                val file = finalBundleFile.asFile.get()
                val finalFile = File(file.parentFile, aabPackageName)
                finalBundleFile.set(finalFile)
            }
        }
    }

It works perfectly with any flavors, dimensions, and buildTypes. No any additional tasks, works with any path set for output in Toolbar -> Generate signed Bundle, a unique name can be set for any flavor.

A: As a more generic way to Martin Zeitlers answer the following will listen for added tasks, then insert rename tasks for any bundle* task that gets added.
Just add it to the bottom of your build.gradle file.

Note: It will add more tasks than necessary, but those tasks will be skipped since they don't match any folder. e.g. > Task :app:renameBundleDevelopmentDebugResourcesAab NO-SOURCE

tasks.whenTaskAdded { task ->
    if (task.name.startsWith("bundle")) {
        def renameTaskName = "rename${task.name.capitalize()}Aab"
        def flavor = task.name.substring("bundle".length()).uncapitalize()
        tasks.create(renameTaskName, Copy) {
            def path = "${buildDir}/outputs/bundle/${flavor}/"
            from(path)
            include "app.aab"
            destinationDir file("${buildDir}/outputs/renamedBundle/")
            rename "app.aab", "${flavor}.aab"
        }

        task.finalizedBy(renameTaskName)
    }
}

A: I've found a much better option to auto increment your app versioning and auto renaming when you generate an apk / aab. Solution as below (do remember to create "version.properties" file on your root folder:
android {
     ...
     ...
    Properties versionProps = new Properties()
    def versionPropsFile = file("${project.rootDir}/version.properties")
    versionProps.load(new FileInputStream(versionPropsFile))
    def value = 0
    def runTasks = gradle.startParameter.taskNames
    if ('assemble' in runTasks || 'assembleRelease' in runTasks) {
        value = 1
    }
    def versionMajor = 1
    def versionPatch = versionProps['VERSION_PATCH'].toInteger() + value
    def versionBuild = versionProps['VERSION_BUILD'].toInteger() + 1
    def versionNumber = versionProps['VERSION_NUMBER'].toInteger() + value
    versionProps['VERSION_PATCH'] = versionPatch.toString()
    versionProps['VERSION_BUILD'] = versionBuild.toString()
    versionProps['VERSION_NUMBER'] = versionNumber.toString()
    versionProps.store(versionPropsFile.newWriter(), null)

    defaultConfig {
    applicationId "com.your.applicationname"
    versionCode versionNumber
    versionName "${versionMajor}.${versionPatch}.${versionBuild}(${versionNumber})"
    archivesBaseName = versionName
    minSdkVersion 26
    targetSdkVersion 29
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    signingConfig signingConfigs.release
    setProperty("archivesBaseName","${applicationId}-v${versionName}")

    ...
}

Credits to this website and this post

A: Solution from @SaXXuM works great! Task is not necessary for renaming artifact. You can call setProperty() directly in the android {} block. I prefer to have in the file name:

*

*app id

*module name

*version name

*version code

*date

*build type

This is how I use it in my projects:
build.gradle:
apply from: "../utils.gradle"

android {
    ...
    setProperty("archivesBaseName", getArtifactName(defaultConfig))
}

utils.gradle:
ext.getArtifactName = {
    defaultConfig ->
        def date = new Date().format("yyyyMMdd")
        return defaultConfig.applicationId + "-" + project.name + "-" + defaultConfig.versionName + "-" + defaultConfig.versionCode + "-" + date
}

The result is:
com.example-app-1.2.0-10200000-20191206-release.aab

It works for both - APK and AAB.

A: Based on Martin Zeitler's answer I did this on Windows:
Please note that on my setup, .aab files are created in release folder and it deletes everything else in that folder as per this bug report.
In my app's module gradle:
apply from: "../utils.gradle"

...

tasks.whenTaskAdded { task ->
    switch (task.name) {
        case 'bundleRelease':
            task.finalizedBy renameBundle
            break
    }
}

And in utils.gradle:
task renameBundle (type: Exec) {
    def baseName = getProperty('archivesBaseName')

    def stdout = new ByteArrayOutputStream()
    def stderr = new ByteArrayOutputStream()

    commandLine "copy.bat", rootProject.getProjectDir().getAbsolutePath() + "\\release\\${baseName}-release.aab", "<MY_AAB_PATH>\\${baseName}.aab", "D:\\Android\\studio\\release"
    workingDir = rootProject.getProjectDir().getAbsolutePath()
    ignoreExitValue true
    standardOutput stdout
    errorOutput stderr

    doLast {
        if (execResult.getExitValue() == 0) {
            println ":${project.name}:${name} > ${stdout.toString()}"
        } else {
            println ":${project.name}:${name} > ${stderr.toString()}"
        }
    }
}

The copy.bat is created in project's folder and contains this:
COPY %1 %2
RMDIR /Q/S %3

Be careful with 3rd argument to make sure you don't use a folder that's important to you.
EDIT: Why a .BAT for 2 commands you might ask. If you try commandLine "copy", ... on Windows it results in "system does not recognize the command copy". Put anything, like COPY, REN, RENAME, etc, won't work.


text:
Q: How to troubleshoot high load when kernel module is suspect? I have noticed a bug with Ubuntu 14.04.4 LTS; if the NFS client loses connection to the NFS server the load on that system will spike to upwards of 30.
The only way I've noticed to bring the load down is to lazily unmount the NFS share: umount -l /path/to/share
The problem is; all the conventional tools to tell me system resource usage are not helpful: top, htop, iotop, perf top, sar, mpstat indicate that there is nothing wrong with the system; no single process or thread is running that could explain why the load is so high.
My assumption is that since NFS is implemented in the kernel in Linux is that these tools simply can't see what's going on; is there a way to better troubleshoot this issue? As the conventional tools seem to not work. Is there a way to monitor the run queue in Linux?

A: The load average computed by counting the number of processes that are:

*

*currently running

*are ready to run, but waiting to be scheduled (the CPU occupied by some other process)

*blocked waiting on I/O (uninterruptable sleep, shown as 'D' in top/ps)

and feeding that through a weighted average (over time, to get the 1, 5, and 15 minutes values).
So your high load average doesn't mean the CPU is overloaded (look at the %Cpu in top, etc. to check that); it probably just means that you have a bunch of processes blocked trying to access the (down) NFS server.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cannot install "global" composer requirements because "composer.json is not writeable" I want to install Laravel but again and again I got the below error,

rukon@rukon-HP-Notebook:~$ composer global require laravel/installer
Changed current directory to /home/rukon/.config/composer
./composer.json is not writable. rukon@rukon-HP-Notebook:~$

I tried to make writable composer.json by
$chmod 777 ./composer.json

but it's not working. my file owner is not root

A: When you run any composer global command, the composer.json used is the one at your HOME directory, not at your projects directory. E.g. at ~/.composer/composer.json.
Looks like your home directory composer is owned by root.
At some point you've executed composer with root and messed up your installation.
To find out where your composer's home directory is at, you should run this (as shown here):
composer config --list --global | grep home

E.g. given your output, it seems your home directory sits at "/home/rukon/.config/composer":
So you'd need to run:
sudo chown -R $USER: ~/.config/composer

To fix your "global" composer configuration directory.
You should be able to run composer global commands after that.
If you have more permissions problems, you'd better fix your home directory so everything in there is owned by your user, and nothing by root as shown here:
sudo find ~ -type d -user root -exec sudo chown -R $USER: {} +

For a regular installation the above should be safe (all the files in your home directory belong to to your own user), but if you have anything special in there you should probably be aware and take a more surgical approach (checking each directory).


text:
Q: Cannot connect to to site - FTP timeout not sure where to ask this question so I figured I would try here to see if there's anyone that can help.
I have an FTP connection where I have the correct ftp information, but the FTP always seems to get hung up on the connection, then eventually hung up in filezilla.
I have the WHM information to this client's server, but I just don't know what I would need to set the ftp settings to in order to fix this?  I'm basically a front-end developer needing to do a few mobile updates so Idon't really know much about server configuration.
In filezilla, this is the last part it gets hung up on:
Command:    PASV
Response:   227 Entering Passive Mode
Command:    MLSD
Does anyone know what I can do to fix this in WHM?

A: If anyone else has this same issue, just set the ftp mode to "active"


text:
Q: How can I use document.createElement DOM in node.js? I'm new in programming and currently learning node.js and express.js
I have a form for user to contact me when submitted it should open windows mail app, in javascript I can just use document.createElement('a')
but when I use it on node.js it says 'document' is not defined or createElement is not a function
I've tried to use jsdom
Here's the js code:
app.post('/contact-me', function(req, res) {
let name = req.body.userName
let email = req.body.userEmail
let phone = req.body.userPhoneNumber
let subject = req.body.userSubject
let message = req.body.userMessage
let form = req.body.contact /
let contact = {
    name,
    email,
    phone,
    subject,
    message
}

let openMail = new JSDOM(contact) //I've also tried let openMail = new JSDOM(form)
let myEmail = "dev@mail.com"

let a = openMail.window.document.createElement('a')
a.href = `mailto:${myEmail}?subject=${subject}&body=Hello, my name is ${name}, ${subject}, ${message}`
a.click()
})`

Form opening tag: <form class="form-container" action="/contact" method="POST" name="contact">
But it says:
Error: Not implemented: navigation (except hash changes)
at module.exports (D:\folder\node_modules\jsdom\lib\jsdom\browser\not-implemented.js:9:17)
at navigateFetch (D:\folder\node_modules\jsdom\lib\jsdom\living\window\navigation.js:77:3)
at exports.navigate (D:\folder\node_modules\jsdom\lib\jsdom\living\window\navigation.js:55:3)
at Timeout._onTimeout (D:\folder\node_modules\jsdom\lib\jsdom\living\nodes\HTMLHyperlinkElementUtils-impl.js:81:7)
at listOnTimeout (node:internal/timers:559:17)
at processTimers (node:internal/timers:502:7) undefined

Do node.js have different code or I have to do something before using DOM?


text:
Q: Removing title tags from each page hello to all I am newbie to wordpress. I want to remove the title tags from every page.Is there any way to remove that part?Thanks in advance..

A: You can open your theme files and remove the code that adds this to the page. The typical files to look in are:
index.php, page.php, post.php, single.php.
Look for this:

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

or it might look like this:
<?php the_title(); ?>

You might want to comment the part of code out so you can easily add it if you want to in the future. To use this method you would surround the part the_title(); with this /**  the_title();  */ It would then look like this:
<?php /**  the_title();  */?>


text:
Q: can't download files
Possible Duplicate:
How do I reset a lost Administrative (root) password?

I'm trying to put skype and yahoo messenger onto my Acer Eee note book and the system keeps asking me to give administrator rights and then a password which I can't remember. I tried to change the password and when it comes to typing, I can't. I'm the only one that uses it, so I'd like to make it open.How please?

A: You really need to give us more information then that. However, admin rights means you need to run the install commands with sudo in front of them. The password is most likely your Ubuntu user password (you were asked to create it at the time of system creation). If you have forgotten that, then you might as well create a new user for yourself.

A: No, you can't create any user account without entering the password, Try this link


text:
Q: convert timestamp in UTC to users local time javascript I have a time stamp like such 1443728852, how do i convert this to the users local time. I have this:
time = new Date(1443728852);
alert(time.toLocaleTimeString());

but this is giving me the UTC/GMT time not my local time like EST for example?

A: By default date object gives date and time in users local timezone. One more thing is that Date object required timestamp in milliseconds so you need to multiply it by 1000.
time = new Date(1443728852 * 1000);
alert(time.toLocaleTimeString());


text:
Q: What is the difference between GraalVM native-image tagged with and without 'muslib' prefix? I do not understand what does this prefix muslib means for GraalVM native-images.
Links to native-image with and without the prefix. Docs does not describe it.
Can anybody explain? Thanks!

A: At here says

Static native images are statically linked binaries which can be used without any additional library dependencies. This makes them easier to distribute and to deploy on slim or distroless container images. They are created by statically linking against musl-libc, a lightweight, fast and simple libc implementation.

That musl-libc used in those dockers and named as muslib. you can find example docker file here
And "ol" stands for Oracle Linux check here.


text:
Q: C code to print the unique numbers of an array I want to create a C program that merges 4 unsorted arrays, sort them and print all the unique numbers from the new merged array.
The results are not correct, but i don't know why.
Here is an example:

*

*a[1,5,13,3]

*b[3,5,9,1,23]

*c[5,23,3,18]

*d[1]

*a_b[1,5,13,3,3,5,9,1,23]

*c_d[5,23,3,18,1]

*e[1,1,1,3,3,3,5,5,5,9,13,18,23,23]

Prints only the unique numbers from array e: 13,18,9
#include <stdio.h>
#include <stdlib.h>

void print_uniques(int x[], int sizex)
{
int i, j;
if(sizex == 0)
    return;
if(sizex == 1){
    printf("%d\n", x[0]);
    return;
}
i = j = 0;
while(i != sizex){
    i++;
    if(i != sizex && x[i] == x[j])
        continue;
    if((i - j) == 1)
        printf("%d\n", x[j]);
    j = i;
}
}

/* print unique numbers from sorted array */

/* merge two already sorted arrays */
void merge(int m[], int x[], int sizex, int y[], int sizey)
{
int i=0, j=0, k=0;
while (i < sizex && j < sizey)
{
    if (x[i] <= y[j])
        m[k++] = x[i++];
    else
        m[k++] = y[j++];
}
while (i < sizex)
    m[k++] = x[i++];
while (j < sizey)
    m[k++] = y[j++];
}

/* compare function for qsort() */
int cmp(const int *i, const int *j)
{
return *i - *j;
}

int main()
{
int i, j,a[30],b[30],c[30],d[30],sizea,sizeb,sizec,sized;
printf("Enter the size of array A: ");
scanf("%d",&sizea);
printf("Enter the %d elements of array A:\n", sizea);
for(i=0;i<sizea;i++)
scanf("%d",&a[i]);
printf("Enter the size of array B: ");
scanf("%d",&sizeb);
printf("Enter the %d elements of array B:\n", sizeb);
for(i=0;i<sizeb;i++)
scanf("%d",&b[i]);
printf("Enter the size of array C: ");
scanf("%d",&sizec);
printf("Eisagete ta %d stoixeia tou pinaka C:\n", sizec);
for(i=0;i<sizec;i++)
scanf("%d",&c[i]);
printf("Eisagete to mege8os tou pinaka D: ");
scanf("%d",&sized);
printf("Eisagete ta %d stoixeia tou pinaka D:\n", sized);
for(i=0;i<sized;i++)
scanf("%d",&d[i]);
int a_b[32];
int c_d[32];
int e[64];
int sizea_b, sizec_d, sizee;

sizea = sizeof(a)/sizeof(a[0]);
sizeb = sizeof(b)/sizeof(b[0]);
sizec = sizeof(c)/sizeof(c[0]);
sized = sizeof(d)/sizeof(d[0]);
sizea_b = sizea   + sizeb;
sizec_d = sizec   + sized;
sizee   = sizea_b + sizec_d;

/* sort the arrays */
qsort(a, sizea, sizeof(a[0]), cmp);
qsort(b, sizeb, sizeof(b[0]), cmp);
qsort(c, sizec, sizeof(c[0]), cmp);
qsort(d, sized, sizeof(d[0]), cmp);

/* merge the arrays */
merge(a_b, a, sizea, b, sizeb);
merge(c_d, c, sizec, d, sized);
merge(e, a_b, sizea_b, c_d, sizec_d);

print_uniques(e, sizee);

return 0;
}

Any help is appreciated!

A: When you merge a_b with c_d you have the sizes back to front with
while(i<size3+size4 && j<size1+size2)

This should be
while(i<size1+size2 && j<size3+size4)

The same applies below when you merge the remaining parts of the arrays, and these have an additional problem: instead of repeating the while loops you used to build a_b and c_d you've used a different technique. I suggest revisiting this section building e, and making it work like you did when buildling a_b and c_d.
Here is the corrected code - except I didn't look at the part after the creation of e[] as I am not sure what you are trying to do.
#include <stdio.h>
#include <stdlib.h>

int main() {
    int size1 = 4, a[] = {1,1,1,2};
    int size2 = 4, b[] = {2,2,2,3};
    int size3 = 4, c[] = {3,3,3,4};
    int size4 = 5, d[] = {4,4,4,5,6};
    int a_b[30], c_d[30], e[30];
    int i,j,k,t, sizefull;

    sizefull=size1+size2+size3+size4;
    printf("%d\n", sizefull);

    i=j=k=0;
    while (i < size1 && j < size2)
    {
        if (a[i] <= b[j])
            {
            a_b[k] = a[i];
            i++;
            k++;
            }
       else {
            a_b[k] = b[j];
            k++;
            j++;
            }
    }
    while (i < size1)
    {
        a_b[k] = a[i];
        i++;
        k++;
    }
    while (j < size2)
    {
        a_b[k] = b[j];
        k++;
        j++;
    }
    printf("\nMerged array is :");
    for (i = 0; i < size1 + size2; i++)
        printf("%d ", a_b[i]);

    i=j=k=0;
    while (i < size3 && j < size4) {
        if (c[i] <= d[j]) {
            c_d[k] = c[i];
            i++;
            k++;
        } else {
            c_d[k] = d[j];
            k++;
            j++;
        }
    }
    while (i < size3) {
        c_d[k] = c[i];
        i++;
        k++;
    }
    while (j < size4) {
        c_d[k] = d[j];
        k++;
        j++;
    }
    printf("\nMerged array is :");
    for (i = 0; i < size3 + size4; i++)
        printf("%d ", c_d[i]);

    i=j=k=0;
    while (i < size1+size2 && j < size3+size4)
    {
        if (a_b[i] <= c_d[j])
            {
            e[k] = a_b[i];
            i++;
            k++;
            }
       else {
            e[k] = c_d[j];
            k++;
            j++;
            }
    }
    while (i < size1+size2)
    {
        e[k] = a_b[i];
        i++;
        k++;
    }
    while (j < size3+size4)
    {
        e[k] = c_d[j];
        k++;
        j++;
    }

    printf("\n After merging: \n");
    for (i = 0; i < sizefull; i++)
    {
        printf("%d ", e[i]);
    }

    for (i=0;i<sizefull;i++)
    {
        for(j=i+1;j<sizefull;j++)
        {
            if(e[i]>e[j])
            {
                t=e[i];
                e[i]=e[j];
                e[j]=t;
            }
        }
    }
    printf("\nAscending Order is:");
    for(j=0;j<sizefull;j++)
    {
        printf("%d ",e[j]);
    }

    printf("\n\n Final Array is \n");
    for(i=0;i<sizefull;i++)
    {
        printf(" %d",e[i]);
    }

    for(i=0; i<sizefull;)
    {
        for(j = (i + 1); j<sizefull; j++)
        {
            if( e[i] != e[j])
                break;
        }
        printf("\nunique element = %d, at index = %d\n", e[i], i);
        printf("\nunique element = %d, at index = %d\n", e[i], i);
        i = j;
        return 0;
    }
}

Program output:
17

Merged array is :1 1 1 2 2 2 2 3
Merged array is :3 3 3 4 4 4 4 5 6
 After merging:
1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 5 6
Ascending Order is:1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 5 6

 Final Array is
 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 5 6
unique element = 1, at index = 0

unique element = 1, at index = 0

A: Well First, You should try to put some comments on your code so that it becomes easy for others to read your code at one go. And I can see a lot of errors in your code. You have taken incorrect sizes of arrays ans also a for loop of yours is incorrect. The loop after you printed your final array  for(i=0; i<sizefull;) is not correct.
I will try to provide a simple solution to your problem.
First, merge the four arrays, Second, perform a sorting algorithm(bubble, say), then try to find unique numbers from them.
int main()
{
    int size1, size2, size3, size4,sizefull,a[30],b[30],c[30],d[30],e[120];
    int i,j,t,match,temp;
    printf("Insert the size of A: ");
        scanf("%d",&size1);
    printf("Insert %d elements of A:\n", size1);
    for(i=0;i<size1;i++)
        scanf("%d",&a[i]);
    printf("Insert the size of B: ");
        scanf("%d",&size2);
    printf("Insert %d elements of B:\n", size2);
    for(i=0;i<size2;i++)
        scanf("%d",&b[i]);
    printf("Insert the size of C: ");
        scanf("%d",&size3);
    printf("Insert %d elements of C:\n", size3);
    for(i=0;i<size3;i++)
        scanf("%d",&c[i]);
    printf("Insert the size of D: ");
        scanf("%d",&size4);
    printf("Insert %d elements of D:\n", size4);
    for(i=0;i<size4;i++)
        scanf("%d",&d[i]);
    sizefull=size1+size2+size3+size4;
    //The below code is for copying.
    i=0;
    j=0;
    while(i<size1)
    {
             e[j]=a[i];
             i++;
             j++;
    }
    i=0;
    while(i<size2)
    {
             e[j]=b[i];
             i++;
             j++;
    }
    i=0;
    while(i<size3)
    {
             e[j]=c[i];
             i++;
             j++;
    }
    i=0;
    while(i<size4)
    {
             e[j]=d[i];
             i++;
             j++;
    }
     //bubble sort
    for(i=0;i<sizfull-i;i++)
    {
         for(j=0;j<sizefull-i;j++)
         {
              if(e[j]>e[j+1])
              {
                  temp=e[j];
                  e[j]=e[j+1];
                  e[j+1]=temp;
              }
         }
    }
    //Code below is for finding and printing unique numbers.
    for(i=0;i<sizefull-1;i++)
    {
        match=0;
        for(j=i+1;j<sizefull;j++)
         {
             if(e[i]==e[j])
             {
                 match++;
                 break;
             }
         }
         if(match==0)
         printf("unique number=%d at index %d",e[i],i);
    }

}

A: Changed example code to get user input. The merge part is the same as Antoine Mathys answer, so this code example mostly shows a simple way to print unique numbers from a sorted array. Added qsort() calls to sort the 4 arrays, since it's not clear if the arrays were supposed to be already sorted.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* print unique numbers from sorted array */
void print_uniques(int x[], int sizex)
{
int i, j;
    if(sizex == 0)
        return;
    i = j = 0;
    while(i != sizex){
        i++;
        if(i != sizex && x[i] == x[j])
            continue;
        if((i - j) == 1)
            printf("%d\n", x[j]);
        j = i;
    }
}

/* merge two already sorted arrays */
void merge(int m[], int x[], int sizex, int y[], int sizey)
{
int i=0, j=0, k=0;
    while (i < sizex && j < sizey)
    {
        if (x[i] <= y[j])
            m[k++] = x[i++];
        else
            m[k++] = y[j++];
    }
    while (i < sizex)
        m[k++] = x[i++];
    while (j < sizey)
        m[k++] = y[j++];
}

/* compare function for qsort() */
int cmp(const int *i, const int *j)
{
    return *i - *j;
}

/* get data (no size check) */
int getdata(int x[], char l)
{
int s, i;
    printf("Enter the number of elements for %c : ", l);
    if(0 == scanf("%d", &s))
        return 0;
    for(i = 0; i < s; i++){
        printf("Enter an element for %c : ", l);
        scanf("%d", x+i);
    }
    return s;
}

int main()
{
int a[64], b[64], c[64], d[64];
int a_b[128], c_d[128];
int e[256];
int sizea, sizeb, sizec, sized;
int sizea_b, sizec_d, sizee;

    sizea = getdata(a, 'A');
    sizeb = getdata(b, 'B');
    sizec = getdata(c, 'C');
    sized = getdata(d, 'D');

    sizea_b = sizea   + sizeb;
    sizec_d = sizec   + sized;
    sizee   = sizea_b + sizec_d;

    /* sort the arrays */
    qsort(a, sizea, sizeof(a[0]), cmp);
    qsort(b, sizeb, sizeof(b[0]), cmp);
    qsort(c, sizec, sizeof(c[0]), cmp);
    qsort(d, sized, sizeof(d[0]), cmp);

    /* merge the arrays */
    merge(a_b, a, sizea, b, sizeb);
    merge(c_d, c, sizec, d, sized);
    merge(e, a_b, sizea_b, c_d, sizec_d);

    printf("\n");
    print_uniques(e, sizee);

    return 0;
}

Alternate get data that lets user input multiple elements on a single line without having to specify the number of elements.
/* get data (no size check) */
int getdata(int x[], char l)
{
char d[] = " ,\t\n";
char t[80];
int i = 0;
char *pt;
    printf("enter element(s) for %c :\n", l);
    if(NULL == fgets(t, sizeof(t), stdin))
        return 0;
    pt = strtok(t, d);
    while(pt){
        sscanf(pt, "%d", x+i);
        i++;
        pt = strtok(NULL, d);
    }
    return i;
}


text:
Q: Example of an infinite sum of functions $f_n(x)$ that converges to $x$, is there a typo in my book? I have a book that says the following:

Let $f_1(x), f_2(x), \dotsc$ a sequence of bounded functions with $f_1(x) + f_2(x) + \dotsb = x$, for example
  $$
 f_1(x) = \frac{\sin x}{x}, \;
 f_n(x) = \frac{\sin xn}{xn} - \frac{\sin (n-1)x}{(n-1)x}
$$

However,
$$
\frac{\sin(x)}{x} +
\sum_{n=2}^{\infty}\left(
 \frac{\sin(xn)}{xn}-\frac{\sin(x (n-1))}{x(n-1)}
\right)
 = 0.
$$
 So is there an error or typo in the book and if so, what do you think the book meant to say? Or am I somehow misinterpreting what it says?

A: Provided $\sin x n \ne 0$ for any $n\in N$, we have $\sum_{n=1}^{\infty}f_n(x)=\lim_{m\to \infty}(\sin m x)/m x=0$ as you said. You are right. The book has an error,maybe a typo.


text:
Q: paramiko - error with a large wget command this is my code:
import paramiko
import time

host = "123.456.789"
username = "myusername"
password = "mypassword"

client = paramiko.client.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(host, username=username, password=password)
_stdin, _stdout,_stderr = client.exec_command("sudo -i")
_stdin.write(password + '\n')
_stdin, _stdout,_stderr = client.exec_command("sudo wget -O- 'https://abc.com.gz' | gunzip | dd of=/dev/sda", get_pty=True)
_stdin.flush()
#Print content
for line in _stdout.readlines():
   print(_stdout.read().decode())
# Close ssh connect
time.sleep(5)
client.close()

the result I get is the screen doesn't print anything, and after a period of ~30-40 minutes the server doesn't receive any files from the wget command....

A: Try to invoke the Shell instead:
import paramiko, time

host = "123.456.789"
username = "myusername"
password = "mypassword"
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(host, username=username, password=password)
remote_shell = client.invoke_shell()

remote_shell.send("sudo -i")
remote_shell.send(password + "\n")
remote_shell.send("sudo wget -O- 'https://abc.com.gz' | gunzip | dd of=/dev/sda")

# print reply
time.sleep(1)
print(remote_shell.recv(65535))
time.sleep(1)
client.close()


text:
Q: How come the gevent timeout exception is never caught by my except clause? The code never reaches the print 'never reach1' or print 'never reach2' line when I try to telnet into the server.
import sys, signal
from gevent.server import StreamServer
from gevent.pool import Pool
from gevent import monkey
import gevent
from gevent import Timeout
import random

class SocketPool(object):

    def __init__(self):
        self.pool = Pool(1000)

    def listen(self, socket):
        while True:
            line = socket.recv(1024)
            print line

    def add_handler(self, socket, address):
        if self.pool.full():
            raise Exception("At maximum pool size")
        else:
            self.pool.spawn(self.listen, socket)
            gevent.spawn(self.wait).join()

    def wait(self):
        try:
            timeout = Timeout(1)
            timeout.start()
        except Timeout:
            print 'never reach1'
        except:
            print 'never reach2'

    def shutdown(self): self.pool.kill()

def signal_handler(signal, frame): sys.exit(0)

signal.signal(signal.SIGINT, signal_handler)
monkey.patch_all()
sockPool = SocketPool()
server = StreamServer(('127.0.0.1', 5000), sockPool.add_handler)
server.serve_forever()

A: As you can see from the documentation:
timeout = Timeout(seconds, exception)
timeout.start()
try:
    ...  # exception will be raised here, after *seconds* passed since start() call
finally:
    timeout.cancel()

So your try block is completely executed and hence cannot catch the exception.
You should put something like a while loop or a computation that requires at least 1 second to see the exception.
If you want to make a method that simply "sleeps" without using CPU I'd recommend using a simple time.sleep instead of using a Timeout.


text:
Q: How to apply a condition only when multiple rows are retrieved in SQL Server My apologies, I am new to SQL Server queries. I am joining two SQL Server tables in my query. This may produce either a single or multiple rows. Currently, I am selecting the top row by using TOP 1.
I want to select the row, if there is more than one row retrieved, where ci.CLOCK_OUT_TIME is NULL. The following is my query, I am not sure how to incorporate the ci.CLOCK_OUT_TIME is NULL condition only when the query pulls multiple rows.
If it pulls just one row, the ci.CLOCK_OUT_TIME is NULL condition should not be applied. I tried to use coalesce function, but it didn't give the desired result.
SELECT TOP 1
    ps.PLANNED_SCHEDULE_ID, ps.SHIFT_ID,
    ps.EMPLOYEE_ID,
    SCHEDULE_SOURCE, ps.JOB_ID, ps.[START_DATE], ps.END_DATE,
    ps.START_TIME, ps.END_TIME,
    ps.STORE_ID, ps.OVERTIME_MINUTES, ps.REGULAR_MINUTES
FROM
    PLANNED_SCHEDULE ps WITH (NOLOCK)
LEFT JOIN
    CLOCK_IN ci ON ci.PLANNED_SCHEDULE_ID = ps.PLANNED_SCHEDULE_ID
WHERE
    DATEDIFF(DAY, ps.START_DATE, '11/3/2018') = 0
    AND EMPLOYEE_ID = '2211'
ORDER BY
    CAST(ps.start_date + ' ' + ps.start_time AS DATETIME)

A: Just order by ci.CLOCK_OUT_TIME if you have multiple rows and some of those are null will be on the top.
ORDER BY
    CAST(ps.start_date + ' ' + ps.start_time AS DATETIME),
    ci.CLOCK_OUT_TIME

SQL DEMO


text:
Q: Process information when interrupted: stack or process control block I am studying an Operating System course and we have this chapter about Processes. In this chapter we define the Process Control Block, which keeps the information about a process such as the program counter, content of registers, state, priority and so on. In this chapter it says that when the processor switches to another process (by interrupt), information will be saved in this process control block (PC, registers,...). In another chapter (1.4 Interrupts) it says when a process gets interrupted the PSW, PC and registers get put on the stack and when processor retakes control of this process it takes it from the stack.
It seems to be there are 2 different explanations here for what happens when an interrupt occurs. Do they both happen simultaneously or what? Can anyone explain this to me?
Thanks in advance
Sander

A: Think of an interrupt as a function call with the difference that it stores more information on the stack and occurs at any time breaking into the normal flow of the program instructions. So, if interrupt handler function decides just to return from the interrupt call, the state is restored from the stack.
Otherwise, if inside the interrupt call, OS decides to preempt the current user process, it saves all the process state to PCB and switch the stack to another process.
BTW, switching to another process can happen not only by interrupt but during any normal call to OS kernel API (syscall).


text:
Q: How do we know if a system of equations has multiple solutions and how to solve it? For example, my equations are
$\lambda_1=\sqrt{\dfrac{\alpha^2}{2}+\sqrt{k^4+\dfrac{\alpha^4}{4}}}$
$\lambda_2=\sqrt{-\dfrac{\alpha^2}{2}+\sqrt{k^4+\dfrac{\alpha^4}{4}}}$
$\lambda_1\tan\!\big(\!\lambda_2L\!\big)-\lambda_2\tanh\!\big(\!\lambda_1L\!\big)=0$
$\alpha$ is a known quantity whereas the unknowns are $\lambda_1, \lambda_2$ and $k$. Since we have 3 equations and 3 unknowns it is solvable.
But how do we figure out if the equation system has multiple solutions and is of this sort? I'm interested in the first five or ten solutions.
Any help on how to approach is highly appreciated.

A: In fact, you only have one equation for one unknown $(k)$ since $\lambda_1$ and $\lambda_2$ are explicit functions of $k$ for given values of $\alpha$ and $L$.
The equation being transcendental, numerical methods would be required to find the zeros of
$$f(k)=\lambda_1\tan(\lambda_2L)-\lambda_2 \tanh(\lambda_1L)$$
To avoid the discontinuities, I should better consider function
$$g(k)=\lambda_1\sin(\lambda_2L)-\lambda_2 \tanh(\lambda_1L)\cos(\lambda_2L)$$
Edit
Consider the case of the $n^{\text{th}}$ root when $n$ is large. The terms in $\alpha$ will be negligible and
$$g(k) \simeq k (\sin (k L)-\cos (k L) \tanh (k L))$$ Since the hyperbolic tangent is quickly close to $1$, the solutions are close to the roots of $\tan(kL)=0$ that is to say $k L=m \pi$ that is to say that, at the limit, the distance between two roots will be approximately $\frac \pi L$.
In any manner, the first root of the equation is such that
$$ 0 < k_1 < \frac {3.9266} L $$
For illustration, let us take the values $\alpha=0.1714$ and $L=1286$ you gave in comments and compute the first roots
$$\left(
\begin{array}{ccc}
n & k_n & k_{n}-k_{n-1} \\
1  & 0.02051017643 & \\
2  & 0.02901018957 & 0.0085000131 \\
3  & 0.03553910523 & 0.0065289157 \\
4  & 0.04105159902 & 0.0055124938 \\
5  & 0.04591800842 & 0.0048664094 \\
6  & 0.05032863202 & 0.0044106236 \\
7  & 0.05439677919 & 0.0040681472 \\
8  & 0.05819647310 & 0.0037996939 \\
9  & 0.06177928968 & 0.0035828166 \\
10 & 0.06518289794 & 0.0034036083 \\
11 & 0.06843583053 & 0.0032529326 \\
12 & 0.07156033949 & 0.0031245090 \\
13 & 0.07457417172 & 0.0030138322 \\
14 & 0.07749177297 & 0.0029176012 \\
15 & 0.08032508633 & 0.0028333134 \\
16 & 0.08308412382 & 0.0027590375 \\
17 & 0.08577737829 & 0.0026932545 \\
18 & 0.08841212654 & 0.0026347482 \\
19 & 0.09099466086 & 0.0025825343 \\
20 & 0.09353046214 & 0.0025358013 \\
\end{array}
\right)$$ while $\frac \pi {1286}=0.00244292$.
So, after a very few solutions, a good estimate of the next is just
$$k^{(0)}_n=2k_{n-1}-k_{n-2}$$
The proof
$$\left(
\begin{array}{ccc}
n & k^{(0)}_n= 2k_{n-1}-k_{n-2} & k_n \\
3 & 0.0375102027 & 0.03553910523 \\
4 & 0.0420680209 & 0.04105159902 \\
5 & 0.0465640928 & 0.04591800842 \\
6 & 0.0507844178 & 0.05032863202 \\
7 & 0.0547392556 & 0.05439677919 \\
8 & 0.0584649264 & 0.05819647306 \\
 9 & 0.0619961669 & 0.06177928962 \\
10 & 0.0653621061 & 0.06518289794 \\
11 & 0.0685865063 & 0.06843583053 \\
12 & 0.0716887631 & 0.07156033949 \\
13 & 0.0746848485 & 0.07457417172 \\
14 & 0.0775880040 & 0.07749177297 \\
15 & 0.0804093742 & 0.08032508633 \\
16 & 0.0831583997 & 0.08308412382 \\
17 & 0.0858431613 & 0.08577737829 \\
18 & 0.0884706328 & 0.08841212654 \\
19 & 0.0910468748 & 0.09099466086 \\
20 & 0.0935771952 & 0.09353046214 \\
\end{array}
\right)$$
Update
It even seems that we could generate an estimate for the first solution
$$k^{(0)}_1=a\,\Bigg[\frac{6 (a L-\tanh (a L))}{a L \left(a^2 L^2+3\right)-3 \tanh (a L) \left(a^2 L^2+a L \tanh (a L)+1\right)}\Bigg]^{\frac 14}$$ For the worked example, this gives $0.018110$


text:
Q: How to properly iterate through array using async functions I have an array of URLs, which I have to download using JS / Cordova async functions. My current implementation looks like this (simplified):
var urls = [ ...... many many ...... ]
var arrayPointer = 0;

downloadData();

function downloadData() {
    if(arrayPointer >= urls.length) {
        do_something_else();

        return false
    }

    downloadURL(urls[arrayPointer++],successDownloadCallback,failDownloadCallback);

    return false;
}

function failDownloadCallback() {
    logError();
    downloadData();

    return false;
}

function successDownloadCallback(data) {
   saveDataToFile(data,saveSuccessCallback,saveFailCallback);

   return false;
}

function saveFailCallback() {
    logError();
    downloadData();

    return false;
}

function saveSuccessCallback() {
    downloadData();

    return false;
}

Unfortunately, I get "Maximum call stack size exceeded" error sometimes. Is there a better way to do this?

A: I had this issue before and managed to resolved it by using async loop (for) here is an example
const downloadAllfiles = async (arr) => {
  for(const x of arr) {
     const file = await downloadURL(x.path);
     await saveFile(file);
  }
  console.log('done with all files');
}


text:
Q: How to Use LINQ to Select List of KeyValuePairs By Matching Key and Values I have a generic list of List of KeyValuePair,
i.e. List<List<KeyValuePair<string, string>>>.
I am trying to extract an internal List List<KeyValuePair<string, string>>
based on the value of the Key and Values.
Here is my code:
            var layer =
            (from item in layers
            from kvp in item
            where kvp.Key == "category" && kvp.Value == category_name
            where kvp.Key == "featureType" && kvp.Value == feature_type
            where kvp.Key == "assetType" && kvp.Value == asset_type
            select item);`

In the code above item will have a List of KeyValuePairs and I want to match those to find the right item.
What I am trying to say in my where clauses is where a KeyValuePair (KVP) has a key == "category" and the value of that KVP == category_name and also where another KVP has a key == "featureType" and the value of that KVP is feature_type and yet another KVP has a key = "assetType" and the value of that KVP == asset_type.
This is not working as layer is an empty list but I know the item that has the matches for the three KVP's is there.
Can anyone help point me in the right direction?

A: I guess this is what you want, all lists which contain those key-value pairs:
IEnumerable<List<KeyValuePair<string, string>>> layer = layers
    .Where(l => l.Any(kv => kv.Key == "category" && kv.Value == category_name)
            &&  l.Any(kv => kv.Key == "featureType" && kv.Value == feature_type)
            &&  l.Any(kv => kv.Key == "assetType" && kv.Value == asset_type));

If you expect only one use SingleOrDefault or (if it's not exceptional) FirstOrDefault.


text:
Q: Model binding not working for List T in case of Web api 2 I have a action method with HTTP Verb: POST which accepts List<Student> student object from body as one of the input parameter of the action method:
[Route("{Id:int}/save", Name = "SaveStudent")]
[HttpPost]
public IHttpActionResult AddStudent(int Id,[FromBody]List<Student> students)
{
   return Ok<List<Student>>(students);
}

Now when I tried to test the above method from the Fiddler using the below request details:
{
  "students": [
    {
      "name": "Test",
      "rollno": null,
      "totalmarks": null
    }
  ]
}
I am getting a 400 bad request error.
Can anyone help me to know what exactly I am missing here?

A: array is not in correct format it should be like this:
[{name: "Test", rollno: null, totalmarks: null }, {name: "Test2", rollno: null, totalmarks: null }]

Model class used in C#
  public class Student {
public string Name { get; set; }
public int RollNo { get; set; }
public int TotalMarks { get; set; }

}
Additional json format resolver added during webapi initialization.
      config.MapHttpAttributeRoutes();

  var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
  jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

I hope this will help you getting this working now


text:
Q: How to installing Windows 10 Phone in Qt? I want to develop Windows 10 Mobile applications. I installed Visual Studio 2015 Community and I installed Qt 5.6 packages from Qt 5.5.1 MaintenanceTool (Image) and I installed Universal Windows packages from VS 2015, so I think Win SDK installed. Then I installed Windows 8 Phone packages from VS 2015. But Win 10 Mobile packages is disabled on the Qt Creator (Image). How can I develop Win 10 Mobile apps with Qt? Thanks.
Edit: Debugger not found: MSVC, win rt armv7, win rt 32 bit

A: You should install Visual Studio 2013 to develop Windows Phone applications. If you want to develop WindowsRT applications you can use Visual Studio 2015.
Look at the picture with packages. There is information which version you should use to develop specific applications.

A: You need to install the debugging tools for windows, which are only available through the Windows SDK. You can select only the debugging tools, and leave the rest of the SDK as it was.


text:
Q: Is there a quick way to remove browser decorations I'm finding that more and more applications use browsers as their user interface and I am caught in a dilemma.

*

*When browsing I want a browser window to have browser buttons, navigation icons, etc.

*When I'm using the browser for an application like twitter or yammer then I don't need those and having them just reduces the application area.  I would rather save the vertical space and have a very sparse undecorated window.

The problem is it does not seem easy to do this.  My initial thought was to just install two different browsers.  For example use Firefox with all the toolbars and then set IE to show no toolbars.  I think this is ok but I would like a cleaner solution.  Maybe a plugin in Firefox that turns everything off easily or something.

A: Try Prism for Firefox or a Google Chrome application. I think these might deliver what you're looking for.

A: I don't know about the other browsers, but in Internet Explorer and Firefox you can hit the F11 key and have it go "Full Screen" which removes all the border stuff and gives you more space to do your work.  Then if you need to, you can hit F11 to go back or mouse up to the top to see your menus.

A: Google Chrome has this feature built in.
For Firefox, you might consider setting up two profiles.  For your applications you  can use the "Apps" profile and then browse under the default profile.  Here are some links for working with Firefox and profiles:

*

*Firefox: Using multiple instances with different profiles?

*Launching Firefox into "chromeless" mode from command prompt

A: I know I'm not directly answering the question, but perhaps a compromise between available function and maximum view would be useful?

*

*LittleFox

is designed for optimal> screen usage,
  leaving lots of room for
  browsing.

*lifehacker-
how-to-consolidate-firefox-3s-chrome

*lifehacker-
maximize-firefox-35s-viewing-area-for-your-netbook

*Status Address Bar

shows the address in the address bar,
  so you don't need the status bar


text:
Q: Best way to run module initialization code from mod_perl2 for every new HTTP request? I have "inherited" a web server that has about 200 cgi scripts, all of them written in perl. One of my tasks is converting them to run unter mod_perl2, without losing CGI runnability.
Now, there are about 10 perl modules, each of which is used from some, but not all, of the CGI scripts; and some of the modules use each other as well.
In the CGI version, some of the modules do their own initialization when they're loaded, with the initialization depending on the script, the QUERY_STRING, PATH_INFO and the like. Think of something like (stripped down a lot to explain, i wouldn't trust PATH_INFO to specify anything written to in a real live situation)
package MyCompany::Directories;
our ($datadir);
sub getDataDir() { return $datadir; }
$datadir=$ENV{PATH_INFO};

package MyCompany::MyModule2
use MyCompany::Directories;
....

# main CGI script
use MyCompany::Directories;
use MyCompany::MyModule2;
....
open(LOG, ">".MyCompany::Directories::getDataDir()."log.txt";
....

In CGI perl, all is well. MyCompany::Directories initializes $datadir the first time it's used, and the initialization code won't get called more than once even if several modules use MyCompany::Directories. In mod_perl2, the module gets 'use'd only once, so $datadir never gets reset on subsequent requests.
To fix this, i could add a MyCompany::Directories::init() function that i call in every CGI script. Or i could convert the MyCompany::Directories module to a "real" OO module, calling new whenever i want to use it. But both cases require me to modify all my CGIs, which i'd like to avoid. Is there any other good way to achieve re-initialization on every new request, preferrably one that requires touching the module only, not the plethora of scripts that use it?


text:
Q: Dynamic formula cell referencing w/offset My formula:
=IFERROR(OFFSET('**2015**'!$A$1,MATCH($A8,'**2015**'!$A$2:$A$6000,0),0),0)
I need the parts in bold to be referencing a cell with a drop down (the drop down obviously has different dates which the formula needs to take into account) - which I guess makes it somewhat dynamic.
I have tried the indirect formula but failed to accomplish anything. I have ran out of ideas unfortunately.

A: I prefer the INDEX/MATCH over the offset:
=IFERROR(INDEX(INDIRECT("'" & $A1 & "'!$AA:$AA"),MATCH($A8,INDIRECT("'" & $A1 & "'!$A:$A"),0)),0)

This will search column A for the matching value and return the corresponding value from column AA in the desired sheet.
Where A1 is the location of your drop down.

A: Merely adding INDIRECT:
=IFERROR(OFFSET(INDIRECT(O2&"!$A$1"),MATCH($A8,INDIRECT(O2&"!$A$2:$A$6000"),0),0),0)

Assumes dropdown value is in O2.


text:
Q: Calculate time using the last two dates with a condition in R I need to calculate a time difference by a record_id using two consecutive dates but only if the category has a specific value that is repeated (category == "1").
My data frame is
structure(list(record_id = c("P1", "P1", "P1", "P2", "P2", "P3", "P3", "P3", "P3", "P3", "P4", "P4", "P4", "P5", "P5", "P5", "P5"), visit_date = structure(c(1547596800, 1548806400, 1552608000, 1560988800, 1611187200, 1576195200, 1577664000, 1579132800, 1594857600, 1609459200, 1577836800,1580515200, 1612137600, 1548979200, 1583020800, 1585699200, 1617235200), class = c("POSIXct", "POSIXt"), tzone = "UTC"),
category = c(0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1,
1, 1)), row.names = c(NA, -17L), class = c("tbl_df", "tbl", "data.frame"))

I need to create a variable (time) as a date difference between visit_dates by record IDs ONLY if they have two consecutive category==1.
Like this:
structure(list(record_id = c("P1", "P1", "P1", "P2", "P2", "P3", "P3", "P3", "P3", "P3", "P4", "P4", "P4"), visit_date = structure(c(1547596800, 1548806400, 1552608000, 1560988800, 1611187200, 1576195200, 1577664000, 1579132800, 1594857600, 1609459200, 1577836800, 1580515200, 1612137600), class = c("POSIXct", "POSIXt"), tzone = "UTC"), category = c(0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 1), time = c(NA, NA, NA, NA, NA, 169, 169, 169, 169, 169, 366, 366, 366)), row.names = c(NA, -13L), class = c("tbl_df", "tbl", "data.frame"))

Note that P5 the date difference is with the first category 1 and the last category 1

A: base R
consec2 <- function(x, n = 2L) {
  r <- rle(x)
  ind <- (r$values & r$lengths >= n)
  r$values[!ind] <- FALSE
  inverse.rle(r)
}
do.call(rbind, by(dat, dat$record_id, function(z) {
  cat1 <- consec2(z$category == 1)
  z$time <- if (sum(cat1) > 1) {
    as.numeric(diff(range(z$visit_date[cat1])), units = "days") else NA_real_
  z
}))
# # A tibble: 17 x 4
#    record_id visit_date          category  time
#  * <chr>     <dttm>                 <dbl> <dbl>
#  1 P1        2019-01-16 00:00:00        0    NA
#  2 P1        2019-01-30 00:00:00        0    NA
#  3 P1        2019-03-15 00:00:00        0    NA
#  4 P2        2019-06-20 00:00:00        0    NA
#  5 P2        2021-01-21 00:00:00        1    NA
#  6 P3        2019-12-13 00:00:00        0   169
#  7 P3        2019-12-30 00:00:00        0   169
#  8 P3        2020-01-16 00:00:00        0   169
#  9 P3        2020-07-16 00:00:00        1   169
# 10 P3        2021-01-01 00:00:00        1   169
# 11 P4        2020-01-01 00:00:00        0   366
# 12 P4        2020-02-01 00:00:00        1   366
# 13 P4        2021-02-01 00:00:00        1   366
# 14 P5        2019-02-01 00:00:00        0   396
# 15 P5        2020-03-01 00:00:00        1   396
# 16 P5        2020-04-01 00:00:00        1   396
# 17 P5        2021-04-01 00:00:00        1   396

dplyr
library(dplyr)
dat %>%
  group_by(record_id) %>%
  mutate(
    r = consec2(category == 1),
    time = if (any(r)) as.numeric(diff(range(visit_date[r])), units = "days") else NA_real_
  ) %>%
  ungroup()
# # A tibble: 17 x 5
#    record_id visit_date          category r      time
#    <chr>     <dttm>                 <dbl> <lgl> <dbl>
#  1 P1        2019-01-16 00:00:00        0 FALSE    NA
#  2 P1        2019-01-30 00:00:00        0 FALSE    NA
#  3 P1        2019-03-15 00:00:00        0 FALSE    NA
#  4 P2        2019-06-20 00:00:00        0 FALSE    NA
#  5 P2        2021-01-21 00:00:00        1 FALSE    NA
#  6 P3        2019-12-13 00:00:00        0 FALSE   169
#  7 P3        2019-12-30 00:00:00        0 FALSE   169
#  8 P3        2020-01-16 00:00:00        0 FALSE   169
#  9 P3        2020-07-16 00:00:00        1 TRUE    169
# 10 P3        2021-01-01 00:00:00        1 TRUE    169
# 11 P4        2020-01-01 00:00:00        0 FALSE   366
# 12 P4        2020-02-01 00:00:00        1 TRUE    366
# 13 P4        2021-02-01 00:00:00        1 TRUE    366
# 14 P5        2019-02-01 00:00:00        0 FALSE   396
# 15 P5        2020-03-01 00:00:00        1 TRUE    396
# 16 P5        2020-04-01 00:00:00        1 TRUE    396
# 17 P5        2021-04-01 00:00:00        1 TRUE    396


text:
Q: How to draw a straight perpendicular line between 2 other parallel lines? enter image description here
I need to draw the first line using location of finger.
Later I need to draw the second parallel line using location of finger.
I have already done it.
And the main task is to draw the third perpendicular line between those parallel lines.
How can I draw the third line?

A: If you have 2 parallel lines and wish to draw perpendicular line between them you will need 1 extra point. Assume that this point is at the middle of first line (call it C).
Also assume we have the following:
L1 // Represents the first line
L2 // Represents the second line
L1.start // Represents the line start point CGPoint
L1.end // Represents the line end point CGPoint

Now you wish to draw a perpendicular line to first line L1 and to do so you will need to get its normal which is pretty simple in 2D. First get the line direction by subtracting start and end point of a given line direction = CGPoint(x: L1.end.x-L1.start.x, y: L1.end.y-L1.start.y). Now to get the normal we simply need to invert coordinates and divide them by direction length:
let length = sqrt(direction.x*direction.x + direction.y*direction.y)
let normal = CGPoint(x: -direction.y/length, y: direction.x/length) // Yes, normal is (-D.y, D.x)

So as said the start point is C now we only need to find the end point on the other line which is C + normal*distanceBetweenLines. So we need the distance between the two lines which should be best received through dot product...
First we need a vector between any pair of points from the two lines (one point on first line and the other one on the second line). So let's take
let between = CGPoint(x: L1.start.x-L2.start.x, y: L1.start.y-L2.start.y)
Now we need to project this line to normal with dot product to get the length of the projection which is the length between the two lines
let distanceBetweenLines = between.x*normal.x + between.y*normal.y.
So now we have all the points to draw perpendicular line between 2 given lines assuming the lines are parallel:
L3.start = C
L3.end = CGPoint(x: C.x + normal.x*distanceBetweenLines, y: C.y + normal.y*distanceBetweenLines)


text:
Q: Summarizing dataframe and sorting with inserting 0 if the target words doesn't exist I have a tab-delimited data frame like this:
Sample  1
A   2
B   1
D   2
Sample  2
C   1
D   1
E   2
Sample  3
D   1
E   3
Sample  4
A   1
E   3
Sample  5
A   2
B   3
Sample  6
C   1
D   2
Sample  7
D   1
E   3
Sample  8
A   3
D   2
Sample  9
A   1
Sample  10
A   1
C   2
E   3

and I would like to transpose it and link the alphabets and the associated values. If the sample does not contain alphabets, I want "0" inserted.
So the modified dataframe I desire is
Sample  A   B   C   D   E
    1   2   1   0   2   0
    2   0   0   1   1   1
    3   0   0   0   1   3
    4   1   0   0   0   3
    5   2   3   0   0   0
    6   0   0   1   2   0
    7   0   0   0   1   3
    8   3   0   0   2   0
    9   1   0   0   0   0
    10  1   0   2   0   3

I tried to summarize the datafreame, and then transpose it. When I used,
awk 'NR==1{print} NR>1{a[$1]=a[$1]" "$2}END{for (i in a){print i " " a[i]}}' TEST

the output data was
Sample  1
A  2 1 2 3 1 1
B  1 3
C  1 1 2
D  2 1 1 2 1 2
E  2 3 3 3 3
Sample  2 3 4 5 6 7 8 9 10

Sample 1 was isolated, and there was no space when the alphabets were not included by the samples.
I hope that makes sense.


text:
Q: how to make kafkaproducer to continuously run I have written kafkaproducer in java to read logs . But after reading logs process is getting finished , how can I make kafkaproducer to continuously run.I dont want kafkaproducer to get stopped after reading logs.

A: The logic is not related to Kafka but you need to continuously listen to the file for data as follows:
    BufferedReader br = new BufferedReader(
            new FileReader("/path/to/log.txt"));

    String line = null;
    while (true ) {
        line = br.readLine();
        if (line == null) {
            //wait till more data is appended to file
            Thread.sleep(1000);
        }
        else {
            //send data to Kafka
            producer.send(new ProducerRecord<String, String>("my-topic", "my-key", line));
        }
    }

A: Use Kafka-Log Appender to re-direct the logs to the central broker.
https://logging.apache.org/log4j/2.x/manual/appenders.html#KafkaAppender


text:
Q: How can I get the current user's ID without Spring Security? im making a Edairy app, and im doing now the StudentGrades HTML page, which should list the Student's Subjects and their grades. It important that different Students have different kind of subjects, so I only want to display the logged-in students Subject and their grades.
(For example student1 have chesmistry and physics, student2 have P.E., Mathematics)
Now im trying to make a method which selects the Subjects from the DB based on the currently logged-in students ID, but I dont use Spring Security. I tried 2 different ways, but both failed.
public List<Subject> findAll(Integer userId) {

    String sql = "SELECT subject.subjectName,subject.subjectId FROM subject inner join subjectgrade on subject.subjectId = subjectgrade.subjectId right join users on subjectgrade.userId = users.user_id where subjectgrade.userId = ?";
    return jdbcTemplate.query(sql, new BeanPropertyRowMapper(Subject.class));
}

With this attempt, the program failed to process the intended task, because the userId was present, however its a primitive type, and didnt like it for some reason:
Request processing failed; nested exception is java.lang.IllegalStateException: Optional int parameter 'userId' is present but cannot be translated into a null value due to being declared as a primitive type. Consider declaring it as object wrapper for the corresponding primitive type.

With the 2nd attempt, I tried passing an User into the parameter. With that method, the program succesfully ran, but It did not select the logged-in user's Subjects, because I could not figure out how to get the user's ID from the session(?).
public List<Subject> findAll(User user) {

    String sql = "SELECT subject.subjectName,subject.subjectId FROM subject inner join subjectgrade on subject.subjectId = subjectgrade.subjectId right join users on subjectgrade.userId = users.user_id where subjectgrade.userId = "+ user.getUserId();
    return jdbcTemplate.query(sql, new BeanPropertyRowMapper(Subject.class));
}

Its important to note, that Im not using Spring Security, because Im just practicing coding. Can I get the user's ID without rebulding my whole program? Or did I commit a huge logical flaw which made me come to a halt?
(?) = not sure how to call it.

A: As the exception says the user_id is of type int which is a primitive type. Primitive types can not be NULL.
To use NULL for int values you need to use the corresponding wrapper class called Integer which allows the assignment of NULL.


text:
Q: How to resolve error in my sql manual? I encounter error like this in my sql in running my program, How can I resol this error?

Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 's', 's', 's','s','s','s','s', 's')' at line 3

This is the syntax I used.
<?php
    include('config.php');
    ERROR_REPORTING("E_ALL");
?>

    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <title>AVAYA</title>
    <link rel="stylesheet" href="css/style.css" type="text/css" media="screen" />

<?php include_once("template_header.php");?>

<?php
$host="localhost"; // Host name
$username="<myusername>"; // Mysql username
$password="<mypassword>"; // Mysql password
$db_name="inventory"; // Database name
$tbl_name="avaya_pabx"; // Table name

mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

$con = mysql_connect("localhost","root","");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db("inventory", $con);

$addavaya="INSERT INTO avaya_pabx
(item_no, critical_spare_id, serial_no, comcode, version, circuit_pack, classification, location, availability)
VALUES ('". $_POST['item_no'] . ", '". $_POST['critical_spare_id'] . "', '" . $_POST['serial_no']. "', '". $_POST['comcode'] . "','". $_POST['version'] . "','". $_POST['circuit_pack'] . "','". $_POST['classification'] . "','". $_POST['location'] . "', '". $_POST['availability'] . "')";

$result = mysql_query($addavaya,$con);

if (!$result)
  {
  die('Error: ' . mysql_error());
  }
echo "1 record added";

mysql_close($con);

?>

<input type=button class='classname' value='Back'>

<?php include_once("template_footer.php");?>

A: Hello SQL injection ...
Try to use the PDO instead of this approach
http://php.net/manual/en/book.pdo.php
However, the solution for your problem is that the first variable in your values must be like this
 VALUES ('". $_POST['item_no'] . "',

A: You're missing a quote at the start :
VALUES ('". $_POST['item_no'] . ", ...

Should be:
VALUES ('". $_POST['item_no'] . "', ...

And you should take a look at the PDO Exceptions in PHP - the mysql_ extensions are being deprecated.

A: You're missing the close quotation mark in the first value:
VALUES ('". $_POST['item_no'] . ",

Should be like this:
VALUES ('". $_POST['item_no'] . "',


text:
Q: StructureMap resolve generic instance based on Type dynamically Is there a way to resolve based on Type?
Type t = typeof(Person);
var test = Container.Current.TryGetInstance(IMapper<t, ViewModel>);

A: Figured it out:
.NET generics: how to resolve type T in run-time?
Type p = typeof(Person);
Type vm = typeof(ViewModel);

var concreteHandlerType = typeof(IMapper<,>).MakeGenericType(p, vm);
var handler = Container.Current.GetInstance(concreteHandlerType);

Container registration:
c.For(typeof(IMapper<,>)).Use(typeof(Mapper<,>));


text:
Q: cassandra Read performance with Collection I have the following columnfamily defined in cassandra
CREATE TABLE metric (
period int,
rollup int,
tenant text,
path text,
time bigint,
data list<double>,
PRIMARY KEY ((tenant, period, rollup, path), time)
) WITH
bloom_filter_fp_chance=0.010000 AND
caching='KEYS_ONLY' AND
comment='' AND
dclocal_read_repair_chance=0.000000 AND
gc_grace_seconds=864000 AND
index_interval=128 AND
read_repair_chance=0.100000 AND
replicate_on_write='true' AND
populate_io_cache_on_flush='false' AND
default_time_to_live=0 AND
speculative_retry='NONE' AND
memtable_flush_period_in_ms=0 AND
compaction={'class': 'SizeTieredCompactionStrategy'} AND
compression={'sstable_compression': 'LZ4Compressor'};

Does the size of data list affect the read performance in cassandra ? If yes how can we measure it..?
The issue is that the time taken to query Data-Set1 from cassandra to get 8640 rows (where # of elements in the data list for each row is 90) for a given path/period/rollup combination is more than the time required to query Data-Set 2 which is 8640 rows of data (where # of elements in the data list for each row is 10).
Also if I run a performance test with 10 users accessing Data-Set1 simultaneously, then I start seeing cassandra timeouts in the backend, and it spends a lot of time in Garbage collection, but the same does not happen when I do the same by querying Data-Set2.
So I am concluding that the number of elements in the data list is affecting performance.
Are you seeing similar performance issues in your cassandra stack....?

A: I wouldn't think that 90 items in a collection would be that big of a deal, but in your case I guess it is.  The problem is that when you query a collection column, Cassandra can't just return parts of the collection.  It has to return the entire column (collection).  That operation isn't free, but I wouldn't think that 90 doubles would be a big deal.
One thing to try is to turn tracing on.  That should give you some idea of what Cassandra is doing when you are running your query.
aploetz@cqlsh:stackoverflow> tracing on;

Often, turning on tracing can lead you to the cuplrit.

it spends a lot of time in Garbage collection

Are you using any special JVM settings?  How much RAM do you have on each node?  GC that interrupts normal operations indicates (to me) that there might be an issue with your JVM heap settings.  The DataStax doc on Tuning Java Resources indicates that you should use the following guidelines on sizing your heap, based on your node's RAM:
System Memory       Heap Size

Less than 2GB       1/2 of system memory
2GB to 4GB          1GB
Greater than 4GB    1/4 system memory, but not more than 8GB


text:
Q: Spotify SDK Swift 3 I am developing an application, but I have never used the Spotify SDK. I managed to get the user login & authorization going despite the tutorial being in Obj-C but my question is in regards to streaming music and pulling down users information. Basically I am trying display the users name and give them access to their songs via my app which then they can use with features I will implement. Is anyone familiar with working with the Spotify SDK and/or could give me a hint as to how I can manage to do the above. Thanks.
Best regards,
Andres

A: This info is in the documentation.
To access the user's info:

*

*You need to have the SPTAuthUserReadPrivateScope scope

*call STPUser.requestCurrentUserWithAccessToken:callback:. Documentation
To access the user's playlists:

*

*These 2 scopes: SPTAuthPlaylistReadScope and SPTAuthPlaylistReadPrivateScope

*Call STPPlaylistList.playlistsForUser:withAccessToken:callback:. Documentation


text:
Q: how to get sum of two jtextfield values divide another jtxt value in jtxtfield I need to get sum two value and divide one value and show the result in Jtxtfield
I use this code
    {
    int num1,num2,num3,sum;
    num1=Integer.parseInt(PB_cash.getText());
    num2=Integer.parseInt(DC_cash.getText());
    num3=Integer.parseInt(BD_cash.getText());
    sum=num1+num2-num3;
    HB_cash.setText(" "+sum);
    }

I tried it from without database connection and it works well
but connection with database it will get runtime error
this is the error
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: " 77000"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:569)
at java.lang.Integer.parseInt(Integer.java:615)
at bankapplication.Withdrawal_Interface.jButton7ActionPerformed(Withdrawal_Interface.java:758)
at bankapplication.Withdrawal_Interface.access$400(Withdrawal_Interface.java:30)
at bankapplication.Withdrawal_Interface$5.actionPerformed(Withdrawal_Interface.java:502)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2346)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6525)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6290)

Plz help me to fix this problem
Thanks

A: Looking at the exception you received, you can not have a space in the string numerical value sent to the: Integer.parseInt() method:
Your exception:
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: " 77000"

Use the String.trim() method to remove tabs and whitespaces:
{
    int num1,num2,num3,sum;
    num1=Integer.parseInt(PB_cash.getText().trim());
    num2=Integer.parseInt(DC_cash.getText().trim());
    num3=Integer.parseInt(BD_cash.getText().trim());
    sum=num1+num2-num3;
    HB_cash.setText(" " + String.valueOf(sum)); //why you want the space is beyond me :)
}

On another note, looking at your JTextField names, it looks like cash is actually to be eventually supplied. Consider using a float or double data type instead of int. That way you can also supply monetary values with decimals like: 5.99.


text:
Q: not found the url in laravel when use prefix I use route group and prefix in Laravel
Route::name("admin.")->prefix("admin")->group(function (){
    Route::get("/",function (){dd("test");});
});

http://127.0.0.1:8000/admin
but this url don't work and return 404 :(
Where did I go wrong?


text:
Q: HTML5 Audio tag not working with IIS7 in different environments I have implemented an HTML5 audio player on a webpage that uses standard ashx handlers to serve the .mp3 to the player. When testing this new feature locally, it works great in all browsers on the desktop as well as android and iOS. Once deploying the project to the test server I loose functionality only in android (the file will not play at all, this isn't an autoplay issue or anything). Once deploying code to the production environment android works again but I loose iOS.
Based on what I have looked at so far it seems to be an issue in IIS. When I localize the file to the web server instead of serving from the db I run into the same issue.
The MIME types are all set up correctly and are the same across the environments, Handler Mappings match in all environments, HTTP Response Headers are the same across the environments.
I'm not sure what other settings in IIS could cause this issue.


text:
Q: Jmeter - how do i run two samplers as a bundle Right now I have two api methods to test

*

*POST indexmember

*DELETE indexmember

The problem is that indexmember has got the fields that have to be unique.
Therefore, when I run POST & DELETE once (# of threads == 1; loop == 1) - it works fine. Indexmember gets posted, then deleted, then i post again and it's fine, the unique values are still unique then.
But when I add more threads => jMeter starts POSTing several indexmembers altogether and some of the methods fail with our custom validation
 "Errors": [
    {
      "Message": "The Index member with IndexId [id] and SecurityId [id] is already present in database."
    }
  ],
  "Success": false

I was thinking on making DELETE function as some kind of sub-sampler to the POST.
So that POST and DELETE go together in one thread.
Any advice will be appreciated.

A: i would suggest to have both POST and DELETE request under the same thread group and Make sure you give enough ramp up time...


text:
Q: Static method of object disappeared after compilation Using this very simple piece of code
import java.util.Properties

class MyProperties extends Properties

object MyProperties {

    def get(): MyProperties = new MyProperties

    def anotherMethod(): MyProperties = new MyProperties

}

the get() method is missing in the compiled code; a Java decompilation of the MyProperties class yields (scala signature omitted)
import java.util.Properties;
import scala.reflect.ScalaSignature;

public class MyProperties extends Properties
{
  public static MyProperties anotherMethod()
  {
    return MyProperties..MODULE$.anotherMethod();
  }
}

If MyProperties does not extend java.util.Properties however, the get() method is generated.
java.util.Properties inherits the public V get(Object key) from java.util.Dictionary but that is a non static method with a different signature.
Why is the (static) get() method missing in the generated bytecode?
Scala 2.10.1-rc2  -   JVM 1.6.0_41
Edit
Same issue with 2.10.0
Edit 2
This "works" in java
import java.util.Properties;

public class MyPropertiesjava extends Properties {

    private static final long serialVersionUID = 1L;

    public static MyProperties get() {

        return new MyProperties();
    }

    public static MyProperties antotherMethod() {

        return new MyProperties();
    }
}

Edit 3
A small edit to Régis workaround below (the type cannot be "global")
import java.util.Properties

class MyPropertiesImpl extends Properties

object MyProperties {

    type MyProperties = MyPropertiesImpl

    def get(): MyProperties = new MyPropertiesImpl

    def anotherMethod(): MyProperties = new MyPropertiesImpl

}

Edit 4
Issue tracked by Typesafe team here

A: You are not looking at the right classfile. Try to decompile MyProperties$.
UPDATE: My bad, I understand now that you were actually looking for the static forwarder for get. The reason it has disappeared from MyProperties.class, is because there is already a get method in class MyProperties (inherited from Properties) which would conflict with the autogenerated static forwarder (and so the compiler does *not generate it). See this other answer I made earlier, for more context: https://stackoverflow.com/a/14379529/1632462
However, I must say that you make a good point that normally there should be no conflict as they have different signatures (unlike the fact that one is static and the other one is not, as static and non-static methods share the same namespace on the JVM AFAIK). I guess the compiler took the easy route and just checks for the presence of the method name as opposed to check for the exact signature.
Here one way to fix it would be to rename MyProperties (and possibly add a type alias so that the API stays the same):
class MyPropertiesImpl extends Properties
type MyProperties = MyPropertiesImpl
object MyProperties {
    def get(): MyProperties = new MyPropertiesImpl
    def anotherMethod(): MyProperties = new MyPropertiesImpl
}

Because MyProperties is no more the companion of MyPropertiesImpl the problem goes away.


text:
Q: iTunes connect - must be uploaded directly I've recently finished development on an app and have reached the point of deploying it to the store via iTunes Connect. I had managed to fill out all the required information under "App information", and "Pricing and Availability".
However my issue is i am currently stuck on the "Prepare for Submission" section. I have managed to upload screenshots and select a build. But it will not allow me to save, so essentially any edits under this section are impossible now due to the below error i am receiving:

"Screenshots and app previews for the largest display sizes of your app's primary localization must be uploaded directly., Screenshots and app previews for the largest display sizes of your app's primary localization must be uploaded directly."

The above seemed to only occur after switching localisation to English(U.K) and then uploading my screenshots, after i saved those last amends this is when the error started occurring. However i am unable to revert any changes due to the above error.
I apologise if i'm missing something obvious here, but looking through iTunes Connect documentation and scouring the internet has came up with nothing.

A: I submitted two videos of the issue, one via Safari and the other via CLI tool deliver. The last response i had from Apple was that they were escalating the issue to their engineering team.
I've tried to edit my submission today ( 24/08/2016 ) and can confirm that the issue seems to of been resolved. I have had no response from Apple, but so far it seems to be working as intended.


text:
Q: iOS Gamekit Blutooth 4+ Players? I want to make a multiplayer game that will allow 4 people to connect their iphones together via bluetooth and play a realtime networked game.
I've been reading and reading about this, but cannot find out if it is possible. I have found documents demonstrating how you connect 2 devices via bluetooth, but I want to connect 4. Is this possible?
Can it be a host client setup, or does it have to be p2p?
Has anyone gone about implementing a 4 player multiplayer ios game over bluetooth? Can you give me any advice on how this is possible?


text:
Q: Object doesn't support property or method 'slider' (jquery in Sharepoint 2010) I'm getting the error Object doesn't support property or method 'slider' when loading my Sharepoint page.
I'm running this function on page load
function sliderFunctionality() {
$("#sliderdiv").css("background-color", "#ccc");
$("#sliderdiv").slider({
    value: 0,
    min: 0,
    max: 5,
    step: 1,
    slide: function (event, ui) {
        $("#amount").val("$" + ui.value);
    }
});
$("#amount").val("$" + $("#sliderdiv").slider("value"));
alert('testing.....');
};

Here is my webpart code
protected override void CreateChildControls()
    {
        //REGISTER STYLESHEETS
        CssRegistration.Register("/_layouts/STYLES/Stylesheet1.css");

        //REGISTER JAVASCRIPT LIBRARIES
        ScriptLink.Register(this.Page, "/_layouts/SCRIPTS/jquery-1.7.1.min.js", false);
        ScriptLink.Register(this.Page, "/_layouts/SCRIPTS/jquery.SPServices-0.7.0.min.js", false);
        ScriptLink.Register(this.Page, "/_layouts/SCRIPTS/JScript1.js", false);

        this.Controls.Add(new LiteralControl("Donation amount ($50 increments):"));
        this.Controls.Add(new LiteralControl("
<input type='text' id='amount' style='border:0; color:#f6931f; font-weight:bold;' />"));
        this.Controls.Add(new LiteralControl("
here

"));

        this.ChildControlsCreated = true;
    }

The change of css background colour works but the slider doesn't.  So jquery is working fine on the page and the DIV is being found.
Why is slider not working?  I'm using jquery 1.7.1

A: I don't see anywhere that you're pulling in the jQuery-UI JavaScript. I think you should have something that looks more like this:
ScriptLink.Register(this.Page, "/_layouts/SCRIPTS/jquery-1.7.1.min.js", false);
ScriptLink.Register(this.Page, "/_layouts/SCRIPTS/jquery-ui-1.8.17.min.js", false);
...

And you might want a CssRegistration.Register for the jQuery-UI stylesheet as well. I don't know what your jquery-ui.js is called so I guessed.

A: Make sure you aren't including jQuery more than once. The second one will reset any earlier plugins you have already added to the rendered HTML.


text:
Q: ERROR Async loop died! org.zeromq I'm new to ubuntu and storm , i need to solve this problem
[ERROR] Async loop died!
org.zeromq.ZMQException: Address already in use(0x62)
at org.zeromq.ZMQ$Socket.bind(Native Method)

it appeared in worker log file due to supervisor still hasn't start and by searching found someone wrote that is due to
ephemeral port range was messed
up on the machines

tried to increase /proc/sys/net/ipv4/ip_local_port_range 1024 65000
but not working

A: This issue is related to already used ports in your system. A port can only be used by a single application. Using lsof -i you can check what application are using which ports. You should spot an conflicting port number. Either terminate this application of change the configuration of Zookeeper or Storm to use a different port.


text:
Q: Why does the frequency of a wave does not change on reflection and on transmission? I wanted to know why the frequency of a wave does not change even on reflection or  transmission and does it only depends on the source only.

A: The frequency can change upon reflection; see e.g. Doppler Radar. And if the reflecting object is not infinitely heavy, have a look here

A: Frequency depends only on the source of the wave.  Whatever is generating a given wave is going through some type of harmonic motion, and that motion generates a disturbance in some medium (for mechanical waves).  The wave may encounter a denser medium in its travels, in which case it will slow down and its wavelength will get shorter.  Despite that, the frequency will remain constant, and given that two out of three from the list of frequency, velocity, and wavelength are known, the unknown variable may be calculated from the equation $v=f\lambda$.

A: In the case of reflection or transmission through simple linear dielectrics here is roughly what happens. Electric fields from the incident light travelling mostly in the $+z$ direction create drive oscillating dipoles in the dielectric. These dipoles create their own electric fields which add to the incident field as reflected and/or transmitted fields. Your question is why the new fields are at the same frequency as the incident field.
The reason the new fields are at the same frequency as the driving field is because the new fields come from the oscillating dipoles which are oscillating at the frequency of the incident field. The question is then why the dipoles oscillate at the frequency of the incident field. The answer is that the definition of a linear dielectric is that the dipoles oscillate at the same frequency as the incident field.
So the short answer to your question is essentially that, by definition, when we consider linear dielectrics the assumption of linearity implies that the transmitted and reflected fields will be at the same frequency as the incident fields.
This of course raises the question of non-linear dielectrics or media. I make a comparison to a non-linear harmonic oscillator. If you drive an oscillator sinusoidally with small amplitude at frequency $\omega$ you will find that it responds sinusoidally frequency $\omega$. However, if you drive it very hard you will see it now starts to respond a little bit non-sinusoidally - higher harmonics are introduced into the motion. A Fourier decomposition of the resultant motion would reveal motion at $2 \omega$ and $3\omega$. We say the oscillator is exhibiting non-linearity. It is the same with the light field. For certain non-linear materials a light field at frequency $\omega$ can induce dipoles which oscillate slightly non-sinusoidally meaning higher harmonics are exhibited. As a result you can have a material where you send in red or infrared light and some green light is generated!
This is the field of nonlinear optics


text:
Q: What Glacier vault does S3 default to? Relating to (or following on from) the question: How does AWS transfer S3 objects to Glacier archives when you use lifecycle archive rules? - where it is explained that S3 is essentially just another multi-tennanted 'customer' of Glacier - does that mean I'm completely unable to configure notification events on the 'default' Glacier vault?
In S3, I'm unable to specify a vault to archive to, so are Glacier notifications only of purpose for bespoke apps that use the API's to handle their storage needs?
I'd really like to enable notifications on archive retrieval (and 'restored item expiry' if possible) - and I've already vaulted a huge stack of things via S3 - into 'the default vault of concealment'.
Is it a turd or am I just doing it wrong? (go on, be honest)?
(EDIT: sorry, forgot question mark)

A: It is concealed.
When archiving from Amazon S3 to Amazon Glacier, there is no ability to configure the back-end vault, nor its notifications. There is also no notification from S3 available to notify of restorations/deletions.


text:
Q: Removing random element from an array /Javascript I googled my question but found no answer, thank you in advance for help. The thing is, I have some code that works ok, but I would like to improve it:
function go(times) {
    function pick(n) {
        return n[Math.floor(Math.random() * n.length)];
    }

    var body = ["face", "nose", "hair", "smile"];
    var adj = ["amazing", "nice", "beautiful", "perfect"];
    var word = ["great", "innocent", "glowing", "adorable"];

    var str = "Your " + pick(body) + " looks " + pick(adj) + " and " + pick(word) + "!";
    if (times > 0) {
        for (i = 0; i < times; i++) {
            str = str + " And " + go().toLowerCase();
        }
    }

    return str;
}

When the random word is picked, it should be removed from an array so there won't be any repeation. I can handle it with splice function if I know exact index of element, but when it's random it doesn't work how I want it to.

A: You can easily add a function to all arrays to return a random value and/or remove one randomly.
// After this, you can call.getRandomValue() on any array!
Array.prototype.getRandomValue = function(removeItem) {
    if (this.length < 1) throw "Cannot get random value from zero-length array";
    var randomIndex = Math.floor(Math.random() * this.length);
    var randomValue = this[randomIndex];
    if (removeItem)
        this.splice(randomIndex, 1);
    return randomValue;
};

function constructDescription(sentenceCount) {
    var body = ["face", "nose", "hair", "smile"];
    var adj = ["amazing", "nice", "beautiful", "perfect"];
    var word = ["great", "innocent", "glowing", "adorable"];

    var description = "";

    for(var i = 0; i < sentenceCount; i++) {
      if (body.length > 0 && adj.length > 0 && word.length > 0) {
        description += (description.length > 0) ? " And your " : "Your ";
        description += body.getRandomValue(true) + " looks " + adj.getRandomValue(true) + " and " + word.getRandomValue(true) + "!"
      }
    }

    return description;
}

Try it out with a Fiddle here.

A: You just need to combine your splice and your randomizer. example:
function go(times) {

    var body = ["face", "nose", "hair", "smile"];
    var adj = ["amazing", "nice", "beautiful", "perfect"];
    var word = ["great", "innocent", "glowing", "adorable"];

    function pick(n) {
        return n.splice(Math.floor(Math.random() * n.length), 1);
    }

    var str = "";

    for (var i = 0; i < times; i++) {
        str += (i > 0 ? " And your ":"Your ") + pick(body) + " looks " + pick(adj) + " and " + pick(word) + "!";
    }

    return str;
}

A: Use a different function instead of calling go() recursively in the loop. By calling go() for each phrase you initialize the original arrays each time. Then do the splicing in pick()

function go(times) {
  var body = ["face", "nose", "hair", "smile"];
  var adj = ["amazing", "nice", "beautiful", "perfect"];
  var word = ["great", "innocent", "glowing", "adorable"];
  var str = ''

  function pick(n) {
    var idx = Math.floor(Math.random() * n.length);
    var str = n[idx];
    n.splice(idx, 1)
    return str;
  }

  function getPhrase(i) {
    var phrase =  pick(body) + " looks " + pick(adj) + " and " + pick(word) + "!";
    return i == 0 ? "Your " + phrase : " And your " + phrase;
  }

  for (var i = 0; i < times; i++) {
    str += getPhrase(i);
  }

  return str;
}

document.body.innerHTML = go(4);

A: @lucounu solution is absolutely spot on.
In case if you just wanted to improve upon your initial solution , you could have done the following :
    var body = ["face", "nose", "hair", "smile"];
    var adj = ["amazing", "nice", "beautiful", "perfect"];
    var word = ["great", "innocent", "glowing", "adorable"];

    function go(times) {

    function pick(n) {
        var index =  Math.floor(Math.random() * n.length)
        var randomString  = n[index];
        n.splice(index,1);
        return randomString;
    }

    var str = "Your " + pick(body) + " looks " + pick(adj) + " and " + pick(word) + "!";

    if (times > 0) {
        for (i = 0; i < times; i++) {
            str = str + " And " + go().toLowerCase();
        }
    }

    return str;
}

console.log(go(2));

A: Give it a try
var data = ["brain", "mitochondria", "microsope", "beaker", "beaker-2", "scientist", "cell", "atom"];

    while (data.length) {
        document.write(data.splice(data.length * Math.random() | 0, 1)[0] + '<br>');
    }


text:
Q: Пропадают русские имена файлов в отправляемом письме (SMTP) Код рабочий, отправляю им PDF файлы с mail.ru на yandex/gmail... Почему при отправке тех же файлов c mail.ru на mail.ru они приходят как "Untitled.bin"? Если изменить расширение в скачанных файлах, они читаются.
server = smtplib.SMTP_SSL('smtp.mail.ru', 465)
server.login(fromaddr, mypass)

def send_mail(toaddr, subjectText, bodyText, filesToAttach=[]):
    msg = MIMEMultipart()
    msg['From'] = fromaddr
    msg['To'] = toaddr
    msg['Subject'] = subjectText
    body = bodyText
    msg.attach(MIMEText(body, 'plain'))

    files=filesToAttach
    for f in files or []:
        with open(f, "rb") as fil:
            part = MIMEApplication(
                fil.read(),
                Name=basename(f)
            )

        part['Content-Disposition'] = 'attachment; filename="%s"' % basename(f)
        msg.attach(part)

    text = msg.as_string()
    server.sendmail(fromaddr, toaddr, text)

server.quit()

A: Заголовки в SMTP должны содержать только ASCII-символы. Так исторически сложилось: SMTP появился в те времена, когда ни Unicode, ни даже кодировок CP866 и CP1251 даже в проекте не было (какой уж там юникод — тогда даже проблемы с восьмибитными символами были).
Чтобы как-то поддержать юникод и прочие кодировки, начали изобретать разнообразные костыли, такие как RFC 2047 или RFC 2231, при которых имя файла (например, файл.txt) будет закодировано в Content-Disposition только ASCII-символами примерно так:
Content-Disposition: attachment; filename="=?UTF-8?B?0YTQsNC50LsudHh0?="

или так:
Content-Disposition: attachment; filename*=utf-8''%D1%84%D0%B0%D0%B9%D0%BB.txt

На наше счастье, в питоне уже встроена поддержка RFC 2231, просто нужно использовать MIMEApplication немножко по-другому:
from email.mime.application import MIMEApplication
# ...
part = MIMEApplication(b'hello', Name='файл.txt')
part.add_header('Content-Disposition', 'attachment', filename='файл.txt')
print(part)

Content-Type: application/octet-stream; Name*=utf-8''%D1%84%D0%B0%D0%B9%D0%BB.txt
MIME-Version: 1.0
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename*=utf-8''%D1%84%D0%B0%D0%B9%D0%BB.txt

aGVsbG8=


text:
Q: Give path as argument for mstsc.exe I want to create a remote desktop connection with C#. I found this question Run mstsc.exe with specified username and password.
At the moment I can create a new connection with username and password, but I want to change the path where the .rdp file will be saved.
Maybe you have an idea how I can change the save path.

A: Better that setting the default path, you can create the rdp file itself and save it in the default path.
the rdp file should contain the below content.
"full address:s:" + IP
"username:s:" + User
"domain:s:" + Domain
"password 51:b:" + Pass
"port:i:" + Port
"screen mode id:i:1"
"desktopwidth:i:800"
"desktopheight:i:600"
"session bpp:i:32"
"auto connect:i:1"
"autoreconnection enabled:i:1"
"compression:i:1"
"keyboardhook:i:2"
"audiomode:i:2"
"redirectdrives:i:1"
"redirectprinters:i:1"
"redirectcomports:i:0"
"redirectsmartcards:i:0"
"displayconnectionbar:i:1"
"alternate shell:s:"
"shell working directory:s:"
"disable wallpaper:i:1"
"disable full window drag:i:1"
"disable menu anims:i:1"
"disable themes:i:1"
"bitmapcachepersistenable:i:1";


text:
Q: Node.js multiple database server connection on SQL SERVER I need to use three database servers at the same time. Is there a way how to do it?
Here's the process I need to do.
Server1[SELECT] -> Server2[Insert] -> Server1[Update(Received)], Server3[Insert] -> Server2[Update(Received)]
Doing this process multiple times.
I getting an error

Cannot close a pool while it is connecting

A: If I understand correctly, you're trying to make three separate calls to three separate servers.
If I also understand correctly, what's happening is, you're making a call to the first server using your client, then as you try to talk to another server, your client says that it has closed the connection.
What you will need to do is have three separate clients, each having its own connection to the server, and using those separately.
The community could provide you with much better answers if you follow @KDani-99's suggestion and post a snippet of your code.


text:
Q: Check if URL available or not using AngularJS I have one URL like www.testsite.com/mypage.I need to check if URL is exist or not using AngularJS.
Is it possible. Any one please suggest.

A: You need to wrap this test by using a server-side api (or service) because embedding this kind of test in JavaScript is considered as cross-domain-query (could be considered as an attack).
For example, consider you have written a wrapper under /myRemoteSiteTester
then I would try whith somethings like that:
$http.get('/api/myRemoteSiteTester', {params: {target: myUrl}})
       .success(function(data) {
              alert(data);
        });


text:
Q: Mocking dependent modules using Jasmine I have a Javascript modular application not using Angular/Backbone.
I am trying to write test case for my startup module but facing issue.
Startup.js:
    window.claimStartup = function (options) {
    this.options = $.extend({}, this.options, options);
    this.cmds = new this.serviceModule(this);
    }

     getClaimsCategories: function (claimTypeCode) {
        var self = this;
        // Refresh claim categories
        return $.when(self.cmds.getClaimsCategories(claimTypeCode))
            .then(function (response) {
                return response;
            });
    },

Service.js:
    claimStartup.prototype.serviceModule = function (cfg) {
    this.cfg = cfg;
    this.init();
    }

StartUp.spec.js:
var claimStartUp;

beforeEach(function () {
spyOn(window.claimStartup.prototype, 'serviceModule');
  claimStartUp = new window.claimStartup();

});

it("should be able to get categories", function () {
jasmine.spyOn(claimStartUp.cmds, 'getClaimsCategories').andReturn('XYZ');
var categories=  claimStartup.getClaimsCategories('ABC');
expect(categories).toEqual('XYZ');
});

I am getting error when populating this.cmds it says serviceModule constructor not defined, actually I need to mock serviceModule when claimStartup is initialised.
Please let me know how can i write test case in this scenario.

A: I am able to fix this, this might be useful for others.
      var claimStartUp;

      beforeEach(function () {
      var spyService = jasmine.createSpy('serviceModule');
      var methodService = window.claimStartup.prototype.serviceModule;
      window.claimStartup.prototype.serviceModule = spyService;

      var spyUI = jasmine.createSpy('uiModule');
      var methodUI = window.claimStartup.prototype.uiModule;
      window.claimStartup.prototype.uiModule = spyUI;

      claimStartUp = new window.claimStartup();

  });


text:
Q: Stop Nokogiri from removing new lines I'm trying to strip out all html from a string so I can perform some regexes on it. I discovered you can use Nokogiri to get the text by using xpath like so:
Nokogiri::HTML(my_string).xpath("//text()").text

This works quite well, but I have found that it removes some new line characters almost randomly, which ends up breaking my regular expressions. The html it receives is always valid (although often not well formed - it was made using a wysiwyg editor) so that shouldn't be an issue.
Is there a reason that Nokogiri would remove the new lines and is there a way to avoid it? This is for a command line script, so I don't have rails or anything else.
here's a sample of the text where it's not preserving newlines:

Composition: 83% Polyester Bright, 17% Spandex

 Washing: Cold hand wash only

 Designer: James Lillis

 Made in: Australia

If it matters, I am reading the html in from a JSON file using Oj. This is how it appears in the JSON file:
"\u003Cp\u003EComposition: \u003Cspan\u003E83% Polyester Bright, 17% Spandex \u0026nbsp; \u0026nbsp;\u003C/span\u003E\u0026nbsp;\u003Cspan\u003E\u003Cbr /\u003E\n \u003C/span\u003EWashing: Cold hand wash only\u003Cspan\u003E\u003Cbr /\u003E\n \u003C/span\u003EDesigner: James Lillis\u0026nbsp;\u003Cspan\u003E\u003Cbr /\u003E\n \u003C/span\u003EMade in: Australia\u0026nbsp;\u003C/p\u003E\n"

And this is how it ends up when i put it through the above nokogiri function call:
Composition: 83% Polyester Bright, 17% Spandex     Washing: Cold hand wash onlyDesigner: James Lillis Made in: Australia

Thanks for any help
UPDATE: I've discovered that it appears to remove the newlines when the \n character is in a span element (which for some reason, the editor did a lot). If there is a way to stop this from happening, I'd like to know, otherwise I'll probably try to detect it beforehand.


text:
Q: Winforms listview programatically cancel item edit I have a listview control in a winforms app (yes, there is still development done in winforms). The listview is set up so the user can click on the first column and start editing.
I also have a button that does other things, and then updates the listview consequence of other actions.
How can I tell the list view to cancel the editor? I need to do this so a bug does not creep up were I end up with a repeated item

A: As soon as I post it I though of the solution, so if anybody needs it:
listViewControl.Focus( );
SendKeys.Send( "{ESC}" );