text:
Q: numpy genfromtxt date conversion error I am loading a file using numpy.genfromtxt and some of the fields are in a date format, however, when I setup a converter to process these items I get an error that I am not sure how to address (see below):
strptime() argument 0 must be str, not <class 'bytes'>

At this point, my objective is to find a simple way to load files (using genfromtxt) and convert selected columns from date format to an integer (epoch, for example) -- however, I am looking for any approach that will work (not necessarily the one I have illustrated).
Any help is appreciated.
(details below)

*

*Running in virtualenv

*Using MacOS

*Using Python v3.5

The file (abbreviated) is a simple CSV format:
SomeField,SomeDate
1,2013-08-16

The code:
import numpy as np
import time

def main():
    pathRaw = 'data/homesite-quote-conversion/temp.csv'
    str2epoch = lambda x: time.mktime(time.strptime(x, '%Y-%m-%d'))
    converters = {1:str2epoch}
    dataset = np.genfromtxt(open(pathRaw,'rb'), converters=converters, dtype=None, delimiter=',', skip_header=1)
    return

if __name__ == '__main__':
    main()

The error:
Traceback (most recent call last):
File "test.py", line 12, in <module>
  main()
File "test.py", line 8, in main
  dataset = np.genfromtxt(open(pathRaw,'rb'), converters=converters, dtype=None, delimiter=',', skip_header=1)
File "{user-directory}/.virtualenvs/demo/lib/python3.5/site-packages/numpy/lib/npyio.py", line 1731, in genfromtxt
  converter.iterupgrade(current_column)
File "{user-directory}/.virtualenvs/demo/lib/python3.5/site-packages/numpy/lib/_iotools.py", line 766, in iterupgrade
_ strict_call(_m)
File "/{user-directory}/.virtualenvs/demo/lib/python3.5/site-packages/numpy/lib/_iotools.py", line 688, in _strict_call
  new_value = self.func(value)
File "test.py", line 6, in <lambda>
  str2epoch = lambda x: time.mktime(time.strptime(x, '%Y-%m-%d'))
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/_strptime.py", line 494, in _strptime_time
  tt = _strptime(data_string, format)[0]
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/_strptime.py", line 306, in _strptime
  raise TypeError(msg.format(index, type(arg)))
TypeError: strptime() argument 0 must be str, not <class 'bytes'>

A: The error is saying that time.strptime expects the first argument to be a str, not bytes:
>>> x = b'2013-08-16'    # x is bytes
>>> import time
>>> time.strptime(x, '%Y-%m-%d')
TypeError: strptime() argument 0 must be str, not <class 'bytes'>
>>> time.strptime(x.decode('ascii'), '%Y-%m-%d')   # x.decode('ascii') is a str
time.struct_time(tm_year=2013, tm_mon=8, tm_mday=16, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=4, tm_yday=228, tm_isdst=-1)

So you can avoid the error by using
def str2epoch(x):
    return time.mktime(time.strptime(x.decode('ascii'), '%Y-%m-%d'))


text:
Q: How can I find the position of one element in a sentence compared to a same element? This sounds very strange, let me explain. I would like to know how i can find the positions of a word if it is shared by two different lists in python. For example:
a =[i,am,using,the,internet]
b =[are,you,using,a,desktop]

It should be able to tell me positions 2 (from the first list, it just happens that's the position of it in both if them). I can see if any words are shared but I don't know how to find the position:
if any(x in a for x in b):

Yet I cannot get this line to tell me the position of it. I know this is incredible simple, my friend is teaching me how to code.

A: You can get the intersections using sets:
intersections = set(a) & set(b)

Then you can find the positions using list.index(element):
for intersection in intersections:
    index_a = a.index(intersection)
    index_b = b.index(intersection)
    # Do something with the indices

From the reference:

list.index(x) Return the index in the list of the first item whose value is x. It is an > error if there is no such item.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Clear input after submit on React Multi Form I can't seem to figure out how to clear the input once a new form is switched. I'm able to gather the input from every form and display it at the end, but for some reason information from the first input is shown in the second and third and requires manual deletion. Any help would be appreciated. Thanks
import React, { useState } from 'react';
import Form from './Form';
import Results from './Results';

    enter code here

function App() {
    const [state, setState] = useState({
        data: 1,
        Name: '',
        Email: '',
        City: ''
    });

    const nextStep = () => {
        setState({
            ...state,
            data: state.data + 1
        });
    };

    const handleChange = e => {
        setState({ ...state, [e.target.name]: e.target.value });
    };

    switch (state.data) {
        case 1:
            return (

                    <Form
                        button='Next'
                        nextStep={nextStep}
                        name='Name'
                        state={state.name}
                        handleChange={handleChange}
                    />

            );
        case 2:
            return (

                    <Form
                        button='Next'
                        nextStep={nextStep}
                        name='Email'
                        state={state.email}
                        handleChange={handleChange}
                    />

            );
        case 3:
            return (

                    <Form
                        button='Submit'
                        nextStep={nextStep}
                        name='City'
                        state={state.city}
                        handleChange={handleChange}
                    />

            );
        case 4:
            return (

                    <Results data={state} />

            );
        default:
            return 'Error';
    }
}

export default App;

import React from 'react';

const Form = ({ button, nextStep, name, state, handleChange }) => {
    const handleSubmit = e => {
        e.preventDefault();
        nextStep();
    };

    return (

            <form onSubmit={handleSubmit}>
                <input
                    type='text'
                    placeholder={name}
                    name={name}
                    value={state}
                    onChange={handleChange}
                />
                <input type='submit' value={button} />
            </form>

    );
};

export default Form;

A: The issue is that you are passing state.name into your Form components, when it should be state.Name, see below:
switch (state.data) {
case 1:
    return (

          <Form
            button='Next'
            nextStep={nextStep}
            name='Name'
            state={state.name} // < --------- This should be state.Name
            handleChange={handleChange}
          />

    );

A: I believe it's because you're not actually resetting your state when calling nextStep().
You're just merging new data but the other values: Name, Email, City stay the same
Fix:
const nextStep = () => {
        setState({
            data: state.data + 1,
            Name: '',
            Email: '',
            City: ''
        });
    };


text:
Q: Making USB devices writeable for users other than root I have a USB device, formatted FAT32 (for the widest possible compatibility), plugged into a system running CentOS 5 (yes, I know it's antiquated).
The whole purpose of its being plugged in is to receive backup files sent from two other systems.
But because (apparently) of UDEV default behavior, it mounts (along with its subdirectories) as "drwxr-xr-x 5 root root," refusing to accept anything sent to it, and refusing any "chown" (with an error message) or "chmod" (quietly failing).
Is there a way to change the default mounting behavior for USB FAT32 devices?
I will note that /etc/udev/rules.d on this box contains:
05-udev-early.rules  60-pcmcia.rules         90-alsa.rules
40-multipath.rules   60-raw.rules            90-dm.rules
50-udev.rules        60-wacom.rules          90-hal.rules
51-hotplug.rules     61-uinput-stddev.rules  95-pam-console.rules
60-libsane.rules     61-uinput-wacom.rules   98-kexec.rules
60-net.rules         85-pcscd_ccid.rules     bluetooth.rules

Note that the object here is to specifically avoid having to explicitly mount the bloody thing (and to not have to add a new fstab entry every time we plug in a different device)!
I've found "udevmonitor" (no "udevadm"), and when I plug the device in:
UEVENT[1618003563.847325] add@/devices/pci0000:00/0000:00:1d.7/usb1/1-5
UEVENT[1618003563.847392] add@/devices/pci0000:00/0000:00:1d.7/usb1/1-5/usbdev1.4_ep00
UEVENT[1618003563.849089] add@/devices/pci0000:00/0000:00:1d.7/usb1/1-5/1-5:1.0
UEVENT[1618003563.849130] add@/class/scsi_host/host4
UEVENT[1618003563.849155] add@/devices/pci0000:00/0000:00:1d.7/usb1/1-5/1-5:1.0/usbdev1.4_ep8b
UEVENT[1618003563.849180] add@/devices/pci0000:00/0000:00:1d.7/usb1/1-5/1-5:1.0/usbdev1.4_ep0a
UEVENT[1618003563.849203] add@/class/usb_device/usbdev1.4
UDEV  [1618003563.850150] add@/devices/pci0000:00/0000:00:1d.7/usb1/1-5
UDEV  [1618003564.062789] add@/devices/pci0000:00/0000:00:1d.7/usb1/1-5/usbdev1.4_ep00
UDEV  [1618003564.186813] add@/devices/pci0000:00/0000:00:1d.7/usb1/1-5/1-5:1.0
UDEV  [1618003564.298705] add@/devices/pci0000:00/0000:00:1d.7/usb1/1-5/1-5:1.0/usbdev1.4_ep8b
UDEV  [1618003564.298769] add@/devices/pci0000:00/0000:00:1d.7/usb1/1-5/1-5:1.0/usbdev1.4_ep0a
UDEV  [1618003564.308695] add@/class/scsi_host/host4
UDEV  [1618003564.614084] add@/class/usb_device/usbdev1.4
UEVENT[1618003569.124366] add@/devices/pci0000:00/0000:00:1d.7/usb1/1-5/1-5:1.0/host4/target4:0:0/4:0:0:0
UEVENT[1618003569.124416] add@/class/scsi_disk/4:0:0:0
UEVENT[1618003569.179432] add@/block/sda
UEVENT[1618003569.179466] add@/block/sda/sda1
UEVENT[1618003569.179485] add@/block/sda/sda2
UEVENT[1618003569.179508] add@/class/scsi_device/4:0:0:0
UEVENT[1618003569.179612] add@/class/scsi_generic/sg0
UDEV  [1618003569.290405] add@/devices/pci0000:00/0000:00:1d.7/usb1/1-5/1-5:1.0/host4/target4:0:0/4:0:0:0
UDEV  [1618003569.423752] add@/class/scsi_generic/sg0
UDEV  [1618003569.423806] add@/class/scsi_disk/4:0:0:0
UDEV  [1618003569.474344] add@/class/scsi_device/4:0:0:0
UDEV  [1618003569.505476] add@/block/sda
UDEV  [1618003569.861895] add@/block/sda/sda1
UDEV  [1618003569.919434] add@/block/sda/sda2
UEVENT[1618003570.253329] mount@/block/sda/sda2
UDEV  [1618003570.254399] mount@/block/sda/sda2

A udevinfo -p /block/sda/sda2 -q all gives me:
P: /block/sda/sda2
N: sda2
S: disk/by-id/usb-Seagate_BUP_Slim_BK_NA7LFNNT-part2
S: disk/by-path/pci-0000:00:1d.7-usb-0:5:1.0-scsi-0:0:0:0-part2
S: disk/by-uuid/6D63-17F2
S: disk/by-label/BACKUP
E: ID_VENDOR=Seagate
E: ID_MODEL=BUP_Slim_BK
E: ID_REVISION=0143
E: ID_SERIAL=Seagate_BUP_Slim_BK_NA7LFNNT
E: ID_TYPE=disk
E: ID_BUS=usb
E: ID_PATH=pci-0000:00:1d.7-usb-0:5:1.0-scsi-0:0:0:0
E: ID_FS_USAGE=filesystem
E: ID_FS_TYPE=vfat
E: ID_FS_VERSION=FAT32
E: ID_FS_UUID=6D63-17F2
E: ID_FS_LABEL=BACKUP
E: ID_FS_LABEL_SAFE=BACKUP

and a udevinfo -p /block/sda2 -1 gives me:
  looking at device '/block/sda/sda2':
    KERNEL=="sda2"
    SUBSYSTEM=="block"
    SYSFS{stat}=="      38      329      661      163        1        1        2        4        0      139      167"
    SYSFS{size}=="1952849920"
    SYSFS{start}=="411648"
    SYSFS{dev}=="8:2"

  looking at parent device '/block/sda':
    ID=="sda"
    BUS=="block"
    DRIVER==""
    SYSFS{stat}=="     112     1237     1811      361        1        1        2        4        0      241      365"
    SYSFS{size}=="1953525167"
    SYSFS{removable}=="0"
    SYSFS{range}=="16"
    SYSFS{dev}=="8:0"
. . .

I tried going into /etc/udev/rules.d/50-udev.rules, and changing
# all block devices
SUBSYSTEM=="block",             GROUP="disk", MODE="0640"
KERNEL=="root",                 GROUP="disk", MODE="0640"

to
# all block devices
SUBSYSTEM=="block",             GROUP="disk", MODE="0660"
KERNEL=="root",                 GROUP="disk", MODE="0640"

and rebooting; no effect
Further down I found this (AFTER "persistent_end"):
ACTION=="add", SUBSYSTEM=="usb_device", \
        PROGRAM="/bin/sh -c 'K=%k; K=$${K#usbdev}; printf bus/usb/%%03i/%%03i $${K%%%%.*} $${K#*.}'", \
        NAME="%c", MODE="0644"

and tried changing 644 to 664; also no effect (and besides, the subsystem is supposed to be "block").
Is there someplace else I could put something to specify a MODE parameter that would open USB device access up?
I noticed the
UEVENT[1618003570.253329] mount@/block/sda/sda2
UDEV  [1618003570.254399] mount@/block/sda/sda2

at the bottom of the udevmonitor output. I note that a grep on "mount" doesn't find a single rule responding to a "mount" event. Is there something I could add, that would respond to this, either changing the mount parameters or remounting the device?

A: chown and chmod doesn't work as FAT doesn't implement them, but when mounting, you can specify umask to allow everybody to wite to it or uid to set owner of everything on the flashdrive. If you are talking about ability to mount it, you can add entry into /etc/fstab with appropriate options and users. I guess with CentOS 5, you don't have that many things connecting to the device to warrant anything more complex then static fstab.

A: If you want to automount using udev you can add something like this to your udev rules:
# Symlinks

SUBSYSTEM=="block", KERNEL=="sd?",       ACTION=="add",    PROGRAM="/etc/udev/scripts/isremovable.sh %k", RESULT=="YES", SYMLINK="usb_flash_raw", RUN+="/etc/udev/scripts/mount.sh %k"
SUBSYSTEM=="block", KERNEL=="sd?[0-9]*", ACTION=="add",    PROGRAM="/etc/udev/scripts/isremovable.sh %k", RESULT=="YES", SYMLINK="usb_flash_p%n", RUN+="/etc/udev/scripts/mount.sh %k"

# umount

SUBSYSTEM=="block", KERNEL=="sd?",       ACTION=="remove", RUN+="/etc/udev/scripts/umount.sh > /dev/null 2> /dev/null"

Where the is removable can be something like this:
#!/bin/sh
DEV="`basename "$1" | sed 's|[0-9]*$||'`"
if [ "`find /sys -name "$DEV" | grep usb`" ]; then
        echo "YES"
        exit 0
else
        echo "NO"
        exit 1
fi

And the mount/umount scripts can be whatever you want, but be aware that handling safe unmounting is not easy.

A: I ultimately took a different approach.
I set up a cron job, running every five minutes, to transfer files uploaded to the backup users' home directories over to the USB drives, under root authority, and to keep them from transferring before the upload is complete, I have the upload client set up to send the files without an extension, then rename them to add the extension once the upload is complete.
Then I discovered that signing off the console unmounts the USB device. So much for using udev-based automounting.
So since the cron job's script was already present, I set up my own mountpoint, then added code to see if a properly set up USB device is present at the mountpoint, and if not, it attempts to mount the device.
Then I found the first pleasant surprise of this whole exercise: while mounting the device at my mountpoint keeps it from showing up under /media, it somehow does not stop Gnome from making it available on the desktop when I sign on.


text:
Q: How do you properly get/deploy ASP.NET MVC? I'm thoroughly confused about how to properly deploy ASP.NET MVC with my application. As far as I understand, there are the following ways you can get it on a machine:

*

*You can download a separate installer and install it on a machine that has the approprite .NET framework (although which MVC version requires which .NET framework?)

*Some versions come along with .NET framework itself (though I can't find which version of MVC is shipped with which version of .NET);

*Some versions are installed with Visual Studio (though again, no idea which versions are installed with which versions of VS). In this case, you can set Copy Locally to true for these references and perform a "bin deploy". You might need to add some extra references though (not sure which though).

*You can also download MVC as a NuGet package, in which case it also downloads some other unrelated packages like WebPages, Infrastructure and Razor (which is my personal WTF - wasn't Razor a core part of MVC?). In this case the build process will automatically do a "bin deploy" by default (I think...)

So... WTF? What is the proper way to add MVC to your development workstation, what is the proper way to add the references to your project (NuGet? GAC?), and what is the proper way to deploy it to the target server (separate installer? .NET installer? bin deploy?)

A: "Proper" Development:
The "proper way" (by which I mean standard/redistributable way) would be using Nuget for your references. This means you can easily manage different versions and anybody else working on your project has a standard repository from which to pull the external requirements.
The NuGet documentation has a decent explanation of how to add references.
To install the appropriate version of MVC for developing through Visual Studio, just download and install it from the ASP.NET MVC website. This will install the necessary templates for you to create a new MVC project in Visual Studio. This will also include the necessary binaries, etc.
"Proper" Deployment:
Use bin deploy to deploy to your webserver. This means you don't need full admin priviledges to install the MVC requirements.
Phil Haack's guide will walk you through the process of bin deploying MVC3+
Keep in mind, the web server does need the appropriate .NET platform installed. You should install this via the appropriate redistributable installer if it is not already installed on the server.

A: Referring to the deployment i publish my asp.net app (i usually make web applications) to the file system in a directory (you can set also a server there, but i don't like it) and make an upload to the server with an FTP client of all the deployed folders. All the changes that i make to the app after (like bug correction) i deploy all the app again and upload single parts.
I hope i get your question in part, this is my first answer in SO.


text:
Q: Add a css class or span to a .js variable I have a working countdown timer "days, hours, minutes, seconds" and I need to change the color of the seconds "var" from white to yellow while the other var's will keep the white color.
The problem is that the whole countdown date is being placed on a single div and I cannot add a specific class or a span to the "seconds" variable.
I tried many different solutions but none seems to work in this case so I decided to ask for help and make a Question.
The HTML.

The JS.
CountDownTimer('06/01/2016 06:00 AM', 'countdown');

    function CountDownTimer(dt, id)
    {
        var end = new Date(dt);

        var _second = 1000;
        var _minute = + _second * 60;
        var _hour = _minute * 60;
        var _day = _hour * 24;
        var timer;

        function showRemaining() {
            var now = new Date();
            var distance = end - now;
            if (distance < 0) {

                clearInterval(timer);
                document.getElementById(id).innerHTML = 'end';

                return;
            }
            var days = Math.floor(distance / _day);
            var hours = Math.floor((distance % _day) / _hour);
            var minutes = Math.floor((distance % _hour) / _minute);
            var seconds = Math.floor((distance % _minute) / _second);

            document.getElementById('countdown').innerHTML = days + ' ';
            document.getElementById('countdown').innerHTML += hours + ' ';
            document.getElementById('countdown').innerHTML += minutes + ' ';
            document.getElementById('countdown').innerHTML += seconds + ' ';

        }

        timer = setInterval(showRemaining, 1000);
    }

Working JS FIDDLE here where you can see for yourself:
https://jsfiddle.net/baqc6nx2/1/
And here is the image explaining how the seconds var should be colored yellow and the others white.

Sorry for my bad English, and thank you for your time.
EDIT:---------------------------------------------------------------
This is not a duplicate, I know the last child selectors, but in this case it wont work, I tried.
Edit-----------------------------------------------------------------
TGO Helped me and now it is working, please reopen the question so I can complete it.

A: Here is an updated fiddle which solves your problem. http://jsfiddle.net/baqc6nx2/2
For convenience, this is the changed line of code:
document.getElementById('countdown').innerHTML += '' + seconds + ' ';

Here I create a span tag, give it the proper CSS style to turn the color yellow, and the seconds value is put inside the span element.


text:
Q: Populating the Rest of a Row/Avoiding Violation of Null Constraint I have a table (called new_table). It consists of 4 fields. id (with PK and NOT NULL) and field1, field2, and field3 (which have do not have NOT NULL).
The only data populated in the table are the 1 and 2 in the id field. (I'll include a screenshot below) Now I want to populate the rest of those two rows with some values by using the query below.
INSERT INTO new_table (field1, field2, field3)
VALUES
 ('value1', 'value2', 'value3'),
 ('value4', 'value5', 'value6');

And here is what I always get:

"ERROR:  null value in column "id" violates not-null constraint
  DETAIL:  Failing row contains (null, value1, value2, value3)."

Is it thinking that I'm trying to populate the third and fourth rows? How do I just populate the rest of rows 1 and 2 with those values?
table currently looks like this

A: You are inserting new rows as you suspected (notionally lets consider them row 3/4) and not updating rows 1 and 2. To update the existing rows, use an update statement.
UPDATE new_table
SET
    field1= 'value1'
    , field2='value2'
    , field3='value3'
WHERE id = 1;

UPDATE new_table
SET
    field1= 'value4'
    , field2='value5'
    , field3='value6'
WHERE id = 2;

A: You would do this in an update, and you can phrase this kind-of-similarly to the insert:
update new_table t
    set field1 = v.field1,
        field2 = v.field2,
        field3 = v.field3
    from ( (<id1>, 'value1', 'value2', 'value3'),
           (<id2>, 'value4', 'value5', 'value6')
         ) v(id, field1, field2, field3)
    where t.id = v.id;

<id1> and <id2> are however you define the match to the "first two rows".


text:
Q: How to count the number of radio button groups (by name attribute)? There are three single selections on document.
<input  type="radio" name="delete1">yes<input  type="radio" name="delete1">no<input  type="radio" name="delete1">all
<input  type="radio" name="delete2">yes<input  type="radio" name="delete2">no
<input  type="radio" name="delete3">yes<input  type="radio" name="delete3">no

There are 7 elements with document.getElementsByTagName('input').
It is 3 groups for people to select,every group can select 1 input.
I want to get the number of groups not the number of input tags in each groups.

A:

groups = {};
var all_input = document.querySelectorAll('input[type="radio"]');
for (var i = 0; i < all_input.length; ++i) {
  if (!(all_input[i].name in groups)) {
    groups[all_input[i].name] = 0;
  } else {
    groups[all_input[i].name] += 1;
  }

}
var message = Object.keys(groups).length;
console.log(message);
alert(message)
<input type="radio" name="delete1">yes
<input type="radio" name="delete1">no
<input type="radio" name="delete1">all
<input type="radio" name="delete2">yes
<input type="radio" name="delete2">no
<input type="radio" name="delete3">yes
<input type="radio" name="delete3">no

A: You should be able to count the number of unique name attributes like this

var inputs = document.querySelectorAll('input[type="radio"][name]'),
  inputsByName = Array.prototype.reduce.call(inputs, function(map, input) {
    if (!Object.prototype.hasOwnProperty.call(map, input.name)) {
      map[input.name] = [input];
    } else {
      map[input.name].push(input);
    }
    return map;
  }, Object.create(null));

console.log('Inputs by name: ', inputsByName);
console.log('Unique radio input group count =',
    Object.keys(inputsByName).length);
<input type="radio" name="delete1" value="yes">yes
<input type="radio" name="delete1" value="no">no
<input type="radio" name="delete1" value="all">all
<input type="radio" name="delete2" value="yes">yes
<input type="radio" name="delete2" value="no">no
<input type="radio" name="delete3" value="yes">yes
<input type="radio" name="delete3" value="no">no

This has the added bonus of providing you with a map of all the radio button elements by name.

A: ES6 Set.
.getElementsByTagName returns an HTMLCollection which behaves similar to an array so that document.getElementsByTagName('input')[2] references the 3rd input element in the DOM.
If you want to count the unique number of radio input groups (those with same name attribute) simply get the HTMLCollection of all radio inputs then loop over them.  Inside the loop, if the name is new .push that name to an array called groups and finally a numberOfGroups.length should give you your number.

var doc = document;
var inputs = doc.getElementsByTagName('input');
var groups = [];

for (var i = 0; i < inputs.length; ++i) {
  groups.push(inputs[i].name)
}

console.log(Array.from(new Set(groups)));
console.log(Array.from(new Set(groups)).length);
<input type="radio" name="fruit">apple</input>
<input type="radio" name="fruit">orange</input>
<input type="radio" name="fruit">grape</input>

<input type="radio" name="vegetable">lettuce</input>
<input type="radio" name="vegetable">tomato</input>

<input type="radio" name="seasoning">salt</input>
<input type="radio" name="seasoning">pepper</input>

A: Did you mean something like this?
var a = document.getElementsByTagName('input');
var b = [a.delete1,a.delete2,a.delete3];


text: Q: What is the most inefficient to pack convex object? Suppose that you have an infinite number of identical $n$-dimensional convex objects.  If the objects are packed optimally (so as to minimize the interstitial space), what object would result in the most interstitial space as a proportion of all of $\mathbb{R}^n$?


text:
Q: xslt xsl:result-document overwrites file Hi everyone i have xsl script, which converts xml to csv and save result to files via <xsl:result-document href="file:///C:/****/*****/result-case.txt" method="text">, but i have a problem. After each xml transformation it overwrite result file and i lose result from previous transformation. How can i transform 100000 xml ,and get all data in one file?
I am using xsl version 2.0.

A: In general, with XSLT 2 or 3, if you want to create a transformation that transforms several files to single result, I would suggest to start with a named template; in XSLT 3 for that you have xsl:template name="xsl:initial-template", in XSLT 2 you need use any template name you want to use as an entry point e.g. xsl:template name="main".
As for the input documents, depending on the processor you might be able to use the uri-collection (XSLT 3) or at least the collection function (XSLT 2) to process a collection of input documents e.g. in Saxon 9 to process all .xml documents from a certain directory you can use e.g. uri-collection('file:/root/dir/subdir/?select=*.xml').
You can then push such a collection to your existing templates, you only have to make sure you use your xsl:result-document once e.g.
<xsl:param name="folder-uri" as="xs:string">file:/root/dir/subdir/</xsl:param>

<xsl:template name="xsl:initial-template">
  <xsl:result-document href="result.csv" method="text">
     <xsl:apply-templates select="uri-collection($folder-uri || '?select=*.xml') ! doc(.)/*"/>
  </xsl:result-document>
</xsl:template>

To run such transformation starting with a named template I would suggest to move away from the JAXP API that expects a single source and use an API designed to work with XSLT 2 or 3, i.e. in the case of Saxon 9 the s9api with XsltTransformer (http://saxonica.com/html/documentation/javadoc/net/sf/saxon/s9api/XsltTransformer.html#setInitialTemplate-net.sf.saxon.s9api.QName-) or Xslt30Transformer (http://saxonica.com/html/documentation/javadoc/net/sf/saxon/s9api/Xslt30Transformer.html#callTemplate-net.sf.saxon.s9api.QName-net.sf.saxon.s9api.Destination-).


text:
Q: CNG (Cryptography Next Generation) Provider doesn't work under regular user account in Win7 I used an example of CNG provider from CSPDK to implement my own CNG Hash Provider. But as appeared when I use PKCS7 (Signed Message) WinApi functions CNG provider doesn't work. CryptMsgOpenToEncode function reports 0xC0000005 error, which appears also when there is no provider at all. Under admin account everything works fine. If I use MicroSoft example of CNG Hash Provider directly it reports same error. Also if I try to install provider under user account without admin permissions I get 0xC0000022 error from BCryptRegisterProvider function. Also the provider doesn't work if UAC (User Access Control) is enabled.
What is the correct way to install CNG provider (it could be done under admin) in order to make it work under user account?


text:
Q: Inserting ASCII symbols into a String (Swift) I'm trying to insert a symbol with ASCII code 255 (Telnet IAC) into a String, but when converting the data back to utf8 I'm getting a different symbol:
var s = "\u{ff}"
print(s.utf8.count) // 2
try! s.write(toFile: "output.txt", atomically: true, encoding: .utf8)

The file contains C3 BF, not FF. I've also tried using
var s = "\(Character(UnicodeScalar(255)))"

but this produced the same result. How to escape it properly?

A: ASCII defines 128 characters from 0x00 to 0x7F. 0xFF (255) is not included.
In Unicode, U+00FF (in Swift, "\u{ff}") represents "ÿ" (LATIN SMALL LETTER Y WITH DIARESIS).
And its UTF-8 representation is 0xC3 0xBF. See UTF-8, characters with code point from U+0080 to U+07FF are represented with two-byte sequence.
Also you need to know that 0xFF is not a valid byte in UTF-8 byte sequence, which means you cannot get any 0xFF bytes in UTF-8 text file.
If you want to output "\u{ff}" as a single-byte 0xFF, use ISO-8859-1 (aka ISO-Latin-1) instead:
try! s.write(toFile: "output.txt", atomically: true, encoding: .isoLatin1)


text:
Q: React Native Not Running projects that I copied from Windows machine to Ubuntu I just moved to Ubuntu from Windows 10, I have installed react-native on my laptop and everytime I do react-native init it creates a project as expected. react-native run-android & react-native start commands are working as you'd expect them to be.
My main problem is I just copied a react native project from my Windows 10 machine to Ubuntu and now everytime I do react-native run-android This is the error I see on my console
This is the error I see on my console

Starting JS server...
  Running /home/adeel/Android/Sdk//platform-tools/adb reverse tcp:8081 tcp:8081
  Building and installing the app on the device (cd android && ./gradlew installDebug...
  Could not install the app on the device, read the error above for details.
  Make sure you have an Android emulator running or a device connected and have set up your Android development environment:
  https://facebook.github.io/react-native/docs/android-setup.html

A: The problem was the React Native project was created in Windows and I was trying to run it in a Linux based platform. So what I did was I created a brand new project in my Linux environment and copied my RN code in the newly created project.
This was I believe due to the android file it created which is platform dependent. Windows and Linux have different GRADLE files. I hope this helps anyone who is having this issue.

A: Seems like it is not recognizing your device/emulator. Run "adb devices" to check. I guess you did the whole Android setup and installed Android Studio (SDK).


text:
Q: Using XOR to encode state A sequence of bits encode the state of a game.
In order to encode subsequent game state changes the difference is encoded using XOR (to take advantage of an assumption that most game states will be closer to the starting state than not so to enable run-length encoding).
eg.
state 1:                         1000000000...
state 2:                         1000001000...
diff1 (XOR state 1 and state 2): 0000001000... => this is recorded

Using this diff, how do I get back to the actual current state (state 2)? Another XOR?


text:
Q: Difference between logic programming and automated theorem proving What is the difference between logic programming and automated theorem proving (ATP) (e.g. with E-Prover, Spass or Princess)?
I searched a lot and the only information I found is that ATP is the precursor of logic programming. But I do not see the difference. But I guess it is more than the syntax.

A: As far as the Prolog part of the question is concerned, this was best said by Richard O'Keefe:

Prolog is an efficient programming language because it is a stupid theorem prover.

Thus, there is a connection between Prolog and theorem proving. Prolog has some features of a theorem prover, for example, it searches for proofs or rather resolution refutations, but it does so in an incomplete way that is more tailored to a general purpose programming language.
Of course, the comparatively close affinity between Prolog and theorem provers makes Prolog an excellent choice to implement more full-fledged theorem provers.
In fact, it is comparatively easy to augment and extend the incomplete default execution strategy of Prolog so that the search becomes more complete.
Note though that Prolog also exhibits some extra-logical features that fall outside the scope of theorem proving and can in fact often get in the way of declarative reasoning. See also logical-purity.


text:
Q: A more efficient Benford's Law code? An academic question. This function computes Benford's Law for integers up to maxvalue, and prints a summary table. I've tried a nested for-loop method, a dict method, and this collections method.  The latter (code below) seems the fastest (timeit result: 1.4852424694 sec), but is there a faster and memory-efficient method for cycling through so many possibilities?
from __future__ import print_function
def BenfordsLaw4(maxvalue = 10**6):
    from collections import Counter
    sqList = (str((i+1)**2)[0] for i in range(maxvalue))
    BenfordList = Counter(sqList)

    print("Benford's Law for numbers between 1 and", maxvalue, "\nDigits,\t\t\t", "Count,\t\t\t", "Percentage")
    for i,j in sorted(BenfordList.iteritems()):
        print(',\t\t\t\t'.join([str(i), str(j), str(j*100./maxvalue)+' %']))

A: Changing the main loop to this:
def BenfordsLaw4(maxvalue = 10**6):
    BenfordList = {str(i+1):0 for i in range(9)}
    for i in (str((i+1)**2)[0] for i in xrange(maxvalue)):
        BenfordList[i] += 1

takes the time from about 1.55s to about 1.25; however taking out the **2 takes the time down to about 0.32s.
In other words, the vast majority of your time is spent squaring your operands.
Curiously, I was able to shave about 0.05s by using "%s" % ((i+1)**2) instead of str((i+1)**2).


text:
Q: Can Roslyn generate source code from an object instance? Using the Roslyn API with Visual Studio 2015, can I convert an object instance to source code? Can I create an extension method like ".ToSourceCode()" as shown below?
class Foo { }
class Program
{
    static string classSourceCode = "class Foo { }";
    static void Main()
    {
        var instance = new Foo();
        var instanceSourceCode = instance.GetType().ToSourceCode();
        System.Diagnostics.Debug.Assert(instanceSourceCode == classSourceCode);
    }
}

A: No. However, ILSpy can.
Based on the comments on the question and what I understand about Roslyn, decompilation is not supported. However, thanks to @Bradley's ILSpy tip, there is a solution:

*

*Download the ILSpy binaries from http://ilspy.net/

*Reference the following assemblies: ICSharpCode.Decompiler.dll, ILSpy.exe, Mono.Cecil.dll, ILSpy.BamlDecompiler.Plugin.dll

*Implement the ".ToSourceCode()" extension method as shown below:

using System;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using ICSharpCode.Decompiler;
using ICSharpCode.ILSpy;
using Mono.Cecil;
class Foo { }
class Program
{
    static string classSourceCode = "using System; internal class Foo { } ";
    static void Main()
    {
        var instance = new Foo();
        var instanceSourceCode = instance.GetType().ToSourceCode();
        System.Diagnostics.Debug.Assert(instanceSourceCode == classSourceCode);
    }
}

static class TypeExtensions
{
    public static string ToSourceCode(this Type source)
    {
        var assembly = AssemblyDefinition.ReadAssembly(Assembly.GetExecutingAssembly().Location);
        var type = assembly.MainModule.Types.FirstOrDefault(t => t.FullName == source.FullName);
        if (type == null) return string.Empty;
        var plainTextOutput = new PlainTextOutput();
        var decompiler = new CSharpLanguage();
        decompiler.DecompileType(type, plainTextOutput, new DecompilationOptions());
        return Regex.Replace(Regex.Replace(plainTextOutput.ToString(), @"\n|\r", " "), @"\s+", " ");
    }
}


text:
Q: It would have been nice to know that shared links include my user id I noticed that every short-link/permalink that I share while I'm logged in includes my user id.
It would have been really nice if the UI had highlighted this fact in the link sharing popup so that people who don't always intend to share their identity elsewhere can remain secure knowing that they haven't.


text:
Q: Draw nicer shadow under an arrow line My existing code draw a fixed 'shadow' color under an arrow line. But from my view, it is urgly. I need a nicer real shadow w/ displacement (Horizontal and vertical),Opacity and blur custom arguments. How to achieve this kind of nice shadow effect in C#?
using (GraphicsPath _Path = new GraphicsPath())
{
    _Path.AddLine(mouseDownX, mouseDownY, mouseUpdX, mouseUpY);
    // Draw the shadow.
    mygraphics.TranslateTransform(3, 3); //displacement
    using (Pen _Pen = new Pen(Color.FromArgb(30, 0, 0, 0), hPen.Width))
    {
         _Pen.CustomStartCap = adjustableArrowCap_0;
         mygraphics.DrawPath(_Pen, _Path);
    }
    mygraphics.ResetTransform();
}
mygraphics.DrawLine(hPen, mouseDownX, mouseDownY, mouseUpdX, mouseUpY);

I attach a picture to show what is the nicer shadow means.


text:
Q: Consul, vault and postgres containers don't communicate I'm trying to set up Consul with Vault for secrets management for Postgres with Docker. Here is my configuration
Dokcerfile:
FROM python:3.6-slim

ENV VAULT_VERSION 0.11.1
ENV CONSUL_VERSION 1.2.3

RUN apt-get update \
  && apt-get install -y \
     build-essential \
     git \
     curl \
     wget \
     vim \
     net-tools \
     iputils-ping \
     dnsutils \
     zip \
     unzip \
  && wget -O /tmp/vault.zip "https://releases.hashicorp.com/vault/${VAULT_VERSION}/vault_${VAULT_VERSION}_linux_amd64.zip" \
  && unzip -d /bin /tmp/vault.zip \
  && chmod 755 /bin/vault \
  && rm /tmp/vault.zip \
  && wget -O /tmp/consul.zip "https://releases.hashicorp.com/consul/${CONSUL_VERSION}/consul_${CONSUL_VERSION}_linux_amd64.zip" \
  && unzip -d /bin /tmp/consul.zip \
  && chmod 755 /bin/consul \
  && rm /tmp/consul.zip \
  && apt-get clean \
  && rm -rf /var/lib/apt/lists/*

docker-compose.yml:
version: '3.6'

services:
  consul:
  container_name: consul.server
  command: agent -server -bind 0.0.0.0 -client 0.0.0.0 -bootstrap-expect=1
  image: consul:latest
  volumes:
    - ./config/consul/config:/consul/config
  ports:
    - "9300:9300"
    - "9500:9500"
    - "9600:9600/udp"
  networks:
    - consul_network

vault:
  container_name: vault.server
  image: vault
  ports:
    - "9200:8200"
  cap_add:
    - IPC_LOCK
  depends_on:
    - consul
  environment:
    - VAULT_LOCAL_CONFIG={"backend":{"consul":{"address":"${LOCAL_IP}:9500","advertise_addr":"http://${LOCAL_IP}", "path":"vault/"}},"listener":{"tcp":{"address":"0.0.0.0:8200","tls_disable":1}}}
  command: server
  networks:
    - consul_network

db:
  image: postgres:10.5-alpine
  volumes:
    - postgres_data:/var/lib/postgresql/data/
  environment:
    - CONSUL_HTTP_ADDR=${LOCAL_IP}:9500
    - VAULT_ADDR=http://${LOCAL_IP}:9200
  networks:
    - consul_network
    - database_network

networks:
  consul_network:
    driver: bridge
  database_network:
    driver: bridge

volumes:
  postgres_data:

And also I'm keeping LOCAL_IP in .env file:
LOCAL_IP=10.0.2.15

(I'm developing on Vagrant machine hence the address).
I was following this tutorial and I assume db container should have access to both consule.server and vault.server from but it doesn't. (?)
Secondly, I've connected into vault.server and tried to get vault status which responded with
Error checking seal status: Get https://127.0.0.1:8200/v1/sys/seal-status: http: server gave HTTP response to HTTPS client

I have just started learning about Docker and frankly I don't even know where to begin looking for some answers so if anyone could give me direction I'd be more than grateful.
Cheers.

A: The VAULT_ADDR environment variable needs to be set to http://127.0.0.1:8200
When normally starting the vault server you'd see this in the output when running with TLS disabled:
You may need to set the following environment variable:

    $ export VAULT_ADDR='http://127.0.0.1:8200'


text:
Q: Jquery leaderboard difference calculation I am working on Leaderboar table project. I need calculate leaders position on this week from last week position.
For example, if user is 1 place on this week, but on last week on 3 place, difference is +2 on green.
Problem is that, that i have no CMS data from last week position, I can get only result points that is set on columns.
Is there a way to calculate hidden fields, values, from columns points and after that make different column with + and - place counts:
100 - 2 place    250 - 3 place = -1
50 - 1 place     350 - 2 place = -1
200 - 3 place    400 - 1 place = +2

Here is my starting demo code: http://jsfiddle.net/Y2DS5/43/ also count is showing wrong difference.

A: You need to convert it into an integral value using parseInt():
$(".mytable tr").not(":first").each(function() {
  // Use this: vvvvvv------------------------------------vvvv
  var td1 = parseInt($(this).children("td.pricea").text(), 10),
      td2 = parseInt($(this).children("td.priceb").text(), 10),
      difference = (td1 - td2),
      absNum = Math.abs(difference),
      largerNum = td1 > td2 ? td1 : td2,
      percentage = (absNum / largerNum).toFixed(2);

  if (difference < 0)
    $(this).children("td.out").text(percentage).addClass("green");
  else
    $(this).children("td.out").text(percentage).addClass("red");
});

Fiddle: http://jsfiddle.net/kx20s917/


text:
Q: iOS Black bar issue when using auto layout I am using Auto layout in my app. I have added constraints on my view. It is working fine in all iPad simulator and iPhone 4s. But when I run this app on iPhone 5s or greater it is showing black bar on left and right side of the screen.

A: Go to your Storyboard.  Click on the UIView.  Click on the third icon in the auto-layout stuff on the bottom.  Now click all of the red line things in the top (stuff circled in pink in below picture) to be set at zero.

EDIT: another possibility is that you have constrained the size of the view in some way. I would try doing reset to suggested constraints, and then set the constraints illustrated above for the background (grey) view so it fills everything up, but do not set it to have an explicit size.
EDIT 2: If that grey thing in the background is a UIImage, I bet the issue is that it is in Aspect Fit. Change the content mode to Aspect Fill and I think it should work.

A: I have also faced this same issue, when I am converting my iPad app to Universal app.
Ref below Image: You can see Main Interface is not set

After that add LaunchScreen.storyboard to your project if not exists.
Ref this Image: Goto your ProjectName-Info.plist add following key

<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>

Now run the project


text:
Q: Why console.log throws an error when used inside a Web Worker in firefox? When I use console.log to write some log to the browser from a web worker it works without issues in Chrome and IE 11 but not in Firefox. Is there any reason behind that? Or should I use a different kind of logging for web workers?

A: The first Firefox version with support for a console in workers is Firefox 29, which will be released in late April.
Unfortunately, there is still no spec for console, so it behaves pretty differently in different browsers in terms of where it's available and how it works.


text:
Q: C++ - How to create factory methods if class does not know about another class? Let's say I have two base classes: A and B. They are both defined in different libraries. A knows about B but not the other way around.
Let's say I have some derived classes as well: C derives from A and D derives from B
I always create an object of type B first before creating an object of type A. So for example:
B *b = B::CreateB(some object); // static factory method that either creates either B or D.
...
A *a = A::CreateA(some object) // static factory method that either creates A or C

Ideally, I would like to be able to do this:
B *b = B::CreateB(some object); // static factory method that either creates either B or D.
...
A *a = b->CreateA() // dynamic factory method that either creates A or C based on the type of b.

The problem is that B is in a common library that does not know anything about the library A is in (and I don't want to change that).
What I would like to avoid is having to do the same work for determining what type to create two times. The "some object" that is passed into the methods is a complex object that I need to dig into in order to find out which type to create. It's not as simple as saying "if some object is this, create B, else create D". I know that I could have the base class store what type it is and use that info when creating A, but then that would defeat the purpose of having these class structures. Is there a cleaner way to create A based on what type B is?

A: Maybe solution is to use visitor pattern.
class B;
class D;
class BVisitor {
public:
   virtual void visit(B&);
   virtual void visit(D&);
};

class B {
public:
   virtual void accept(BVisitor& bVisitor) { bVisitor.visit(*this); }
};

class D: public B {
public:
   virtual void accept(BVisitor& bVisitor) { bVisitor.visit(*this); }
};

So, your B/D library does not know nothing about A/c classes.
Then use the real type information of B in this way:
class AFactory : public BVisitor {
public:
   A* getCreatedObject() { return a; }
   void visit(B& b) { a = new A(); }
   void visit(D& d) { a = new D(); }
private:
   A* a = nullptr;
};

A* A::createA(B& b) {
   AFactory af;
   b.accept(af);
   return af.getCreatedObject();
}

This is just a scheme of solution. Pass in constructor of AFactory whatever extra-data you need.


text:
Q: access elastic search using C# after setting up security I setup security following this link. This means that I have to now enter a username and password when I access:
http://localhost:9200/

Let us say the username is un and the pw is pw234. How do I now use this in my C# code. I tried:
public static ElasticClient GetClient(string indexName)
{
    var node = new Uri(ConfigurationManager.AppSettings["Search-Uri"]);
    var settings = new ConnectionSettings(node)
      .DefaultIndex(indexName);
      settings.ThrowExceptions(alwaysThrow: true); // I like exceptions
      settings.PrettyJson(); // Good for DEBUG
      settings.RequestTimeout(TimeSpan.FromSeconds(300));
      settings.BasicAuthentication("un", "pw234");
    return new ElasticClient(settings);
}

Do I have to use BasicAuthentication? Please note that this is by no means production code. I would never hardcode the username and password like this. Thanks.

A: Basic Authentication is one authentication scheme that built-in user accounts (native realm) can use to authenticate. Other token-based authentication services are supported:

*

*Token service using Bearer (authentication scheme) tokens, based on the OAuth2 specification

*API keys using ApiKey (authentication scheme) tokens
Typically, for applications interacting with Elasticsearch (i.e. non-users), you would probably use one of these token based authentication services. The client exposes configuring API keys for authentication on ConnectionSettings
public static ElasticClient GetClient(string indexName)
{
    var node = new Uri(ConfigurationManager.AppSettings["Search-Uri"]);
    var settings = new ConnectionSettings(node)
      .DefaultIndex(indexName)
      .ThrowExceptions(alwaysThrow: true) // I like exceptions
      .PrettyJson() // Good for DEBUG
      .RequestTimeout(TimeSpan.FromSeconds(300))
      .ApiKeyAuthentication("<id>", "<api key>");

    return new ElasticClient(settings);
}

Bearer tokens can also be used with the client, but there is no dedicated method exposed to set the header as there is for basic authentication and api key authentication, so the .GlobalHeaders() method on ConnectionSettings and on a per request basis (through .RequestConfiguration()) needs to be used.
In addition to the native realm, Elasticsearch also supports the following realms

*

*LDAP user authentication

*Active Directory user authentication

*PKI (Client certificate) user authentication

*File-based user authentication

*SAML authentication: intended to be used in conjunction with Kibana for SSO

*Kerberos authentication

*OpenID Connect authentication


text:
Q: Checkbox value is refreshed after page reload in node JS "I am creating TODO list using Node as backend. after adding every new item, a checkbox is also generating in front of them so I can apply "CSS line-through" to let user know that item is done or of no use. But when I add another item, the page refreshes and that checkbox is unchecked as I am not storing that value anywhere. Can you tell me how to store the value of that checkbox in the backend?
HTML -

    <% for (var i=0; i<newListItems.length; i++) { %>

        <input type="checkbox" id="checkBox">

 <%= newListItems[i] %>

    <% } %>
    <form action="/" method="post" class="item">
        <input class="inputBox" type="text" name="newItem" placeholder="New item" autocomplete="off" required="required">
        <button type="submit" name="list" value=<%= listTitle%>> +</button>
    </form>

Node JS -
const items = [];
app.post("/", function(req, res){
let item = req.body.newItem;
    items.push(item);
    res.redirect("/");

});

A: The answer involves a lot of code, so I will give you a set of steps that can help in your case.

*

*You need to change your data scheme. Currently looks like you are just storing the string in an array of items. You need to change it to be array of objects. Each object should have the field task and done. So you could know which task is done or not.
app.post("/", function(req, res) {
    let item = req.body.newItem;
    items.push({ name: item, done: false });
    res.redirect("/");
});

*Next step will be adding an endpoint that will be changing the done field of an array item to true.

*Then on a front-end you will need to write some JS code that will be sending an HTTP request to the endpoint that marks the task as done. You need to use AJAX call for that, for example, NPM package axios.

*Change the template to reflect the changes to the data. e.g. instead of  <%= newListItems[i] %> do <%= newListItems[i].name %> and add logic to render checked checkbox based on done property.
It worth to mention, that you should not store data in memory, because once the process is done, you will lose your data. It is okay for learning purposes, but in production, you should use a database.


text:
Q: Navigation bar disappear When i do as the Xcode doc says, on "Your second iOS App", after i add some code, the navigation bar just disappeared.
i believe i didn't add some code associated with the bar.
what can i do to take it back?
and my issue is different from this body's Navigation bar disappeared from my storyboard items
Thanks a lot. sorry to have not enough reputation to post a pic

A: Wow, so bad. I was nervous at that time. So i do it again with starting a complete code. I didn't remember the problem i got.

A: Did you complete the BirdWatching app and then added the code? Did you mess with the navigation controller in the Main.storyboard by any chance?


text:
Q: How can I disable in LimeSurvey the Registration e-mail confirmation? How can I disable in LimeSurvey the "Registration" e-mail confirmation after an user insert his name, surname and e-mail address? What I want is the user starts the survey right away without need to confirm his email in order to start the survey.
OBS: Anonymized responses is set to 'NO'
I'm using LimeSurvey Version 2.00+ Build 130923.
Anyone can help me with that? Thanks.

A: With 2.05 : you can replace default register system with a plugin. See https://github.com/Shnoulle/LS-replaceRegister for some example.
With 2.06 (next version), you have new events to do it more easily beforeRegister can redirect to the survey with the good token.


text:
Q: angular ui.router html5mode unable to reload in apache I'm trying to remove '#' from urls.
Using link with ui-sref or href attributes navigation works properly, but accessing directly to the same url, or refreshing page or pressing enter into url bar of the browser i get 404 not found error.
I enabled html5 mode:
$locationProvider.html5Mode(true);

Added base tag in head before any inclusion:
<base href="/folder/" />

Here is .htaccess file content (copied from angular-ui faq):
RewriteEngine on

# Don't rewrite files or directories
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]

# Rewrite everything else to index.html to allow html5 state links
RewriteRule ^ /folder/index.html [L]

Seems to be a problem related to .htaccess file.
What is wrong?

A: I've to:

*

*enable AllowOverride in /etc/apache2/apache2.conf (enable AllowOverride)

*enable mod_rewrite, from terminal a2enmod rewrite

*restart apache from terminal service apache2 restart


text:
Q: How to dynamically assign hash with $1, $2, $3 I want to dynamically create a %detail hash, without using an eval statement.
This code is working fine with an eval statement, but is there any better way to perform this without using eval?
my @input=('INFO: Vikram 32 2012','SAL: 12000$','ADDRESS: 54, junk, JUNK');

my %matching_hash= (
                    qr/^INFO:\s*(\S+)\s+(\S+)\s+(\S+)/ =>['name','age','joining'],
                    qr/^SAL:\s*(\S+)/ => ['salary'],
                    qr/ADDRESS:\s*(.*)/ =>['address']
                    );
my %detail;
while(my ($regex, $array) = each(%matching_hash)) {
    foreach (@input){
        if(/$regex/) {
            for(my $i=0;$i<=$#$array; $i++) {
                $j=$i+1;
                eval '$detail{$array->[$i]} = $$j';
            }
        }
    }
}
use Data::Dumper;

print Dumper(\%detail);
++++++++++++++

$VAR1 = {
          'name' => 'Vikram',
          'address' => '54, junk, JUNK',
          'age' => '32',
          'joining' => '2012',
          'salary' => '12000$'
        };

A: Change the for loop:
for(my $i=0;$i<=$#$array; $i++) {
    $j=$i+1;
    eval '$detail{$array->[$i]} = $$j';
}

by:
@detail{@{$array}} = ($_ =~ $regex);

A: If you can use lastest version of Perl, see to this notation (?<name>...) in regexp perlre docs It's more clear then using $1, $2, $3 etc.
SCRIPT
use v5.14;
use Data::Dumper;

my @inputs = ( 'INFO: Vikram 32 2012', 'SAL: 12000$','ADDRESS: 54, junk, JUNK' );

my %matching_hash= (
    qr/^INFO:\s*(?<name>\S+)\s+(?<age>\S+)\s+(?<joining>\S+)/ => [ 'name', 'age', 'joining' ],
    qr/^SAL:\s*(?<salary>\S+)/                                => [ 'salary' ],
    qr/ADDRESS:\s*(?<address>.*)/                             => [ 'address' ],
);

my %detail;
while (my ($regex, $array) = each %matching_hash ) {

    INPUT:
    foreach my $input ( @inputs ) {

        next INPUT if not $input =~ m{$regex};

        for my $name ( @$array ) {
            $detail{$name} = $+{$name};
        }
    }
}

say Dumper( \%detail);

OUTPUT
$VAR1 = {
          'name'    => 'Vikram',
          'address' => '54, junk, JUNK',
          'age'     => '32',
          'joining' => '2012',
          'salary'  => '12000$'
        };

A: Relevant part:
if(my @m = /$regex/) {
  for(my $i=0;$i<=$#$array; $i++) {
      $detail{$array->[$i]} = $m[$i];
  }
}

A: You can use the two arrays @LAST_MATCH_START and @LAST_MATCH_END (see perldoc perlvar) together with substr instead of $1, $2.... Something similar to
$detail{ $array->[$i] } = substr $_, $LAST_MATCH_START[$j], $LAST_MATCH_END[$j] - $LAST_MATCH_START[$j];

A: Using named capture groups, you can eliminate the need for %matching_hash to be a hash. While at the same time eliminating the need to use the number variables, or assigning the result of the match in an array. This is because it will store the relevant information into %+.
use 5.10.1;

my @match = (
  qr'^INFO:\s*(?<name>\S+)\s+(?<age>\S+)\s+(?<joining>\S+)',
  qr'^SAL:\s*(?<salary>\S+)',
  qr'ADDRESS:\s*(?<address>.*)',
);

sub get_details{
  my %detail;

  for my $input ( @_ ) {
    for my $match ( @match ){
      next unless $input =~ $match;
      @detail{keys %+} = values %+;
      last;
    }
  }

  return \%detail;
}

use Data::Dumper;
my @inputs = ( 'INFO: Vikram 32 2012', 'SAL: 12000$','ADDRESS: 54, junk, JUNK' );
say Dumper get_details @inputs

It can get even simpler if you combine your qr's into one.
use 5.10.1;

my $match= qr"
    ^INFO:   \s* (?<name>\S+) \s+ (?<age>\S+) \s+ (?<joining>\S+)
  | ^SAL:    \s* (?<salary>\S+)
  | ADDRESS: \s* (?<address>.*)
"x;

sub get_details{
  my %detail;

  for my $input ( @_ ) {
    $input =~ $match;
    @detail{keys %+} = values %+;
  }

  return \%detail;
}

use Data::Dumper;
my @inputs = ( 'INFO: Vikram 32 2012', 'SAL: 12000$','ADDRESS: 54, junk, JUNK' );
say Dumper get_details @inputs


text:
Q: Redux reducer return previous state dynamically I have a Redux Reducer that needs to store the previously selected option each time a user selects a new option.

*

*User Selects A (returns empty array)

*User Selects B (returns A)

*User Selects C (returns B)

*User Selects D (returns C)

.
export default function reducer(state = [], action) {
  switch (action.type) {
    case previousSelectionAction.PREVIOUS_SELECTION: {

      // Need to return the previous selection
      // Have tried:
      //  return [...state] and other variations with action.payload and dropping item in array
      // but this just returns the same state, does not update each tie a user selects a new option

    }
default:
  return state;

}
}

A: Store the previous value in a different state property when the selection changes:
case updateSelection:
  return {
    ...state,
    previous: state.current,
    current: action.payload
  }

And then you can select that previous value.

A: Instead of making your state a single object, it can be 2 objects one storing the previous value and one storing the current value.
The logic will be something like the following:
initialState = { previous: {}, current: {}}

Case updateSelection:
      return {
        ...state,
        previous: state.current,
        current: action.payload
      }

Then, you could check state.previous in your code.


text:
Q: How to modify the line as per the newer version of scikit learn? I want to change the following lines according to the newer version of scikitlearn since grid_scores_ are replaced  by cv_results_ also, mean_validation_score is replaced by mean_test_score
log_likelyhoods_5 = [round(gscore.mean_validation_score) for gscore in model.grid_scores_ if gscore.parameters['learning_decay']==0.5]
log_likelyhoods_7 = [round(gscore.mean_validation_score) for gscore in model.grid_scores_ if gscore.parameters['learning_decay']==0.7]
log_likelyhoods_9 = [round(gscore.mean_validation_score) for gscore in model.grid_scores_ if gscore.parameters['learning_decay']==0.9]

I tried:
log_likelyhoods_5 = [round(gscore.mean_validation_score) for gscore in model.cv_results_ if gscore.parameters['learning_decay']==0.5]
log_likelyhoods_7 = [round(gscore.mean_validation_score) for gscore in model.cv_results_ if gscore.parameters['learning_decay']==0.7]
log_likelyhoods_9 = [round(gscore.mean_validation_score) for gscore in model.cv_results_ if gscore.parameters['learning_decay']==0.9]

shows the error: no attribute 'parameters'
What will be the correct line in this case for newer version of scikitlearn?

A: I believe you are looking for the params key of cv_results_ in GridSearchCV:

The key params is used to store a list of parameter settings dicts for all the parameter candidates.

So you should use gscore.params['learning_decay']


text:
Q: Adding CSS styles to Admin Area PAGES only (not POSTS or CPT) I am using this to load css styles in the admin area (for any user who is not an administrator):
function wpse_admin_styles() {
    if ( !current_user_can( 'manage_options' ) ) {
        echo '<style>
                .fun-stuff-here {color:aqua;}
            </style>
        ';
    }
}
add_action('admin_head', 'wpse_admin_styles');

But I need to have some styles only load if the admin page being viewed is a page (not a post or custom post type post)
Is this possible? I think the answer selected in this WPSE question has some potential, but I don't know how to add in the necessary code to what I have: How to add an admin function only to posts, not pages?
I also came across this Wordpress Support Forum post. The OP's reply near the bottom (8th post from the top) looked promising, but in use it applies the CSS to all Pages, Posts and Custom Post Type sections: http://wordpress.org/support/topic/add-new-page-button-in-admin-area

A: I was having the same kind of problem, eventually I fixed it by calling the main css file of the front-end and making specific ID's for the admin-only stuffs like so:
function your_css() {
    wp_register_style('your_css', plugins_url('style.css',__FILE__ ));
    wp_enqueue_style('your_css');
}
add_action( 'init','your_css');

the wp_register_style & wp_enqeue_style are wordpress hooks/handlers to get the css file instead of placing the css code within your function ;)
Make sure to place it in the root plugin file!
I've got this follow up problem of 2 css files conflicting with each other so I'm still fiddling around with it, but at least your css file gets called and (partially) applied.
Good Luck

A: Like the front-end in WordPress, the admin pages have various css classes added to the <body> tag.
You could use:
body.post_type-page .fun-stuff-here {
  color:aqua;
}

Keep your action the same - the CSS will be loaded everywhere on admin, but only becomes relevant in the Pages section.
(There's a post_type-... for each.)


text:
Q: Why does SSE/AVX lack loading an immediate value? As far as I know, there is no instruction in SSE/AVX for loading an immediate. One workaround is loading a value to a normal register and movd, but compilers seem to think this is more costly than loading from memory even for a single scalar value.
This makes memory access necessary every time doing an operation with common constants such as 1, 0x80000000, 0x7fffffff, 0x3f800000, 0x3f000000, etc. Well, having these values encoded in the machine code will occupy 4 bytes each, but so does a 32-bit absolute or rip-relative address, and I believe an immediate load is cheaper than any sort of memory load.
I always thought something like movss xmm, imm32 or broadcastss xmm, imm32 would be nice to have, but there must be a reason for not making such instructions. Why was it designed this way?


text:
Q: How do I get the Catch a Cold achievement? In Toki Tori, the Catch a Cold achievement requires me to find ten snowflakes before they melt.
What levels are those snowflakes in, and is there a guide to getting each one of them fast enough?

A: The snowflakes are in these Forest Falls levels:

*

*Normal: 1, 6, 11, 12

*Hard: 1, 2, 3, 5

*Bonus: 2, 3

I've found this helpful video guide for reaching them quickly:

Note that the solution for Hard 1 is incorrect (because it was changed since this guide was uploaded), but the annotations tell you what to do.


text:
Q: Convert quaternions to xyz degrees I knew quaternion for the first time a few days ago and I still don't get the way it works even when reading explanations.
All I want to do is to make a subtraction between two quaternions and convert the variations into XYZ angles (radians or degrees) but I don't know from where I have to start… Can I simply subtract values one by one to make the difference?
If I apply the equations written on this site, what will be the unit of the results?
Thanks in advance.

A:
I knew quaternion for the first time a few days ago and I still don't get the way it works even when reading explanations.

Don't get discouraged, some of the concepts take a while.

All I want to do is to make a subtraction between two quaternions

As @rschwieb wrote in a comment, subtracting quaternions doesn't make a lot of sense geometrically. That's because quaternions as rotations operate multiplicative: you get the combination of two rotations by multiplying the quaternions, not by adding them. So the analogon to a difference of rotation angles would be the quotient of two quaternions.

convert the variations into XYZ angles

The Wikipedia page Rotation formalisms in three dimensions has a nice overview of different formalisms and how to convert between them. In particular, you should be precise whether "XYZ angles" refers to simultaneous rotations around all three axes, or to sequential rotation around each of these axes in the sense of Tait–Bryan angles.

If I apply the equations written on this site, what will be the unit of the results?

I haven't read all that, but unless stated otherwise I'd assume radians, since degrees are a pretty arbitrary choice of unit, while radians have deep mathematical connections. Also most programming languages, and definitely the Java used there, represent angles for their trigonometric functions in radians by default.


text:
Q: Is it possible to decompose 3-factor change in growth rate terms? Let's say, we investigate what caused the growth in working-age population (W). There are basically three factors causing the change in W. First, mortality at working ages (MT). Second, migration balance at working ages (MG). Finally, we have cohort turnover (CT) which is the number of those entering working ages minus the number of those leaving working ages (e.g. # of people turned 15 in some year minus # of people turned 65). So,
$$ W_2 - W_1 = MT + MG + CT $$
I want to know how much each factor contribute to the growth in W. The simple decomposition looks like
$$ \frac{W_2}{W_1} = \frac{W_1+MT+MG+CT}{W_1} = 1 + \frac{MT}{W_1} + \frac{MG}{W_1} + \frac{CT}{W_1}$$
Is there any way of decomposing growth in a form of product of three partial growth rates? Something like
$$ \frac{W_2}{W_1} = mt * mg * ct $$
Thanks in advance for any help, reference or hint.
This is my first question at CrossValidated. Excuse me if it is not worded properly.


text:
Q: Getting a SameSite cookie issue when trying to load recaptcha api.js in ASP.Net core project I am trying to add a Google v2 reCaptcha on my ASP.Net Core 6 Web Application and test it on my localhost. When I add the following line:

<script src="https://www.google.com/recaptcha/api.js" async defer></script>

to my page and open the page I am getting the following error in Chrome's console:

Because a cookie's SameSite attribute was not set or is invalid, it
defaults to SameSite=Lax, which prevents the cookie from being sent in
a cross-site request. This behavior protects user data from
accidentally leaking to third parties and cross-site request forgery.
Resolve this issue by updating the attributes of the cookie: Specify
SameSite=None and Secure if the cookie should be sent in cross-site
requests. This enables third-party use. Specify SameSite=Strict or
SameSite=Lax if the cookie should not be sent in cross-site requests.

All the cookies and request given after are from google.com.
The Captcha is not working and it also prevents some other JS scripts from execution.
If I remove the above line the page loads normally.
Here is how my Program.cs file looks like:
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Serilog;
using Serilog.Events;
using XQ.XGoogleInvisibleCaptcha;

[assembly: System.Runtime.InteropServices.ComVisible(true)]

Log.Logger = new LoggerConfiguration()
          .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
          .Enrich.FromLogContext()
          .WriteTo.File(
                "logs\\Logs.txt",
                rollingInterval: RollingInterval.Day,
                outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}\n")
          .WriteTo.Console(
                outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}\n")
          .CreateLogger();

var lBuilder = WebApplication.CreateBuilder(args);

lBuilder.Host.UseSerilog();

// Build configuration
string lBasePath = Directory.GetParent(AppContext.BaseDirectory) == null ? string.Empty : Directory.GetParent(AppContext.BaseDirectory).FullName;

var lConfiguration = new ConfigurationBuilder()
    .SetBasePath(lBasePath)
    .AddJsonFile("appsettings.json", false)
    .Build();

// Add caching of the static files
lBuilder.Services.AddResponseCaching();

// Add cookies
var cookieOptions = new CookieOptions
{
    // Set the secure flag, which Chrome's changes will require for SameSite none.
    // Note this will also require you to be running on HTTPS.
    Secure = true,

    // Set the cookie to HTTP only which is good practice unless you really do need
    // to access it client side in scripts.
    HttpOnly = true,

    // Add the SameSite attribute, this will emit the attribute with a value of none.
    // To not emit the attribute at all set
    // SameSite = (SameSiteMode)(-1)
    SameSite = SameSiteMode.None,
};

// Use memory cache for the session
lBuilder.Services.AddDistributedMemoryCache();

// Add session to store data
lBuilder.Services.AddSession(options =>
{
    options.Cookie.Name = ".MyWeb.Session";
    options.IdleTimeout = TimeSpan.FromMinutes(2.0);
});

lBuilder.Services.AddCors();

// Add services to the container.
lBuilder.Services.AddSingleton<IConfigurationRoot>(lConfiguration);

// Add the configuration of the Google Invisible Captcha
XGoogleInvisibleCaptchaKeys lGoogleInvisibleCaptchaKeys = lBuilder.Environment.IsDevelopment() ?
    lConfiguration.GetSection("GoogleInvisibleCaptchaDev").Get<XGoogleInvisibleCaptchaKeys>() :
    new(); //

lBuilder.Services.AddSingleton<ICaptchaKeys>(lGoogleInvisibleCaptchaKeys);

// Add the service for obtaining user IP and cookies
lBuilder.Services.AddHttpContextAccessor();

lBuilder.Services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();

// Add services to the container.
lBuilder.Services.AddRazorPages(options =>
{
    options.Conventions.AddPageRoute(
            "/Account/Signup", "Signup");
});

var lApp = lBuilder.Build();

// Configure the HTTP request pipeline.
if (!lApp.Environment.IsDevelopment())
{
    lApp.UseExceptionHandler("/Error");

    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    lApp.UseHsts();
}
else
{
    lApp.UseDeveloperExceptionPage();
}

lApp.UseHttpsRedirection();

lApp.UseStaticFiles();

lApp.UseRouting();

lApp.UseResponseCaching();

// Global CORS policy
lApp.UseCors(x => x
    .SetIsOriginAllowed(origin => true)
    .AllowAnyMethod()
    .AllowAnyHeader()
    .AllowCredentials());

// Global Headers
lApp.Use(async (context, next) =>
{
    context.Response.Headers.Add("X-Developed-By", "Xequtor");
    context.Response.Headers.Add("Cache-Control", "no-store");
    context.Response.Headers.Add("X-Content-Type-Options", "nosniff");
    context.Response.Headers.Add("X-Frame-Options", "DENY");
    context.Response.Headers.Add("Strict-Transport-Security", "max-age=63072000; includeSubDomains; preload");
    context.Response.Headers.Add("X-XSS-Protection", "1; mode=block");
    context.Response.Headers.Add("Content-Security-Policy", "form-action 'self'");

    // Cache control
    context.Response.GetTypedHeaders().CacheControl =
        new Microsoft.Net.Http.Headers.CacheControlHeaderValue
        {
            Public = true,
            MaxAge = TimeSpan.FromDays(365),
        };
    context.Response.Headers[Microsoft.Net.Http.Headers.HeaderNames.Vary] =
        new[] { "Accept-Encoding" };

    context.Response.Cookies.Append("MyCookies", "cookieValue", cookieOptions);

    await next();
});

// Redirect to this page when a server error occurs
lApp.UseStatusCodePagesWithReExecute("/Error");

lApp.UseSession();

lApp.UseAuthorization();

lApp.MapRazorPages();

lApp.Run();

From all the post I have seen so far I understood it has to do something on the Google side but might as well be something I am missing. Any ideas?
Thanks.


text:
Q: AngularJS 1.2 View leave/enter animation? Basically I want to slide out a view and slide in a new view, but the "leave event" is not happening at all, the old view disappears (before the leave effect) and the new view comes in with the transition effect.
FILE = index.html
<!--Placeholder for Views-->
<div id="main" ng-view="" class="slide-animation">

</div>

FILE = app.css
/* Animations */
.slide-animation.ng-enter, .slide-animation.ng-leave {
  transition: 0.5s cubic-bezier(0.420, 0.000, 1.000, 1.000) all;
}

.slide-animation.ng-enter {
  left: 100%;
}

.slide-animation.ng-enter.ng-enter-active {
  left: 0;
}

.slide-animation.ng-leave {
  left: 0;
}

.slide-animation.ng-leave.ng-leave-active {
  left: -100%;
}

any help is appreciated, Thanks.

A: Try adding position: absolute; to your first css block.


text:
Q: Issues updating an MSI through GPO (failures to overwrite/uninstall) Thank you in advance for considering this question. If a similar question existed, I was unable to find it.
The Issue: Our company packages an application into an MSI. This MSI when installed outside of any GPO properly updates, blocks attempts to downgrade (or move from a higher revision to a lower revision), and never has trouble uninstalling previous versions of the application regardless of how long ago those versions were created/installed. For example, we can install version 1.2.3 and then install version 2.3.4 and the application will properly install without issue. However, we work with a customer who uses GPO to deploy our application to hundreds of PC's. Each time we have provided an updated version of the application the following has been indicated:
On any machine where a previous version of our application was installed via GPO, no matter what the previous version is, the update successfully installs without issue.
On a machine where the application was manually installed (outside of the GPO), and an attempt to update the application via GPO is made - either the application is installed in addition to the old version, OR there remain registry keys to the previous version of the application and the application cannot open/run correctly. In this case the registry keys must be manually removed, and the install is then attempted again from a clean machine.
What we know is that on any machine where the application was originally installed via GPO - updating the application is no problem. On every machine where the application was not installed with the GPO in the first place, updating via GPO fails with one of the problems presented above.
My question is: Is there a technical issue with how the installation is being handled partially through the GPO and partially outside? Does the GPO need to be responsible for the entire life-cycle of the application? OR is it a reasonable expectation that the application be updated both on machines where the original version was manually (outside the GPO ) installed, and when it was installed initially from within the GPO?
One solution we are aware of is simply having all computers manage the application life-cycle (since we know updates work in that environment already), however this would mean that many computers would need to have the manually installed versions removed by hand - and then properly handle the installation through GPO which is an extensive bit of work.
We would greatly welcome any solutions, references to technical documentation that formally shed light on the proper management or expectations here, or links to information. Our research suggests that it is "best" to manage the entire applications life-cycle inside the GPO - but I have as of yet been unable to determine that it is 100% necessary to do so.
Looking forward to any assistance. If any further technical details are required to help the viability of the question, please don't hesitate to request such details.

A: If you end up with two versions installed in Control Panel, then all other things being correct, the most likely explanation is that you upgraded a per user install with a per machine install (or vice versa). In the GPO world that's related to assigning it to a user or to the computer, something like that.  That's easy to verify by getting a verbose log and checking the FindRelatedProducts actions for an indication that another product was found but in a different context.
When you're in GPO mode all the time, I assume each one (whether it's per user or per machine) is consistent, therefore upgrades always work, but they don't work cross-context.
I believe GPO suppresses the UI in most cases, and the UI (or the UI sequence) is sometimes where per user/per machine is set. That might be something else that would cause it, depending on how the GPO publishes to the computer or the user.


text: Q: FaunaDB Query Multiple Fields I am starting a project with faunadb, where users can login using either their email, username or phone number. Is there a way to query fauna for any of those 3 fields submitted by the user?


text:
Q: Disable Windows Task Manager so he cant kill my process I have built an app that can count the time.
After two hours its says "please stop playing or I will shut down the computer".
So, my brother can stop the process from the "Windows Task Manager".
Is it possible to stop it? So he can't kill it form there?
I have tried to reopen the app when the windows forms close - any other ways?

A: Haha, good on your brother. He is a hacker in the making.
You need to run the process with administrator  privileges and make sure his login dosent have administrator privileges.

A: Maybe using a Service is a better approach, because it is harder to find in the task manager and it should automatically restart if "killed", but as long as the user has administrator rights he is always able to disable such things.
See THIS WALKTHROUGH on how to create a service with C#.

A: Perhaps slight over-kill (and not easily possible in C#), but you could instead write a DLL that implements the timer, and inject it into another process (e.g. Explorer.exe), which means that it won't appear as a separate process in Task Manager, and so won't be possible to kill in that way.

A: I probably shouldn't mention this as it can be easy to abuse, but knowledge needs to be free, right?
If you run your process as the SYSTEM user, then it cannot be shut down, even by anyone logged in as Administrator. Quite simply, you use psexec from Sysinternals to run your process, check this blog post for details: How to: Run a cmd under system account / gain access to system account

A: I'm afraid this is not possible in general. As long as the user has administrative rights he can kill any process.
I would suggest to implement and run your application as a windows service. An administrator can stop the service as well. But users without administrative rights are not allowed to do so.


text:
Q: updating nested documents in mongoDB(node.js) i am trying to update a value in the object of my embedded schema(comments schema) whose value i had previously stored 0 by default. i have tried all the ways to update but none of the stackoverflow answer worked.
my code is
var checkedBox = req.body.checkbox;
User.updateOne({_id: foundUser._id},{$set :{comments:{_id :checkedBox,cpermission:1,}}},function(err,updatec){
          if(err){
            console.log(err);
          }
          else{
            console.log("successfull");
      console.log(updatec);

          }
        });

i had comment schema nested in user schema,here foundUser._id is the particular users id,and checkedBox id is the embedded objects particular id. previously my cpermission was 0,set by default,but now i want to update it to 1. although this is updating my schema,but deleting the previous images and comments in the schema aswell.
where am i going wrong?
here is my schema
const commentSchema = new mongoose.Schema({
  comment: String,
  imagename: String,
    cpermission:{type:Number,default:0},
});

const Comment = new mongoose.model("Comment", commentSchema);

const userSchema = new mongoose.Schema({
  firstname: String,
  lastname: String,
  email: String,
  password: String,
  comments: [commentSchema],
  upermission:{type:Number,default:0},
});

userSchema.plugin(passportLocalMongoose);

const User = new mongoose.model("User", userSchema);

A: First, you need to convert checkbox in the array, as it will be a string if you select a single element
Then wrap it with mongoose.Types.ObjectId as a precaution
Then you can use arrayFilters to update multiple matching array elements
var checkedBox = req.body.checkbox;
if (!Array.isArray(checkedBox)) {
   checkedBox = [checkedBox]
}

checkedBox = checkedBox.map(id => mongoose.Types.ObjectId(id))

User.updateOne(
    { _id: foundUser._id }, // filter part
    { $set: { 'comments.$[comment].cpermission': 1 } }, // update part
    { arrayFilters: [{ 'comment._id': {$in: checkedBox }}] }, // options part
    function (err, updatec) {
        if (err) {
            console.log(err);
        }
        else {
            console.log("successfull");
            console.log(updatec);

        }
    });

A: your comment is the array of documents. if you want to update an element of an array must be select it. for that must be added another condition to the first section of updateOne then in seconde section use $ for update selected element of the array.
User.updateOne(
        {_id: foundUser._id, 'comments._id': checkedBox},
        {
            $set: {'comments.$.cpermission': 1}
        }
        , function (err, updatec) {
            if (err) {
                console.log(err)
            }
            else {
                console.log('successfull')
                console.log(updatec)
            }
        })

for more information, you can read this document form MongoDB official website.
Array Update Operators

A:   var checkedBox = req.body.checkbox;

  User.updateOne(
  { _id: foundUser._id, "comment._id": checkedBox },
  { $set: { "comment.$.cpermission": 1 } },
  function (err, update) {
  if (err) {
    console.log(err);
  } else {
    console.log("successfull");
    console.log(update);
  }
 }
 );


text:
Q: How to delete re-create tables in a SQLite database from Android when an application is started? I am building an application which has a database with two tables created internally using SQLiteOpenHelper.When ever the application is running,it receives some data and saves it into the tables.What I want is to clear the data tables when ever the application is started?
I looked into this post How can I clear an SQLite database each time I start my application? which is not clear of how to use application.

A: SQLiteOpenHelper has the ability of creating in-memory databases if you pass the constructor a null name. Probably this is what you are looking for.
For example:
SQLiteOpenHelper sqloh = new SQLiteOpenHelper(context, null, null, 1);
SQLiteDatabase sqldb = sqloh.getWritableDatabase();

will create an in-memory db.

A: SqliteDatabase uses the method openOrCreate(...) which opens a database if it exist and creates and opens it when it doesn't exist. see docs based on that you could just delete the database file that is created before you do any database calls so that a new one is created each time.
This SO question gives the location of the file: Location of sqlite database on the device
There other route would be just to delete the data in the tables when the application starts by executing a sqlite query:
DELETE FROM your_table

My only thought would be do you really need a database if you are going to delete it every time the application starts. If you are not updating the data then why not just "cache" a json file with the data. The GSON library is awesome for taking json and converting it to java object with very little code, going to be less code than working with sqlite. But the recommendation comes from not having the big picture for what you are trying to accomplish. You then would just delete the json file(s) when the app starts instead of the db file.


text:
Q: Using In-band commissioning with SAMR21s ftd cli returns Join failed [InvalidArgs] Im trying the guide at https://codelabs.developers.google.com/codelabs/openthread-hardware/#8, with two SAMR21s running the SAMR21 ftd cli examples. Everything seems to work until I need to do joiner start J01NME, which returns with Join failed [InvalidArgs].
Fresh upload of SAMR21 ftd cli examples with parameters COMMISSIONER=1 JOINER=1 DHCP6_CLIENT=1 DHCP6_SERVER=1 on both SAMR21s.
With the two SAMR21s I typed the following commands into the clis:
SAMR21 1:
> dataset init new
> dataset commit active
> ifconfig up
> thread start
> state
leader
> commissioner start
Commissioner: petitioning
done
> commissioner joiner add 0004251918018576 J01NME
done
SAMR21 2:
> eui64
0004251918018576
> ifconfig up
>scan
| J | Network Name     | Extended PAN     | PAN  | MAC Address      | Ch | dBm | LQI |
| 1 | OpenThread-f171  | 1b6239e953fd2be4 | f171 | 76144ebb984c039a |  0 |  -7 |   0 |
> joiner start J01NME
done
> Join failed [InvalidArgs]
Observations
I have noticed when the commissioner times out the follow is displayed which doesnt seem right, as the eui64 being removed doesnt match what i added:
> commissioner joiner add 0004251918018576 J01NME
Done
> Commissioner: Joiner remove b34a468958787c5e
Any help would be appreciated thanks.


text:
Q: Is there any way to sync only few tables of two different postgresql database? There are two postgresql table in two different region, and I would like to sync just one table inside both database. Is it possible?

A: I figured out his with pgloical.
(Docker PostgreSQL) Bi-directional Replication with pglogical

*

*Launch two PostgreSQL container with different port

*

*docker volume create sync_test_1

*docker run --name sync_test_1 -e POSTGRES_USER=postgres -e POSTGRES_PASSWORD=qwerty1234 -p 5433:5432 -d -v sync_test_1:/var/lib/postgresql/data postgres:9.5.23

*docker volume create sync_test_2

*docker run --name sync_test_2 -e POSTGRES_USER=postgres -e POSTGRES_PASSWORD=qwerty1234 -p 5434:5432 -d -v sync_test_2:/var/lib/postgresql/data postgres:9.5.23

*Get into PostgreSQL container shell and update and install essential tools

*

*docker exec -it sync_test_1 /bin/bash

*apt -y update

*apt install -y vim

*apt install -y procps

*do step 1 to 3 with sync_test_2 too

*Install pglogical package

*

*apt install -y postgresql-9.5-pglogical

*Change postgresql.conf

*

*vi /var/lib/postgresql/data/postgresql.conf

*

*wal_level = logical

*track_commit_timestamp = onenter code here

*shared_preload_libraries = 'pglogical'

*max_replication_slots = 10

*Restart PostgreSQL

*

*docker restart sync_test_1

*Use pglogical

*

*create database localharvest

*psql -U postgres localharvest

*CREATE EXTENSION pglogical;

*SELECT pglogical.create_node(node_name := 'db1_local', dsn := 'host=127.0.0.1 port=5432 dbname=localharvest user=postgres password=qwerty1234');

*SELECT * FROM pglogical.replication_set;

*SELECT pglogical.replication_set_add_table('default', 'users');

*ALTER SEQUENCE users_id_seq RESTART WITH 1 INCREMENT 20;

*add 'host replication postgres 172.17.0.1/32 trust' in /var/lib/postgresql/data/pg_hba.conf

*subscribe each other

*SELECT pglogical.create_subscription(subscription_name := 'db2_subscription', forward_origins := '{}', provider_dsn := 'host=host.docker.internal port=5434 dbname=localharvest user=postgres password=qwerty1234');
ref: https://eradman.com/posts/active-active-pglogical.html
From inside of a Docker container, how do I connect to the localhost of the machine?
https://github.com/2ndQuadrant/pglogical
https://www.2ndquadrant.com/en/resources/pglogical/pglogical-docs/#Replication-sets


text:
Q: Creating hash from an array of values in Ruby I want to use each item in the array as values in a hash with the same key "name".
people = ["Bob", "Mary", "Sarah", "Tim", "Maggie"]
I want to get:
{ name: => "Bob", name: => "Mary", name: => "Sarah", name: => "Tim", name: => "Maggie"}
When I do Hash[people.map {|v| ["name", v]}] or
people.map{|v| hash['name'] = v}
it zips only the last item so I get this as a result :
{"name"=>"Maggie"}

A: This is impossible. Keys in a hash cannot be duplicated. Each key may only exist once, and map to exactly one value.


text:
Q: stop redirect? watch code in Visual Studio? I am using Visual Studio to compile and run my ASP.NET website. Now, one of the pages have searchbox acting very odd, because it's redirecting to typical "FileNotFound" page which we're using to redirect when there is a typo in URL or something (and definitely not for searches).
The search is a separate .ascx control, so it's exactly the same for all pages.
So is there a way I can see what's happening behind the scenes to trigger that redirect? It is not firing the click event of the search button either, something is taking place even before the click??!
Is there a way I can watch the code run in Visual Studio without placing a breakpoint, because I do not know where to place it!

A: I would use Fiddler or Firebug to watch the requests and responses.  That might help diagnose where the redirect is happening.


text:
Q: Can't retrieve image from QR Generator API Android I am trying to generate a QR code in my app by sending a HTTP request to a QR generator API and placing the image into an imageview. I'm just getting a blank screen however. I've tried a couple of different solutions that I've found but no luck. Here is the code that I am using. I've also added the internet permission in the manifest
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <ImageView android:id="@+id/qrImageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" />

</RelativeLayout>

MainActivity.java
public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ImageView imageview = (ImageView) findViewById(R.id.qrImageView);

        String qrURL = "http://api.qrserver.com/v1/create-qr-code/?data=thisisatest&size=300x300";
        String src = "QRGenerator";

        Drawable qrCode=null;
        try {
            qrCode = drawable_from_url(qrURL, src);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        imageview.setImageDrawable(qrCode);
    }

        Drawable drawable_from_url(String qurl, String src_name) throws MalformedURLException, IOException {
            URL url = new URL(qurl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            InputStream is = connection.getInputStream();
            Drawable d = Drawable.createFromStream(is, src_name);
            return d;
        }

}

A: You'll have to download the image firstly:
public static Bitmap loadBitmap(String url) {
    Bitmap bitmap = null;
    InputStream in = null;
    BufferedOutputStream out = null;

    try {
        in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);

        final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
        out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
        copy(in, out);
        out.flush();

        final byte[] data = dataStream.toByteArray();
        BitmapFactory.Options options = new BitmapFactory.Options();
        //options.inSampleSize = 1;

        bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
    } catch (IOException e) {
        Log.e(TAG, "Could not load Bitmap from: " + url);
    } finally {
        closeStream(in);
        closeStream(out);
    }

    return bitmap;
}

Then use the Imageview.setImageBitmap to set  bitmap into the ImageView

A: I've solved it. I was running it on an emulator that had no internet connection, so it obviously couldn't contact the API. I ran it on my phone and it worked. I'll leave the question up for reference for others. Thanks for the input


text:
Q: Dúvida em Complexidade de Algoritmos Estou com uma dúvida em Complexidade de Algoritmos. Como podem ver, na imagem abaixo, as expressões são equivalentes, ou seja, possuem as mesmas qualidades e o mesmo termo dominante (n²), então porque os resultados são diferentes?

A: Na verdade, não está completamente errado. Tudo o que vou escrever aqui foi retirado do livro e das videoaulas de Cormen et al (2002).
Para começar, a notação Big-O (ou O-grande) serve-nos apenas para um "limite assintótico superior". É importante saber disso, pois a notação Teta (Θ) refere-se a limites assintóticos uma função acima e abaixo (ou seja, um limite assintótico "firme", ou "justo" em algumas traduções).
Quando se escreve normalmente que f(n) = O(g(n)), se está simplesmente afirmando que algum múltiplo constante de g(n) é um limite assintótico superior sobre f(n). O Detalhe é que na notação big-O não há qualquer menção sobre o quanto o limite superior é restrito.
Ou seja, a notação diz que existe uma função f(n) que é O(n2) tal que, para qualquer valor de n, não importa o tamanho escolhido, o tempo de execução sobre essa entrada tem um limite superior determinado pelo valor de f(n).
Em tese, portanto, uma função f=n2-1 também tem um "limite superior" não-restrito de O(n3). Afinal, para todo n positivo, como n3 é monoticamente crescente quando n > 0, vai existir constantes positivas c e n0, tais que 0<= f(n) <= cg(n), para todo n >=  n0.
Faça o teste!
Porém, não se usa a notação big-O dessa forma. Embora exista (e ela represente, de fato) um "conjunto de funções" que fazem a notação ser verdadeira (basicamente, nesse caso, toda função que tenha limite superior acima da função f por um fator c, polinomialmente), usa-se, sempre o limite assintótico mais "próximo".
Talvez tenha ficado confuso, mas a partir de 2:51 desse vídeo: https://www.youtube.com/watch?v=whjt_N9uYFI, Erik Demaine explica direitinho os "abusos" matemáticos da notação big-O (e o fato do sinal de igual ser assimétrico é um deles!) demonstrando como esses limites funcionam
De fato, ele usa o seguinte exemplo: 2n2= O(n3) e explica que isso, na verdade quer dizer que 2n2 ∈ O(n3), ou seja que ela faz parte do "conjunto" de funções limitados assintoticamente por O(n3). Entende?
Ou seja, vc pode SIM, afirmar que g(n) = 3n3 + 2n2 + n é O(n4), mas essa afirmação é muito mais "fraca" ou imprecisa (ou melhor, "assintoticamente imprecisa") do que dizer que g(n) é O(n3), entende? Já que para provar, pela definição que  g(n) acima é O(n3) basta provar que ela é <= 6n3, para n>=0.
Espero ter ajuda a entender esse assunto, ao menos um pouquinho.
Qualquer dúvida, vá nos comentários!

A: Não tem absolutamente nada de errado.
Se f ∈ O(g) e g ∈ O(h), então f ∈ O(h).
Ou seja, toda função f(n) pertence a O(g(n)) se para todo n for verdade que g(n) >= f(n).
É evidente que para todo n é verdade que n^3 >= n^2, então f(n^2) ∈ O(n^3).


text:
Q: Query range in activeworkbook using ADODB I'm trying to write some VBA that can query a named range in VBA using SQL. Currently, it works reasonably well, but i have the problem that every time i run the macro a read-only instance of the worksheet is opened. I want to use the macro to query ranges within the same workbook without opening a read-only copy.
Here is my code
Public Sub QueryAndOutputToCell(ByVal query As String, rng As Range)

Dim conn As ADODB.Connection
Set conn = New ADODB.Connection

Dim DBFullName, connString, SQL As String
DBFullName = ThisWorkbook.path & "\" & ThisWorkbook.name

connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & DBFullName & "';Extended Properties='Excel 12.0;HDR=Yes;IMEX=1';"
conn.connectionString = connString
conn.Open ' Read-only copy is opened here
conn.commandtimeout = 0

Dim cubeData As ADODB.Recordset
Set cubeData = New ADODB.Recordset

cubeData.Open query, conn, adOpenDynamic, adLockReadOnly

rng.CopyFromRecordset cubeData

cubeData.Close
conn.Close
Set cubeData = Nothing
Set conn = Nothing

End Sub

Do anyone know if this is possible?


text:
Q: Android, background drawable appear black in genymotion but looks fine in intellij I'm trying to set background image for my activity like this:
<LinearLayout
            android:id="@+id/container"
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:gravity="center"
            android:background="@drawable/login_background"
            android:orientation="vertical">

which looks great in the preview in intellij

but in genymotion it looks black:

after trying to change the name of the file, the size of the file and trying various export methods from photoshop, I'm clueless.
Any ideas?

A: Have you tried another genymotion config yet?
Or have you tried it on a real Device?
I would suggest to use some other Configuration first, according to this post it could help.
https://github.com/facebook/fresco/issues/298
PS: I know not a real answer, got not enough reputation yet, thought i could help anyway.

A: After playing with the issue more I truly don't know what was the problem. After trying the same image in different activity it started to show even without modified the genymotion settings.