text:
Q: You will need to set up login with Facebook to access the API I've recently seen on Facebook/Meta audience network dashboard the following alert on the top.

You will need to set up login with Facebook to access the API
Starting in July 2022, you will need to use Facebook Login for your
apps to access the Audience Network Reporting API, so you will no
longer be able to generate a token to access the API. Signing in with
Facebook is more secure and convenient, and protects against
unauthorized ID sharing.

I don't understand exactly what i means. I'm using Facebook bidding with Applovin, that alert means that in July all my apps that don't have Facebook login will stop Audience network so will not show ads. It is a bit strange that i have to implement obligatorily Facebook Login if is not necessary. Can anyone explain me?
I appreciate.
Thank you!

A: Actually what it is trying to say is not that in every app where you have Meta ads you compulsorily have to put Facebook login. It is a change in how we as developers will access the API.
Before we used to generate a API token and use it for authentication. Now in place of that we have a Facebook account login to authenticate and then we can use the API.
These is done to prevent the auth token sharing and also as they say its more secure and convenient then the traditional token way for using API.
You can check out the new documentation of how to use Facebook login for API authentication. Hope it helps.


text:
Q: php 7.4 auto format typed properties in sublime text 3 I use Sublime Text 3 and CodeFormatter plugin to auto format my PHP on save.  Recently I updated to PHP 7.4 which introduces typed properties:
class Person {
  private string $name;
  private int $age;
}

Unfortunately CodeFormatter doesn't handle these and after saving converts the class to look like this:
class Person {
  stringprivate $name;
  intprivate $age;
}

Seems CodeFormatter relies on phpF which hasn't been updated in years (according to GitHub).
Thoughts (other than trying VS Code)?

A: *

*php-cs-fixer
It's an external PHP tool which allows you to format a whole project with defined rules. But there is a plugin Phpcs to call it in ST.

*LSP + LSP-intelephense (node.js required)
I mention this just because it provides code formatting too. But I can't find a reason to use it for formatting (unless you don't have PHP installed on your machine but that's weird since you develop PHP) because php-cs-fixer is far more flexible. I use this setup for code completion, refactoring, ... but not code formatting.
I would say don't be bound in ST. If something can be achieved in command line, then it can be done in ST. So you may find external command line tools and write your own plugin to call them too. There are many useful command line tools and they won't be bound to a certain editor.

redpajama_set_name: RedPajamaStackExchange


text:
Q: MySQL select in one row values from the other row I have a supersimple query SELECT TIME, VALUE, TYPE from mylog;
My query show the next:
| TIME            | VALUE |      TYPE |
 -------------------------------------
| 2013-09-26 04:45|  18.7 |         1 |
| 2013-09-26 04:45|  84.5 |         2 |
| 2013-09-26 05:00|  18.6 |         1 |
| 2013-09-26 05:00|  84.7 |         2 |

But I want the query show the next:
| TIME            | VALUE A |  VALUE B  |
 ----------------------------------------
| 2013-09-26 04:45|  18.7   |  85.5     |
| 2013-09-26 05:00|  18.6   |  84.7     |

where VALUE A is Type = 1 and VALUE B is Type = 2
All data is stored in a just one table, and contains the columns:
TIME, VALUE, TYPE

A: SELECT TIME,
MIN(CASE WHEN TYPE= '1' THEN VALUE ELSE NULL END)   AS VALUE_A,
MIN(CASE WHEN TYPE= '2' THEN VALUE ELSE NULL END)   AS VALUE_B From mylog GROUP BY time

SQL fiddle

A: SELECT
  `TIME`,
  MIN(IF(`TYPE`=1,`VALUE`,99999999)) AS `Value A`,
  MIN(IF(`TYPE`=2,`VALUE`,99999999)) AS `Value B`
FROM mylog
GROUP BY `TIME`

with 99999999 menaing "no value available"
EDIT
I do no use NULL, as it will deny me the MIN(or MAX). If you want NULL instead, you must wraop this in
SELECT `TIME`,
  IF(`Value A`=99999999,NULL,`Value A`),
  IF(`Value B`=99999999,NULL,`Value B`)
FROM (
   -- ...
) AS baseview


text:
Q: Office 365 call site event Receiver but did not work event Receiver Office 365 Solutions upload then site event Receiver call & Feature activated, did not work Event Receiver..
Below Code And Error Image
Code For Site EventReceiver
public class Project_SiteEventReceiver : SPFeatureReceiver
{

    public override void FeatureActivated(SPFeatureReceiverProperties properties)
    {
    try
    {
        using (SPSite site = (properties.Feature.Parent as SPSite))
        {
            using (SPWeb web = site.RootWeb)
            {
    site.RootWeb.Features.Add(new Guid("a2992ae0-0a71-4443-b334-8a961c131d35"),true,SPFeatureDefinitionScope.Site);
            }
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
 }


text:
Q: PGM Mysql PDO WHEN or IF STATEMENT Is it possible to have a WHEN statement or IF Statement within a PDO Statement? I've tried the following but it does not work
$stmt = $conn->prepare('SELECT company_id, name, alias, fk_company_type as type, is_active as active FROM company WHERE (CASE WHEN :srchBy = "alias" THEN alias ELSE name END)  LIKE :srchField');

$stmt->bindParam(':srchBy', $srchBy, PDO::PARAM_INT); //bind :srchField to $srchField in sql statement
$stmt->bindParam(':srchField', $srchField, PDO::PARAM_INT); //bind :srchField to $srchField in sql statement

Table Structure
company_id      |23980471998218241  | 23980471998218242       |
fk_company_type |HQ                 |SITE                     |
name            |JOHN PLUMBING HQ   |JOHN PLUMBING - BRIDGE ST|
alias           |CITY RD HQ         |BRIDGE ST SERVICE        |
is_active       |1                  |1                        |
created_date    |2015-04-18 19:35:32|2015-04-18 19:34:46      |

A: Unfortunately, you can't bind parameters by column names. but you can do other way
$stmt = $conn->prepare('SELECT company_id, name, alias, fk_company_type as type, is_active as active FROM company WHERE (CASE WHEN "'.$srchBy.'" = "alias" THEN alias ELSE name END)  LIKE ?');
$stmt->bindValue(1, "%$srchField%", PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetchAll();
print_r($result);

Every operator/identifier must be hardcoded but if that's not case you need to validate identifier


text:
Q: embedding an X11 widget in Cocoa I'm working on pythonocc, which exposes the OpenCasCade API in a pythonic manner.
OCC is coupled to either the windows or X11 gui environment.
This is somewhat problematic on OSX; I need to build [Py]Qt4 for X11, rather than Cocoa, which makes distribution much harder than it should be. Hence the following question; is it possible to embed a X11 widget in Cocoa? That would allow me to use PyQt4 / PySide for Cocoa and make things a lot easier.


text:
Q: Class Inheritance/Override I have a general class.
And I want to create another class, but with less (or more) specific information.
So I convert from one class to another.
How I can build a dynamic inheritance "OtherClass"?
How  I can overwrite when creating a new class?
public class NewClass: Atom
{
 ...
}
public class OtherNewClass
    {
        // Elements

        [XmlElement(ElementName = "id")]
        public string id { get; set; }
        [XmlElement(ElementName = "name")]
        public string name { get; set; }
        [XmlElement(ElementName = "NewNew")]
        public string newnew { get; set; }
}

My code:
public class Atom
{
    [XmlType(TypeName = "feed", Namespace = "http://www.w3.org/2005/Atom")]
    public class Feed
    {
        [XmlElement(ElementName = "title")]
        public string Title { get; set; }

        [XmlElement(ElementName = "updated")]
        public DateTime? Updated { get; set; }

        [XmlElement(ElementName = "id")]
        public string Id { get; set; }

        [XmlElement(ElementName = "link")]
        public Link Link { get; set; }

        [XmlElement(ElementName = "entry")]
        public List<Entry> Entries { get; set; }

        public Feed()
        {
            Entries = new List<Entry>();
        }
    }

    public class Entry : OtherClass
    {
        [XmlElement(ElementName = "title")]
        public string Title { get; set; }

        [XmlElement(ElementName = "updated")]
        public DateTime? Updated { get; set; }

        [XmlElement(ElementName = "id")]
        public string Id { get; set; }

        [XmlElement(ElementName = "link")]
        public List<Link> Link { get; set; }

        [XmlElement(ElementName = "category")]
        public Category Category { get; set; }

        [XmlElement(ElementName = "author")]
        public Author Author { get; set; }

        [XmlElement(ElementName = "content")]
        public string Content { get; set; }           [

    }

    [XmlType(TypeName="otherclass", Namespace ="spec/1.0/")]
    public class OtherClass
    {
        // Elements

        [XmlElement(ElementName = "id")]
        public string id { get; set; }
        [XmlElement(ElementName = "name")]
        public string name { get; set; }
        [XmlElement(ElementName = "code")]
        public string code { get; set; }
}

One tip that you can give me to do this.


text:
Q: Array slicing between different types in Ada An Ada tutorial I'm reading says that this is a valid thing to do in Ada:
Large : array (0 .. 100) of Integer;
Small : array (0 .. 3) of Integer;

-- extract section from one array into another.
Small(0 .. 3) := Large(10 .. 13);

However, when I actually try it, it doesn't work.
I'm using ideone's online Ada environment to play with this stuff, for simplicity (link above). Is the tutorial wrong, or is it referring to a version of Ada which ideone doesn't implement?

A: The tutorial is wrong.
This will compile, though:
type Integer_Array is array (Natural range <>) of Integer;
Large : Integer_Array (0 .. 100);
Small : Integer_Array (0 .. 3);

...
Small (0 .. 3) := Large (10 .. 13);

The details: In my example, Integer_Array is a type (actually a type and a "first subtype"), and Integer_Array(0..100) and Integer_Array(0..3) are constrained subtypes.    Array types in Ada specify the type(s) of the index(es) and the type of the element, but not the bounds; bounds are specified by subtypes, specifically constrained subtypes.  (That doesn't mean that you need a subtype declaration; a type declaration can cause both a type and a constrained subtype to be defined.)
An Ada assignment requires (usually) that the source and destination be of the same type, but they can be different subtypes.  So in my example, both the source and destination are subtypes of Integer_Array, and therefore the assignment meets this requirement.
In the original example, the declarations of Large and Small define new anonymous array types.  Each type is unbounded, and the declarations also define bounded subtypes that are used as the variables' subtypes.  But the important thing here is that two distinct types are defined, and you can't assign one type to the other.  Furthermore, since the types are unnamed, you can't use a type conversion to make the assignment work, as you could in an example like this:
type Integer_Array is array (Natural range <>) of Integer;
Large : array (0 .. 100) of Integer;
Small : Integer_Array (0 .. 3);

...
Small (0 .. 3) := Integer_Array (Large (10 .. 13));

Here, Large and Small again have two distinct types, but a type conversion is possible because the destination type is named.
The moral here is that it's better to use named array types.  Variable declarations like
Large : array (0 .. 100) of Integer;

can be good enough in some instances; but as this example shows, there are certain things you can't do with them.


text:
Q: C++: returning shared pointer destroys the object I'm trying to return a new shared_ptr from a method:
std::shared_ptr<VertexBuffer> VertexBuffer::Create(float* vertices, uint32_t size)
{
    return std::make_shared<OpenGLVertexBuffer>(std::move(OpenGLVertexBuffer(vertices, size)));
}

I have a destructor and VertexBuffer gets destroyed after exiting this method. Why is that?

A: The destructor is being called on this temporary object:
return std::make_shared<OpenGLVertexBuffer>(std::move(OpenGLVertexBuffer(vertices, size)));
                                                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

You're slightly misusing std::make_shared and invoking the move/copy constructor instead. This shouldn't be a correctness issue if your class follows the Rule of Three/Five/Zero, but it is inefficient.
You should instead directly construct the object using std::make_shared as intended, which is to forward constructor arguments rather than constructing an object explicitly.
return std::make_shared<OpenGLVertexBuffer>(vertices, size);

Also note that calling std::move(x) where x already is a temporary achieves nothing.


text:
Q: Systemd, cgroup, and LXC After much trial and error, I was finally able to get Spice working in a Fedora LXC container under Ubuntu 14.04. However, the same can't be said of an Ubuntu 14.04 container. It appears that the problem lies within Ubuntu's fractional implementation of systemd, whereas Fedora's full implementation (even with LXC restrictions) doesn't seem to have a problem in this case.
My test case relies on the Spice vdagent git sources. Once spice-vdagent connects to spice-vdagentd, vdagentd attempts to get session information for vdagent PID via libsystemd-login0 call sd_pid_get_session. This call returns with "No such file or directory", preventing Spice form working correctly. After digging through the source of libsystemd-login0, it appears that this call is reliant on the systemd cgroup.
Unfortunately, this cgroup doesn't exist within a container due to the file /etc/init/systemd-logind.conf explicitly not mounting the cgroup when running in a container. After removing the LXC check and rebooting the LXC container, I am left with a cgroup mounted in /sys/fs/cgroup/systemd. All appears to be well and good until examining /sys/fs/cgroup/systemd/cgroup.procs -- it's empty, as are all other cgroup.procs files underneath. The comment in the systemd-logind.conf above the LXC check states "mounting the cgroup does not work in LXC, there it uses cgmanager," but this doesn't give me any insight into how it should be done, or how it can be worked around.
I'm really unsure if this is an LXC-specific issue (perhaps LXC is preventing it from working properly?) or whether it's a systemd-logind issue. I should clarify that, for the moment, I have assigned my Ubuntu 14.40 LXC container to the 'unrestricted' profile so as to ensure it's not some kind of funky permissions issue.
Does anybody have any insight on what can be done to get the systemd cgroup within the LXC container working properly so that I can use Spice happily?
EDIT: After checking my host system, the systemd cgroup there seems to be working just fine, hm...
Despite lacking systemd-cgls, I can still provide some similar information:
Here is a tree of the /sys/fs/cgroup/systemd directory:
ubuntu@ubuntu2:/sys/fs/cgroup/systemd$ tree
.
├── cgroup.clone_children
├── cgroup.event_control
├── cgroup.procs
├── cgroup.sane_behavior
├── lxc
│   ├── cgroup.clone_children
│   ├── cgroup.event_control
│   ├── cgroup.procs
│   ├── notify_on_release
│   ├── tasks
│   └── ubuntu2
│       ├── cgroup.clone_children
│       ├── cgroup.event_control
│       ├── cgroup.procs
│       ├── notify_on_release
│       ├── tasks
│       └── user
│           ├── 1000.user
│           │   ├── c1.session
│           │   │   ├── cgroup.clone_children
│           │   │   ├── cgroup.event_control
│           │   │   ├── cgroup.procs
│           │   │   ├── notify_on_release
│           │   │   └── tasks
│           │   ├── cgroup.clone_children
│           │   ├── cgroup.event_control
│           │   ├── cgroup.procs
│           │   ├── notify_on_release
│           │   └── tasks
│           ├── cgroup.clone_children
│           ├── cgroup.event_control
│           ├── cgroup.procs
│           ├── notify_on_release
│           └── tasks
├── notify_on_release
├── release_agent
├── tasks
└── user
    ├── 1000.user
    │   ├── c2.session
    │   │   ├── cgroup.clone_children
    │   │   ├── cgroup.event_control
    │   │   ├── cgroup.procs
    │   │   ├── notify_on_release
    │   │   └── tasks
    │   ├── cgroup.clone_children
    │   ├── cgroup.event_control
    │   ├── cgroup.procs
    │   ├── notify_on_release
    │   └── tasks
    ├── cgroup.clone_children
    ├── cgroup.event_control
    ├── cgroup.procs
    ├── notify_on_release
    └── tasks

And a mapping of PIDs per cgroup:
./lxc/ubuntu2/user/1000.user/c1.session/cgroup.procs:
    860 /bin/login -- 2596 grep --color=auto 860 /bin/login -- 2596 grep --color=auto 860
    1281 -bash 2605 grep --color=auto 1281 -bash 2605 grep --color=auto 1281
    2614 grep --color=auto 2593 grep --color=auto 2593
./lxc/ubuntu2/user/1000.user/cgroup.procs:
./lxc/ubuntu2/user/cgroup.procs:
./lxc/ubuntu2/cgroup.procs:
    1 /sbin/init 194 upstart-udev-bridge --daemon 431 avahi-daemon: running [ubuntu2.local] 487 dhclient -1 -v -pf /run/dhclient.eth0.pid -lf /var/lib/dhcp/dhclient.eth0.leases eth0 513 upstart-file-bridge --daemon 767 /usr/lib/policykit-1/polkitd --no-debug 811 /usr/sbin/spice-vdagentd -f -s /tmp/xspice-virtio -u /tmp/xspice-uinput -d 862 /sbin/getty -8 38400 tty1 871 /usr/lib/accountsservice/accounts-daemon 903 lightdm --session-child 16 20 915 /bin/sh /usr/lib/lightdm/lightdm-greeter-session /usr/sbin/unity-greeter 921 //bin/dbus-daemon --fork --print-pid 5 --print-address 7 --session 941 /usr/lib/gvfs/gvfsd 958 lightdm --session-child 12 20 961 init --user --startup-event indicator-services-start 971 /usr/lib/x86_64-linux-gnu/indicator-datetime/indicator-datetime-service 1042 /usr/bin/pulseaudio --start --log-target=syslog 1045 /usr/lib/rtkit/rtkit-daemon 1065 /usr/lib/x86_64-linux-gnu/gconf/gconfd-2 1069 /usr/lib/x86_64-linux-gnu/notify-osd 1222 /usr/lib/colord/colord 1281 -bash 2626 grep --color=auto 1 /sbin/init 194 upstart-udev-bridge --daemon 431 avahi-daemon: running [ubuntu2.local] 487 dhclient -1 -v -pf /run/dhclient.eth0.pid -lf /var/lib/dhcp/dhclient.eth0.leases eth0 513 upstart-file-bridge --daemon 767 /usr/lib/policykit-1/polkitd --no-debug 811 /usr/sbin/spice-vdagentd -f -s /tmp/xspice-virtio -u /tmp/xspice-uinput -d 862 /sbin/getty -8 38400 tty1 871 /usr/lib/accountsservice/accounts-daemon 903 lightdm --session-child 16 20 915 /bin/sh /usr/lib/lightdm/lightdm-greeter-session /usr/sbin/unity-greeter 921 //bin/dbus-daemon --fork --print-pid 5 --print-address 7 --session 941 /usr/lib/gvfs/gvfsd 958 lightdm --session-child 12 20 961 init --user --startup-event indicator-services-start 971 /usr/lib/x86_64-linux-gnu/indicator-datetime/indicator-datetime-service 1042 /usr/bin/pulseaudio --start --log-target=syslog 1045 /usr/lib/rtkit/rtkit-daemon 1065 /usr/lib/x86_64-linux-gnu/gconf/gconfd-2 1069 /usr/lib/x86_64-linux-gnu/notify-osd 1222 /usr/lib/colord/colord 1281 -bash 2626 grep --color=auto 1
    194 upstart-udev-bridge --daemon 2635 grep --color=auto 194 upstart-udev-bridge --daemon 2635 grep --color=auto 194
    202 dbus-daemon --system --fork 2644 grep --color=auto 202 dbus-daemon --system --fork 2644 grep --color=auto 202
    252 /lib/systemd/systemd-udevd --daemon 2653 grep --color=auto 252 /lib/systemd/systemd-udevd --daemon 2653 grep --color=auto 252
    320 /lib/systemd/systemd-logind 2662 grep --color=auto 320 /lib/systemd/systemd-logind 2662 grep --color=auto 320
    402 /usr/sbin/cupsd -f 2671 grep --color=auto 402 /usr/sbin/cupsd -f 2671 grep --color=auto 402
    420 rsyslogd 2680 grep --color=auto 420 rsyslogd 2680 grep --color=auto 420
    431 avahi-daemon: running [ubuntu2.local] 2689 grep --color=auto 431 avahi-daemon: running [ubuntu2.local] 2689 grep --color=auto 431
    440 avahi-daemon: chroot helper 2698 grep --color=auto 440 avahi-daemon: chroot helper 2698 grep --color=auto 440
    459 /usr/lib/cups/notifier/dbus dbus:// 2707 grep --color=auto 459 /usr/lib/cups/notifier/dbus dbus:// 2707 grep --color=auto 459
    460 /usr/lib/cups/notifier/dbus dbus:// 2716 grep --color=auto 460 /usr/lib/cups/notifier/dbus dbus:// 2716 grep --color=auto 460
    487 dhclient -1 -v -pf /run/dhclient.eth0.pid -lf /var/lib/dhcp/dhclient.eth0.leases eth0 2725 grep --color=auto 487 dhclient -1 -v -pf /run/dhclient.eth0.pid -lf /var/lib/dhcp/dhclient.eth0.leases eth0 2725 grep --color=auto 487
    505 upstart-socket-bridge --daemon 2734 grep --color=auto 505 upstart-socket-bridge --daemon 2734 grep --color=auto 505
    513 upstart-file-bridge --daemon 2743 grep --color=auto 513 upstart-file-bridge --daemon 2743 grep --color=auto 513
    643 /usr/sbin/ModemManager 2752 grep --color=auto 643 /usr/sbin/ModemManager 2752 grep --color=auto 643
    690 NetworkManager NetworkManager
    692 /sbin/getty -8 38400 tty4 2770 grep --color=auto 692 /sbin/getty -8 38400 tty4 2770 grep --color=auto 692
    702 /sbin/getty -8 38400 tty2 2779 grep --color=auto 702 /sbin/getty -8 38400 tty2 2779 grep --color=auto 702
    703 /sbin/getty -8 38400 tty3 /sbin/getty -8 38400 tty3
    739 /usr/sbin/sshd -D 2797 grep --color=auto 739 /usr/sbin/sshd -D 2797 grep --color=auto 739
    754 acpid -c /etc/acpi/events -s /var/run/acpid.socket 2806 grep --color=auto 754 acpid -c /etc/acpi/events -s /var/run/acpid.socket 2806 grep --color=auto 754
    755 cron 2815 grep --color=auto 755 cron 2815 grep --color=auto 755
    756 whoopsie 2824 grep --color=auto 756 whoopsie 2824 grep --color=auto 756
    757 atd 2833 grep --color=auto 757 atd 2833 grep --color=auto 757
    767 /usr/lib/policykit-1/polkitd --no-debug /usr/lib/policykit-1/polkitd --no-debug
    772 /usr/sbin/kerneloops 2851 grep --color=auto 772 /usr/sbin/kerneloops 2851 grep --color=auto 772
    811 /usr/sbin/spice-vdagentd -f -s /tmp/xspice-virtio -u /tmp/xspice-uinput -d 2860 grep --color=auto 811 /usr/sbin/spice-vdagentd -f -s /tmp/xspice-virtio -u /tmp/xspice-uinput -d 2860 grep --color=auto 811
    847 lightdm 2869 grep --color=auto 847 lightdm 2869 grep --color=auto 847
    862 /sbin/getty -8 38400 tty1 2878 grep --color=auto 862 /sbin/getty -8 38400 tty1 2878 grep --color=auto 862
    868 /usr/bin/X -core :0 -seat seat0 -auth /var/run/lightdm/root/:0 -nolisten tcp vt7 -novtswitch 2887 grep --color=auto 868 /usr/bin/X -core :0 -seat seat0 -auth /var/run/lightdm/root/:0 -nolisten tcp vt7 -novtswitch 2887 grep --color=auto 868
    871 /usr/lib/accountsservice/accounts-daemon 2896 grep --color=auto 871 /usr/lib/accountsservice/accounts-daemon 2896 grep --color=auto 871
    897 /usr/sbin/cups-browsed 2905 grep --color=auto 897 /usr/sbin/cups-browsed 2905 grep --color=auto 897
    903 lightdm --session-child 16 20 2914 grep --color=auto 903 lightdm --session-child 16 20 2914 grep --color=auto 903
    915 /bin/sh /usr/lib/lightdm/lightdm-greeter-session /usr/sbin/unity-greeter 2923 grep --color=auto 915 /bin/sh /usr/lib/lightdm/lightdm-greeter-session /usr/sbin/unity-greeter 2923 grep --color=auto 915
    921 //bin/dbus-daemon --fork --print-pid 5 --print-address 7 --session 2932 grep --color=auto 921 //bin/dbus-daemon --fork --print-pid 5 --print-address 7 --session 2932 grep --color=auto 921
    922 /usr/sbin/unity-greeter 2941 grep --color=auto 922 /usr/sbin/unity-greeter 2941 grep --color=auto 922
    924 /usr/lib/at-spi2-core/at-spi-bus-launcher --launch-immediately 2950 grep --color=auto 924 /usr/lib/at-spi2-core/at-spi-bus-launcher --launch-immediately 2950 grep --color=auto 924
    930 /bin/dbus-daemon --config-file=/etc/at-spi2/accessibility.conf --nofork --print-address 3 2959 grep --color=auto 930 /bin/dbus-daemon --config-file=/etc/at-spi2/accessibility.conf --nofork --print-address 3 2959 grep --color=auto 930
    936 /usr/lib/at-spi2-core/at-spi2-registryd --use-gnome-session 2968 grep --color=auto 936 /usr/lib/at-spi2-core/at-spi2-registryd --use-gnome-session 2968 grep --color=auto 936
    941 /usr/lib/gvfs/gvfsd 2977 grep --color=auto 941 /usr/lib/gvfs/gvfsd 2977 grep --color=auto 941
    949 /usr/lib/dconf/dconf-service 2986 grep --color=auto 949 /usr/lib/dconf/dconf-service 2986 grep --color=auto 949
    958 lightdm --session-child 12 20 2995 grep --color=auto 958 lightdm --session-child 12 20 2995 grep --color=auto 958
    961 init --user --startup-event indicator-services-start 3004 grep --color=auto 961 init --user --startup-event indicator-services-start 3004 grep --color=auto 961
    963 nm-applet 3013 grep --color=auto 963 nm-applet 3013 grep --color=auto 963
    966 /usr/lib/x86_64-linux-gnu/indicator-messages/indicator-messages-service 3022 grep --color=auto 966 /usr/lib/x86_64-linux-gnu/indicator-messages/indicator-messages-service 3022 grep --color=auto 966
    967 /usr/lib/x86_64-linux-gnu/indicator-bluetooth/indicator-bluetooth-service 3031 grep --color=auto 967 /usr/lib/x86_64-linux-gnu/indicator-bluetooth/indicator-bluetooth-service 3031 grep --color=auto 967
    968 /usr/lib/x86_64-linux-gnu/indicator-power/indicator-power-service /usr/lib/x86_64-linux-gnu/indicator-power/indicator-power-service
    971 /usr/lib/x86_64-linux-gnu/indicator-datetime/indicator-datetime-service 3049 grep --color=auto 971 /usr/lib/x86_64-linux-gnu/indicator-datetime/indicator-datetime-service 3049 grep --color=auto 971
    978 /usr/lib/x86_64-linux-gnu/indicator-keyboard-service --use-gtk 3058 grep --color=auto 978 /usr/lib/x86_64-linux-gnu/indicator-keyboard-service --use-gtk 3058 grep --color=auto 978
    979 /usr/lib/unity-settings-daemon/unity-settings-daemon 3067 grep --color=auto 979 /usr/lib/unity-settings-daemon/unity-settings-daemon 3067 grep --color=auto 979
    985 /usr/lib/upower/upowerd 3076 grep --color=auto 985 /usr/lib/upower/upowerd 3076 grep --color=auto 985
    986 /usr/lib/x86_64-linux-gnu/indicator-sound/indicator-sound-service 3085 grep --color=auto 986 /usr/lib/x86_64-linux-gnu/indicator-sound/indicator-sound-service 3085 grep --color=auto 986
    987 /usr/lib/x86_64-linux-gnu/indicator-session/indicator-session-service 3094 grep --color=auto 987 /usr/lib/x86_64-linux-gnu/indicator-session/indicator-session-service 3094 grep --color=auto 987
    993 /usr/lib/x86_64-linux-gnu/indicator-application/indicator-application-service 3103 grep --color=auto 993 /usr/lib/x86_64-linux-gnu/indicator-application/indicator-application-service 3103 grep --color=auto 993
    1042 /usr/bin/pulseaudio --start --log-target=syslog 3112 grep --color=auto 1042 /usr/bin/pulseaudio --start --log-target=syslog 3112 grep --color=auto 1042
    1045 /usr/lib/rtkit/rtkit-daemon 3121 grep --color=auto 1045 /usr/lib/rtkit/rtkit-daemon 3121 grep --color=auto 1045
    1065 /usr/lib/x86_64-linux-gnu/gconf/gconfd-2 3130 grep --color=auto 1065 /usr/lib/x86_64-linux-gnu/gconf/gconfd-2 3130 grep --color=auto 1065
    1069 /usr/lib/x86_64-linux-gnu/notify-osd 3139 grep --color=auto 1069 /usr/lib/x86_64-linux-gnu/notify-osd 3139 grep --color=auto 1069
    1222 /usr/lib/colord/colord 3148 grep --color=auto 1222 /usr/lib/colord/colord 3148 grep --color=auto 1222
./lxc/cgroup.procs:
./user/1000.user/c2.session/cgroup.procs:
./user/1000.user/cgroup.procs:
./user/cgroup.procs:
./cgroup.procs:

A: I made spice-vdagentd work by running it with "-X" option to disable systemd-login integration.
https://bugs.launchpad.net/ubuntu/+source/spice-vdagent/+bug/1633609?comments=all

A: Take a look here:
https://s3hh.wordpress.com/2014/04/18/xspice-in-containers/
That is the blog site of one of the LXC developers.
He also might be interested in your approach/progress.


text:
Q: disable cropping featured image in wordpress I am using featured image as a post image but on uploading a image it crops while setting it as featured image, i dnt find any solution for it, Can any one help?
Wordpress Admin panel screenshot:-

This image is actually 1024x702 but it cuts to 940x198, i cant find any soltuion for this how to disabling the cropping...

A: Not sure how to disable cropping but you could try to use add_image_size function to register a bigger image size.
Something like this: (add this in functions.php)
add_image_size( 'featuredImageCropped', 1024, 768, true );

And then locate the_post_thumbnail in the template and modify it like this:
the_post_thumbnail( 'featuredImageCropped' );

A: Inside your theme there is file called functions.php - inside functions.php you will find a line of code similar to this:
add_image_size('featured', 940, 198, true);

These parameters are the name, width, height, and crop.
When crop is set to "true" your image will be resized so that it fills the width-height dimensions completely. The shortest side of the image will be equal to the maximum allowed value, and the longest side of the image will be cropped.
When crop is set to "false" your image will be resized so that it fits inside the width-height dimensions. The longest side of the image will be equal to the maximum allowed value, and the shorter side of the image will be smaller.
I would recommend playing with these settings to achieve the exact effect that you're after. Most likely what you want is not to disable cropping, but rather to simply increase the maximum allowed height of your featured image.


text:
Q: What is the term for an inheriting class constructor with different parameters? Take the example below.  What term do you use to describe an inheriting class with different parameters then the base class?  I understand that subbase is implicitly calling base().  You wouldn't call this overriding, correct, since the base constructor is still called?
#include <iostream>
#include <stdio.h>
#include <string>

using namespace std;

class base
{
public:
   base()
   {
      cout << "Hello!\n";
   }
};

class subbase : public base
{
public:
   subbase(string s)
   {
      cout << s << endl;
   }
};

int main()
{
   subbase test("Hello World!\n");

   return 0;
}

A: Overloaded my friend. It has same method name but differing parameter or return type
But in this case you are just creating whole new constructor. Not really inheriting or anything.

A: Overloading: When you change the signature of the inherited functions in the derived class.
Redefinition(In case of normal functions)/Overriding(In case of virtual functions): When you keep the signature of the base class functions same in the derived class. But you change the implementation part.
But I am not talking in terms of Constructors here. I am talking about the usual member functions of the class.


text:
Q: How can RxJava interval/infinite counter be implemented with Kotlin Flow in reactive way? How can interval counterpart of RxJava interval, infinite counter with delay and time unit, implemented with Flow in reactive way? And how should cancel mechanism work since only way to cancel a Flow is to cancel scope or job of the coroutine and after that coroutine is canceled it does not work?

A: I made a simple implementation of RxJava interval.
fun interval(timeInMillis: Long, timeUnit: TimeUnit): Flow<Long> = flow {

    var counter: Long = 0

    val delayTime = when (timeUnit) {
        TimeUnit.MICROSECONDS -> timeInMillis / 1000
        TimeUnit.NANOSECONDS -> timeInMillis / 1_000_000
        TimeUnit.SECONDS -> timeInMillis * 1000
        TimeUnit.MINUTES -> 60 * timeInMillis * 1000
        TimeUnit.HOURS -> 60 * 60 * timeInMillis * 1000
        TimeUnit.DAYS -> 24 * 60 * 60 * timeInMillis * 1000
        else -> timeInMillis
    }

    while (true) {
        delay(delayTime)
        emit(counter++)
    }

}

And used it  with launchIn to have job similar to disposable.
val coroutineScope = CoroutineScope(SupervisorJob())

  val job =  coroutineScope.launch {
        val job = interval(1, TimeUnit.SECONDS)
            .onStart {
                emit(-1)
            }
            .onEach {
                println(it)
            }
            .map {
                "Current time $it"
            }
            .launchIn(coroutineScope)

    }

Used another coroutineScope to not cancel other jobs that are in existing coroutineScope, when a coroutineScope.cancel() or cancel function of job belong to that coroutineScope is canceled jobs cannot be started again.
Of course this answer might be improved or better one, i don't accept it.


text:
Q: Mathematica not creating Graph Trying to make a graph according to the  documentation, but it isn't being made. I try plotting with no success; it seems like the graph isn't being created.
Does this have anything to do with importing Combinatorica?


text:
Q: Handling null, even if annotations are used I started using javax.annotation especially to warn the next developer who maybe will be working with my code in the future.
But while I was using the javax.annotation @Nonnull annotation, a question came into my mind:
If you mark f.e. a parameter of a method thorugh the @Nonnull annotation that it haves to have a value,
do you still need to handle the case, that the next developer who is using your code could be parsing null to your function?
If found one con argument and one pro argument to still handle the special cases.
con: The code is cleaner, especially if you have multiple parameters that you mark with @Nonnull
private void foo(@Nonnull Object o)
{
    /*do something*/
}

vs
public void foo(Object o)
    throws NullPointerException
{
    if (o == null)
    {
        throw new NullPointerException("Given Object must have a value!");
    }
    /*do something*/
}

pro: It could cause unhandled errors if the next developer ignore the annotations.

A: This is an unsolved problem in the nullity annotation space. There are 2 viewpoints that sound identical but result, in fact, in the exact opposite. Given a parameter void foo(@NonNull String param), what does that imply?

*

*It's compiler-checkable documentation that indicates you should not pass null as param here. It does not mean that it is impossible to do this, or that one ought to consider it impossible. Simply that one should not - it's compiler-checkable documentation that the method has no defined useful behaviour if you pass null here.

*The compiler is extended to support these annotations to treat it as a single type - the type of param is @NonNull String - and the compiler knows what that means and will in fact ensure this. The type of the parameter is @NonNull String and therefore cannot be null, just like it can't be, say, an InputStream instance either.

Crucially, then, the latter means a null check is flagged as silly code, whereas the former means lack of a null check is marked as bad. Hence, opposites. The former considered a nullcheck a warnable offense (with something along the lines of param can never be null here), for the same reason this is silly code:
void foo(String arg) {
  if (!(arg instanceof String)) throw new IllegalArgumentException("arg");
}

That if clause cannot possibly fire. The mindset of various nullchecker frameworks is identical here, and therefore flags it as silly code:
void foo(@NonNull String arg) {
  if (arg == null) throw new NullPointerException("arg");
}

The simple fact is, plenty of java devs do not enable annotation-based nullity checking, and even if they did, there are at least 10 competing annotations and many of them mean completely different things, and work completely differently. The vast majority will not be using a checking framework that works as you think it should, therefore, the advice to remove the nullcheck because it is silly is actively a bad thing - you should add that nullcheck. The linting tools that flag this down are misguided; they want to pretend to live in a world where every java programmer on the planet uses their tool. This isn't try and is unlikely to ever become true, hence, wrong.
A few null checking frameworks are sort of living both lives and will allow you to test if an argument marked as @NonNull is null, but only if the if body starts with throw, otherwise it's flagged.
To answer your questions:

*

*You should nullcheck. After all, other developers that use your code may not get the nullity warnings from the nullcheck tool (either other team members working on the same code base but using slightly different tools and/or configurations of those tools, or, your code is a library and another project uses it, a more obvious route to a situation with different tools/configs). The best way to handle a null failure is a compile time error. A close second is an exception that is clear about the problem and whose stack trace can be used to very quickly solve the bug. A distant third is random bizarreness that takes a whole to debug - and that explicit nullcheck means you get nice fallback: If for whatever reason the write-time tooling doesn't catch the problem, the check will then simply turn it into the second, still quite acceptable case of an exception at the point of failure that is clear about what happened and where to fix it.

*Lombok's @NonNull annotation can generate it for you, if you want. Now you have the best of both worlds: Just a @NonNull annotation (no clutter) and yet a runtime exception if someone does pass null anyway (DISCLAIMER: I'm one of the core contributors to Lombok).

*If your linting tool complains about 'pointless null check' on the line if (param == null) throw new NullPointerException("param");, find the option in the linting tool to exclude if-checks that result in throw statements. If the linting tool cannot be configured to ignore this case, do not use the linting tool, find a better one.

*Note that modern JVMs will throw a NullPointerException with the name of the expression as message if you dereference a null pointer, which may obviate the need to write an explicit check. However, now you're dependent on that method always dereferencing that variable forever more; if ever someone changes it and e.g. assigns it to a field and returns, now you have a problem: It should have thrown the exception, in order to ensure the bug is found quickly and with an exception that explains what happened and where to go and fix the problem. Hence I wouldn't rely on the JVM feature for your NPEs.

*Error messages should be as short as they can be whilst not skimping on detail. They should also not end in punctuation; especially exclamation marks. Every exception tends to be noteworthy enough to warrant an exclamation mark - but it gets tedious to read them, so do not add them. In fact, the proper thing to throw, is this: throw new NullPointerException("o"). - and you might want to rename that parameter to something more readable if you find o ugly. Parameters are mostly public API info (JVM-technically they are not, but javadoc does include them, which is the basis of API docs, so you should consider them public, and therefore, they should have clear names. Which you can then reuse). That exception conveys all relevant information to a programmer: The nature of the problem (null was sent to code that does not know how to handle this), and where (the stack trace does that automatically), and the specifics (which thing was null). Your message is much longer and doesn't add anything more. At best you can say your message might be understood by a non-coder, except this is both not true (as if a stack trace is something random joe computeruser is going to understand), and irrelevant (it's not like they can fix the problem even if they do know what it means). Using exception messages as UI output just doesn't work, so don't try.

*You may want to adjust your style guides and allow braceless if statements provided that the if expression is simple (no && or ||). Possibly add an additional rule that the single statement is a control statement - break;, continue;, return (something);, or throw something;. This will significantly improve readability for multiparams. The point of a style guide is to create legible code. Surely this:
if (param1 == null) throw new NullPointerException("param1");
if (param2 == null) throw new NullPointerException("param2");

is far more legible, especially considering this method has more lines than just those two, than this:
if (param1 == null) {
  throw new NullPointerException("param1");
}

if (param2 == null) {
  throw new NullPointerException("param2");
}

Styleguides are just a tool. If your styleguide is leading to less productivity and harder to read code, the answer should be obvious. Fix or replace the tool.


text:
Q: c++ vector iterator deference inconsistency I have the following code. When dereference in line 5, I got wrong value of (*it)->sec. while in line 8, I can obtain correct value. The only difference I noticed is one is inside the for loop, the other is outside the for loop. Is there some subtle point I missing here.  I basically want to obtain the member value of the first element in the vector. What's the correct way of obtaining the first (*it)->sec before(outside) the for loop?
void print_allAddresses(std::vector<EntryObj *> EntryObj_vec){
    std::cout << "time(sec:microsec) dataType memoryValue" << std::endl;
    std::vector<EntryObj *>::iterator it;
    it = EntryObj_vec.begin();
    std::cout << (*it)->sec << std::endl; //EntryObj_vec.front()->sec also wrong here.
    for(it = EntryObj_vec.begin(); it != EntryObj_vec.end(); ++it){
        if(!(*it)->parameters.empty()){
            std::cout << (*it)->sec << "." << (*it)->microsecond << " ";

            std::map<std::string, std::string>::iterator it_map;
            for (it_map = (*it)->parameters.begin(); it_map != (*it)->parameters.end(); it_map++){
                std::cout << "(" << it_map->first<< ")" << " " << it_map->second << std::endl;
            }
        }
    }
    return;
}


text:
Q: How to upload multiple files form local directory via PowerShell to SharePoint Online? I have a lot of files in a local folder (> 5.000) which need to be uploaded to SharePoint Online through PowerShell.
How can i loop through all files within a local folder, authenticate myself againt SharePoint Online and upload the files to a document library through PowerShell?


text:
Q: Overriding a apply_filter with add_filter duplicates the output? I have this function
function bp_insert_activity_meta( $content ) {
    global $activities_template;

    // Strip any legacy time since placeholders from BP 1.0-1.1
    $content = str_replace( '%s', '', $content );

    // Insert the time since.
    $time_since = apply_filters_ref_array( 'bp_activity_time_since', array( '' . bp_core_time_since( $activities_template->activity->date_recorded ) . '', &$activities_template->activity ) );

    // Insert the permalink
    if ( !bp_is_single_activity() )
        $content = apply_filters_ref_array( 'bp_activity_permalink', array( sprintf( '%1$s %4$s', $content, bp_activity_get_permalink( $activities_template->activity->id, $activities_template->activity ), esc_attr__( 'View Discussion', 'buddypress' ), $time_since ), &$activities_template->activity ) );
    else
        $content .= str_pad( $time_since, strlen( $time_since ) + 2, ' ', STR_PAD_BOTH );

    return apply_filters( 'bp_insert_activity_meta', $content );
}

I want to add_Filter to this part:
$content = apply_filters_ref_array( 'bp_activity_permalink', array( sprintf( '%1$s %4$s', $content, bp_activity_get_permalink( $activities_template->activity->id, $activities_template->activity ), esc_attr__( 'View Discussion', 'buddypress' ), $time_since ), &$activities_template->activity ) );

This is how I tried to add_filter, but the output comes out twice, one for the original code and a second time with my code (note I added a "testing-class-for-filter" class to the link to see if it is outputting it)
function testing_filter_abc( $content ) {
    global $activities_template;

    // Insert the time since.
    $time_since = apply_filters_ref_array( 'bp_activity_time_since', array( '' . bp_core_time_since( $activities_template->activity->date_recorded ) . '', &$activities_template->activity ) );

    return sprintf( '%1$s %4$s', $content, bp_activity_get_permalink( $activities_template->activity->id, $activities_template->activity ), esc_attr__( 'View Discussion', 'buddypress' ), $time_since );
}

add_filter( 'bp_activity_permalink', 'testing_filter_abc' );

Is there something obvious that I am not doing? Been trying for hours to get this to work!
Thanks in advance

A: In your function testing_filter_abc( $content )
$content is an array with 2 elements; a string and a reference.
There is no variable $content like that variable in function bp_insert_activity_meta
Your return in testing_filter_abc() includes the array that was passed to your filter.
Use a different name for the array passed to your filter and it will be more obvious.
function testing_filter_abc( $content_array ) {
  var_dump( $content_array )


text:
Q: Adding a QWidget to a QGraphicsScene I have a QGraphicsScene for drawing, where I now want to "add" a QWidget to a QGraphicsItem (display on top of the item, which can of course be moved).
How could this be accomplished? Is there any QGraphicsItem, which may function as a Widget container?

A: You can use QGraphicsScene::addWidget  which creates a new QGraphicsProxyWidget for widget, adds it to the scene, and returns a pointer to the proxy :
QGraphicsProxyWidget * item = myScene->addWidget(myWidget);
item->setParentItem(anOtherItem);
item->setPos(100,100);
item->setZValue(1);


text:
Q: Display distinct data from column (and count) within SQL I have an issue with a trigger I am trying to create. I want the trigger to display an error message if the D_EMP_ID entries (for each individual ID) exceeds 9. in other words an employee with the ID of '1000' can have no more than 9 entries. If the tenth entry is added for '1000' it should display error.
But at the moment it doesn't show the error. whenever I add a new entry it gets added. Even if its the tenth, 11th, 12th etc.
Below is the code of the trigger:
CREATE OR REPLACE TRIGGER tri_order_line_count
  BEFORE INSERT OR UPDATE ON pl_work_allocation FOR EACH ROW
DECLARE
  order_count INTEGER;
BEGIN
  SELECT COUNT(*) INTO order_count
   FROM pl_work_allocation WHERE d_emp_id = :new.d_emp_id;

  IF (order_count > 9) THEN
    raise_application_error(-20001, 'Too many roles for ' || :new.d_emp_id || '');
  END IF;
END;

Below is the layout of the PL_WORK_ALLOCATION table:
S_REPORTED_CRIME_ID- D_EMP_ID-  WORK_DESC-  LEAD_POLICE_OFFICER-    WORK_START_DATE-   WORK_END_DATE-
12                   1000         example       1001                 08/26/2011         09/27/2012
15                   1010          test         1001                 08/26/2011         09/27/2012
1                    1000       Investigation   1003                 08/26/2011         08/26/2012

A: i think you should add Rollback after raising error
if (order_count > 9)
             then raise_application_error(-20001,
         'Too many roles for '|| :new.D_EMP_ID ||'' );
         ROLLBACK;
end if;


text:
Q: xs="0" in Reactstrap is not working for mobile view I want to set column to be invisible in the mobile view. Setting 12 for the content works but 0 for the sidebar column doesn't - (it renders full width). How can I achieve this?
I tried to set Collapse around the first column, which didn't work. I wanted to ask to learn the best practice. Thanks.
<Row>
    <Col xs="0" sm="3">
        <Sidebar></Sidebar>
    </Col>
    <Col xs="12" sm="9">
        ... Rest of the content here.

A: I found an answer.
I added the following classes to the sidebar wrapper. I believe this is missing in reactstrap.
<Col xs="0" sm="3" className="d-none d-lg-block">
    <Sidebar></Sidebar>
</Col>
<Col xs="12" sm="9">


text:
Q: Bootstrap screen demo needs to be responsive Take a look at this http://jsfiddle.net/0ftrnkxo/
and the site http://omarhabash.com/sites
This looks great from a desktop.. I usually dont have problems with responsive design but what can I do to make this responsive?
THE HTML

    <button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#site1">

    </button>

THE CSS
.same-s {
    height: 160px;
    width: 100%;
    margin: 0 auto;
}
.same-s img {
    width: 100%;
    display: block;
    margin: 0 auto;
    height: auto;
}
.same-s.same-1 {
    width: 66.5%;
    overflow: scroll;
    position: absolute;
    margin-left: 174px;
    margin-top: 65px;
    height: 57.25%;
}
.demo-container {
    height: 56em;
}
button.btn.btn-primary.btn-lg {
    margin-left: 9.9em;
    margin-top: 26.5em;
    position: absolute;
}
img.site {
    border: 4px solid #ccc;
}

A: With any grid system it's best to keep it and your content separate. Don't "hack the core", as the saying goes. Here's a simplified start:
http://jsfiddle.net/isherwood/0ftrnkxo/3
.demo-container {
    overflow: hidden; /* demo only--accounts for image whitespace */
}
.mac {
    position: relative;
    margin: -5.3% -20.5% 0 -18.5%; /* demo only--accounts for image whitespace */
}
.screen {
    position: absolute;
    top: 9%; /* demo only--accounts for image whitespace */
    right: 17%; /* demo only--accounts for image whitespace */
    left: 15.6%; /* demo only--accounts for image whitespace */
    height: 58%;
    overflow: auto;
}

To eliminate all those negative margins and the corresponding values on .screen, crop your Mac image tight to the black border. Of course, you'll still need smaller top, right, and left values to allow the Mac's frame to show around it.
I'd also fill the Mac image's screen entirely with black. That will eliminate the need to so perfectly position what's overlaying it.
Here's a demo with two Macs in two rows.


text:
Q: Is there an easy way to place grid in plot to background R I have to plot grid in my plots. I have found one solution for this purpose
barplot(1:50)
grid()
box()
par(new = TRUE)
barplot(1:50)

And following is the plot

I am ok with it. But why I should call barplot twice. Is there some easy way to move grid to background ?
I have faced following problem is my plot (boxplot)
png("test2.png")
bm = boxplot(exuper, fuper, super, tuper, dat$uper, outline = F, names=names, panel.first = grid())
box()
dev.off()

AND THE ERROR is
Error in int_abline(a = a, b = b, h = h, v = v, untf = untf, ...) :
  plot.new has not been called yet
> box()
Error in box() : plot.new has not been called yet


text:
Q: How to float li elements inside multi column list I have the following HTML:

10.09

My title is here

Author

with the following css:
.baseList {
    border: 1px solid #F00;
}

.baseListColumn {
    -moz-column-count:3;
    -webkit-column-count:3;
    column-count:3;

    -moz-column-gap: 10px;
    -webkit-column-gap: 10px;
    column-gap: 10px;
}

My problem is, that this centers the content of every li of baseListColumn and gives every column the same width. I would like to make the columns fit it's content apart from the last li element (Author) and float the content of the last li element right.
This is what happens with the current code: http://jsfiddle.net/aLGRJ/1/
           10.09                   My title is here                 Author
     asdfasdfasdfasdf           My title is here abababa            Author

In fiddle you can even see what happens if the width of the root li is big enough while the equal splitting of the columns is too small to contain some of the content.
This is what I would like to have:
10.09                My title is here                                      Author
asdfasdfasdfasdf     My title is here abababa                              Author

I can't guarantee that all the columns will always have the same length otherwise I would use absolute positioning and at the same time I don't want to reserve too much unnecessary space for the first column for example. Note I'm planning to use this for lists with more columns than just 3 as well.
Is this one of the cases where a table would be the better solution? Anyways I hope someone can help me, and if there is a better solution to this, I'm always open for suggestions.

A: It looks like a table would be a better solution, not because of the display properties, but because of the nature of your content (remember, organizing content is still the responsibility of HTML).
Take a look at this page.
While most of the points are generally agreeable, I tend to focus on two things:

*

*Don't Use Faux Tables (
,
, etc.)

*Tables Should Be Filterable & Sortable (If more then just a few rows)

You can generate all of the CSS yourself... or, use your favorite ECMAScript library to make short work of styling.


text:
Q: HtmlUnit - PKIX path building failed: unable to find valid certification path to requested target I have a JAVA EE webapp on Glassfish using a GoDaddy SSL certificate. The HTTP listener redirects to the HTTPS one.
I'm trying to get HtmlUnit to fetch a page from the webapp for Googlebot crawler. The code works as intended on the staging server which doesn't have SSL enabled. However, on the live server with the GoDaddy SSL certificate, I get the below error when HtmlUnit tries to get the webpage.
I've tried the workaround specified here (http://www.mkyong.com/webservices/jax-ws/suncertpathbuilderexception-unable-to-find-valid-certification-path-to-requested-target/), but that didn't help. Any ideas as why I get this error ?
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1917)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:301)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:295)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1471)
at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:212)
at sun.security.ssl.Handshaker.processLoop(Handshaker.java:936)
at sun.security.ssl.Handshaker.process_record(Handshaker.java:871)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1043)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1343)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1371)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1355)
at org.apache.http.conn.ssl.SSLConnectionSocketFactory.createLayeredSocket(SSLConnectionSocketFactory.java:275)
at org.apache.http.conn.ssl.SSLConnectionSocketFactory.connectSocket(SSLConnectionSocketFactory.java:254)
at com.gargoylesoftware.htmlunit.HtmlUnitSSLConnectionSocketFactory.connectSocket(HtmlUnitSSLConnectionSocketFactory.java:155)
at org.apache.http.impl.conn.HttpClientConnectionOperator.connect(HttpClientConnectionOperator.java:117)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:314)
at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:363)
at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:219)
at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:195)
at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:86)
at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:108)
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:186)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:72)
at com.gargoylesoftware.htmlunit.HttpWebConnection.getResponse(HttpWebConnection.java:178)
at com.gargoylesoftware.htmlunit.WebClient.loadWebResponseFromWebConnection(WebClient.java:1313)
at com.gargoylesoftware.htmlunit.WebClient.loadWebResponse(WebClient.java:1230)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:338)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:407)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:392)

A: A workaround is to just disable SSL on the requested page. Not the same thing, granted, but this crap just got too annoying. To disable SSL use the following on the webClient object:
 webClient.getOptions().setUseInsecureSSL(true);


text:
Q: How to get intervals as a list of vectors? I have a numeric vector and I need to get the intervals as a list of vectors.
I thought it was easy but I'm really struggling to find a good, simple way.
A bad, complex way would be to paste the vector and its lag, and then split the result.
Here is the working but ugly reprex:
library(tidyverse)
xx = c(1, 5, 10 ,15 ,20)
paste0(lag(xx), "-", xx-1) %>% str_split("-") #nevermind the first one, it cannot really make sense anyway
#> [[1]]
#> [1] "NA" "0"
#>
#> [[2]]
#> [1] "1" "4"
#>
#> [[3]]
#> [1] "5" "9"
#>
#> [[4]]
#> [1] "10" "14"
#>
#> [[5]]
#> [1] "15" "19"

Created on 2020-09-06 by the reprex package (v0.3.0)
Is there a cleaner way to do the same thing?

A: You can use Map :
Map(c, xx[-length(xx)], xx[-1] - 1)

#[[1]]
#[1] 1 4

#[[2]]
#[1] 5 9

#[[3]]
#[1] 10 14

#[[4]]
#[1] 15 19

We can also use lapply iterating over the length of the variable.
lapply(seq_along(xx[-1]), function(i) c(xx[i], xx[i+1] - 1))

A: We can use map2 from purrr
library(purrr)
map2(xx[-length(xx)], xx[-1] -1, c)


text:
Q: Send Email without attachments I have a Problem i know how to send email with attachment but i want to learn that if i dont have screenshot.png then i want to send it without attachment my code is below
string email = "hammadptc93@gmail.com";
string pass = "mypassword";
NetworkCredential loginInfo = new NetworkCredential(email, pass);
MailMessage msg = new MailMessage();
SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587);

msg.From = new MailAddress(email);
msg.To.Add(new MailAddress("hammadptc93@gmail.com"));
msg.Body = value;
msg.Subject = Environment.UserName +"   " +
              Environment.UserDomainName +"    "+ Environment.SystemDirectory ;
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("screenshot.png");
msg.Attachments.Add(attachment);
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = loginInfo;

smtpClient.SendAsync(msg, "hammad");

A: Simply checking whether file is present or not will be enough.
if(File.Exists("screenshot.png"))
{
   System.Net.Mail.Attachment attachment;
   attachment = new System.Net.Mail.Attachment("screenshot.png");
   msg.Attachments.Add(attachment);
}

A: Use File.Exists method to check whether you have the attachment. If File.Exists returns false, side step from following lines (wrap them in a if statement)
    System.Net.Mail.Attachment attachment;
    attachment = new System.Net.Mail.Attachment("screenshot.png");
    msg.Attachments.Add(attachment);

Hope this helps


text:
Q: Let $c:I\rightarrow\mathbb R^3$ a regularly parametrized curve with curvature $\kappa=0$ where $I\subset\mathbb R$ is an interval. Show that the image of $c$ is contained in a straight line.
we defined the curvature with;
$\kappa_c(t)= \frac{1}{||\dot{c}(t)||^3}det(\dot{c}(t),{\ddot{c}(t)})$
Since it's regularly parametrized, $\dot{c}(t)≠0$, therefore $det$ must be zero,
Hence $\dot{c}\ and\ \ddot{c} $are linearly dependent $\Rightarrow\lambda\dot{c}=\ddot{c}$???
this has nothing to do with a line.

A: The formula you want to use is given for a plane curve only (the determinant of two vectors in $\mathbb R^3$ is not well defined).
If $c:I\rightarrow \mathbb R^3$ is a curve, then its curvature is given by $$\kappa_c(t)=\dfrac{\|\dot{c}(t)\times \ddot{c}(t) \|}{\|\dot{c}(t)\|^3}$$
Actually, you can check that the curvature of a curve is independent of the choice of the parametrization. It is a geometric invariant of a curve, so you can choose the arc-length parametrization when the curve is regular.
Assume now that $c$ is parametrized by the arc-length i.e. $\|\dot{c}(t)\|^2=\langle \dot c(t),\dot c(t)\rangle = 1$. Then you can differentiate this last expression to get : $$\langle \ddot{c}(t), \dot c(t)\rangle =0.$$
This means that this two vectors are perpendicular. But, $$\kappa_c(t)=\|\dot{c}(t)\times \ddot{c}(t) \|=0$$
so $\ddot c(t)=0$ for all $t\in I$ since $\dot c(t)\neq 0$.
Hence, $c(t)=c(0)+tc'(0)$ on $I$ and the curve is contained in a line.


text:
Q: CURL With Spoof ip address I heard from some friend that we can spoof our ip address in Curl with HTTP_X_FORWARDED_FOR , so i decide to test it and i create three file one to send Curl :
<?php

$ip = '1.1.1.1';
$url = "http://127.0.0.1/mydir/getdata.php";
$options = array (
    CURLOPT_CONNECTTIMEOUT => 1, // timeout on connect
    CURLOPT_TIMEOUT => 1, // timeout on response
    CURLOPT_MAXREDIRS => 1 ,
    CURLOPT_HTTPHEADER => array("REMOTE_ADDR: $ip", "HTTP_X_FORWARDED_FOR: $ip"),
    CURLOPT_URL => $url ,
    );
$ch = curl_init();
curl_setopt_array ( $ch, $options );
print_r("+");
$result = curl_exec($ch);
curl_close($ch);

?>

one to get and save data :
<?php
    $file = 'ip.txt';
    $ipaddress = $_SERVER["REMOTE_ADDR"] .'\n';
    file_put_contents($file, $ipaddress, FILE_APPEND );
?>

and one to see the ip addresses as you can see 'ip.txt'.
But the problem is all i get in ip.txt is '127.0.0.1' and no spoof ip !!
If this is not working at all , What is the solution ?
Update :
I find out this :

No. libcurl operates on a higher level than so. Besides, faking IP
  address would imply sending IP packages with a made-up source address,
  and then you normally get a problem with intercepting the packages
  sent back as they would then not be routed to you!

Then how can i test a webpage with different IP address ?
I have some experience with programming language python , it can send a packet with spoof ip address but the problem is , it cant fully create TCP three way hand shaking process and the main website understand it.


text:
Q: Updating to Wakanda 11: "[Backend] Cannot read property 'replace' of undefined in undefined on line undefined" I am looking to move my Wakanda application, created in Enterprise Studio v10, to Enterprise Studio/Server v11. I can start the solution successfully, but when I try to view my webapp in browsers, Wakanda Studio logs the error:

[Backend] Cannot read property 'replace' of undefined in undefined on line undefined

and the browser shows just a white page with some console errors (below).
Edit: commenting out all occurrences of .replace() does not solve the problem. I do not believe it is possible that this issue is the result of .replace() statements that I've written.
I do use string.replace() with regular expressions in a few places. The code works perfectly fine in v10 and am confused about what could be wrong.
Here is an example of how I am using replace() in the code:
var tempString = "";
tempString = tempEntity.sourceProjects;
tempString = tempString.replace(/,/g, " ");
tempString = tempString.replace(/other_/, "Other: ");

The code was more streamlined before- I broke it out into pieces in an attempt to get rid of the error, but no dice.
Browser with console errors:

What I see when I click on "Loader.js: 2073"

A: 1) Quit Wakanda
2) Delete the old index.package.json file inside of index.waPage
3) Restart Wakanda and let Wakanda v11 regenerate it

A: You have the error :  "Cannot read property 'replace' of undefined" because in line 2, tempEntity is an empty string and  you write tempEntity.sourceProjects.
The value of tempEntity.sourceProjects is "undefined", so when you try to use replace in line 3 you get this error.
Issam


text:
Q: How to load theme textdomain from plugin? I built a simple localization plugin to suit some specifications needed by my orgnanization. For each language there is a single .mo file  that contains both the theme translations as the page content translations. The .mo files are located in  myplugin/languages/en_US.mo. I'm trying to use these .mo files for all gettext calls however I cannot get them to work.
Here is the code I'm using to load the text domain:
echo get_locale(); // es_ES
$directory = dirname(plugin_basename(__FILE__)) . '/lang/';
load_plugin_textdomain('localization-v', false, $directory);
_e("English");

A: You are completely loading your language file wrong in your plugin, and your file naming is also wrong.
load_theme_textdomain('my_plugin', plugin_dir_path( __FILE__ ) . '/languages');

should be
load_plugin_textdomain('my_plugin', false, dirname(plugin_basename(__FILE__)) . '/lang/');

Also, your mo and po files should be named my_plugin-en_US.mo and my_plugin-en_US.po. Go have a look at this tutorial also, this will help you out a lot.


text:
Q: Centering inline-block - Chrome ignore css top position after window resize, BUG? I am trying to use vertical centering through http://jsfiddle.net/AqcfN/:
.is-verticallyCentered {
    position: relative;
    top: 50%;
    -webkit-transform: translateY(-50%);
    -ms-transform: translateY(-50%);
    transform: translateY(-50%);
}

Everything is working fine until I resize Chrome window to met mediaQueries at (min-width: 500px) from higher resolution.
.windowOverlay_container {
    display: block;
}

@media all and (min-width: 500px) {
    .windowOverlay_container {
        display: inline-block;
    }
}

Parent of whiteBox is changed from inline-block to block (whiteBox is on the left then) and it is still ok (whiteBox is vertically centered) but after resize from <500px to 501px+ -> Chrome ignore "top: 50%" on the parent and whiteBox is no longer centered.
Simply Chrome ignore top position when element changed display: block to inline-block by mediaQueries.

(I don't want to use display: table/table-cell.)
(When I used only "display: inline-block" whole time, then there is no problem. - it solved my problem on my project)

A: Remove:
top: 50%;
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
transform: translateY(-50%);

And add:
-webkit-transform: translateY(25%);
-moz-transform: translateY(25%);
-ms-transform: translateY(25%);
-o-transform: translateY(25%);
transform: translateY(25%)


text:
Q: Determine which version of OpenCV I want to write to short code snippet in python, to determine which version of OpenCV has been installed in my System. How do i do it ?
Thank you.

A: One line way can be like below:-

A: >>> from cv2 import __version__
>>> __version__
'$Rev: 4557 $'

If that doesn't work then, use cv instead of cv2.

A: Convenient functions to check OpenCV version in run-time
def cv2():
    return opencv_version("2")

def cv3():
    return opencv_version("3")

def cv4():
    return opencv_version("4")

def opencv_version(version):
    import cv2
    return cv2.__version__.startswith(version)

Useful when performing cv2.findContours() since return signature varies by version
# Using OpenCV 2.X or OpenCV 4
if cv2() or cv4():
    cnts, _ = cv2.findContours(image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

# Using OpenCV 3
elif cv3():
    _, cnts, _ = cv2.findContours(image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

A: In terminal write:

*

*for python 2.X python2 -c 'import cv2; print cv2.__version__'

*for python 3.X python3 -c 'import cv2; print(cv2.__version__)'


text:
Q: Issue With Counting Number of Characters in Two Strings The purpose of this function is to compare the number of times a color appears in the code and the number of times it appears in the guess to ultimately determine how many colors were guessed correctly. I am experiencing some errors with my current code, and I believe that the number of lines could be greatly simplified. More specifically, I think I am overcomplicating the task at hand.
Does anyone have a suggestion of a better way to tackle this problem? I am very new to programming and it would be greatly appreciated.
validColors = ("R", "G", "B", "Y", "O", "P")

secretCode = "YBGG"
guess = "BYYG"

def correctColorCount(secretCode, guess, validColors):

    count = 0

    numRedGuess = guess.count("R")
    numRedCode = secretCode.count("R")
    sumR = numRedGuess + numRedCode

    numGreenGuess = guess.count("G")
    numGreenCode = secretCode.count("G")
    sumG = numGreenGuess + numGreenCode

    numBlueGuess = guess.count("B")
    numBlueCode = secretCode.count("B")
    sumB = numBlueGuess + numBlueCode

    numYellowGuess = guess.count("Y")
    numYellowCode = secretCode.count("Y")
    sumY = numYellowGuess + numBlueCode

    numOrangeGuess = guess.count("O")
    numOrangeCode = secretCode.count("O")
    sumO = numOrangeGuess + numOrangeCode

    numPurpleGuess = guess.count("P")
    numPurpleCode = secretCode.count("P")
    sumP = numPurpleGuess + numPurpleCode

    if numRedCode == numRedGuess and sumR != 0 and sumR != 1:
        count += 1
        if numRedGuess == 2:
            count += 1
        elif numRedGuess == 3:
            count += 2
        elif numRedGuess == 4:
            count += 3
    elif numRedGuess >= 1 and numRedCode >= 1 and sumR != 0 and sumR != 1:
        count += 1
    if numGreenCode == numGreenGuess and sumG != 0 and sumG != 1:
        count += 1
        if numGreenGuess == 2:
            count += 1
        elif numGreenGuess == 3:
            count += 2
        elif numGreenGuess == 4:
            count += 3
    elif numGreenGuess >= 1 and numGreenCode >= 1 and sumG != 0 and sumG != 1:
        count += 1
    if numBlueCode == numBlueGuess and sumB != 0 and sumB != 1:
        count += 1
        if numBlueGuess == 2:
            count += 1
        elif numBlueGuess == 3:
            count += 2
        elif numBlueGuess == 4:
            count += 3
    elif numBlueGuess >= 1 and numBlueCode >= 1 and sumB != 0 and sumB != 1:
        count += 1
    if numYellowCode == numYellowGuess and sumY != 0 and sumY != 1:
        count += 1
        if numYellowGuess == 2:
            count += 1
        elif numYellowGuess == 3:
            count += 2
        elif numYellowGuess == 4:
            count += 3
    elif numYellowGuess >= 1 and numYellowCode >= 1 and sumY != 0 and sumY != 1:
        count += 1
    if numOrangeCode == numOrangeGuess and sumO != 0 and sumO != 1:
        count += 1
        if numOrangeGuess == 2:
            count += 1
        elif numOrangeGuess == 3:
            count += 2
        elif numOrangeGuess == 4:
            count += 3
    elif numOrangeGuess >= 1 and numOrangeCode >= 1 and sumO != 0 and sumO != 1:
        count += 1
    if numPurpleCode == numPurpleGuess and sumP != 0 and sumP != 1:
        count += 1
        if numPurpleGuess == 2:
            count += 1
        elif numPurpleGuess == 3:
            count += 2
        elif numPurpleGuess == 4:
            count += 3
    elif numPurpleGuess >= 1 and numPurpleCode >= 1 and sumP != 0 and sumP != 1:
        count += 1

    return count

A: assuming we ignore colors missing from both input strings, here is a way:
def correctColorCount(secretCode, guess, validColors):
    count = 0
    # for all the color characters
    for color in validColors:
        # if color count is not zero and same for both strings
        if secretCode.count(color) == guess.count(color) != 0:
            count += 1
    return count

A: Here's one way to do it:
def countColors(word, colors):
    return (word.count(color) for color in colors)

def correctColorCount(secretCode, guess, colors):
    for index, (guessedColor, correctColor) in enumerate(zip(*map(lambda word:
        countColors(word, colors), (secretCode, guess)))):
        color = colors[index]
        if guessedColor == correctColor:
            print("You guessed", color, "correctly!")
        else:
            print("You guessed", color, "incorrectly. You guessed", guessedColor, "but it was", str(correctColor) + ".")

>>> validColors = ("R", "G", "B", "Y", "O", "P")
>>> secretCode = "YBGG"
>>> guess = "BYYG"
>>> correctColorCount(secretCode, guess, validColors)
You guessed R correctly!
You guessed G incorrectly. You guessed 2 but it was 1.
You guessed B correctly!
You guessed Y incorrectly. You guessed 1 but it was 2.
You guessed O correctly!
You guessed P correctly!

countColors will count the number of each color in a word, given a list of colors to count from. This uses a list comprehension.
correctColorCount explained:
map(lambda word: countColors(word, colors), (secretCode, guess))
This will run countColors with secretCode and guess. Equivalent to writing:
[countColors(secretCode, colors), countColors(guess, colors)]
zip(*....)
This will take them in pairs: the first one of each, then the second, etc. So, this will essentially create a list for each color:
[actualNumberOfTimes, guessedNumberOfTimes].
enumerate is probably easier to understand here.

A: Maybe you can build up from something like this, using collections.Counter:
from collections import Counter

def correct_color_count(secret, guess):
    correct = Counter(secret) & Counter(guess)
    return sum(correct.values())

correct_color_count(secret="YBGG", guess="BYYG")
>>> 3

This will give you the count of correct guesses, disregarding position.

A: Wow, that's a lot of code... Can be simplified to:
def correctColorCount(secretCode, guess):
    guess_list = list(guess)
    return len(guess) - sum(1 for color in secretCode
                            if color not in guess_list or guess_list.remove(color))

No additional modules required. validColors are not needed for this comparison, you should check against validColors when users input their combination.


text:
Q: Is there any way to export/save a gtsummary object (like tbl_strata or a tbl_svysummary) into a doc or csv document? I want to use the table obteined by using gtsummary components.
For example, I'd like to use a tbl_svysummary object as a new dataframe. Also, beign able to report a tbl_strata in a word document would be great. Nontheless, I don´t know it this is actually possible.


text:
Q: Calculate the mean and variance of the discrete random variable X with: Calculate the mean and variance of the discrete random variable X with:
$f(x)=\frac{1}{2^x}$ if $x=1, 2, 3, \ldots$, $f(x)=0$ otherwise.
Then, $E[X]=1(1/2)+2(1/2^2)+3(1/2^3)+4(1/2^4)+\ldots$
But now, I don't know how to express this in order to continue with my calculations.


text:
Q: Custom Model Binder, asp.net mvc 2 rtm 2, Parsing ID to ComplexModel I have found myself with at little problem, and I think a custom model binder is the way to go.
My Domain model looks like this,readly standard
I got a Page and a Template. The Page has the Template  as a ref.
So the Default asp.net mvc Binder, does not know how to bind it, therefore I need to make some rules for it. (Custom Model Binder)
public class PageTemplate
{
    public virtual string Title { get; set; }
    public virtual string Content { get; set; }
    public virtual DateTime? Created { get; set; }
    public virtual DateTime? Modified { get; set; }
}

public class Page
{
    public virtual string Title { get; set; }
    public virtual PageTemplate Template { get; set; }
    public virtual string Content { get; set; }
    public virtual DateTime? Created { get; set; }
    public virtual DateTime? Modified { get; set; }
}

So I have Registreted the ModelBinder in globals.asax
ModelBinders.Binders.Add(typeof(Cms.Domain.Entities.Page),
                        new Cms.UI.Web.App.ModelBinders.PageModelBinder(
                                new Services.GenericApplicationService<Cms.Domain.Entities.Page>().GetEntityStore()
                            )
                        );

My ModelBinder tage a paremeter, witch is my Repository, where I get all my Entities ( Page, Template )
My Controller for a Page looks like this.
I have posted into a Create Controler, it does not matter for now, if it was a Update method.
Since I in this case have a dropdown, that represents the Template, I will get an ID in my form collection.
I then call: TryUpdateModel and I got a hit in my PageModelBinder.
[AcceptVerbs(HttpVerbs.Post), ValidateAntiForgeryToken]
[ValidateInput(false)]
public ActionResult Create(FormCollection form)
{
    Page o = new Page();

    string[] exclude = new { "Id" }
    if (base.TryUpdateModel<Page>(o, string.Empty, null, exclude, form.ToValueProvider()))
    {
        if (ModelState.IsValid)
        {
            this.PageService.Add(o);
            this.CmsViewData.PageList = this.PageService.List();
            this.CmsViewData.Messages.AddMessage("Page is updated.", MessageTypes.Succes);
            return View("List", this.CmsViewData);
        }
    }

    return View("New", this.CmsViewData);
}

So I end op with the Model Binder.
I have search the internet dry for information, but im stock.
I need to get the ID from the FormCollection, and parse it to at Model from my IEntityStore.
But how ?
public class PageModelBinder : IModelBinder
{

    public readonly IEntityStore RepositoryResolver;

    public PageModelBinder(IEntityStore repositoryResolver)
    {
        this.RepositoryResolver = repositoryResolver;
    }

    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        if (bindingContext == null)
        {
            throw new ArgumentNullException("bindingContext");
        }

        if (modelType == typeof(Cms.Domain.Entities.Page))
        {
            // Do some magic
            // Get the Id from Property and bind it to model, how ??
        }
    }

}

// Dennis
I hope, my problom is clear.

A: Did find a work around.
I download the sourcecode for asp.net r2 rtm 2
And did copy all code for the default ModelBinder, and code it need. Did some minor change, small hacks.
the work around is doing a little hack in this method:
[SuppressMessage("Microsoft.Globalization", "CA1304:SpecifyCultureInfo", MessageId = "System.Web.Mvc.ValueProviderResult.ConvertTo(System.Type)",
        Justification = "The target object should make the correct culture determination, not this method.")]
    [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
        Justification = "We're recording this exception so that we can act on it later.")]
    private static object ConvertProviderResult(ModelStateDictionary modelState, string modelStateKey, ValueProviderResult valueProviderResult, Type destinationType)
    {
        try
        {
            object convertedValue = valueProviderResult.ConvertTo(destinationType);
            return convertedValue;
        }
        catch (Exception ex)
        {
            try
            {
                // HACK if the binder still fails, try get the entity in db.
                Services.GenericApplicationService<Cms.Domain.Entities.PageTemplate> repo;
                repo = new Services.GenericApplicationService<Cms.Domain.Entities.PageTemplate>();
                int id = Convert.ToInt32(valueProviderResult.AttemptedValue);
                object convertedValue = repo.Retrieve(id);
                return convertedValue;
            }
            catch (Exception ex1)
            {
                modelState.AddModelError(modelStateKey, ex1);
                return null;
            }
        }
    }

This question is closed.


text:
Q: Getting the return type of a function which uses generics
Disclaimer: overly simplified functions follow, I'm aware they're
  useless

function thinger<T>(thing: T): T {
    return thing;
}

const thing = thinger({ a: "lol" });

thing.a;

The above code transpiles just fine. But I need to place result of thinger<T> into an object.
interface ThingHolder {
    thing: ReturnType<typeof thinger>;
}

const myThingHolder: ThingHolder = {
    thing: thinger({ a: "lol" }),
};

However I have lost my type information so myThingHolder.thing.a does not work

Property 'a' does not exist on type '{}'

So I tried the following
interface ThingHolder<T> {
    thing: ReturnType<typeof thinger<T>>;
}

const myThingHolder: ThingHolder<{ a: string }> = {
    thing: thinger({ a: "lol" }),
};

But typeof thinger<T> is not valid typescript.
How can I get the return type of a function which has a different return type based on generics?

A: I might as well put this in an answer although it doesn't look like it will meet your needs.  TypeScript currently has neither generic values, higher kinded types, nor typeof on arbitrary expressions. Generics in TypeScript are sort of "shallow" that way.  So as far as I know there's unfortunately no way to describe a type function that plugs type parameters into generic functions and checks the result:
// doesn't work, don't try it
type GenericReturnType<F, T> = F extends (x: T) => (infer U) ? U : never

function thinger<T>(thing: T): T {
  return thing;
}

// just {},
type ReturnThinger<T> = GenericReturnType<typeof thinger, T>;

So all I can do for you is suggest workarounds.  The most obvious workaround would be to use a type alias to describe what thinger() returns, and then use it multiple places.  This is a "backwards" version of what you want; instead of extracting the return type from the function, you build the function from the return type:
type ThingerReturn<T> = T; // or whatever complicated type you have

// use it here
declare function thinger<T>(thing: T): ThingerReturn<T>;

// and here
interface ThingHolder<T> {
  thing: ThingerReturn<T>;
}

// and then this works
const myThingHolder: ThingHolder<{ a: string }> = {
  thing: thinger({ a: "lol" }),
};

Does that help?  I know it's not what you wanted, but hopefully it's at least a possible path forward for you.  Good luck!

A: Probably this would solve the problem. But you need to create a fake class. It works because classes are types and JS-runtime objects at the same time.
// generic function
// we want to get its result, but we cannot do it like
// ReturnType<typeof foo<T>()> // syntax error
const foo = <T,>(arg: T) => ({ test: arg });
// so, let's create a parametric class
class Wrapper<T> {
  // with the only method that uses our "foo"
  wrapped = (arg: T) => foo(arg);
};
// due to the fact that class is a type we can use it as a type
// with a generic parameter.
type GetFooResult<T> = ReturnType<Wrapper<T>['wrapped']>
type Bingo = GetFooResult<number>; // { test: number }

TS Playground link. Based on this answer. Thx to @Colin


text:
Q: Realm Swift: Question about Query-based public database I've seen all around the documentation that Query-based sync is deprecated, so I'm wondering how should I got about my situation:
In my app (using Realm Cloud), I have a list of User objects with some information about each user, like their username. Upon user login (using Firebase), I need to check the whole User database to see if their username is unique. If I make this common realm using Full Sync, then all the users would synchronize and cache the whole database for each change right? How can I prevent that, if I only want the users to get a list of other users' information at a certain point, without caching or re-synchronizing anything?
I know it's a possible duplicate of this question, but things have probably changed in four years.

A: The new MongoDB Realm gives you access to server level functions. This feature would allow you to query the list of existing users (for example) for a specific user name and return true if found or false if not (there are other options as well).
Check out the Functions documentation and there are some examples of how to call it from macOS/iOS in the Call a function section
I don't know the use case or what your objects look like but an example function to calculate a sum would like something like this. This sums the first two elements in the array and returns their result;
your_realm_app.functions.sum([1, 2]) { sum, error in
   if let err = error {
      print(err.localizedDescription)
      return
   }

   if case let .double(x) = result {
      print(x)
   }
}


text:
Q: watch changes in html element using vue I'm trying to watch HTML element in the followiing way:
 computed: {
    content(){
      return document.querySelector(".tab-content")
    }
 },
 watch: {
    content(newVal) {
      return newVal;
    }
 }

but when .tab-content changes (it's innerHTML) , vue wont track/respond to that. any idea why?

A: You can use MutationObserver.
It's a vanilla JS feature that lets you watch DOM element and react to the changes(aka mutations)
https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
https://developer.mozilla.org/en-US/docs/Web/API/MutationRecord

<template>

</template>

A: You can't watch computed values, the computed methods are already like watchers that are updated when the content changes. You use watch methods to watch for changes in data or props
export default {
    data: () => ({
        content: ''
    }),
   watch: {
       content () {
           return this.content
       }
   }
}


text:
Q: ways to reduce the time taken to convert db records to dataframe I am using below command to fetch the data from mongodb collection and convert to dataframe. The time taken to fetch 30000 records is >15 seconds. How can I convert it to dataframe without taking more time?
db = conn.db
collection = db.collection_name
pd.DataFrame(list(collection.find()))

A: This question may be a duplicate of this question.
I made a short performance test from the presented options in the linked question above (with example data from my MongoDB database):
In [1]: %timeit df = pd.DataFrame(list(collection.find()))
1.11 s ± 2.44 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [2]: %timeit df = pd.DataFrame.from_records(collection.find())
1.11 s ± 1.69 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [3]: %timeit df = pd.json_normalize(collection.find())
4.89 s ± 13.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Disclaimer

*

*This is only reprensentative for the ratio between the execution times and cannot be applied to your exact question as I don't have access to your data.

*json_normalize() returns other dataframe (unnested) columns than the others.

If you don't need all fields from the MongoDB documents, I recommend to only search for the fields you really need. See MongoDB documetation.


text:
Q: Comparing CSV::Row objects to singleton nil vs using nil? So I generate an array containing CSV::Row objects and nil as follows in Ruby 1.9.3-p374:
 csv_array = [nil, #<CSV::Row "name":John>, nil, nil, #<CSV::Row "name":John>]

The following line of code works fine:
 csv_array.delete_if { |x| x.nil? }

But this line gives an error:
 csv_array.delete_if { |x| x==nil }

Error:
.rvm/rubies/ruby-1.9.3-p374/lib/ruby/1.9.1/csv.rb:478:in `==': undefined method `row' for nil:NilClass (NoMethodError)

Any ideas on why this might be?  I thought ==nil and .nil? would yield the same result.

A:
I thought ==nil and .nil? would yield the same result.

Yes they are giving. Look my below example:
require 'csv'

c1 = CSV::Row.new(["h1","h2","h3"],[1,2,3])
# => #<CSV::Row "h1":1 "h2":2 "h3":3>
c2 = CSV::Row.new(["h1","h3","h4"],[1,2,3])
# => #<CSV::Row "h1":1 "h3":2 "h4":3>
[nil,c1,c2].delete_if { |x| x.nil? }
# => [#<CSV::Row "h1":1 "h2":2 "h3":3>, #<CSV::Row "h1":1 "h3":2 "h4":3>]
[nil,c1,c2].delete_if { |x| x==nil }
# => [#<CSV::Row "h1":1 "h2":2 "h3":3>, #<CSV::Row "h1":1 "h3":2 "h4":3>]
c1.respond_to?(:nil?) # => true
c1.respond_to?(:==) # => true
c1==nil # => false
c1.nil? # => false

Your code,which you suspect as an error,is perfect. But from the line '==': undefined method 'row' for nil:NilClass (NoMethodError), it is much clear that,you used some where else in your code something == something.row, where that something is nil. Thus you got the error as NilClass do not have any #row method.

A: CSV::Row overrides == and the implementation assumes that the thing you are comparing it to is also a CSV::Row. If you pass it anything that isn't of that class it is likely to blow up.
You could argue that this is poor practice, and that it should return false in this case rather than blowing up (this looks to have been changed in ruby 2.0)
nil? on the other hand has not been overridden and so works as you expect.


text:
Q: mysql.sock does not exist error in fresh install of MySQL on Arch Linux I'm trying to use MySQL on Arch Linux. it is already installed but this error comes up when I try to connect:
connect to server at 'localhost' failed
error: 'Can't connect to local MySQL server through socket '/run/mysqld/mysqld.sock' (2 "No such file or directory")'

I've looked for /etc/my.cfg but the file does not exist.
Something must have gone wrong during the installation.
How can I "purge" MariaDB and reinstall it?

A: If you're using archlinux it is a vital idea to understand the package manager (pacman).  For the question about /etc/my.cfg you can run
pacman -Ql mariadb

there you will see that the file is actually called:
/etc/mysql/my.cnf

Arch linux will not configure the package for you, that is part of the arch philosophy.  It will provide example configurations, and even provide you with a systemd unit file
usr/lib/systemd/system/mysqld.service

but it is your responsibility to ensure that the configuration is correct and actually start the daemon.
systemctl enable mysqld   # add the unit file to the boot sequence
systemctl start mysqld    # runs ExecStart= in the unit file
systemctl stop mysqld     # kills the daemon
systemctl disable mysqld  # remove unit from boot sequence

reinstall
Since the word reinstall is in the title of the question and someone might find this question thanks to that: To reinstall mariadb you simply do
pacman -S mariadb

pacman will reinstall a package that is already installed, there is no need to remove the package (for completeness, package removal happens with pacman -R)

A: as of 7-28-17 I had to do this on a new install. Newbie here might save someone some time. It was a real pain.
OK HERE IS THE DEAL!!!!!
INSTALL APACHE _ NO PROB
INSTALL MYSQL _PROBLEM
pacman -S mysql then before starting service

*

*MUST UNCOMMENT INNODB IN:
nano /etc/mysql/my.cnf

*then must initialize datadirectory before starting service:
mysql_install_db --user=mysql --basedir=/usr --datadir=/var/lib/mysql
You need to initialize the MariaDB data directory prior to starting
   the service. This can be done with mysql_install_db command, e.g.:
   mysql_install_db --user=mysql --basedir=/usr --datadir=/var/lib/mysql
Optional dependencies for mariadb
    galera: for MariaDB cluster with Galera WSREP
    perl-dbd-mysql: for mysqlhotcopy, mysql_convert_table_format and
    mysql_setpermission

A: CNF file is /etc/mysql/my.cnf in Arch Linux.
One simple way I can reproduce your issue is when MariaDB is shut down. Sorry if it sounds dumb but as you did not mention it: is MariaDB started? sudo systemctl start mysqld.service
You should have a look at MariaDB logs to get some clue: journalctl _SYSTEMD_UNIT=mysqld.service (maybe paste some part if you still don't get what is going on).

A: This happens the first time you install MySQL and MariaDB. As grochmal pointed out, you have to set up configurations before first use. But, the user teckk sent these three links in the archlinux newbie corner:

*

*https://wiki.archlinux.org/index.php/MariaDB

*https://wiki.archlinux.org/index.php/MariaDB#Reset_the_root_password

*https://bbs.archlinux.org/viewtopic.php?id=51981
In short, you have to run the command below before starting the service:
sudo mariadb-install-db --user=mysql --basedir=/usr --datadir=/var/lib/mysql

Optionally (recommended) you should improve the initial security by calling:
sudo mysql_secure_installation

Now you can start the service:
sudo systemctl start mariadb

Optionally, you could install and use a graphical front-end tool.
Carry on with setting up the configurations as described in the archwiki post on MariaDB Configuration.


text:
Q: Startswith with a range of number instead an unit ip = a list of ips
ipf = list(filter(lambda x: x if not x.startswith(str(range(257,311))) else None, ip))

Is is possible to do something like this? I tested it and it doesn't work.
I'd like to delete all ips from "ip" list that start with 256. 257. 258. ecc... to 310.

A: No, str.startswith() doesn't take a range.
You'd have to parse out the first part and test it as an integer; filtering is also easier done with a list comprehension:
[ip for ip in ip_addresses if 257 <= int(ip.partition('.')[0]) <= 310]

The alternative would be to use the ipaddress library; it'll reject any invalid address with a ipaddress.AddressValueError exception, and since addresses that start with anything over 255 are invalid, you can easily co-opt that to filter out your invalid addresses:
import ipaddress

def valid_ip(ip):
    try:
        ipaddress.IPv4Address(ip)
    except ipaddress.AddressValueError:
        return False
    else:
        return True

[ip for ip in ip_addresses if valid_ip(ip)]


text:
Q: Bootstrap 5: Run javascript only with validated form I have a form with various input fields that are validated using bootstrap 5 validation.
<form class="needs-validation asset-test" action="{{ url_for('asset_test') }}" method="post" novalidate>
[...]
</form>

According to the documentation, the following code is responsible for this:
// Example starter JavaScript for disabling form submissions if there are invalid fields
(() => {
    'use strict'

    // Fetch all the forms we want to apply custom Bootstrap validation styles to
    const forms = document.querySelectorAll('.needs-validation')

    // Loop over them and prevent submission
    Array.from(forms).forEach(form => {
      form.addEventListener('submit', event => {
        if (!form.checkValidity()) {
          event.preventDefault()
          event.stopPropagation()
        }

        form.classList.add('was-validated')
      }, false)
    })
  })()

Now I want to execute a javascript function on a successful form send:
$('.asset-test').on('submit', function () {
    alert('form submitted');
});

But this function is now always executed when the submit button is pressed. So even if some input fields do not have valid content yet and the bootstrap validation fails.
I see that 'was-validated' must be added to each field. Presumably all input fields in the forms must be checked for this? Unfortunately I lack the javasctipt knowledge for this. Can someone please guide me on the right path?
Execute my javascript function only if the bootstrap validation was successful.

A: You could add an else clause after the call of checkValidity() :
// Example starter JavaScript for disabling form submissions if there are invalid fields
(() => {
    'use strict'

    // Fetch all the forms we want to apply custom Bootstrap validation styles to
    const forms = document.querySelectorAll('.needs-validation')

    // Loop over them and prevent submission
    Array.from(forms).forEach(form => {
      form.addEventListener('submit', event => {
        if (!form.checkValidity()) {
          event.preventDefault()
          event.stopPropagation()
          console.log("invalid form");
        } else {
          console.log("valid form");
          //add some code here
        }

        form.classList.add('was-validated')
      }, false)
    })
  })()


text:
Q: Unable to install mclust package in rstudio I am having an issue when installing the "mclust" package on rstudio.
Here is the warning message:
>install.packages("mclust")
trying URL 'https://cran.rstudio.com/src/contrib/mclust_5.4.tar.gz'
Content type 'application/x-gzip' length 2535477 bytes (2.4 MB)
==================================================
downloaded 2.4 MB

* installing *source* package 'mclust' ...
** package 'mclust' successfully unpacked and MD5 sums checked
** libs

/home/usr/anaconda3/bin/x86_64-conda_cos6-linux-gnu-cc -
I/home/usr/anaconda3/lib/R/include -DNDEBUG   -D_FORTIFY_SOURCE=2 -O2
-I/home/usr/anaconda3/include   -fpic  -march=nocona -mtune=haswell -
ftree-vectorize -fPIC -fstack-protector-strong -fno-plt -O2 -pipe -
I/home/usr/anaconda3/include  -c init.c -o init.o

make: /home/usr/anaconda3/bin/x86_64-conda_cos6-linux-gnu-cc: Command
not found

/home/usr/anaconda3/lib/R/etc/Makeconf:160: recipe for target 'init.o'
failed

make: *** [init.o] Error 127

ERROR: compilation failed for package 'mclust'
* removing '/home/usr/anaconda3/lib/R/library/mclust'

Warning in install.packages :
 installation of package 'mclust' had non-zero exit status

The downloaded source packages are in
  '/tmp/RtmpGCCIZS/downloaded_packages'
Updating HTML index of packages in '.Library'
Making 'packages.html' ... done

In addition, I also tried to access the directory /home.usr/anaconda3/x86_64-conda_cos6-linux-gnu-cc ,which apparently doesn't exist.


text:
Q: How to keep the footer at the bottom of the page? Here is my html page.
<!DOCTYPE HTML>

My Page

            My footer

But this keeps the footer in between the page. Can some one help me out here?

A: You want to use
position:fixed;

for the #foot
http://jsfiddle.net/q3U4R/
possibly a better way:
http://jsfiddle.net/q3U4R/1/
* { margin:0; padding:0; }

html, body, #wrap { height: 100%; }

body > #wrap {height: auto; min-height: 100%;}

. container { padding-bottom: 150px; }  /* must be same height as the footer */

#foot {
    position: fixed;
    margin-top: -150px; /* negative value of footer height */
    height: 150px;
    clear:both;
    background:#ff0;
    bottom:0px;
    width:100%;
}

A: <!DOCTYPE HTML>

My Page

    My footer

</style>

A: I think this is what your looking for. Press the button in my example to see how the footer is sticked to the bottom no matter how much content you put into your body. Hope this helps you out <3

$("#add").on("click", function() {
  $("
Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.
").appendTo(".page-wrap");
});
* {
  margin: 0;
}
html, body {
  height: 100%;
}
.page-wrap {
  min-height: 100%;
  /* equal to footer height */
  margin-bottom: -142px;
}
.page-wrap:after {
  content: "";
  display: block;
}
.site-footer, .page-wrap:after {
  height: 142px;
}
.site-footer {
  background: orange;
}

Sticky Footer

with Fixed Footer Height

  <button id="add">Add Content</button>

  I'm the Sticky Footer.