text:
Q: How to reload previously loaded classes that changed during runtime? I'm writing an application that needs to reload a previously loaded class during runtime. The reason is that the class is auto-generated during runtime, and the new implementation changes the way the app works. I generate only one object of the said class, and I stripped it from all dependencies but an interface that defines constant values. There's no problem reseting the values of any or all of the members when reloading. I know exactly when it changes and I can control it. The only problem I have is the reload itself.
From what I read, I should use a ClassLoader. I tried to do so, but I can't make it work.
I tried the following:

*

*Getting the current ClassLoader (myClassObject.getClass().getClassLoader()) and using it to reload the class - Doesn't work. It probably keeps loading the old implementation.

*Generating my own (AKA copy-paste from SO with modifications) - Doesn't work because the ClassLoader I generate is different than the one that generated the class (Exception: myClass cannot be casted to myClass).

*Creating a constructor that sets the ClassLoader of the superclass doesn't seem to have any effect.

*Using my new ClassLoader to generate the class that has myClassObject as a member solved the ClassLoader mismatch for myClassObject, but created a new mismatch one level up. I used getClassLoader() everytime and I see they don't match.

*I tried adding -Djava.system.class.loader=com.test.Reoader com.test.myMainClass to make it my default reloader, but I get an error from the compiler.

*Google keeps pointing me back to the same stuff I read already.

*EDIT: I tried creating an interface and reload the class implementing it. That didn't solve it either.

I know I should override the default ClassLoader, but nothing I do seems to succeed at that.
My ClassLoader:
public class Reloader extends ClassLoader {

    public Reloader(){
        super(Reloader.class.getClassLoader());
    }

    @Override
    public Class<?> loadClass(String s) {
        return findClass(s);
    }

    @Override
    public Class<?> findClass(String s) {
        try {
            byte[] bytes = loadClassData(s);
            return defineClass(s, bytes, 0, bytes.length);
        } catch (IOException ioe) {
            try {
                return super.loadClass(s);
            } catch (ClassNotFoundException ignore) {}
            ioe.printStackTrace(java.lang.System.out);
            return null;
        }
    }

    private byte[] loadClassData(String className) throws IOException {
        File f = new File("out\\production\\ManoCPU\\" + className.replaceAll("\\.", "/") + ".class");
        int size = (int) f.length();
        byte buff[] = new byte[size];
        FileInputStream fis = new FileInputStream(f);
        DataInputStream dis = new DataInputStream(fis);
        dis.readFully(buff);
        dis.close();
        return buff;
    }
}

Thanks very much to anyone that can help.

A: You can only load a class once (per instance of a classloader). That means you have to throw away the classloader you have loaded your class with and instantiate a new one for your updated version of the class.
When dealing with multiple class loaders also have in mind that if you load the same class with several classloaders they are NOT recognized as being the same class.


text:
Q: Recovering GRUB after installing Windows 7?
Possible Duplicate:
How can I repair GRUB? (How to get Ubuntu back after installing Windows?)

I installed Windows 7 after it crashed, and now I am unable to boot Ubuntu. Ubuntu partitions are still there. I tried using Boot-Repair, but it didn't work!

A: You can re-install grub in the Master Boot Record using the LiveCD for you distribution version,
It goes like this:

*

*Boot from LiveCD ⋯ please try to use a LiveCD that has the same version of Grub2 as the installed version

*Mount the root of the installed Ubuntu at /mnt

*Change root

*Update grub

*Install grub

*Reboot
The above steps are from near the bottom of the Ubuntu Community Documentation of Grub2
After booting from the liveCD ( select "Try Ubuntu" on the opening screen)
Then start up a terminal (dash, type-in terminal, … )…

*

*It may be easier to open this web page while running LiveCD.  Firefox should allow you  to do this.

Type in the terminal sudo fdisk -l - and enter your password if asked.  That's a lower case L. Find the installed Ubuntu partitions, (from mine with other disks snipped ― here):
me@mycomputer:~$sudo fdisk -l
...
Disk /dev/sde: 300.1 GB, 300089646592 bytes
255 heads, 63 sectors/track, 36483 cylinders, total 586112591 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0xc3f5ebeb

Device    Boot      Start         End      Blocks   Id  System
/dev/sde2       138464296   586110975   223823340    5  Extended
/dev/sde3   *        2048   138463231    69230592   83  Linux
/dev/sde5       138464298   313460279    87497991    7  HPFS/NTFS/exFAT
/dev/sde6       313460736   317650943     2095104   82  Linux swap / Solaris
/dev/sde7       317652992   581922815   132134912   83  Linux
/dev/sde8       581924864   586110975     2093056   82  Linux swap / Solaris

Partition table entries are not in disk order

Find your Linux installation (Id=83, System=Linux0 then type in
sudo mount /dev/sde3 /mnt

but use your partition instead of /dev/sde3(my root partition is sde3, sde7 is my home partition).
This is assuming that you do not have a separate /boot partition.  If you do, you will need to also mount it by typing
sudo mount /dev/sd·· /mnt/boot

where sd·· is the partition where you installed the separate boot directory.
ls /mnt - just checking to see if I got it right:
me@mycomputer:~$ sudo mount /dev/sde3 /mnt
me@mycomputer:~$ ls /mnt
bin   cdrom  etc   initrd.img      lib         media  opt   root  sbin     srv  tmp  var      vmlinuz.old
boot  dev    home  initrd.img.old  lost+found  mnt    proc  run   selinux  sys  usr  vmlinuz

You should test to see if the boot directory is properly installed.  Type in ls /mnt/boot and if it is empty, the boot directory is not installed.  It should look something like this:
me@mycomputer:~$ ls /boot
abi-2.6.35-30-generic     initrd.img-2.6.35-30-generic  System.map-2.6.35-31-generic
abi-2.6.35-31-generic     initrd.img-2.6.35-31-generic  vmcoreinfo-2.6.35-30-generic
config-2.6.35-30-generic  memtest86+.bin                vmcoreinfo-2.6.35-31-generic
config-2.6.35-31-generic  memtest86+_multiboot.bin      vmlinuz-2.6.35-30-generic
grub                      System.map-2.6.35-30-generic  vmlinuz-2.6.35-31-generic

Then:
for i in /dev /dev/pts /proc /sys; do sudo mount -B $i /mnt$i; done
sudo chroot /mnt #change the root
sudo update-grub # now update grub

Example:
me@mycomputer:~$ sudo for i in /dev /dev/pts /proc /sys; do sudo mount -B $i /mnt$i; done
me@mycomputer:~$ sudo chroot /mnt
me@mycomputer:~$ sudo update-grub
Generating grub.cfg ...
Found linux image: /boot/vmlinuz-3.0.0-13-generic
Found initrd image: /boot/initrd.img-3.0.0-13-generic
Found linux image: /boot/vmlinuz-3.0.0-12-generic
Found initrd image: /boot/initrd.img-3.0.0-12-generic
Found memtest86+ image: /boot/memtest86+.bin
Found Microsoft Windows XP Professional on /dev/sdc1
done

Now to re-install grub in the MBR.  You will need to know which disk your system boots from, and find it in the fdisk -l listing you have already done.  Then type in sudo grub-install /dev/sd replacing sd· with the disk you will boot from.
me@mycomputer:~$ sudo grub-install /dev/sd·

Then type in Crtl-D to exit chroot.
Then type in sudo for i in /sys /proc /dev/pts /dev; do sudo umount /mnt$i; done - as one line
me@mycomputer:~$ sudo for i in /sys /proc /dev/pts /dev; do sudo umount /mnt$i; done

If you mounted a separate /boot partition, type in sudo umount /mnt/boot
me@mycomputer:~$ sudo umount /mnt/boot

Then type in sudo umount /mnt
me@mycomputer:~$ sudo umount /mnt

Then type in sudo reboot to restart he system (remember to remove the LiveCD).
me@mycomputer:~$ sudo reboot

Hopefully, grub will be installed.

A: Try this...
To recover grub:

*

*Open the live version.

*Open the terminal and run sudo fdisk -l to see where Linux is installed.

*Run sudo mount /dev/sdaX /mnt where x is the number you have found Linux word in

*Run sudo grub-install --root-directory=/mnt /dev/sda to install grub.

*Run sudo update-grub to update grub and if this command didn't work run it after rebooting.

*Reboot.

A: Boot-Repair is a simple tool to repair frequent boot issues you may encounter in Ubuntu like when you can't boot Ubuntu after installing Windows or another Linux distribution, or when you can't boot Windows after installing Ubuntu, or when GRUB is not displayed anymore, some upgrade breaks GRUB, etc.

Remark: this can also be performed from a live-CD or live-USB.
Either add 'ppa:yannubuntu/boot-repair' to your Software Sources via the Software Centre or, for speeds-sake, add it using a new Terminal session:
sudo add-apt-repository ppa:yannubuntu/boot-repair && sudo apt-get update
sudo apt-get install -y boot-repair && boot-repair

Boot-Repair can be installed & used from any Ubuntu session (normal session, or live-CD, or live-USB). PPA packages are available for Ubuntu 10.04, 10.10, 11.04, 11.10, 12.04 and 12.10.
source

A: Boot-Repair works:

*

*I had Windows XP and Ubuntu on my PC.

*I installed Windows 7 which resulted in new boot loader without Ubuntu.

*I installed Boot-Repair with the startup disc and GRUB was updated along with Windows 7 and Windows XP.

A: After installing Windows 7, Windows bootloader has overridden the MBR.
To fix this you can install a program 'EasyBCD' in Windows
Follow these steps to restore GRUB when after installing EasyBCD:

*

*Launch the program and select ADD NEW ENTRY from the EasyBCD Toolbox

*Select the 'Linux/BSD' from the operating systems column

*Choose GRUB (Legacy) under type and Click on the ADD ENTRY icon

*Choose YES to the restart prompt

*GRUB will be displayed after the restart which will detect the Ubuntu partition for you to be able to boot into Ubuntu
GOOD LUCK
Download link: http://neosmart.net/download.php?id=1

A: One nuance to be careful about - the instructions say to check if you have a separate boot partition, and if so then do sudo mount /dev/sd·· /mnt/boot. I got confused here - I did have a boot partition that was not my Linux, it was my base partition (/sda0). So I did that command, and ended up getting a grub menu that only showed my Windows boot. I re-ran the procedure without the doing the sudo mount /dev/sd·· /mnt/boot and it worked beautifully - my old GRUB menu was back, with all the Linux options as well as Windows. The instructions are only referring to a separate Linux boot partition, not for the case where your boot partition is not Linux.

redpajama_set_name: RedPajamaStackExchange


text:
Q: .htaccess simple redirection and too many rediercections: how to solve that? my site (domain.com) is now located into /var/www/
and you can also access it directly through its IP: 88.88.88.88
I would like to obtain:
when user enter the IP : 88.88.88.88, it redirects to 88.88.88.88/reboot/
if user enters the full domain name, it shows the site as it does now.
I tried with .htaccess
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} 88.88.88.88
RewriteRule .* http://88.88.88.88/reboot/ [R=301,L]
RewriteCond %{HTTP_HOST} ^mysite.com
RewriteRule .* http://www.mysite.com [R=301,L]

does not work good:
www.mysite.com :GOOD
mysite.com: GOOD
88.88.88.88 ->redirects to 88.88.88.88/reboot : GOOD
but then it generates an error: Error 310 (net::ERR_TOO_MANY_REDIRECTS)
Any clue ?

A: When you're on 88.88.88.88/reboot, your HTTP_HOST is still equal to 88.88.88.88.
Try adding a RewriteCond rule depending on the REQUEST_URI, which will redirect everything that is not /reboot to /reboot :
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} 88.88.88.88
RewriteCond %{REQUEST_URI} !^/reboot/
RewriteRule ^(.*)$ http://88.88.88.88/reboot/$1 [R=301,L]
RewriteCond %{HTTP_HOST} ^mysite.com
RewriteRule .* http://www.mysite.com [R=301,L]

A: The ERR_TOO_MANY_REDIRECTS comes because your rule loops.
Whenever a request comes to host 88.88.88.88 , you redirect it to 88.88.88.88/reboot/ , but /reboot/ uri is also on that host, so it redirects again and loops.
If you only want to redirect / to /reboot/ on host 88.88.88.88 , you need to alter your RewriteRule to this:
RewriteCond %{HTTP_HOST} 88.88.88.88
RewriteRule ^/$ http://88.88.88.88/reboot/ [R=301,L]

If, however, you wish to redirect everything outside of /reboot/ , then you need to add a condition (RewriteCond):
RewriteCond %{HTTP_HOST} 88.88.88.88
RewriteCond %{REQUEST_URI} !^/reboot/
RewriteRule ^/$ http://88.88.88.88/reboot/ [R=301,L]

(keep the rest of the rules intact).


text:
Q: Why do I get a recursion call runtime error? I expected the code below to print the sequence 0 1 2 3.
Instead I got a recursion call runtime error (causing a stack overflow).
Can you explain why ?
#include <bits/stdc++.h>

using namespace std;

#define ll long long
void print(int n)
{
    if (n < 0)
        return;
    if (n == 0)
    {
        cout << n << " ";
        return;
    }
    print(n--);
    cout << n << " ";
}
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int num = 3;
    print(num);
    return 0;
}

A: Look at this:
print(n--);

Here, the recursive call is made with the same value of n as it was called with. The decrement isn't performed until after the recursive call returns. The recursion is therefore theoretically infinite.
Rather, I don't believe you need to increment or decrement n at all. Just use n-1:
print(n-1);


text:
Q: pip install PyAudio I am trying to install some packages in Python and when I try to run the command
pip install PyAudio
this error show up:
Collecting PyAudio
Using cached PyAudio-0.2.11.tar.gz (37 kB)
Preparing metadata (setup.py) ... done
Using legacy 'setup.py install' for PyAudio, since package 'wheel' is not installed.
Installing collected packages: PyAudio
Running setup.py install for PyAudio ... error
error: subprocess-exited-with-error
× Running setup.py install for PyAudio did not run successfully.
│ exit code: 1
╰─> [17 lines of output]
running install
c:\users\user\pycharmprojects\romanticalexa\venv\lib\site-packages\setuptools\command\install.py:37: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip
and other standards-based tools.
setuptools.SetuptoolsDeprecationWarning,
running build
running build_py
creating build
creating build\lib.win-amd64-3.7
copying src\pyaudio.py -> build\lib.win-amd64-3.7
running build_ext
building '_portaudio' extension
creating build\temp.win-amd64-3.7
creating build\temp.win-amd64-3.7\Release
creating build\temp.win-amd64-3.7\Release\src
"C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.31.31103\bin\HostX86\x64\cl.exe" /c /nologo /O2 /W3 /GL /DNDEBUG /MD -DMS_WIN64=1 -Ic:\users\user\pycharmpr
ojects\romanticalexa\venv\include "-IC:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.2544.0_x64__qbz5n2kfra8p0\include" "-IC:\Program Files\WindowsApps\PythonSoftware
Foundation.Python.3.7_3.7.2544.0_x64__qbz5n2kfra8p0\Include" "-IC:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.31.31103\include" "-IC:\Program Files (x86)\Window
s Kits\NETFXSDK\4.8\include\um" /Tcsrc/_portaudiomodule.c /Fobuild\temp.win-amd64-3.7\Release\src/_portaudiomodule.obj
_portaudiomodule.c
src/_portaudiomodule.c(27): fatal error C1083: Cannot open include file: 'stdio.h': No such file or directory
error: command 'C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.31.31103\bin\HostX86\x64\cl.exe' failed with exit code 2
[end of output]
note: This error originates from a subprocess, and is likely not a problem with pip.
error: legacy-install-failure
× Encountered error while trying to install package.
╰─> PyAudio
note: This is an issue with the package mentioned above, not pip.
hint: See above for output from the failure.


text:
Q: How to test RXJS utils like pipe,skip,tap,retry etc.. inside any angular app with Jasmine I am trying to test my components inside an angular app using Jasmine.
I am unable to mock certain utils like a pipe, skip, switch map, etc from RXJS.
this.route.queryParams.pipe(skip(1)).subscribe(params => comsole.log(params);
Can someone help me suggest a way to test this piece out?
Thanks in advance.

A: I think you are little bit on a wrong track. Let's bring you on the right way.
First of all you need to test observables like a blackbox. You don't need to know what happens in there. You only want to know what goes in and what goes out. You can test that perfectly with jasmine marble. This link might help you here:
https://medium.com/@bencabanes/marble-testing-observable-introduction-1f5ad39231c
By this blackbox principle you can test the effect of certain operators on your stream. You don't want to mock them. skip(1) for example can be testet by an in-Observable like of(1, 2) and expect an out-Observable of(2).
What you could mock and e.g. expect toHaveBeenCalled are external ressources called within those operators, which is most likely to happen within the switchMap.


text:
Q: Apache Commons : List Handling in CompositeConfiguration I have two configuration files :
override.xml looks like this ...
<paths>
 <path>1</path>
 <path>2</path>
 <path>3</path>
</paths>
<numbers>
 <number>100</number>
 <number>200</number>
</numbers>

default.xml looks like this ...
<paths>
 <path>4</path>
 <path>5</path>
 <path>6</path>
</paths>
<alphabets>
 <alphabet>A</alphabet>
 <alphabet>B</alphabet>
</alphabets>

I'm using a CompositeConfiguration. Adding override.xml first and then default.xml.
When I do a getList("paths.path") on the CompositeConfiguration, I get back 1,2,3,4,5,6.

This tells me I'm getting back values from both override.xml and default.xml.
Is there any way to get back values only from override.xml only since it overrides the default.xml values ?
At the same time if I were to do a getList("numbers.number"), I would expect 100,200 to be returned. A getList("alphabets.alphabet") to return A,B.

A: Combining the contents of the list is the default behavior of getList of CompositeConfiguration. What you need to use is a CombinedConfiguration with appropriate NodeCombiner. For your use case, OverrideCombiner is appropriate.
Sample code :
XMLConfiguration x1 = new XMLConfiguration();
....
XMLConfiguration x2 = new XMLConfiguration();
....
CombinedConfiguration config = new CombinedConfiguration(new OverrideCombiner());
config.addConfiguration(x1);
config.addConfiguration(x2);

Here the list defined in configuration x1 is returned when you do a config.getList("numbers.number")


text:
Q: Execution of the expression failed. (org.mule.api.expression.ExpressionRuntimeException). Message payload is of type: String I am trying to create a simple mule application that reads the name and content of a file on the disk and displays it on the web browser.
My flow is as follows HTTP -> JAVA TRANSFORMER - SETPAYLOAD - HTTP
My Java transformer code includes the following
public class ReadFile extends AbstractMessageTransformer {

    /**
     * loads the content of the file specified in the parameter
     *
     * @param filename
     *            the name of the file
     * @return the content of the file
     */
    public String readFile(String filename) {
        File file;
        file = new File("O:\\test.txt");
        StringBuilder builder = new StringBuilder();
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            String line = null;
            while ((line = reader.readLine()) != null)
                builder.append(line);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            closeQuietly(reader);
        }
        return builder.toString();
    }

    public String getFileName(MuleMessage message) {

        Path p = Paths.get("O:\\Test.txt");
        String file = p.getFileName().toString();
        return file;

    }

    public String setPayload(MuleMessage message, String outputEncoding) {

        String payload1 = "#[ReadFile]";
        return payload1;

    }

    private void closeQuietly(Closeable c) {
        if (c != null) {
            try {
                c.close();
            } catch (IOException ignored) {
            }
        }
    }

    @Override
    public Object transformMessage(MuleMessage message, String outputEncoding)
            throws TransformerException {
        String filename = getFileName(message);
        String content = readFile(filename);
        setPayload(message, content);
        return message;
    }

}

I am getting the error Execution of the expression ReadFile failed. (org.mule.api.expression.ExpressionRuntimeException). Message payload is of type: String
and have no idea why?

A: Your doing small mistake in your method setPayload. there your not adding file content to MuleMessage. Do like below it will work
public String setPayload(MuleMessage message, String outputEncoding) {

    message.setPayload(outputEncoding);
    //String payload1 = "#[ReadFile]";
    return null;

}

and my flow looks like below (Where I have implemented onCallable method)
 <flow name="filetestFlow1">
    <http:listener config-ref="HTTP_Listener_Configuration" path="/" doc:name="HTTP"/>
    <logger message="--- Service triggred --" level="INFO" doc:name="Logger"/>
    <component class="filetest.ReadFile" doc:name="Java"/>
</flow>


text:
Q: 10W LED, no need for constant current? I've got few of these LEDs which are in a 3S3P configuration and rated 9-12V 900-1050mA.
I tried to power one of these with this module which I earlier set at 12V and 1A with a multimeter in short circuit.
The problem is that when I connect the LED in series with the multimeter, the latter tells me that is drawing less than 400mA.
So, out of curiosity and willing to fry one LED, I connected it directly to a power supply (a laptop brick, 12V 3A) and the LED doesn't draw more than 600mA.
More LEDs in parallel gives me these values:

*

*2 LEDs: 1200mA

*3 LEDs: 1600mA

I'd like to push the rated current through the LEDs (so to take them to full brightness), also is weird that seems like they're current-limiting themselves without the need of a constant-current circuit.
Does anyone have any explanation/experience with this behaviour?
Thanks

A: You have not mentioned the color of the LEDs. The typical white LEDs that make up modules like yours would take more than 3V to reach maximum rated power. I would say around 3.5V could be a common number.
For a 3.5V white LED, probably around 20% of the voltage drop is due to ESR. A LED (of the same base color) requiring lower voltage and therefore has a corresponding lower ESR would be more efficient.
So there is an unavoidable resistor in series with every LEDs already. If you use the number 12V, 0.6A, 20% ESR then the ESR = 12 * 20% / 0.6A = 4 ohms. These are guesses and may not reflect what you have. But say if these guesses are exactly right, then you would get 1A at 13.6V.
(The simple ESR model breaks down badly at low current).

Rereading what I wrote, I was assuming 4 x 3V. But there are only 3 LEDs in series, so the numbers do not add up.

A:
rated 9-12V 900-1050mA

That's a clue that your LED arrays have built in current limiting and are designed to be powered by a voltage, not current.
But if they are rated for 1050mA, why do they only draw 600mA or less? Ask your vendor. Perhaps the 1050mA is for a higher voltage (eg. 14V), or perhaps you were sold sub-standard parts, or the specs are just plain wrong. If you bought them from a website such as eBay or Amazon then just be happy that they work at all!

A: What you may be missing is that you are not really connecting the LEDs directly to the power supply- the ammeter acts as a resistor - the more current the more voltage drop.
A constant current circuit- or a substantial series resistance and the associated wasted power is highly recommended if you want to run the LEDs at near maximum current.


text:
Q: Mongo bi shut down when sampling MongoDB for schema,How to debug and find the reason? the mongosqld.log show me that mongobi is shutting down

2021-10-15T10:04:11.538+0800 I NETWORK    [initandlisten] waiting for
connections at [::]:3307 2021-10-15T10:04:11.538+0800 I NETWORK
[initandlisten] waiting for connections at /tmp/mysql.sock
2021-10-15T10:04:11.547+0800 I SCHEMA     [sampler] sampling MongoDB
for schema... 2021-10-15T10:04:17.949+0800 I CONTROL
[signalProcessingThread] shutting down
But I coundnt find why,what should i do to find the reason?

A: The clue there is signalProcessingThread - something sent the process a signal like SIGTERM.


text:
Q: name for a function that transforms assignment statements to expressions update
Since one effect of these functions is to provide a way to use method chaining on methods that would not normally support it *, I'm considering calling them chain and copychain, respectively.  This seems less than ideal though, since the would-be copychain is arguably a more fundamental concept, at least in terms of functional programming.

original
I'm calling it a boxer for now.  The code is in Python, though the question is general:
def boxer(f):
    """Return a function g(o, *args, **keyargs) -> o

    `g` calls `f` on `o` with the remaining arguments
        and returns `o`.

    >>> l = [2]
    >>> def increment_list_element(l, i):
    ...     l[0] += i
    >>> adder = boxer(increment_list_element)
    >>> adder(l, 2)
    [4]
    >>> def multiply_list_element(l, i):
    ...     l[0] *= i
    >>> multiplier = boxer(multiply_list_element)
    >>> sum(multiplier(l, 6))
    24
    """
    def box(o, *args, **keyargs):
        f(o, *args, **keyargs)
        return o
    return box

A similar concept copies the would-be assignee, and assigns to and returns the copy.  This one is a "shadow_boxer":
from copy import deepcopy

def shadow_boxer(f):
    """Return a function g(o, *args, **keyargs) -> p

    `g` deepcopies `o` as `p`,
        executes `f` on `p` with the remaining arguments,
        and returns `p`.

    >>> l = [2]
    >>> def increment_list_element(l, i):
    ...     l[0] += i
    >>> adder = shadow_boxer(increment_list_element)
    >>> adder(l, 2)
    [4]
    >>> def multiply_list_element(l, i):
    ...     l[0] *= i
    >>> multiplier = shadow_boxer(multiply_list_element)
    >>> sum(multiplier(l, 6))
    12
    """
    def shadow_box(o, *args, **keyargs):
        p = deepcopy(o)
        f(p, *args, **keyargs)
        return p
    return shadow_box

In addition, I'd like to find out about resources for learning more about these sorts of things — though I'm similarly unsure of a name for "these sorts of things".  It does seem related to functional programming, although as I understand it, these technique would be unnecessary in a true functional language.

A: This is pretty much the same thing as Ruby's Object#tap. Don't know how you feel about the name, but that's what they call it.

A: What the boxer function returns is probably defined closure in some programming languages. If there is not already a function with this name, I would call the function closure.


text:
Q: SQL - Select preferred version I have a speed table with a version field. Here is a partial sample :
     id    milepost  speed version

     1           0     40       1
     2           0     30       2
     3           5     50       1

Basically, I want to do a query with a "preferred version" : try to fetch rows (mileposts) with the specified speed version, and if a certain milepost is not found with that version, take version 1 by default.
So, for example, if my preferred speed version was 2, my result would contain speeds from rows 2 and 3 :
   milepost  speed

          0     30
          5     50

But how can I build a single SELECT to do that ?
Thank you, and have a nice stack overday.
EDIT :
Both of your answers have inspired me to find a solution. The following is not the complete query, but it gives an idea :
select s1.milepost_from milepost, s1.value speed from speeds s1
where s1.version = 2 or (s1.version = 1 and not exists
(select 1 from speeds s2 where s2.milepost_from = s1.milepost_from and s2.version = 2))

The key is to do a subselect that matches the main select's permanent info (milepost_from in the example).
Thank you !

A: One method uses union all:
select t.*
from t
where version = @preferred_version
union all
select t.*
from t
where version = 1 and
      not exists (select 1 from t t2 where t2.version = @preferred_version and t2.id = t.id);

A: You could use a left joins and coalesce
SELECT IDLIST.ID AS ID, COALESCE(T1.SPEED, T2.SPEED, <final default value>) AS SPEED
FROM (SELECT DISTINCT ID FROM TABLE) AS IDLIST
LEFT JOIN TABLE T1 ON IDLIST.ID = T1.ID AND T2.VERSION = <ver you look for>
LEFT JOIN TABLE T2 ON IDLIST.ID = T2.ID AND T2.VERSION = <default marker>

As you can see this lets you have multiple "defaults" so it is more general.


text:
Q: android to draw vertical line using style tag inside CDATA in string file To draw vertical line to left of text.
My string file looks like this
    < string name="first2">
     < ![CDATA[
      < div style="border-left:3px solid #8080ff;height:15px;float:left"/>< font color="#8080ff"> public< /font>
    ]]>
    < /string>
and my java file uses this string like this
    Spanned sp=Html.fromHtml(getString(R.string.first2));
    TextView tv2=(TextView)findViewById(R.id.textView7);
    tv2.setText(sp);
But I dint get that vertical line

A: Salaam, you can just use these tags in cdata:

b, strong   :Bold
i, em, cite, dfn    :Italics
u   :Underline
sub     :Subtext
sup     :Supertext
big     :Big
small   :Small
tt  :Monospace
h1 … h6     :Headlines
img     :Image
font    :Font face and color
blockquote  :For longer quotes
a   :Link
div, p :    Paragraph
br  :Linefeed

 use a webView instead of TextView!


text:
Q: How I can avoid the hole in the plot forecast with series plot R I write this question because I can't link (I tried for many times), in the plot, the series with the forcast.
Here the code that I used.
AA1<-AA_1
str(AA1)#OUTPUT: Time-Series [1:60] from 2013 to 2018: 309 368 1602 6742 19396

Serie1<-Serie_1
str(Serie1) ##OUTPUT:Classes 'tbl_df', 'tbl' and 'data.frame':  60 obs. of  7 variables:

X_Reg_Mod_Completo <- cbind(A=ts(Serie1$A),B=ts(Serie1$B),
                     C=ts(Serie1$C), D=ts(Serie1$D),
                     E=ts(Google1$E), F=ts(Serie1$F))

Mod_Completo<-auto.arima(AA1, xreg=X_Reg_Mod_Completo, trace = TRUE, test = "kpss", ic="aic", seasonal = TRUE)
AIC(Mod_Completo)
FOR_Mod_Completo<-forecast(Mod_Completo,xreg=X_Reg_Mod_Completo)
plot(FOR_Mod_Completo,xlim=c(2016, 2019))

My goal is to avoid the hole between the end of 2018 and gennary 2018.
If somebody need the data, please, write a comment and I will update.
Thank you in advance for your help.
Francesco

A: I've tried something with ggplot2 without messing up too much with the forecast, maybe it could help as a start:
library(forecast)
library(tidyverse)
fit <- auto.arima(WWWusage)
forec <- forecast(fit,h = 10)

Now, we have to put the ts and the forecast in data.frames, bind them, and plot the result with ggplot2:
# time series
ts_ <- data.frame(Point.Forecast = WWWusage,
                  Lo.80=NA,
                  Hi.80=NA,
                  Lo.95=NA,
                  Hi.95=NA,
                  type = 'ts')

# forecasting
forec <- data.frame(forec, type ='fc')

# together
tot <- union_all(ts_,forec)

# now add the date, in this case I put a sequence: len
tot$time <- seq( as.Date("2011-07-01"), by=1, len=nrow(ts_)+nrow(forec))

Now you can plot it:
  ggplot(tot) + geom_line(aes(time,Point.Forecast))+
                geom_line(aes(time, Lo.95))+
                geom_line(aes(time, Hi.95))+
                geom_line(aes(time, Lo.80))+
                geom_line(aes(time, Hi.80))+
                geom_vline(xintercept=tot$time[nrow(ts_)], color = 'red') + theme_light()


text:
Q: How to do these matrix operations in GLSL? In this language
https://en.wikibooks.org/wiki/GLSL_Programming/Vector_and_Matrix_Operations
How can I do operations like this:

Does anyone know? The page seems to talk about fixed width like 2x2, 3x3, 4x4, but mine can be much more in dimensions for width.

A: If i understood your question right you want to know how to multiplicate matrecies and vectors in glsl.
It's realy easy for example
mat4 a;
mat4 b;
vec4 c;
vec4 d = a * b * c;

or
mat4 a;
mat4 b;
mat4 c = a * b;

but keep in mind that matrecies are not commonicative so the order you multiplicate them are important.


text:
Q: Scala Error Import I'm learning Scala, and I was attempting to import from 2 scrips in different classes, but, I get an error, and I don't know why.
This class, in Summer.scala, is where I try to import the singleton object from class  ChecksumAccumulator.
import ChecksumAccumulator.calculate

object Summer{
  def main(args: Array[String]): Unit= {
    for (arg <- args)
      println(arg + " : " +  calculate(arg))
  }
}

Class ChecksumAccumulator, with the singleton object ChecksumAccumulator.
object ChecksumAccumulator {

/*
 When a singleton object shares the same name
 with a class, it is called that class's companion object.
*/

  private val cache = mutable.Map.empty[String, Int]

  def calculate(s: String): Int =
    if (cache.contains(s))
      cache(s)
    else {
      val acc = new ChecksumAccumulator

      //The object with the same name of the class can acces to the private members.
      //println(acc.sum)
      for (c <- s)
        acc.add(c.toByte)
      val cs = acc.checksum()
      cache += (s -> cs)
      cs
    }
    def showMap() : Unit = {
      for(base:String <- cache.keys)
        println(cache(base))
    }
//def showMap(): String = { var cadena = cache("Every value is an object.") +  " "+ cache("Every value is an object. per second time!!");  cadena  }
}

This script throw this mistake

scala Summer.scala
Summer.scala:8: error: not found: object ChecksumAccumulator import
  ChecksumAccumulator.calculate ^ Summer.scala:14: error: not found:
  value calculate println(arg + " : " + calculate(arg)) ^ two errors
  found

A: It seems like it's a duplicated question, but I can't yet mark questions as duplicated nor comment on them.
If that is all your code, it means you're missing:
class ChecksumAccumulator { ... }

Because you're trying to create an instance of this class:
val acc = new ChecksumAccumulator

And it's impossible to achieve with just:
object ChecksumAccumulator { ... }

Check out this answer about exactly the same code example. There is the missing definition of  class ChecksumAccumulator :
https://stackoverflow.com/a/8681616/5100014
Just make sure to paste it into the same file with object ChecksumAccumulator


text:
Q: How to pull the data partially from firebase database I wanna pull whole data from the firebase database and access that without change data.
firebase.database().ref('someBigNode').once('value', (snapshot) => {
    //do something
}

But it will cost many memory.
May I ask how to pull whole data partially and save memory?

A: When you read data from Firebase Database with the JavaScript (or iOS or Android) SDK, it will always read complete nodes. So the only way to retrieve less data is to retrieve a node lower in the JSON tree.
If you find you need to retrieve a part of each node under someBigNode, you should split that part of each node out into a top-level node of their own importantBitsOfSomeBigNode.
It's unfortunately hard to be more helpful without a more concrete example of your data structure and the bits you're trying to retrieve (and the reason why those bits are special).


text:
Q: Getting users with permissions for specific devices would like to know is it possible to get users who are allowed to access/login for a specific devices
it's not useful for me to get information for all my servers. i would like to know for some specific devices
please advice

A: Try the following requests for Virtual Guests:
https://$user:$apiKey@api.softlayer.com/rest/v3/SoftLayer_Account/getVirtualGuests?objectFilter={"virtualGuests":{"hostname":{"operation":"in","options":[{"name":"data","value":["vsi1","vsi2"]}]}}}&objectMask=mask[users]

Replace: $username, $apiKey
and vsi1 and vsi2 with the vsi's hostnames

*

*In this case the mask[users] mask will retrieve a lot of information and it can raise an issue due to the large set of data. See: How to Solve: Error fetching http headers, for that reason I recommend to use a mask like this: mask[users[id,username]]

To get users which has access for a specific BMS:
https://$user:$apiKey@api.softlayer.com/rest/v3/SoftLayer_Account/getHardware?objectFilter={"hardware":{"hostname":{"operation":"in","options":[{"name":"data","value":["server1","server2","server3"]}]}}}&objectMask=users

*

*Unfortunately, in this case it's not possible to get only id and username from users, it will retrieve a lot of set of information from the users

To get users for VSI/BMS through FQDN
I can recommend another alternative using rest, but you can only get devices (bms/vsi) which has a specific text in its fullyQualifiedDomainName, in this example I tried for servers with "testName", replace it for your requirements
https://$username:$apiKey@api.softlayer.com/rest/v3.1/SoftLayer_Search/advancedSearch?objectMask=mask[resource(SoftLayer_Hardware_Server)[id,datacenter,fullyQualifiedDomainName,users.id,users.username],resource(SoftLayer_Virtual_Guest)[id,datacenter,fullyQualifiedDomainName,users.id,users.username]]

Method: Post

{"parameters":["fullyQualifiedDomainName:testName _objectType:SoftLayer_Virtual_Guest,SoftLayer_Hardware _sort:[fullyQualifiedDomainName:asc]"]}

I hope it helps, let me know if you need further assistance or any doubt
References:

*

*SoftLayer_Account::getVirtualGuests

*SoftLayer_Account::getHardware

*SoftLayer_Search::advancedSearch


text:
Q: Image upload to Facebook from HTML drag and drop I've got a PHP script that can upload images stored on my server to a Facebook post. I've tried and tested it and the post gets to Facebook just fine.
I also have a drag and drop area on my webpage, based on this tutorial. What I've hit a brick wall on is getting the file dropped onto the DOM element that I'm listening to and then passing it over to the PHP script or, for that matter, a Javascript function.
I suspect that Javascript might be my best option, so I've looked at Dropzone.js but it appears to require that the image first goes to my server and then onto Facebook - I'd really like to avoid that for storage and upload time reasons.
I think in terms of a Javascript solution it's got something to do with FileReader() and here's my code so far:
function handleFileSelect(evt) {
    evt.stopPropagation();
    evt.preventDefault();
    var files = evt.dataTransfer.files;
    for (var i = 0, f; f = files[i]; i++) {
    if (!f.type.match('image.*')) { continue; }
    var fileReader = new FileReader();
    fileReader.onload = (function(theFile) {
        return function(e) {
            var blob = e.target.result;
            var fd = new FormData();
            fd.append("access_token",fbAccessToken);
            fd.append("source", blob);fd.append("message","This is another post test...");
    try{
        $.ajax({
            url:"https://graph.facebook.com/" + fbuserid + "/photos?access_token=" + fbAccessToken,
            type:"POST",
            data:fd,
            processData:false,
            contentType:false,
            cache:false,
            console.log("success " + data);
        },
        error:function(shr,status,data){
                console.log("error " + data + " Status " + shr.status);
        },
        complete:function(){
                    console.log("Ajax Complete");
        }
    });
    }catch(e){console.log(e);}
};})(f);

fileReader.readAsDataURL(f);
}
}

and I can see that raw image data is accessible through there but then how can I pass that to the Formdata?


text:
Q: attemp to join incorrect SQL 2008 Want to join these 2 tables I have show the query I use on each individual and my attempt to join below. any help scripting would be much appreciated
SELECT [Date] = CONVERT(char(10),
       CURRENT_TIMESTAMP -3, 103),
       Items = SUM(NumberOfItems),
       'DUAL' as Sorter
FROM  [DB2].[DB2].[dbo].[SortStatistics]
WHERE RecordedPeriod  Between '06/23/17 01:00:00AM' and '06/23/17 23:59:00PM'
AND   WorkstationID IN ('D11', 'D12', 'D13')

SELECT [Date] = CONVERT(char(10),
       CURRENT_TIMESTAMP -3, 103),
       Misfires = SUM(Resolved),
       'DUAL' as Sorter
FROM  [DB1].[DB1].[dbo].[MisfireLog]
WHERE RecordedPeriod  Between '06/23/17 01:00:00AM' and '06/23/17 23:59:00PM'
and   WorkstationID  IN ('D11', 'D12', 'D13')

Results are...
Date        Items   Sorter
23/06/2017  39983   DUAL

Date        Misfires    Sorter
23/06/2017  247         DUAL

Here is my attempt to join
SELECT [Date] = CONVERT(char(10),
       CURRENT_TIMESTAMP -3, 103),Items = SUM(SortStatistics.NumberOfItems),
       Misfires = SUM(MisfireLog.Resolved),
       'DUAL' as Sorter
FROM [DB2].[DB2].[dbo].[SortStatistics]
  LEFT JOIN [DB1].[DB1].[dbo].[MisfireLog]
    ON SortStatistics.RecordedPeriod = MisfireLog.RecordedPeriod
WHERE SortStatistics.RecordedPeriod  Between '06/23/17 01:00:00AM' and '06/23/17 23:59:00PM'
AND   SortStatistics.WorkstationID IN ('D11', 'D12', 'D13')
and   MisfireLog.WorkstationID IN ('D11', 'D12', 'D13')

Results from Join attempt shown like this, which is off some how
Date         Items  Misfires    Sorter
23/06/2017   691822 735         DUAL

A: When you join the tables, on
SortStatistics.RecordedPeriod = MisfireLog.RecordedPeriod

The result will not contain the same no of records as the base table.
To get the result as
23/06/2017 39983 247 DUAL

you just need to concatenate the output of the 2 queries which you have. since its just a single row output for both, we can use CROSS JOIN like this
SELECT t1.[Date],t1.Items,t2.Misfires,t1.Sorter
FROM
(
SELECT [Date] = CONVERT(char(10),
       CURRENT_TIMESTAMP -3, 103),
       Items = SUM(NumberOfItems),
       'DUAL' as Sorter
FROM  [DB2].[DB2].[dbo].[SortStatistics]
WHERE RecordedPeriod  Between '06/23/17 01:00:00AM' and '06/23/17 23:59:00PM'
AND   WorkstationID IN ('D11', 'D12', 'D13')
)t1
CROSS JOIN
(
SELECT [Date] = CONVERT(char(10),
       CURRENT_TIMESTAMP -3, 103),
       Misfires = SUM(Resolved),
       'DUAL' as Sorter
FROM  [DB1].[DB1].[dbo].[MisfireLog]
WHERE RecordedPeriod  Between '06/23/17 01:00:00AM' and '06/23/17 23:59:00PM'
and   WorkstationID  IN ('D11', 'D12', 'D13')
)t2;


text:
Q: Can Tampermonkey edit popups from other extensions Is it possible to change other extension popups (like Google tag assistant legacy or even LastPass)?
Can't find documentation or anything about it, but it would be a lifesaver for my everyday automatization.

A: Neither userscripts nor extensions have access to modify other extensions as it would be a security risk.


text:
Q: Accessing /page/2 on WordPress directly breaks infinite-scroll I added infinite-scroll.js library to Wordpress (manually, not via plugin). On index i have wrote a loop to make the pagination and everything works fine, however then i'm accessing URL/page/2 directly not from index i see that it is broken. Any ideas how to avoid this? Maybe doing some redirect to index when accessing page/x/ or any other way? Or maybe it is possible to preload everything from index (page1) and continue loading on page/2?
Also tried if is_paged -> when redirect to index on index.php template file. This method works, but of course infinite-scroll doesn't load any new items.
Thanks


text:
Q: Need help creating a basic template Would anyone be able to create a LaTeX template of this?

A: I accept unicoins... and compile this with XeLaTeX:

\documentclass[10pt]{article}
\usepackage{geometry}
\geometry{
  vmargin=0.75in,
  hmargin=1.00in
}
\usepackage{multicol,enumitem,caption,graphicx}
\captionsetup[figure]{
  font=small,% 9pt
  labelsep=endash
}

\usepackage{fontspec}
\setmainfont{Times New Roman}
\newfontfamily{\titlefont}{Rockwell Bold}
\newfontfamily{\headingfont}{Rockwell Bold}
\newcommand{\heading}[1]{%
  \par
  {\large\headingfont #1\par}% 12pt
  \vspace{-\baselineskip}
}

\setlength{\parindent}{0pt}
\setlength{\columnsep}{0.15in}
\pagestyle{empty}
\begin{document}

\begin{center}
  \huge\titlefont Transparent Aluminum Revolutionizes Structural Materials% 20pt
\end{center}

\begin{tabular}[b]{@{}l@{}}
  Blair London \\
  MatE 330
\end{tabular} \hfill
April 13 or 17, 2015

\vspace{-.5\baselineskip}

\rule{\textwidth}{.4pt}\par\vspace{-.8\baselineskip}
\rule{\textwidth}{1pt}

\begin{multicols}{2}
\setlength{\parskip}{\baselineskip}
\raggedright
\heading{Background}
This section of your Application Page presents the
background behind your particular application. The font
is 10pt Times New Roman. The line spacing is single spaced.
Use this font, size and line spacing for each
section of the Application Page. The body of the text is
a two-column format with 0.15in between columns of
equal width. The page has 0.75in margins on the top
and bottom, 1.0in margins on the left and right. The
section headings are 12pt Rockwell bold font.

Between paragraphs, you can have a blank line space as
shown, or you can indent without a blank line space.
The sections are separated by one blank line. The
Background section will explain some of the context of
your fiber or composite application. You might include
how it came to be, where it is used, and other features of
interest. You will probably present a photograph or
diagram of your application in this section (Figure~\ref{fig1}).
Your figure must be clear and meaningful. Do not use
CES or our course textbook for figures. You will likely
need to call on different references\textsuperscript{\ref{ref1}}. We will use
superscript numbers for the references\textsuperscript{\ref{ref2}}. Note that the
reference numbers must be in order in the text.

\begin{minipage}{\columnwidth}
  \centering
  \includegraphics[width=.7\columnwidth]{example-image-a}
  \captionof{figure}{The figure caption describes the image shown, and
it must be referenced properly\textsuperscript{\ref{ref3}}. 9pt Times New Roman font.\label{fig1}}
\end{minipage}

\heading{Application}
This section is where you describe your application in
more detail. Go into how fibers or composites are used
specifically for the application you have chosen. You
will need to use references here; they can be the same
ones you referred to in the previous section. Challenges
with this section are to be specific and to explain the
details of your application to the reader.

You may find overlap in writing this section and the
Background section. Effective editing will be necessary
to make the sections separate and meaningful. With
each section, you will need to follow proper technical
writing format, rules, etc. More detail is posted on the
MatE 330 PolyLearn site. Proper technical writing
means clear, formal communication – following the
rules is necessary to meet those goals.

The title of your Application Page is in 20pt bold
Rockwell font. Your name, course number, and date are
in 10pt Times New Roman font. Note that there is a
double line below these items to set them off from the
rest of the Application Page. The Application Page must
be one side of one page – it should look like this page.

\heading{Science}
Likely, the most challenging section of the Application
Page to write is this one. Here is where you go into
detail behind the \emph{science} of your application. You could
take the materials engineering approach and investigate
how structure controls properties. You may consider
other approaches. This section has to have a figure or
table with \emph{data} about your fiber or composite (Figure~\ref{fig2}).
Your data must be clear, readable, and accurate. Do not
use CES or our course textbook for data.

\begin{minipage}{\columnwidth}
  \centering
  \includegraphics[width=.6\columnwidth]{example-image-b}
  \captionof{figure}{An example of data about transparent aluminum.
This is not a good example – the axes are difficult to read\textsuperscript{\ref{ref3}}.\label{fig2}}
\end{minipage}

Part of this section will explain the data you show. It is
important for you to understand the data you present to
the reader. It is not a good idea simply to show data
without an explanation of how it affects the fiber or
composite in its application.

\heading{References}
\begin{enumerate}[label=\arabic*.,ref=\arabic*,nosep,leftmargin=*]
  \item \label{ref1}First reference. Be sure it is in the proper format;
    consult a style manual to check.
  \item \label{ref2}You can have 3-5 references for the Application
    Page; not all of the references can be websites.
  \item \label{ref3}There is line space between each reference citation.
\end{enumerate}
\end{multicols}
\end{document}

The "template" uses nothing special: minipages for "floats" and a list - enumerate - for references.


text:
Q: How do I get a desktop notification from a web app? I need to create a web app for a client, and one of the requirements is whenever an event is triggered there should be some desktop notification in Windows XP/7 that tells them of the event. Similar to the balloon that pops-up when a new file is added to a folder in Dropbox.
I am using Rails for the web app, but have never done any desktop development. What should I be looking at?

A: Would this: Growl Notifications from a Web Server
plus Growl for windows meet your needs? http://www.growlforwindows.com/gfw/developers.aspx

A: It may be worth looking at Noti.
This tool allows web apps to push notifications to a small app running on OS X, Windows and Linux.

A: Would RSS-enabling the application, coupled with a RSS widget on the desktop, suffice? This has a few drawbacks - for example, it requires setup on the workstations and is not immediate. But it is non-proprietary.
If this is a Windows environment, perhaps the application could use the Windows command msg.exe to pop up an alert box (assuming Windows messenger service is enabled on the workstations).

A: You can use Telegram (desktop portable version included) with TeleNotify gem. Downside is, your app must have HTTPS. But with CloudFlare you can get your app working with SSL for free, even without changing your source code.


text:
Q: Difference between port mapping of Docker Service and Docker run Usually when we create docker container ( For example nginx ) and expose it to outside we use port mapping.
docker run -p 8091:80 --name container1 --net my-overlay-a nginx
docker run -p 8092:80 --name container1 --net my-overlay-a nginx ( if in this line if I specified 8091:80 then it create problem as on host machine 8091 already used to map 80 port of container1).

Now instead of docker run if I use docker service ( I did docker swarm init before that).
docker service create --name redis --replicas=2 --publish 8080:80 nginx

This will also create two containers but both are accessed by same port 8080.
How this is possible  ?

A: docker swarm use route mesh technology, ingress network. when you define port while creating service, service will expose same port in each node, even though created multiple containers.   and the swarm has inbuilt load balancer it will route traffic across all containers


text:
Q: Entity framework creating duplicate tables I have inherited an entity framework application that i have been tasked to create within a separate environment with a completely separated database as well on a new db server. Seems easy enough. I backup the database from the original and restore it on the new database server. the data is the exact same at this point.
For testing purposes i change the local connection string to the new database server and run my web app locally. I get an error in the browser that is "MySql.Data.MySqlClient.MySqlException: Can't write; duplicate key in table '#sql-3b87_2d5f91'" i dont even have a table with that name and have no idea where it comes from. entity framework also creates duplicate tables for all of my tables except for migrations table.
I have tried other things as well, after restoring the db in the new db server to the original again, i have tried running 'update-database' and the same issues happen.
Now if i disregard restoring the new database with the backup from the original and run "update-database" on the new database server. it creates the schema correctly, but it lacks the data i need for testing.
Any ideas why this may be happening? i would like to avoid writing a sql script to transfer data.


text:
Q: How do I plot two data streams in Numbers as a graph? I have two different streams of fractional values I want to visualize using Numbers for Mac.
They both have one value per line and both look would look something like this (with different values obviously):
0.04
0.1
0.05
0.0993
1.3
0.534
...

And I basically want it to have the index (so 1, 2, 3, 4, etc.) as the x axis and the amount (in seconds) on the y axis, and have the two data streams. And I'd like to have it as a line graph or a bar graph.
I can't figure out how to do this however.

A: Add a chart, I used this one:

Then click [Add Chart Data] and select the columns for the data streams


text:
Q: Setting state inside firebase snapshot listener not working in the following code snippet, I'm trying to set to use the data from the snapshot listener outside of its scope, so I decided to use a useState hook for it, but my data isn't being properly set.
useEffect(() => {
    const unsubscribeAuth = onAuthStateChanged(auth, (authUser) => {
      if (authUser) {
        const userStatsQuery = query(
          collection(db, "Users", authUser.uid, "UserStats")
        );

        const unsubscribeUserStats = onSnapshot(
          userStatsQuery,
          (userStatsSnapshot) => {
            const userStatsDocs = [];
            userStatsSnapshot.forEach((doc) => {
              userStatsDocs.push(doc.data() as UserStats);
            });
            setUserStats(userStatsDocs);
            console.log(userStatsDocs);
            console.log(userStats);
          }
        );

        setIsLoading(false);
      } else {
        setUser(null);
        setIsLoading(false);
      }
    });

    return () => {
      unsubscribeAuth();
    };
  }, []);

Here I also have an auth state handler to check if the user is logged in to query for the stats.
console.log(userStatsDocs) returns the data properly in a typed format, but console.log(userStats) returns an empty array (the states initial value)
Any help?


text:
Q: How to tell what version of libfortran I need I've been searching for quite a while for this answer, but I'm trying to find out what libgfortran versions correspond to the actual gfortran versions.
There is only 3 available and when I try to compile some code it tries to search for 5. I'm using g++/gfortran 8.3.1, so I'm not sure why its reaching for 5??
Could anyone help me out on what gfortran version corresponds to libgfortran5?
I'll have to ask a sys admin to install it, so if it's possible I'd rather just make it use libgfortran3 which is already there.

A: The major version number for libgfortran is changed when the
ABI is changed.  This happens seldomly.  If gfortran 8.3.1 is
looking for libgfortran.so.5, then that is what you need.  I'll
note that the major version number has not changed in a long
time, and in fact, 5 is the version for all version of gfortran newer
than 8.3.1.  If you try to use libgfortran.so.3, you'll likely
have an unpleasant experience.


text:
Q: Problem when using unity addressable and amazon s3 I am currently using unity addressable and amazon s3 in my project to pack my assets and reduce build size.
Here is my current setting
My addressable group settings
I have disabled CRC to make sure that I can build addressable in other computer and can upload them to s3 server to update game contents (that is my intention). When I test this on Window build everything work fine, here are my steps:

*

*Step 1: I use new build to build catalog and bundle files.

*Step 2: I upload them to s3 server

*Step 3: I open window build and load all assets.

*Step 4: I update assets, prefab and use new build again (this equal to build in other device).

*Step 5: I clear delete files in s3 server and upload new catalog, bundle files

*Step 6: I open window build and see that only updated assets is downloaded.

*Step 7: I instantiate prefab and confirm that assets has ben changed.

But on android builds: I do the same step but when I do step 6, Addressable.GetDownloadSizeAsync receive no change (download size = 0) and when I try instantiate it still the old prefab.


text:
Q: Sicstus Prolog - Put words into a list Got another problem:
There is a list with some words. If the length of the word is more than a given length (ex. 4), it will be put in an another list.
I tried:
require_min_length([], _, []).
require_min_length([Word|Words], Minl, [List]):-
     word_length(Word, W),    % method word_length return the length of a word.
     (W >= Minl -> append(Word, List, List), require_min_length(Words, Minl, List);
     require_min_length(Words, Minl, List)).

Results I got:
| ?- Words=["ABCD", "ABCDE", "AAA"], require_min_weight(Words, 5, Lists).
! Resource error: insufficient memory.

The right result will be:
Lists = [[65, 66, 67, 68, 69]].   (% ascii)

How to change the code? Any help pls! Thanks.

A: The problem with your predicate is that you are using append wrong.
You are using append(Word, List, List), this would only succeed if Word is an empty list. Also you really don't want to append the codes of your word to the output list, but the word itself.
Consider something like this:
require_min_length([], _, []).
require_min_length([Word|Words], Minl, NList):-
     word_length(Word, W),    % method word_length return the length of a word.
     (W >= Minl -> NList=[Word|List] ; NList=List),
     require_min_length(Words, Minl, List)).


text:
Q: Binary tree implementation I seem to be getting a segmentation fault, and it seems as though the error is coming from the call to tra, but I am unable to see exactly what is wrong with the code that I have written. Really have no clue, any want to give me a hint? Thanks a lot.
struct node *tra(struct node * start) {
  struct node * current = start;
  return current; }

Table ins(Key_Type input, Table table) {
  if ((find(input, table)) == FALSE) {
    struct node *newVal = tra(table -> head, input);
    newVal -> element = input;

I have defined a struct node which contains head, left and right elements. I know for sure that tra returns current when it is null, as I am creating a tree which is empty at first, so all nodes will be empty.

A: tra looks suspicious. What is the check for? If current is NULL return it, else fall of the stack and return trash to the caller.

A: There's some weird stuff going on there.
if (current == NULL)
  return current;

Why return current? Current is null?
struct node *new = tra(table -> head, input);

tra takes a single argument?
I'd recommend you use gdb. Learn to use it now, and it will give you the power to answer this question yourself. It's not difficult.


text:
Q: Does the Android operating system have files like /etc/passwd, /etc/shadow, and /etc/group? If not, how does android determine whether a user belongs to a certain group?

A: This thread discusses how that is done: http://groups.google.com/group/android-ndk/browse_thread/thread/adddb27c1a5438e9
It contains a broken link to a git repository though, you can find a list of name and IDs in https://android.googlesource.com/platform/system/core.git/+/master/include/private/android_filesystem_config.h.


text:
Q: Do anyone know how to Multiple N Odd Number Using Assembly x86 Language? Do anyone know how to Multiple N Odd Number Using Assembly x86 Language that using MUL mnemonic
Ex : SUM=1*3*5*7*..........*n

A: To multiply numbers with the MUL instruction you put one number in eax (or rax or ax depending on operand size) and another number somewhere else (in any other register or in memory), then do MUL and expect the result in edx:eax (or rdx:rax or dx:ax).
For example (32-bit, NASM syntax, untested):
    mov eax,1      ;eax = 1
    mov ebx,2      ;ebx = 2
    mov ecx,5      ;ecx = 5
    mul ebx        ;edx:eax = 1 * 2
    mul ecx        ;edx:eax = (1 * 2) * 5

Of course when they're constants you can cheat and let the assembler do it when the code is assembled. For example (32-bit, NASM syntax, untested):
    mov eax,1*2*5*7

You can also do the MUL in a loop. For example, if the values come from a table or array (32-bit, NASM syntax, untested):
    mov eax,[table]
    mov esi,table+4
    mov ecx,31-1            ;31 items in table?
.next:
    mul dword [esi]         ;edx:eax = temp * table[i]
    add esi,4
    loop .next

However, if there's some sort of relationship between the values you don't need a table. Your sequence seems wrong to me and I suspect you actually wanted "1*3*5*7 ... N" (and suspect that the 2 was a typo), and "1*3*5*7 ... N" is a sequence that can be done without a table. For example (32-bit, NASM syntax, untested):
    mov ecx,31          ;ecx = N = 31
    mov ebx,1           ;ebx = the value the result was multiplied with last
    mov eax,1           ;eax = the result
.next:
    lea ebx,[ebx+2]     ;ebx = the value to multiply with the result next
    mul ebx             ;edx:eax = new current result
    cmp ebx,ecx         ;Has N been reached?
    jb .next            ; no, keep going

Note that you can cheat to improve performance. For example, you can do something like this (32-bit, NASM syntax, untested):
    mov ecx,31          ;ecx = N = 31

    mov eax,1           ;eax = the current result
    mov ebx,1           ;ebx = the value the result was multiplied with last
    cmp ecx,9           ;Is the last value greater than 9?
    jle .next           ; no, don't cheat
    mov eax,1*3*5*7*9   ; yes, cheat by skipping the first 4 multiplications
    mov ebx,9

.next:
    lea ebx,[ebx+2]     ;ebx = the value to multiply with the result next
    mul ebx             ;edx:eax = new current result
    cmp ebx,ecx         ;Has N been reached?
    jb .next            ; no, keep going

You can cheat a lot more using a pre-computed lookup table. For example (32-bit, NASM syntax, untested):
    mov ecx,31                      ;ecx = N = 31
    mov eax,[resultTable + ecx*4]   ;eax = result for N

Of course you can halve the size of the table like this:
    mov ecx,31                      ;ecx = N = 31
    shr ecx,1                       ;ecx = N/2 = 15
    mov eax,[resultTable + ecx*4]   ;eax = result for N

You can also build the table at run time, effectively turning it into a kind of cache:
    mov ecx,31                         ;ecx = N = 31

    mov edx,ecx                        ;edx = N
    shr edx,1                          ;edx = N/2
    cmp dword [resultTable + edx*4],0  ;Is the result for this N already known?
    je .unknown                        ; no, have to calculate it
    mov eax,[resultTable + edx*4]      ; yes, just use the result from last time
    jmp .done

.unknown:
    mov eax,1                          ;eax = the current result
    mov ebx,1                          ;ebx = the value the result was multiplied with last
    cmp ecx,9                          ;Is the last value greater than 9?
    jle .next                          ; no, don't cheat
    mov eax,1*3*5*7*9                  ; yes, cheat by skipping the first 4 multiplications
    mov ebx,9

.next:
    lea ebx,[ebx+2]                    ;ebx = the value to multiply with the result next
    mul ebx                            ;edx:eax = new current result
    cmp ebx,ecx                        ;Has N been reached?
    jb .next                           ; no, keep going

    shr ecx,1                          ;ecx = N/2
    mov [resultTable + edx*4],eax      ;Store the result for next time

.done:

However, any previous result for a lower value of N can be used as a starting point to calculate the result for any higher value of N. This leads to the following approach (32-bit, NASM syntax, untested):
    mov ecx,31                    ;ecx = N = 31

    shr ecx,1                     ;ecx = N/2
    mov ebx,[highestN2]           ;ebx = the highest N/2 that's been done before
    cmp ecx,ebx                   ;Has this N/2 been done before?
    ja .unknown                   ; no
    mov eax,[resultTable + ecx*4] ; yes, use the previously calculated result
    jmp .done

.unknown:
    mov eax,[resultTable + ebx*4] ;eax = highest result previously calculated
.next:
    inc ebx                       ;ebx = next N/2 to use
    lea edx,[ebx*2+1]             ;edx = next N to use
    mul edx                       ;edx:eax = old result * N
    mov [resultTable + ebx*4],eax ;Store it for later
    cmp ebx,ecx                   ;Have we done enough?
    jb .next                      ; no, keep going
    mov [highestN2],ebx           ;Set the new highest N/2 calculated so far

.done:


text:
Q: In an iPad SplitView, how do I add a Date Picker control to the Root View? I'm diving into iPhone OS development on the iPad and one of the things I'm playing with is the SplitView template.  The template provides a window with a UISplitView view, containing the Root View (on the left of the window) and the Detail View (on the right of the window).  The Root View is a subclass of a TableView.  Rather than having the entire Root View consist of a TableView, I'd like it to contain a DatePicker view along with the TableView under it.  When I go into IB and try and drop a DatePicker into the Root View, it won't let me.  It will only let me add a DatePicker view to the Detail View.

*

*Why wont IB let me drop a DatePicker view into the Root View?

*How can I add a DatePicker to the RootView in addition to the TableView?

I'm still learning this new platform, so I apologize if these questions are absurd in any way.  Thanks so much in advance for your help, I'm going to continue researching these questions right now.

A:
Why wont IB let me drop a DatePicker
  view into the Root View?

For starters, RootViewController is a UITableView. You can't add a UIDatePicker to a UITableView.

How can I add a DatePicker to the
  RootView in addition to the TableView?

If you want to add a UIDatePicker, you have to replace RootViewController with a UIViewController then add a UITableView and UIDatePicker.


text:
Q: java change variable argument value I am not sure if I am doing some silly mistake, What I am trying to achieve is I have JSON list and I want to convert them into multiple objects depending on variable argument passed to function.
Unit u1= new Unit();
User us = new User();
//calling funtion
StaticUtil.MagicJsonMapper(list, u1,us);
System.out.println(u1.getUnitName()); //place -1 unitName is null after function call

Inside static class I have create a function
@SuppressWarnings("rawtypes")
public static void MagicJsonMapper(List list,Object... objects){
    if(list.size()!= objects.length){
        //TODO
        System.out.println("parame`ter mismatch");
        return;
    }
    int i=0;
    ObjectMapper mapper = new ObjectMapper();
    for(Object object : objects){
        if(list.get(i) instanceof List){
            MagicJsonMapper((List)list.get(i),object);
        }
        else{
            objects[i] = mapper.convertValue(list.get(i), object.getClass());
        }
        i++;
    }
 //place -2 "objects" contains proper value of unitname
}

The issue is I am still not getting proper value in parameter after finished running this method. It means argument values are not retained as in contrast of normal java behaviour, is it something to do with variable argument.
Just for clarity I debugged the code and values are proper at the end of the function.

A: The objects array is created during the function call and discarded afterwards. If you need to access the values from the array after the call, you need to create the array explicitly.


text:
Q: How to sort new data for display? I am new to SQL. I have a table called Categories with 3 columns:
id int(25)
category varchar(25)
subcategory varchar(25)

I would like to add a new subcategory "Real Estate Agency" in the category "Accommodation". When I do that, the new subcategory appears at the bottom of my table:
[
All my data have an increase ID (1, 2, 3, 4) so when I add new data it takes the new ID order ( for instance : 157 ). If I understand correctly the ordering is done by the ID.
The problem is that now the new sub-category appears in my website drop-down menu but it's not in alphabetical order. It appears at the end of the category list:
[
I have been searching in my SQL for Beginners book, in Google and Stack Exchange but I didn't find help for my issue.
If someone has a good idea how to solve this I would appreciate it.

A: Ok, so why don't you just use the ORDER BY clause? Like you have said, by default the SELECT statement will return our data ordering by ID, so you need to specify that you want your own order.
SELECT id, category, subcategory
FROM Category
ORDER BY subcategory ASC

The ASC means ascendant order [that's default behavior], so it will return ordered from A-Z. You can specify DESC that refers to descendant order, which will return ordered from Z-A.
P.S.: I saw you have you categories and subcategories in the same table, and they have a one to many relationship, shouldn't you normalize that? It will help you while you data in that table get bigger. Normalization of Database


text:
Q: Error when uploading mySQL file After i used the new answer i uploaded the file and this is what i get now.
SQL query:

CREATE TABLE IF NOT EXISTS `games` ( ) INSERT INTO `games` (`name`, `creatorid`, `gameid`, `id`, `plays) VALUES ('בדיקה', 'לא ידוע', 1,1,0) CREATE TABLE IF NOT EXISTS `gamewall` ( `userid` int(11) NOT NULL, `reason` text NOT NULL, `comment` text NOT NULL, `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `bannedbyid` int(11) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; CREATE TABLE IF NOT EXISTS `bans_IP` ( `IP` mediumtext NOT NULL, `id` int(11) NOT NULL AUTO_INCREMENT, `bannerid` int(11) NOT NULL, `reason` mediumtext NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ; CREATE TABLE IF NOT EXISTS `buysell` ( `buysell` int(11) NOT NULL, `sellerid` int(11) NOT NULL, `price` int(11) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; CREATE TABLE IF NOT EXISTS `competitions` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` mediumtext NOT NULL, `startedbyid` int(11) NOT NULL, `descripti[...]

MySQL said: Documentation

#1064 - 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 ')

INSERT INTO `games` (`name`, `creatorid`, `gameid`, `id`, `plays) VALUES
('' at line 3

A: You are receiving this error because you have selected all the columns of your table but values are available for first 11 columns and you missed ) in last
This code will fix your problem
INSERT INTO `accounts` (
   `Username`,
   `Password`,
   `Email`,
   `salt`,
   `Reebs`,
   `online`,
   `lastOnline`,
   `lastOnlineMinutes`,
   `lastOnlineHours`,
   `status`,
   `blurb`
)
VALUES
   (
      'AvatarLife',
      'df3ed1ad53c4cc2f3b5c6bdf04d33a9f094df53b',
      'fawrsnipng@gmail.com',
      'jBqnW?Dk9Epzpg4',
      '9223372036854775807',
      '1',
      '205',
      '26',
      '13',
      '',
      'Avatar Life is the only good life!')


text:
Q: USB Devices stop working randomly in Windows 10, Event 3 usbehci My computer has been having a problem where randomly any USB port that I have a device connected to will stop working. There are a couple ways of temporarily fixing this: Plug all USB devices into a previously unused port, or restart my computer.
I've done some research, and though many people have this problem, I can't seem to find a fix that works for me. I've tried reinstalling the drivers for all my USB devices, reinstalling Windows updates, hell I even reinstalled Windows 10 entirely and this problem is still present.
The only thing I can find on my system is an error in the System logs which is as follows:
Event 3, usbehci;
A timeout occurred while waiting for the EHCI host controller Asynchronous Schedule to transition to the enabled state.
This error keeps being logged, once to twice every minute after the USB ports stop working. It seems to be the cause as well, but I can't find a fix.
Windows 10 Home, MSI 970A Gaming Pro Carbon MOBO, 1x8GB Kingston HyperX Fury 1866MHz RAM, AMD FX-8350 CPU, 850W power supply, GTX 7xx something Ti video card.
I recently replaced my motherboard. And CPU. And RAM. The problem started to occur after I replaced all this (about 2 weeks ago). The latest bios is the only bios, though I still tried to update it to what it already was. And as far as I know, it happens regardless of what's plugged in.
The previous motherboard was some ASUS AI Lifestyle, CPU Intel, various speeds and brands of ram. I don't have them anymore so that's the best I can do.


text:
Q: Compact variety which is not projective While reading Andreas Gathmann's notes on Algebraic Geometry, I stumbled upon this statement: "Projective varieties form a large class of "compact" varieties that do admit such a unified global description. In fact, the class of projective varieties is so large that it is not easy to construct a variety that is not (an open subset of) a projective variety.".
I know that we can sometimes glue affine varieties together and create compact spaces (in fact, Gathmann constructs $\mathbb{P^1}(\mathbb{C})$ as a compactification of $\mathbb{A}^1$). Also affine varieties are not compact unless they are single points. But my question is: is there an example of a variety which is "compact" but not projective?
Gathman does not provide such an example, so maybe someone here can help.

A: Such example does not exist in dimension 1. For dimension 3, see the appendix B in Hartshorne, Example 3.4.1
As Liu pointed out below, there is a list discussing related questions in Hartshorne Chapter II Beneath Remark 4.10.2.


text:
Q: Histogram in log scale with Python Hello I have this code :
import matplotlib.pyplot as plt
import math
import numpy as np

a = np.array([2.79e-06,2.47e-06,0.000122,3.9e-05,0.000527,9.41e-06,3.11e-05,4.63e-05,0.000749,0.000499,0.000174,0.000984,0.000912,5.86e-05,0.000344,0.000754,0.000267,2.53e-06,8.73e-05,0.000791,1.69e-06,7.56e-05,0.001,3.1e-06,0.000305,2.4e-06,6.37e-06,3.25e-07,6.67e-05,0.000167,0.000954,2.36e-07,3.8e-06,0.000337,8.1e-06,1.68e-05,0.000332,3.64e-06,2e-05,5.97e-06,0.000808,2.34e-06,0.000121,0.000972,2.59e-05,0.000761,8.76e-05,0.000253,0.000819,7.88e-06,5.04e-05,1.75e-05,5.83e-05,0.000271,3.18e-06,3.29e-05,0.000979,0.000925,2.55e-05,0.000347,0.000269,9.51e-06,5.54e-06,7.18e-05,1.44e-05,8.42e-09,1.86e-05,0.000377,1.68e-05,0.000991,4.69e-06,9.87e-05,4.45e-05,4.05e-06,6.76e-05,5.66e-06,6.51e-06,3.76e-06,6.44e-05,2.91e-09,0.000565,9.18e-06,0.0003,0.0002,9.43e-05,8.57e-06,6.32e-05,4e-06,5.18e-06,0.000181,0.000999,1.67e-05,0.000941,6.49e-05,0.000141,4.07e-06,2.68e-06,0.000407,1.47e-05,5.2e-06,6.53e-06,0.000462,1.38e-05,0.000794,3.32e-07,2.19e-06,0.000432,0.000156])

plt.clf()
plt.hist(a)
plt.xscale('log')
plt.title('Histogram of a')
plt.savefig('a.png')

But I don't understand when I see the histogram I get this picture :

But it is not good because the length of the different bins are not equals !
Could you help me please ?
Thank you so much !
Edit :
This is the new code for Florian :
import matplotlib.pyplot as plt
import math
import numpy as np

a = np.array([2.79e-06,2.47e-06,0.000122,3.9e-05,0.000527,9.41e-06,3.11e-05,4.63e-05,0.000749,0.000499,0.000174,0.000984,0.000912,5.86e-05,0.000344,0.000754,0.000267,2.53e-06,8.73e-05,0.000791,1.69e-06,7.56e-05,0.001,3.1e-06,0.000305,2.4e-06,6.37e-06,3.25e-07,6.67e-05,0.000167,0.000954,2.36e-07,3.8e-06,0.000337,8.1e-06,1.68e-05,0.000332,3.64e-06,2e-05,5.97e-06,0.000808,2.34e-06,0.000121,0.000972,2.59e-05,0.000761,8.76e-05,0.000253,0.000819,7.88e-06,5.04e-05,1.75e-05,5.83e-05,0.000271,3.18e-06,3.29e-05,0.000979,0.000925,2.55e-05,0.000347,0.000269,9.51e-06,5.54e-06,7.18e-05,1.44e-05,8.42e-09,1.86e-05,0.000377,1.68e-05,0.000991,4.69e-06,9.87e-05,4.45e-05,4.05e-06,6.76e-05,5.66e-06,6.51e-06,3.76e-06,6.44e-05,2.91e-09,0.000565,9.18e-06,0.0003,0.0002,9.43e-05,8.57e-06,6.32e-05,4e-06,5.18e-06,0.000181,0.000999,1.67e-05,0.000941,6.49e-05,0.000141,4.07e-06,2.68e-06,0.000407,1.47e-05,5.2e-06,6.53e-06,0.000462,1.38e-05,0.000794,3.32e-07,2.19e-06,0.000432,0.000156])

plt.clf()
plt.hist(a, bins=np.logspace(a.min(), a.max(), 50))
plt.xscale('log')
plt.title('Histogram of a')
plt.savefig('a.png')

And this is what I get :
Histogram of a

A: You are using a logarithmic scale, that's why some bins seem larger. But they are actually all the same size if you remove plt.xscale('log') from your code.
If you need to keep the logarithm scale, then, create your own customised scale for the bins.
Look at the documentation here
https://matplotlib.org/devdocs/api/_as_gen/matplotlib.pyplot.hist.html
Florian


text:
Q: Managing two apps on bitbucket and linode I am fairly new to the repository management and deploying apps on server. Till now, I was working on single rails project, where I used to code on my local server and used to push it to bitbucket repository and then pull it on my linode server.
Now, I have one more app. I am not getting how to push it to bitbucket and pull it on linode so it won't get mixed with my previous code.
I have few questions:

*

*Should I push the code to same repo on bitbucket and pull it on different folder on linode?

*Or should I create another repo for new code?

*If i create another repo, how to switch between two repo. I mean how the command for push will be so it will push the code to respective repo on bitbucket and how to pull so it will pull from desired repo.
It may sound very basic. I have search a lot on google, but may be my wording would be wrong, I am not getting how to handle two apps on bitbucket and how to pull them on server.
I will really appreciate it someone can help in doing this.
Thank you.

A: You should use a different repository for each app you create.
Git remotes are what points your repositories to different repositories on Bitbucket, or Github, or wherever else. Remotes are directory specific, so you can have each git repository pointed to it's own respective remote repository.
To see what repository your app is pointed at, run this in the terminal:
git remote -v

To add a repository as a remote, run this in the terminal:
git remote add origin https://[USER]@bitbucket.org/[USER]/[APPNAME].git

So, for your new app, you will want to:

*

*create the repository on bitbucket

*get the repository link (https://[USER]@bitbucket.org/[USER]/[APPNAME].git)

*add the repository as a remote to your local machine

*add the repository as a remote on your linode server

Now, when you push on your local machine from the app's directory, it will push to the new repository. And the same will be true for when you pull from your linode server.


text:
Q: Excel function for multiple formula How can I do this equation in excel
If text "t" then goto cell x if not goto cell y

And perform function
I.e
If cell has letter t do (28.5%*cell) if not do (15%*cell)

A:
If text "t" then goto cell x if not goto cell y

Assuming you meant "resolve to" by goto, this could be what you are looking for:
=IF(S1="t",X1,Y1)

When the value of cell S1 is "t", the value of the cell the formula is in, would be the value of cell X1, Y1 otherwise.

If cell has letter t do (28.5%*cell) if not do (15%*cell)

This would be the formula:
=IF(IFERROR(SEARCH("*t*",A1)), 28.5% * B1, 15% * C1)

Some test-data:
   A      | B    | C
1  mytest | 100  | 200

EDIT   a ','  was missed there.. I popped that into Excel and it didn't work.
should be  =IF(IFERROR(SEARCH("*t*",A1),), 28.5% * B1, 15% * C1)
and that works

A: So the way i understand, You have 3 columns, 1 with a letter, and 2 with numbers. column 1 is either t or something else, and then column 2 and 3 are various answers. So my solution assumes that the letter is column a, and the numbers are columns b and c, and the function goes in d. you can adjust accordingly if the columns are different. then you can drag the function down (or up if you place it in a cell thats on at the top) and it will adjust the row numbers.
=IF(A1 = "t",B1 * 0.285,C1 * 0.15)
so basically it takes cell A1 and checks if it is the letter t. if so, it takes the number in b1` and multiplies it by 28.5% and if not, it takes the number in c1 and multiplies it by 15%.


text:
Q: Wordpress: how to override or remove a function of plugin in child theme? I do researched the related topics.
I would like to override the includes/functions.php in a plugin.
But there is no any apply_filters do_action and hook, just a function.
I don't want to make a direct change in any plugin file.
Is there no way to modify the function in my child theme?
Or can I remove the function & write a new one in my child theme?
Or can I redirect to my new function in child theme?
..\wp-content\plugins\xxx\admin\includes\functions.php
function email_footer(){
    ob_start();
    ?>
    <div class="wpc-contact-info" style="margin-top: 10px;">
        ...
    </div>
    <?php
    $output = ob_get_clean();
    return $output;
}

..\wp-content\plugins\xxx\admin\classes\class-xxx.php
function __construct( ){
    $this->mail_footer  = $this->mail_footer();
}
protected function mail_footer(){
    $mail_footer = email_footer();
    return $mail_footer;
}

function email_footer will need to rewrite/override

A: K, given your code. There is no way to override the email_footer function and there are no hooks/filters showing in your code either. One option (depending on your WordPress knowledge) is search the code (ideally through step debugging with something like xDebug) and see if that code eventually runs through some filter before it is sent to the user.


text:
Q: How should I manage in-memory data in Node? I have a simple app built using Node, Express, and Socket.io on the server side. My page queries my API when it needs to retrieve data that will not change, and uses WebSockets for getting live updates from the server for dynamic data. The app allows a single person, the "Supervisor", to send questions to any number of "Users" (unauthenticated) and view their answers as they trickle in. The Users send their data to the server using a POST request, and it is streamed to the Supervisor over a WebSocket. The server stores user data in a simple array, and uses an ES6 map of the items in the array (users) to objects containing each their questions and answers, like this:
class User {}
let users = [], qa = new Map();
io.on('connection', socket => {
  let user = new User(socket.id);
  users.push(user);
  qa.set(user, {});
  socket.on('question-answered', ({id, answer}) => {
    let questionData = qa.get(user);
    questionData[id] = answer;
    qa.set(user, questionData);
  });
});

This is obviously a very primitive way of handling data, but I don't see the need for additional complexity. The data doesn't need to persist across server crashes or restarts (the user's questions and answers are also stored in localStorage), and MongoDB and even Redis just seem like overkill for this kind of data.
So my question is, am I going about this the right way? Are there any points I'm missing? I just want a simple way to store data in memory and be able to access it through client-side GET requests and socket.io. Thank you for any help.

A: If an array and a map provide you the type of access you need to the data and you don't need crash persistence and you have an appropriate amount of memory to hold the amount of data, then you're done.
There is no need for more than that unless your needs (query, persistence, performance, multi-user, crash recovery, backup, etc...) require something more complicated.  A simple cliche applies here: If it ain't broke, it don't need fixing.


text:
Q: Error in Handlebar.js while using ember I have downloaded startpack from emberjs.com, it contains 3 js files:

*

*ember-1.0.0-rc.5

*handlebars-1.0.0-rc.4

*jquery-1.9.1

I created a dynamic web project in eclipse and pasted this js file in WebContents/views/js/lib folder under project.
I am getting an error in handlebars-1.0.0-rc.4.js file at line:
lexer.rules = [/^(?:\\\\(?=(\{\{)))/,/^(?:[^\x00]*?(?=(\{\{)))/,/^(?:[^\x00]+)/,/^(?:[^\x00]{2,}?(?=(\{\{|$)))/,/^(?:[\s\S]*?--\}\})/,/^(?:\{\{>)/,/^(?:\{\{#)/,/^(?:\{\{\/)/,/^(?:\{\{\^)/,/^(?:\{\{\s*else\b)/,/^(?:\{\{\{)/,/^(?:\{\{&)/,/^(?:\{\{!--)/,/^(?:\{\{![\s\S]*?\}\})/,/^(?:\{\{)/,/^(?:=)/,/^(?:\.(?=[}/ ]))/,/^(?:\.\.)/,/^(?:[\/.])/,/^(?:\s+)/,/^(?:\}\}\})/,/^(?:\}\})/,/^(?:"(\\["]|[^"])*")/,/^(?:'(\\[']|[^'])*')/,/^(?:@[a-zA-Z]+)/,/^(?:true(?=[}\s]))/,/^(?:false(?=[}\s]))/,/^(?:-?[0-9]+(?=[}\s]))/,/^(?:[a-zA-Z0-9_$:\-]+(?=[=}\s\/.]))/,/^(?:\[[^\]]*\])/,/^(?:.)/,/^(?:\s+)/,/^(?:[a-zA-Z0-9_$\-\/]+)/,/^(?:$)/];

Syntex error token "," delete this token
Syntex error token ")" delete this token
Syntex error token "]" delete this token
Kindly help me.

A: when you have 3rd party js libraries that gives errors
exclude them from the eclipse validation
How to exclude a Javascript file from Javascript Validation in Eclipse
this way you keep all error validation on your code, but can exclude on jquery handlebars etc
and makes you built the app

A: I guess your problem is then the order in which you are loading the js files, try to change it to:

*

*jquery-1.9.1

*handlebars-1.0.0-rc.4

*ember-1.0.0-rc.5

*your app.js etc...
Please see here a working example with the order showed above.
Hope it helps


text:
Q: Unique violation when I was training my conversation service In my conversation service, I'm using Watson conversation service. In dialog nodes, one branch has sub-nodes. When I train the bolt, it didn't go to the sub-node I defined, so I picked the one I defined, but I got "Unable to change the intent. Error: Unique Violation". What does this error mean? How to fix it?
Thanks for your help!
Emily

A:
I have seen such an error when you try to add a question to an intent that is a duplicate to an all ready defined question within the same intent. It also happens when you try and define a duplicate to an Entity.
Double check your questions. Otherwise I think we will need more info or examples of the code etc.


text:
Q: Do I need Amazon ECS or EC2 instances when I am planning to deploy IBM Bluemix fabric images on docker? So scenario is to create a Blockchain network that is around a use case that takes input every 2 minutes. Now I need to do this on Bluemix hyperledger v0.6 and using docker. Should I deploy it on ECS or EC2 instances as blockchain is meant for multiple peers and they should be residing on each instance?

A: Bluemix has an excellent documentation which provides step by step instruction on getting started with block chain here: https://www.ibm.com/developerworks/cloud/library/cl-ibm-blockchain-101-quick-start-guide-for-developers-bluemix-trs/index.html?ca=drs-
The above doc provides you information such as - setting up your network, writing the chaincode, writing client apps, monitoring your code etc. you can follow that article to get an insight on how to proceed further. Hope this helps.


text:
Q: The theorem applies to? for? in? Or What is the correct way to say that a certain mathematical theorem is relevant to a certain case?

*

*The theorem applies to the case;

*The theorem applies for the case;

*The theorem applies in the case;

*The theorem is applicable to the case;

*The theorem is applicable for the case;

*The theorem is applicable in the case;

*Something else?

A: Any of these is OK. They give slightly different emphasis. You might choose between them based on context. But all are correct.


text:
Q: Why setInterval is not working properly after a while? I have written a javascript code to show users a random quote every 10 second. I use jquery to update the div and setInterval to repeat the action. I'm fetching a random quote from a javascript array.
But when i tested this, it seems, it is not working properly after a while (like 3-5 mins) , I have some jquery effects like fadeIn and fadeOut but they are executed before the quote changes. Here is the js code;
var quotes = [
    "Some String",
    "Some String",
    "Some String"
];

$(function() {
    var $rand = $('div#randomQuote > p');
    var random_quote = quotes[Math.floor(Math.random() * quotes.length)];
    $rand.html(random_quote);
    $rand.animate( {"opacity" : 0}, 0);
    $rand.animate( {"opacity" : 1}, 500);
    $rand.delay("9000");
    $rand.animate( { "opacity" : 0 }, 500 );
});

function randomQuote () {
    var $rand = $('div#randomQuote > p');
    var random_quote = quotes[Math.floor(Math.random() * quotes.length)];
    $rand.html(random_quote);
    $rand.animate( {"opacity" : 1}, 500 );
    $rand.delay("9000");
    $rand.animate ( {"opacity" : 0}, 500 );
}

$(function () {
    setInterval(randomQuote, 10000);
});

Although I'm not sure, I think, these lines take some time to calculate and it breaks the loop.
var $rand = $('div#randomQuote > p');
var random_quote = quotes[Math.floor(Math.random() * quotes.length)];

Q: How can i improve this code to get it working as expected?
Thanks in advance.

A: That way your queue of events will grow indefinitely. What you want to use in this case is probably setTimeout instead of setInterval. I suggest to try this link: http://ejohn.org/blog/how-javascript-timers-work/


text:
Q: Getting timestamp to date and time I have a timestamp column in my db. I need to convert timestamp in to date and time respectively.
I use
$timestamp = strtotime($row1['timestamp']);
$date = date('d-m-Y', $timestamp);
$time = date('Gi.s', $timestamp);

When I use this code, I am not getting the time correctly.
INPUT: 2017-06-06 08:06:14
OUTPUT:
date: 06-06-2017
Time : 806.14
Thanks in Advance

A: <?php
$timestamp = strtotime( '2017-06-06 08:06:14');
$date = date('d-m-Y', $timestamp);
$time = date("H:i:s", $timestamp);
echo "$date $time";
?>

This will work..
Hope it helps

A: Try This
$timestamp='1496736374';                   //fetch timestamp value form DB.
$date = date('d-m-Y H:i:s', $timestamp);
dd($date);