text:
Q: to create a population of "A" and "B" alphabets with 50% frequency of each I am writing this code to generate a txt file which should have total of 600 letters comprising only of A(50%) and B(50%), distributed randomly. How should I do that, I am new to coding, please help.
q=[A, B]
popsize=500
def gen_pop(A):
      population=[]
      B=A
      while len(population)<popsize:
             random.shuffle(B)
             print A
         print B

gen_pop(q)

A: Create a list of 300 A and 300 B the shuffle it with random.shuffle:
>>> from random import shuffle
>>> mylist = ['A'] * 300 + ['B'] * 300
>>> shuffle(mylist)
>>> mylist
 ['B', 'B', 'A', 'B', 'A', 'A', ... 'A', 'B', 'A']

A: The best answer may depend on what exactly you want your distribution to be.
If you want exactly half your letters to be A and half to be B, use the technique from jabaldoneodo's answer, and build the sequence first, then shuffle it:
 import random

 result = ["A"]*300 + ["B"]*300
 random.shuffle(result)

If on the other hand, you want each value to be selected independently of the others, with a 50% chance of it being A and a 50% chance of it being B, picking the number of each ahead of time will be inappropriate. Instead, you can use random.choice to pick from your alphabet in a list comprehension:
 import random

 alphabet = "AB"
 result = [random.choice(alphabet) for _ in range(600)]

Using this method, the number of As (and Bs, for that matter) will be normally distributed, with a mean of 300. The same technique also works for larger alphabets.

A: Generate an array of 300 A's and 300 B's, and then shuffle it using an algorithm.


text:
Q: React and Storybook working with both TSX and MDX files I'm picking up a project with has a custom setup using React, NextJS, and Storybook. I'm trying to add TypeScript and use both "x.stories.tsx" and "x.stories.mdx" for the stories (storybook-addon-docs). I've got the TSX files working, but the MDX ones complain about the loader being used. Do I need a specific loader for the MDX files and if so what? Reading around people say it should work by default.... but it doesn't appear to be. I'm guessing it's using the "awesome-typescript-loader" to try loading the MDX file but any help would be good.
webpack.config.js

module.exports = ({ config }) => {
  config.module.rules.push({
    test: /\.(ts|tsx)$/,
    use: [
      {
        loader: require.resolve('awesome-typescript-loader'),
        options: {
          configFileName: './.storybook/tsconfig.json'
        }
      }
    ]
  });
  config.resolve.extensions.push('.ts', '.tsx');
  return config;
};

config.ts

import { configure, addParameters } from '@storybook/react';

const req = require.context('../src/components', true, /\.stories\.(tsx|mdx)$/);

function loadStories() {
  req.keys().forEach(req);
}

configure(loadStories, module);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Automatic cache updates do not work in react apollo The document says the cache can be automatically updated in the following example:
{
  post(id: '5') {
    id
    score
  }
}

mutation {
  upvotePost(id: '5') {
    id
    score
  }
}

Would the automatic update work in the following case when the cached object is in a list ? Like this:
This is a query that fetches a list of reviews:
{
  reviewList(model:12){
    list{
      reviewId
      text
    }
    cursor
  }
}

When I update one of the reviews from the list to the server, react apollo does not automatically update the cached review:
mutation{
  updateReview(reviewId:'1',text:'new text'){
     reviewId
     text
  }
}

Is it a must to use update properties of the mutation component to update the cache?

A: Assuming you're using apollo-cache-inmemory, unless you are adding an item to or removing an item from the list, it shouldn't be necessary to use update. However, it's important to keep in mind that the cached data is normalized, and that Apollo utilizes the __typename and id (or _id) field to generate the cache key for any queried object. From the docs:

The InMemoryCache normalizes your data before saving it to the store
  by splitting the result into individual objects, creating a unique
  identifier for each object, and storing those objects in a flattened
  data structure. By default, InMemoryCache will attempt to use the
  commonly found primary keys of id and _id for the unique identifier if
  they exist along with __typename on an object.

If the id field is missing, Apollo won't know how to match up the data from your query and the data from your mutation:

If id and _id are not specified, or if __typename is not specified,
  InMemoryCache will fall back to the path to the object in the query,
  such as ROOT_QUERY.allPeople.0 for the first record returned on the
  allPeople root query. That would make data for given type scoped for
  allPeople query and other queries would have to fetch their own
  separate objects.

Fortunately, there's a workaround. You can of course just rename reviewId to id on the server side. However, if you want the cache to just use the reviewId field, you can pass in a dataIdFromObject function to your InMemoryCache constructor:
import { InMemoryCache, defaultDataIdFromObject } from 'apollo-cache-inmemory'

const cache = new InMemoryCache({
  dataIdFromObject: object => {
    switch (object.__typename) {
      case 'Review': return object.reviewId
      default: return defaultDataIdFromObject(object)
    }
  }
})

As long as resulting value is unique, you can utilize any other field (or combination of fields) in a similar fashion.


text:
Q: Sort a list of directories based on alphanumerical date I have a list of directories and I would like to sort the list based on the date followed by a number. Here is an example of the unsorted list:
L = ['C:\\Users\\...\\file1\\sample_nov1_1',
    'C:\\Users\\...\\file2\\sample_sep1_1',
    'C:\\Users\\...\\file3\\sample_oct15_2',
    'C:\\Users\\...\\file2\\sample_sep1_2',
     'C:\\Users\\...\\file4\\sample_sep10_2',
    'C:\\Users\\...\\file4\\sample_sep10_1']

I would like to sort it so I get the following output:
['C:\\Users\\...\\sample_sep1_1',
 'C:\\Users\\...\\sample_sep1_2',
 'C:\\Users\\...\\sample_sep10_1',
 'C:\\Users\\...\\sample_sep10_2',
 'C:\\Users\\...\\sample_oct15_1',
 'C:\\Users\\...\\sample_nov1_2']

I get this list by making a walk from a parent directories, but because these files were not created chronologically in the same order that I want the output, I am not sure if I can modify that part of the code. I have already looked at a few other answers such as this one, but they do not have the same complications that I have here. How can I achieve this? I suppose using regular expressions I might be able to simplify a bit, but not sure if that is the correct approach.

A: Use the following key method
It is working alphabetically
month=['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec']
L.sort(key=lambda value:( month.index(value.split('_')[-2][:3]), value.split('_')[-2][3:] , value.split('_')[-1]))
print(L)

A: This should work:
import re

files = ['C:\\Users\\...\\sample_sep1_1',
 'C:\\Users\\...\\sample_sep1_2',
 'C:\\Users\\...\\sample_sep10_1',
 'C:\\Users\\...\\sample_sep10_2',
 'C:\\Users\\...\\sample_nov1_1',
 'C:\\Users\\...\\sample_oct15_2']

lf = [file.split("\\")[-1].split("_") for file in files]

R = []
for index, x in enumerate(lf):
    dval, num = x[1], int(x[2].split(".")[0])
    grps = re.match("([a-z]+)([0-9]+)", dval).groups()
    R.append((grps[0], int(grps[1]), num, files[index]))

month_map = {'jan': 1, 'feb': 2, 'mar': 3, 'apr': 4, 'may': 5, 'jun': 6, 'jul': 7, 'aug': 8, 'sep': 9, 'oct': 10, 'nov': 11, 'dec': 12}

sorted_files = sorted(R, key=lambda x: (month_map[x[0]], x[1], x[2]))
print(sorted_files)

Output:
[('sep', 1, 1, 'C:\\Users\\...\\sample_sep1_1'), ('sep', 1, 2, 'C:\\Users\\...\\sample_sep1_2'), ('sep', 10, 1, 'C:\\Users\\...\\sample_sep10_1'), ('sep', 10, 2, 'C:\\Users\\...\\sample_sep10_2'), ('oct', 15, 2, 'C:\\Users\\...\\sample_oct15_2'), ('nov', 1, 1, 'C:\\Users\\...\\sample_nov1_1')]

A: I got this so far. Any other test-edge cases to suggest?

    month_value = {"jan": 1, "feb": 2, "mar": 3, "apr": 4, "may": 5, "jun": 6,
                   "jul": 7, "aug": 8, "sep": 9, "oct": 10, "nov": 11, "dec": 12}
    out = sorted(a, key=lambda x: (month_value[x.split("\\")[-1][7:][:3]], x.split("\\")[-1][7:][3:].split('_')))

A: Can you try this:
import os
from pathlib import Path

paths = sorted(Path("<file_dir>").iterdir(),key=os.path.getmtime)

print(paths)

Maybe it will help you.


text:
Q: Unbind GPU from Radeon drivers without restarting lightdm I use a bash script to rebind my GPU for KVM PCI passthrough, but it requires me to stop lightdm to unbind/bind it from the radeon drivers. If I do not stop lightdm, the entire system hangs after a few seconds and I can't even SSH in to see what is going on. There must be some way to safely detach the drivers. I am using kernel 4.1.6, as 4.2 currently breaks PCI passthrough.
I attempted to remove the radeon driver before unbinding, but that did not work.
modprobe --remove-dependencies radeon

I suspect this is because it is being used by these which for some reason did not get removed:
lsmod | grep radeon
radeon               1589248  0
ttm                    94208  1 radeon
i2c_algo_bit           16384  2 i915,radeon
drm_kms_helper        126976  2 i915,radeon
drm                   352256  7 ttm,i915,drm_kms_helper,radeon

There were many stack traces like this one. Some from sysfs/group.c and the rest from drm. Looks like this is an issue with memory management. I am not sure how I would go about unbinding properly.
WARNING: CPU: 3 PID: 10935 at /home/kernel/COD/linux/drivers/gpu/drm/radeon/radeon_object.c:83 radeon_ttm_bo_destroy+0xea/0xf0 [radeon]()
Modules linked in: pci_stub joydev binfmt_misc arc4 nls_iso8859_1 eeepc_wmi asus_wmi sparse_keymap ath9k ath9k_common intel_rapl iosf_mbi amdkfd x86_pkg_temp_thermal intel_powerclamp snd_hda_codec_realtek amd_iommu_v2 snd_hda_co$
CPU: 3 PID: 10935 Comm: echo Tainted: G        W       4.1.6-040106-generic #201508170230
Hardware name: ASUS All Series/Z97-E/USB 3.1, BIOS 0403 04/07/2015
ffffffffc08d62a0 ffff88010656fa38 ffffffff817d1363 0000000000000000
0000000000000000 ffff88010656fa78 ffffffff81079c3a ffff88012d9d1ec0
ffff880220a6f868 ffff880220a6f800 0000000000002480 ffff880220a6f868
Call Trace:
[<ffffffff817d1363>] dump_stack+0x45/0x57
[<ffffffff81079c3a>] warn_slowpath_common+0x8a/0xc0
[<ffffffff81079d2a>] warn_slowpath_null+0x1a/0x20
[<ffffffffc07bf5ba>] radeon_ttm_bo_destroy+0xea/0xf0 [radeon]
[<ffffffffc042e4d9>] ttm_bo_release_list+0xa9/0x180 [ttm]
[<ffffffffc04351e0>] ? ttm_bo_man_put_node+0x40/0x50 [ttm]
[<ffffffffc042e6cd>] ttm_bo_release+0x11d/0x2b0 [ttm]
[<ffffffff81507816>] ? __dev_printk+0x46/0xa0
[<ffffffffc042e889>] ttm_bo_unref+0x29/0x30 [ttm]
[<ffffffffc07bfada>] radeon_bo_unref+0x2a/0x50 [radeon]
[<ffffffffc07d4cdb>] radeon_gem_object_free+0x4b/0x50 [radeon]
[<ffffffffc00254a7>] drm_gem_object_free+0x27/0x30 [drm]
[<ffffffffc07bff78>] radeon_bo_force_delete+0x128/0x130 [radeon]
[<ffffffffc07d4ebe>] radeon_gem_fini+0xe/0x10 [radeon]
[<ffffffffc083ebad>] si_fini+0xbd/0x110 [radeon]
[<ffffffffc07a1612>] radeon_device_fini+0x42/0x140 [radeon]
[<ffffffffc07a3d40>] radeon_driver_unload_kms+0x50/0x70 [radeon]
[<ffffffffc002a8cd>] drm_dev_unregister+0x2d/0xc0 [drm]
[<ffffffffc002af87>] drm_put_dev+0x27/0x80 [drm]
[<ffffffffc079f295>] radeon_pci_remove+0x15/0x20 [radeon]
[<ffffffff8140193f>] pci_device_remove+0x3f/0xc0
[<ffffffff8150b297>] __device_release_driver+0x87/0x120
[<ffffffff8150b353>] device_release_driver+0x23/0x30
[<ffffffff8150a04d>] unbind_store+0xbd/0xe0
[<ffffffff81509484>] drv_attr_store+0x24/0x40
[<ffffffff8127478d>] sysfs_kf_write+0x3d/0x50
[<ffffffff81273c3a>] kernfs_fop_write+0x12a/0x180
[<ffffffff811f8d98>] __vfs_write+0x28/0x100
[<ffffffff811fba19>] ? __sb_start_write+0x49/0xf0
[<ffffffff81320993>] ? security_file_permission+0x23/0xa0
[<ffffffff811f9499>] vfs_write+0xa9/0x1b0
[<ffffffff817d6f66>] ? mutex_lock+0x16/0x37
[<ffffffff811fa2a6>] SyS_write+0x46/0xb0
[<ffffffff81067240>] ? do_page_fault+0x30/0x80
[<ffffffff817d8f32>] system_call_fastpath+0x16/0x75

Here is my current script for those interested. (Execute from tty console outside xsession)
#!/bin/bash

read -n3 -rsp "Restart lightdm to unbind the GPU? [yes] " res
test "$res" != 'yes' && exit 1
echo

sudo service lightdm stop
sudo echo "1002 683d" > /sys/bus/pci/drivers/vfio-pci/new_id
sudo echo "1002 aab0" > /sys/bus/pci/drivers/vfio-pci/new_id
sudo echo "0000:01:00.0" > /sys/bus/pci/devices/0000:01:00.0/driver/unbind
sudo echo "0000:01:00.1" > /sys/bus/pci/devices/0000:01:00.1/driver/unbind
sudo echo "0000:01:00.0" > /sys/bus/pci/drivers/vfio-pci/bind
sudo echo "0000:01:00.1" > /sys/bus/pci/drivers/vfio-pci/bind
sudo echo "1002 683d" > /sys/bus/pci/drivers/vfio-pci/remove_id
sudo echo "1002 aab0" > /sys/bus/pci/drivers/vfio-pci/remove_id
sudo service lightdm start

echo "Rebind Audio"
sudo modprobe pci_stub
sudo echo "8086 8ca0" > /sys/bus/pci/drivers/pci-stub/new_id
sudo echo "0000:00:1b.0" > /sys/bus/pci/drivers/snd_hda_intel/unbind
sudo echo "0000:00:1b.0" > /sys/bus/pci/drivers/pci-stub/bind
sudo echo "8086 8ca0" > /sys/bus/pci/drivers/pci-stub/remove_id

# Check if VM drive is mounted
if ! grep -qs '/media/ljosalfur/VM' /proc/mounts; then
echo "Attempting to mount VM drive. I don't know how though."
#sudo mkdir /media/ljosalfur/VM
#sudo mount /dev/disk/by-id/0BD253F0-EF7F-6F40-BDD8-FABF85161762 /media/ljosalfur/VM
fi

sudo kvm -monitor stdio -vnc :0 \
-m 6G -mem-path /dev/hugepages \
-drive if=pflash,format=raw,file=./OVMF.fd -rtc base=localtime \
-cpu host -smp 6,sockets=1,cores=6,threads=1 \
-device vfio-pci,host=01:00.0,multifunction=on,x-vga=on \
-device vfio-pci,host=01:00.1 \
-device pci-assign,host=00:1b.0 \
-drive file=/media/ljosalfur/VM/vm7.img,format=raw,cache=writethrough \
-smb /media/ljosalfur \
-usb -usbdevice host:046d:c24a -show-cursor \
-usb -usbdevice host:1b1c:1b08

echo
echo "Re-Rebind Audio"
sudo echo "0000:00:1b.0" > /sys/bus/pci/drivers/pci-stub/unbind
sudo echo "0000:00:1b.0" > /sys/bus/pci/drivers/snd_hda_intel/bind

echo "Unbind GPU from vfio-pci"
sudo echo "0000:01:00.0" > /sys/bus/pci/drivers/vfio-pci/unbind
sudo echo "0000:01:00.1" > /sys/bus/pci/drivers/vfio-pci/unbind

read -n3 -rsp "Restart lightdm to rebind the GPU? [yes] " ress
test "$ress" != 'yes' && (exit 1)
echo
sudo echo "0000:01:00.0" > /sys/bus/pci/drivers/radeon/bind

A: Finally found a way to do it using the information in this thread: https://www.reddit.com/r/VFIO/comments/41pm1q/my_bash_script_for_rebinding_a_secondary_nvidia/
The working  script is:
#!/bin/bash
# Which device and which related HDMI audio device. They're usually in pairs.
export VGA_DEVICE=0000:01:00.0
export AUDIO_DEVICE=0000:01:00.1

export VGA_DRIVER=radeon
export AUDIO_DRIVER=snd_hda_intel

# Passing through USB devices. Querying bus address and feeding that to QEMU
# instead of the device ID, so you can yank and replug the keyboard to regain
# control.
export KEYBOARD="1b1c:1b08"
export MOUSE="046d:c24a"

# Unbinds a device and loads the driver specified.
flipdriver() {
    dev="$1"
    driver="$2"

    if [ -z $driver ] | [ -z $dev ];
    then
        return 1
    fi

    vendor=$(cat /sys/bus/pci/devices/${dev}/vendor)
    device=$(cat /sys/bus/pci/devices/${dev}/device)

    echo -n Unbinding $vendor:$device ...

    if [ -e /sys/bus/pci/devices/${dev}/driver ]; then
        echo ${dev} > /sys/bus/pci/devices/${dev}/driver/unbind
        while [ -e /sys/bus/pci/devices/${dev}/driver ]; do
            sleep 0.5
            echo -n .
        done
    fi
    echo " OK!"

    echo -n Binding \'$driver\' to $vendor:$device ...
    echo ${vendor} ${device} > /sys/bus/pci/drivers/${driver}/new_id

    echo " OK!"

    return 0
}

# Common error message
fliperror()
{
    echo "Couldn\'t perform required driver switch\'n\'bait!"
    exit 1
}

# Xorg shouldn't run.
if [ -n "$( ps -C xinit | grep xinit )" ];
then
    echo "Don\'t run this inside Xorg!"
    exit 1
fi

# Unbind specified graphics card and audio device.
echo "Pulling the plug on the specified passthrough devices..."
flipdriver $VGA_DEVICE vfio-pci
flipdriver $AUDIO_DEVICE vfio-pci

export QEMU_PA_SAMPLES=128
export QEMU_AUDIO_DRV=alsa

# Get the bus addresses for keyboard and mouse.
export QEMU_KEYB=$( lsusb | sed -n 's/Bus \([0-9]*\) Device \([0-9]*\): ID '$KEYBOARD'.*/-device usb-host,bus=xhci.0,hostbus=\1,hostaddr=\2/p' )
export QEMU_MOUS=$( lsusb | sed -n 's/Bus \([0-9]*\) Device \([0-9]*\): ID '$MOUSE'.*/-device usb-host,bus=xhci.0,hostbus=\1,hostaddr=\2 -show-cursor/p' )

# Check if VM drive is mounted
if ! grep -qs '/media/user/VM' /proc/mounts; then
echo "Attempting to mount VM drive."
sudo mount /dev/sdc1
fi

#network stuff
tunctl -t vmtap10
ip link set dev tap10 address 42:42:42:42:42:10
ifconfig vmtap10 192.168.42.1 up
echo 1 > /proc/sys/net/ipv4/ip_forward
iptables -t nat -A POSTROUTING -o eno1 -j MASQUERADE
iptables -A FORWARD -i vmtap10 -j ACCEPT
iptables -A FORWARD -o vmtap10 -m state --state RELATED,ESTABLISHED -j ACCEPT

#pactl set-sink-volume 2 50%

echo Starting virtual machine...
sleep 0.2

# QEMU stuff
sudo kvm -monitor stdio -vnc :1 -vga none \
-drive if=pflash,format=raw,file=./OVMF.fd -rtc base=localtime \
-m 4G -mem-path /dev/hugepages \
-cpu host -smp sockets=1,cores=6,threads=1 \
-soundhw ac97 \
-device vfio-pci,host=01:00.0 \
-usb -usbdevice host:046d:c215 \
-usb -device nec-usb-xhci,id=xhci \
$QEMU_KEYB \
$QEMU_MOUS \
-net nic,macaddr=42:42:42:42:42:42 -net tap,ifname=vmtap10,script=no,downscript=no,vhost=on \
-drive file=/media/user/VM/vm10.img,format=qcow2,cache=writeback \
-smb /media/ljosalfur \
-cdrom /home/user/Downloads/virtio-win-0.1.105.iso

# Rebind the devices for the host.
echo Adios vfio, reloading the host drivers for the passedthrough devices...
flipdriver $AUDIO_DEVICE $AUDIO_DRIVER
flipdriver $VGA_DEVICE $VGA_DRIVER

iptables -F
iptables -t nat -F POSTROUTING
ip link delete vmtap10


text:
Q: How can I free space in oracle mount point (/u01/app/oracle/)? My question is what can I delete or how can I free space so that I can log onto oracle via sqlplus as sysdba. When I execute the command df -k to see the free space in the current directory it appears to be full and on the other machine its at 52%.
Filesystem                   1K-blocks     Used        Available  Use%    Mounted on

/dev/mapper/rootvq-rootlv    51606140    48985496      0          100%    /

A: If your oracle installation is on your root volume you should have a look at the DIAG_DESTINATION, e.g. /u01/app/oracle/diag/. If there's a lot of old trace files in there you can safely remove them with adrci. If your oracle installation is on a separate disk you have to check where the space is consumed (/var?) and free space there.


text:
Q: Apply jquery script to only one class at a time How can I apply this script to only one class at a time
<script>

    $(document).ready(function(){

        // set up click/tap panels
        $('.click').toggle(function(){

            $(this).addClass('flip');
        },function(){
            $(this).removeClass('flip');
        });

        // set up block configuration
        $('.action').click(function(){;
            $('.card').addClass('flip');
        });
        $('.action2').click(function(){
            $('.card').removeClass('flip');
        });

});

When I click the action class all the card classes flip and I wanted to rotate one at a time.
My idea is to click on one and flip only that one, click on another and flip only that card not all the cards at the same time.

A: Use a delay
$('.action').click(function(){
    $('.card').each(function(i, el) {
        setTimeout(function(){ $(this).addClass('flip'); }, i*300);
    });
});

A: If you just want to flip the .card div that contains the action you clicked on, do:
    $('.action').click(function(){;
        $(this).closest(".card").addClass('flip');
    });

A: If you want to toggle a class onclick, you can utilize toggleClass().
$(document).on("click", ".click", function() {
    $(this).toggleClass('flip');
});

Now if you want to flip one at a time. That is a little tough to know exactly what you want. I am guessing you want something like this.
$('.action').click(function(){;
    var cards = $('.card');
    var current = cards.filter(".flip").removeClass('flip');
    var next = current.length===1 && next.index()+1<cards.length? current.next() : cards.first();
    next.addClass("flip");
});

A: You can use setInterval()
Live Demo
var cards;
index = 0;
var interval1;
function repeat()
{
      cards.eq(index++).addClass('flip');
      if(index  == cards.length)
          clearInterval(interval1);
}
$('.action').click(function(){
    cards = $('.card');
    interval1 = setInterval(repeat, 1000);
});


text:
Q: How to deactive java error popup when I try to connect a qc server through jacob sometimes java stops to working and a get a error popup window with message "Java(TM) Platform SE binary doesn't work", where I can close the window or run a debug tool.
My tool has to run all the time. So my idea is to write a second script that rerun my tool always if it is down. But to do this i must "tell" java to not popup any window if a problem occur again or when java just stop to work.
How can I do this ?


text:
Q: What is the best practice to pass pickles between workers in Dask I'm trying to implement a data pipeline using Dask and Airflow.  I want to be able to add/remove nodes to an existing DAG, similar to middleware in NodeJS. My idea is to pickle the Dataframe so the next step can pick up and apply any transformation to it before pickle and pass on to the next step.  But with Dask parallel processing, the next node could be assigned to any worker.
I'm thinking having the scheduler and a few workers locally. When I have a big job I can fire up some EC2 workers to handle the job.
Any suggestion?

A: You don't need to explicitly serialize data for transfer yourself.
Dask will move data between nodes for you automatically, serializing data as necessary.


text:
Q: How to highlight specific text in a RichTextBox? In a RichTextBox control, I am trying to highlight a specific text in RED color as a result from a Regex match.
Sample:
This text statement works fine and highlights the 'Deans' in red shade:

select top 10 * from client where MailName='Deans'

This text statement works fine also and highlights the code in red shade:

select top 10 * from client where MailName='De a ns'

But this statement fails:

select top 10 * from client where MailName='Deans '

It fails because there is space in between the single quotes, it throws an exception on the line making the start TextRange at
TextRange result = new TextRange(start, start.GetPositionAtOffset(word.Length));

The exception says:

invalid parameter position 2.

Please suggest me a solution. Where am I making a mistake?
Here is the code snippet:
string StringFromRichTextBox(RichTextBox rtb)
{
    TextRange textRange = new TextRange(rtb.Document.ContentStart,
                rtb.Document.ContentEnd);

    return textRange.Text;
}

private void TextChangedEventHandler(object sender, TextChangedEventArgs e)
{
    TextRange documentRange = new TextRange(txtQueries.Document.ContentStart, txtQueries.Document.ContentEnd);
        documentRange.ClearAllProperties();

    MatchCollection match = Regex.Matches(StringFromRichTextBox(txtQueries), @"'([^']*)'");
    for (int z = 0; z < match.Count; z++)
    {
        CheckKeyword(documentRange, match[z].ToString().Trim());
    }
}

private void CheckKeyword(TextRange textRange, string word)
{
    //txtQueries.TextChanged -= this.TextChangedEventHandler;
    if (textRange.Text.Contains(word))
    {
        int offset = textRange.Text.IndexOf(word);
        if (offset < 0)
        {
            return;
        }// Not found
        else
        {
            // Try to select the text as a contiguous range
            for (TextPointer start = textRange.Start.GetPositionAtOffset(offset); start != textRange.End; start = start.GetPositionAtOffset(1))
            {
                try
                {
                    TextRange result = new TextRange(start, start.GetPositionAtOffset(word.Length));
                    if (result != null && result.Text == word)
                    {
                        result.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.Red));
                        break;
                    }
                }
                catch(Exception ex)
                {
                    throw new Exception(ex.Message);
                }
            }
        }
    }
    //txtQueries.TextChanged += this.TextChangedEventHandler;
}

Error Message:

Value cannot be null.
  Parameter name: position2
  at System.Windows.Documents.TextRange..ctor(TextPointer position1, TextPointer position2)

A: Resolution :: Added 4 to the offset length to account for special invisible characters coming up with space in richtextbox.
    var length = word.Length;
                // Try to select the text as a contiguous range
                for (TextPointer start = textRange.Start.GetPositionAtOffset(offset); start != textRange.End; start = start.GetPositionAtOffset(1))
                {
                    try
                    {

                        TextRange result = new TextRange(start, start.GetPositionAtOffset(word.Contains(" ") ? word.Length + 4: word.Length)); //Added 4 to the offset length to account for special invisible characters coming up with space in richtext box
                        if (result.Text.Trim() == word.Trim())
                        {
                            result.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.Red));
                            break;
                        }

                    }
                    catch (Exception ex)
                    {
                        throw new Exception(ex.Message);
                    }

A: I had a LOT of trouble wrestling with this issue as well! After lots of wtf's with GetPositionAtOffset I came up with this method to get accurate TextPointers when searching in a RichTextBox:
public static TextRange FindStringRangeFromPosition(TextPointer position, string str) {
     //what makes this work is checking the PointerContext so you avoid the markup characters
     while (position != null) {
            if (position.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text) {
                string textRun = position.GetTextInRun(LogicalDirection.Forward);

                // Find the starting index of any substring that matches "str".
                int indexInRun = textRun.IndexOf(str);
                if (indexInRun >= 0) {
                //since we KNOW we're in a text section we can find the endPointer by the str.Length now
                    return new TextRange(position.GetPositionAtOffset(indexInRun), position.GetPositionAtOffset(indexInRun + str.Length));
                }
            }
            position = position.GetNextContextPosition(LogicalDirection.Forward);
        }

        // position will be null if "str" is not found.
        return null;
    }


text:
Q: Iam trying to run this code in sql . but gives me a missing keyword error SELECT order_id,   ordered_quantity,  product_description , standard_price FROM m_product
JOIN m_order_line
WHERE product_description = 'End Table' OR product_description = 'Coffee Table' OR product_description   = 'Dining Table'
ORDER BY product_description;

A: You have to define that join perform on which common column
Using ON and give  Alies to your table
Alies :- m1 ane m2
Use Alies as :- m1.yourcolumn or m2.yourcolumn
SELECT
        order_id,
        ordered_quantity,
        product_description,
        standard_price
    FROM m_product as m1
    JOIN m_order_line as m2 on m1.columnname = m2.columnname
    WHERE product_description = 'End Table' OR product_description = 'Coffee Table' OR product_description   = 'Dining Table'
    ORDER BY product_description;


text:
Q: How to send functional data to another page in React Playing.js File
import { useState } from "react";
function Playing(){
  const [sidebar, setSidebar] = useState(false);

  const sidebarFunc = () => {
    sidebar ? setSidebar(false) : setSidebar(false);
  }

  return(
    Click
  );
}

export default Playing;

Sidebar.js File
function SideBar() {
  return (

Side Bar

  );
}

export default SideBar;

App.js File
import Sidebar from "./Sidebar.js";
import Playing from "./Playing.js";
function App(){
  return(
    <>
      <Sidebar />
      <Playing />
    </>
  );
}

I'm new to react, so try avoiding mistakes by my side. Here i'm trying a way in which the after clicking the Click text, the usestate variable sidebar gets triggered. But the sidebar couldn't be exported so as to get an outcome for Sidebar functional div as
Side Bar
.
Is there a solution for the same or any other ways it can be done.
Thank you in advance

A: You can create a state in parent component and then use this state in child component by passing through props and a callback function
App.js File
import Sidebar from "./Sidebar.js";
import Playing from "./Playing.js";
function App(){

 const [sidebar, setSidebar] = useState(false);

  return(
    <>
      <Sidebar sidebar={sidebar}/>
      <Playing  sidebar={sidebar} setSidebar={setSidebar}/>
    </>
  );
}

Playing.js
import from "react";
function Playing({sidebar,setSidebar}){

  const sidebarFunc = () => {
    sidebar ? setSidebar(false) : setSidebar(false);
  }

  return(
    Click
  );
}

export default Playing;

SideBar.js
   function SideBar({sidebar}) {
      return (
        <div className=`${sidebar?"Show":"Hide"}`>Side Bar

      );
    }

export default SideBar;

A: Place the useState() declaration in App.js.
App.js
function App(){
    const [sidebar, setSidebar] = useState(false);

    return(
        <>
            <Sidebar sidebar={sidebar}/>
            <Playing sidebar={sidebar} setSidebar={(bool) => setSidebar(bool)}/>
        </>
    );
}

SideBar.js
function SideBar(props) {
  return (

Side Bar

  );
}

export default SideBar;

Playing.js
function Playing(props){
    const sidebarFunc = () => {
        props.sidebar ? props.setSidebar(false) : props.setSidebar(false);
    }

    return(
        Click
    );
}

export default Playing;


text:
Q: Android location update using fused returns null. How to ensure I get it from foreground activity? I need the location once in my foreground activity. But I get a null response.
Weirdly once I open google maps the location callback returns a valid object. What is google maps doing that I'm not? How do I ensure the value is not null in my foreground activity?
code:
@SuppressLint("MissingPermission")
fun getLastLocation(): LiveData<Location> {
    registerLocationUpdates()
    try {
        this.getFusedLocationProviderClient(context).lastLocation.addOnSuccessListener { loc: Location? ->
            if (loc != null) {
                util.toast(util.getStringRes(R.string.fetching_location, "${loc.latitude}, ${loc.longitude}"))
                postValue(loc)
            } else util.toast(util.getStringRes(R.string.null_location))
        }.addOnFailureListener { e: Exception ->
            Log.e(LocationModule::class.java.canonicalName, e.toString())
        }
    } catch (ex: Exception) {
        Log.e(LocationModule::class.java.canonicalName, ex.toString())
    }
    return this
}

private fun getFusedLocationProviderClient(context: Context): FusedLocationProviderClient {
    if (fusedLocationProviderClient == null) fusedLocationProviderClient =
        LocationServices.getFusedLocationProviderClient(context)
    return fusedLocationProviderClient!!
}


text:
Q: "Timeout expired" exception happens before the defined timeout Using ADO.NET and SQL Server 2008.
The SqlCommand's CommandTimeout property was not changed, so it has the default value of 30.
The application runs some dozens command and logs the result (or exception) to an SQL table, so i know the start time of each execution. The start time of the next log record gives me an estimate of the duration.
I got two exception that don't make sense, because their duration is much smaller than the defined CommandTimeout.
This happend randomly. It's not reproducible.
Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.

My question is: can this exception be raised by other causes than and actual timeout?

A: It was probably related with some lock in participating tables.


text:
Q: When The RPC Server is unavailable How Can I Pass It? Here is my codes. I am trying to get computer information on network and I have two methods to get them. But when the machine is not online I got this Error. How can I pass these machine when they are not online.
public string GetBoardSerNo(string machineName)
    {
        string y = "";

        try
        {
            ManagementObjectSearcher searcher = new
                ManagementObjectSearcher("\\\\" + machineName + "\\root\\CIMV2", "SELECT * FROM Win32_BaseBoard");

            foreach (ManagementObject wmi in searcher.Get())
            {

                return wmi.GetPropertyValue("SerialNumber").ToString();

            }
        }
        finally
        {
            y = "Serial Number: Unknown";

        }

        return y;

    }
    public string GetModel(string machineName)
    {
        string x = "";

        try
        {

            ManagementObjectSearcher searcher = new
                ManagementObjectSearcher("\\\\" + machineName + "\\root\\CIMV2", "SELECT * FROM Win32_ComputerSystem");

            foreach (ManagementObject wmi in searcher.Get())
            {
                return wmi.GetPropertyValue("Model").ToString();

            }

        }
        finally
        {
            x = "Model No: Unknown";

        }
        return x;

    }

A: I solved it by myself. Thanks for your help.
    {

        try
        {
            ManagementObjectSearcher searcher = new
                ManagementObjectSearcher("\\\\" + machineName + "\\root\\CIMV2", "SELECT * FROM Win32_BaseBoard");

            foreach (ManagementObject wmi in searcher.Get())
            {

                return wmi.GetPropertyValue("SerialNumber").ToString();

            }
        }
        catch (COMException ce)
        {
            if ((uint)ce.ErrorCode == 0x800706BA)
            {
                return "Serial Number : Null";
            }
        }

        return "Serial Number : Null";

    }


text:
Q: How to get verbose information from `zfs get` Running Ubuntu 14...
"14.04.5 LTS, Trusty Tahr"

...with Ubuntu zfs...
libzfs2/trusty,now 0.6.5.11-1~trusty amd64 [installed,automatic]
mountall/trusty,now 2.53-zfs1 amd64 [installed,upgradable to: 2.53-zfs1]
ubuntu-zfs/trusty,now 8~trusty amd64 [installed]
zfs-dkms/trusty,now 0.6.5.11-1~trusty amd64 [installed]
zfs-doc/trusty,now 0.6.5.11-1~trusty amd64 [installed,automatic]
zfsutils/trusty,now 0.6.5.11-1~trusty amd64 [installed]

I've set the NFS share using ...
zfs set sharenfs="rw=@1xx.xxx.xxx.0/255.255.254.0,rw=@10.0.0.0/24" zpool/datashare

...but when I query I only get ON/OFF reporting...
root# zfs get  sharenfs zpool/datashare
NAME             PROPERTY  VALUE     SOURCE
zpool/datashare  sharenfs  off       local

root# zfs get  sharesmb zpool/datashare
NAME             PROPERTY  VALUE     SOURCE
zpool/datashare  sharesmb  on        local

Is there any way to get a full reporting of the sharenfs options?

A: According to the Oracle docs for ZFS:

As in the previous releases, you display the value of the sharenfs
  property by using zfs get sharenfs property or by using the zfs get all command syntax.
# zfs get sharenfs rpool/fs1
  NAME       PROPERTY  VALUE     SOURCE
  rpool/fs1  sharenfs  on        local
The new share information is available by using the zfs get share
  command.
# zfs get share rpool/fs1
  NAME       PROPERTY  VALUE  SOURCE
  rpool/fs1  share     name=rpool_fs1,path=/rpool/fs1,prot=nfs  local
The new share information is not available in the zfs get all command
  syntax.

Try this:
# zfs get share zpool/datashare


text:
Q: Extract image data from EPS I have an encapsulated PostScript file which appears to only wrap an image file.
Is there a tool to extract the image data from it?

A: "convert" will use ghostscript to render the eps, and then continues with the rendered bitmap; this makes it difficult to get the original image back, in most cases you get a re-sampled image.
I understand that you want the image out in the original resolution. I haven't got a direct route for you. However, for getting images from pdf files, you can use pdfimages. Assuming you are running this on a Linux box (or with cygwin)
ps2pdf file.eps
pdfimages file.pdf basename

This gives you a basename.pnm or basename.ppm file. Use convert to get it to jpeg or png. If you had a lossy format (jpg) in the .eps, this would re-code the jpg, so some additional loss is unavoidable.
convert basename.pnm file.jpg

or
convert basename.ppm file.png

p.s. The  file from the question is no longer available. However, this answer might still be of interest to others.

A: ImageMagick can do that:
convert file.eps file.jpg

or you can do
convert file.eps file.png
convert file.eps file.tif

ImageMagick is available here.


text:
Q: How to use image source from tmp folder of ubuntu I have a jsp web application running on Ubuntu apache server. I take screen shot of different picture and save those in tmp folder of the server. Now I need to show this picture in my web application. How can I show picture in my application from tmp folder?
when I set image source src="/tmp/zzz.png" is not working.

A: I'm not sure if its the correct way of doing this but it works.
You simply make a symbolic link
ln -S /tmp /your/project/directory

for the /tmp directory inside your project and you can use it like a normal image inside a directory.
Hope this helps


text:
Q: Getting a String from a list of strings Is there a way to write down Mathematica with a string such as:
{"M","a","t","h","e","m","a","t","i","c","a"}?

A: Use StringJoin:
StringJoin @@ {"M", "a", "t", "h", "e", "m", "a", "t", "i", "c", "a"}

"Mathematica"

A: If we're going to get silly about it:
TextRecognize @ Graphics @ MapIndexed[Text[Style[#1, 50], {#2[[1]], 0}] &, list]

A: At risk of taking "even more" too far here is a method that does not use any function with "String" in the name:
list = {"M", "a", "t", "h", "e", "m", "a", "t", "i", "c", "a"};

FromCharacterCode @ Flatten @ ToCharacterCode @ list

Or using an export function:
ExportString[{list}, "Table", "FieldSeparators" -> ""]

Or a formatting function:
ToString @ Row @ list

A: Just to stretch even more the limits of "there is always another way to do it" (Mr.Wizard), here is a way to NOT use StringJoin at all:
chars = {"M", "a", "t", "h", "e", "m", "a", "t", "i", "c", "a"};
Fold[StringInsert[#1, #2, -1] &, "", Flatten@chars]

"Mathematica"

And a simpler one:
StringExpression @@ chars

Using built-in path functions to complicate things (use ToFileName if prior to version 7):
StringReplace[FileNameJoin@chars, "\\" -> ""]

A: In versions 10.1+, there is also StringRiffle:
StringRiffle[list, ""]

"Mathematica"

A: Supporting the maxim "there is always another way to do it":
list = {"M","a","t","h","e","m","a","t","i","c","a"};

StringJoin accepts lists directly, and in fact is faster this way:
StringJoin @ list

"Mathematica"

Also, StringJoin has the short form <> therefore you could also use:
"" <> list

"Mathematica"

Speed check:
large = Characters@ExampleData[{"Text", "LoremIpsum"}];

Do[StringJoin @@ large, {5000}] // Timing

Do[StringJoin @ large, {5000}]  // Timing

Do["" <> large, {5000}]         // Timing

Version 7.0.1 timings:

{1.622, Null}

{0.702, Null}

{0.718, Null}

Version 10.1.0 timings:

{0.6864, Null}

{0.4524, Null}

{0.4524, Null}

A: Just for something different Fold works too:
Fold[#1 <> #2 &, "", {"M", "a", "t", "h", "e", "m", "a", "t", "i",
  "c", "a"}]

"Mathematica"


text:
Q: Magnitude help!! A basket of flowers of mass 2kg in a garden. Gravity $g=9.8\frac{m}{s^2}$
The basket is suspended between two tree branches by two ropes. The left rope(S) makes an angle of 54 with the horizontal, and the right rope(T) makes an angle of 43 with the horizontal. Calculate the magnitude in newtons of the tension in each rope.
So far I have
We know that $|W| =2g$,
$$T=|T|\cos(43)i+|T|\sin(43)\hat{j}$$
$$=0.73T\hat{i}+0.68T\hat{j}$$
$$S=-S\cos(54)\hat{i}+S\sin(54)\hat{j}$$
$$=-0.59S\hat{i}+0.81S\hat{j}$$
Also $W=-2g\hat{j}$
$$0.73T\hat{i}+0.68T\hat{j}-0.59S\hat{i}+0.81S\hat{j}-2g\hat{j}=0$$
Resolving this equation in the $\hat{i}$- and $\hat{j}$- directions gives the simultaneous equations
$$0.73T-0.59S=0$$
$$0.68T+0.81S-2g=0$$
I know I have gone wrong somewhere as when I solve these equations both S and T come to 0, really stuck as can't figure out where I have gone wrong!!

A: Starting from your last system of equations
$$
\begin{cases}
0.73\ T - 0.59\ S = 0 \\
0.68\ T + 0.81\ S - 2g = 0
\end{cases}
$$
I am sure you're familiar with the method of solving couple equations; but let's use the raw way of finding one parameter as a function of the other one and then substitute: in the first one we can find $T$ as
$$T = \frac{0.59}{0.73}S = 0.8082\ S$$
And substitute it into the $T$ in the second equation
$$0.68 \cdot (0.8082\ S) + 0.81\ S - 2g = 0$$
Hence
$$0.549\ S + 0.81\ S = 2g$$
$$1.359\ S = 2g$$
Which means
$$S = \frac{2g}{1.359} = 14.422\ \text{N}$$
And consequently
$$T = 11.656\ \text{N}$$
I used $g = 9.8$ so it's quite a raw result ($g = 9.80665$).


text:
Q: query group by with order by i need to create query with group by and order by, and i dont know how to do it.
query should return one record for the newest date for existing device_serial_number. enter image description here
so i would to get id 591 nad 592
solution can be in sql or the best way it will be in symfony, through query builder etc.

A: There are many ways to accomplish what you want.
First Way
The oldest way to select first, best, worst, whatever within a group is with a correlated subquery:
Select * from mytable outer
Where created_at = (
    Select max(created_at)
    from mytable inner
    Where inner.device_serial_number = outer.device_serial_number
)

Second Way
Use a subselect to find earliest dates for all devices, them join back to the original table to filter:
Select a.*
From mytable a Inner Join
     (Select device_serial_number, max(created_at) as latedate
       From mytable b
       Group By device_serial_number
      ) b
      On a.device_serial_number=b.device_serial_number
       And a.created_at=b.latedate

Third way
Use a window function to rank order all the dates and then pick the number one ranking.
Select * From (
    Select *
        , rank() Over (Partition By device_serial_number Order by created_at desc) as myrank
    From mytable
)
Where myrank=1

Notice that while these 3 solutions use different aspects of SQL, they all have a common analytical approach.  They are all two step processes whose first (inner) part involves finding the most recent created_at date for each device_serial_number and then reapplying that result back to the original table in the second (outer) part.


text:
Q: When adding ul element into Kendo Grid Column ul element always behind an other columns I try to add ul element into kendo-grid-column. When I did ul element always look like as in the picture. z-index is not working.
Here is my code:
<kendo-grid-column>
  <ng-template kendoGridCellTemplate let-dataItem>

            {{itemData.Desc}}

  </ng-template>
</kendo-grid-column>

My grid looks like the following:

Sorry for my English :)
Thank you...


text:
Q: Volume of Gabriel's horn using double integral I am trying to use a double integral to calculate the volume of Gabriel's horn:
https://en.wikipedia.org/wiki/Gabriel%27s_Horn
$V = \int\int_R (x^2+y^2)^{-1/2} dx dy$
Converting to polar coordinates:
$V = \int_{0}^{2\pi} \int_{0}^{1} \frac{1}{r} r\:dr\:d\theta$
$=2\pi$
But the answer should be $V = \pi$.
Should the limits for $\theta$ be $0 \rightarrow \pi$ or have I made a mistake somewhere else?

A: I think the integral you want is
$$\int\int_R\left(\frac1{\sqrt{x^2+y^2}}-1\right)\,dx\,dy$$
where $R$ is the unit disc. This gives the volume of the
set
$$\{(x,y,z):z\sqrt{x^2+y^2}\le1,z\ge1\}.$$

A: Gabriel's horn is obtained by rotating the graph of $f(x)=\frac{1}{x}$ over $(1,+\infty)$ around the $x$-axis.
For any $t\in(1,+\infty)$ the section $x=t$ is given by a circle with radius $\frac{1}{t}$ and area $\frac{\pi}{t^2}$, hence by Cavalieri's principle
$$ V = \int_{1}^{+\infty}\frac{\pi}{t^2}\,dt = \color{red}{\large\pi}. $$

A: The problem with your analysis is that the volume should be expressed formally as
$$V=2\pi\int_1^{\infty}\int_0^{1/x}y\,dy~dx=2\pi\int_1^{\infty}\frac{y^2}{2}\biggr|_0^{1/x}~dx=\pi\int_1^{\infty}\frac{1}{x^2}~dx=\pi$$


text:
Q: Can't update Rubymine due to permission issue I'm trying to update Rubymine to 8.0.4.
The UPDATE button was not active due to a permission issue, and I got this alert:

RubyMine does not have write access to /opt/Rubymine. Please run it by
  a privileged user to update.

Then I tried running sudo ./rubymine.sh from the /bin folder, but I get the following error:
[  29530]   WARN - pl.local.NativeFileWatcherImpl - Watcher terminated with exit code 0
Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=250m; support was removed in 8.0
Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=250m; support was removed in 8.0
log4j:WARN No appenders could be found for logger (io.netty.util.internal.logging.InternalLoggerFactory).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.

I'm stuck, any clue about what to do next? Thanks


text:
Q: Adding two Integers to array index without summing them I'm a beginner in C# ,
I'm trying to do this ..... user input "43 24" and the application take this input , put 43 in arr1[0] , and 24 in arr1[1] . The arr1 is char[] type .. i tried this : (This is only a part of the code of course) (wholeLine is type string)
foreach (char ch in wholeLine)
      {
          if (ch != ' ')
              {
                 arr1[0]  += ch ;
              }
      }

and the output for arr[0] is : g
I tried to make arr1 an int[] type and did this :
foreach (char ch in wholeLine)
      {
          if (ch != ' ')
              {
                 int z = Convert.ToInt32(ch.ToString());
                 arr1[0]  += z ;
              }
      }

But the output is : 7
I just want arr[0] to contain 43 , i think it's a conversions issue , but i have no clue what to do , so help please :)
Thanks in advance .

A: You could use a string array. If you call .Split on your string, it will return an array of strings:
string words = "This is a list of words, with: a bit of punctuation" +
                   "\tand a tab character.";

string [] split = words.Split(new Char [] {' ', ',', '.', ':', '\t' });

foreach (string s in split) {

    if (s.Trim() != "")
        Console.WriteLine(s);
}

A: you can use wholeLine.Split(" ") which will split your string and make string[] array out of it.

A: Try string[] arr1 = wholeLine.Split(new char[] {' '});


text:
Q: Web Based WYSIWYG Editor with Photo Upload support Does anyone know what my options are for Web-based WYSIWYG editors (the type which acts like a textarea but produces HTML) are?
I need one with support for image uploads - This would be for a basic CMS that I am developing which needs to be fairly user-friendly. I can handle the server-side upload processing, but I need an upload option to be there.
A combination of CKEditor and CKFinder may have been ideal, but CKEditor seems to have been commercialised - I'm looking for something which is free/open source.
I think that this post belongs here... It was a tossup between stackoverflow and webmasters. Sorry if I'm wrong!

A: I use TinyMCE and there are several upload plugins that you can use with it, including these here.


text:
Q: Remove some x labels with Seaborn In the screenshot below, all my x-labels are overlapping each other.
g = sns.factorplot(x='Age', y='PassengerId', hue='Survived', col='Sex', kind='strip', data=train);

I know that I can remove all the labels by calling g.set(xticks=[]), but is there a way to just show some of the Age labels, like 0, 20, 40, 60, 80?

A: I am not sure why there aren't sensible default ticks and values like there are on the y-axis. At any rate you can do something like the following:
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

titanic = sns.load_dataset('titanic')
sns.factorplot(x='age',y='fare',hue='survived',col='sex',data=titanic,kind='strip')
ax = plt.gca()
ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%d'))
ax.xaxis.set_major_locator(ticker.MultipleLocator(base=20))
plt.show()

Result:


text:
Q: Echarts3.0 display percent on y-axis in stacked bar chart Using Echarts3.0 in Vuejs2.0 component, I am trying to assign percent on y-axis in  a stacked bar chart. I tried boundaryGap, splitnumber,  etc, but none of them worked.
But i cannot achieve it, Anyone has idea how can i get % on y-axis?
export default {
  data: () => ({
    loading: true,
    bar: {
    xAxis:  {
            type: 'category',
            data: ['Location1','Location2']
        },
    yAxis: {
            type: 'value',
           splitNumber: 10,
           boundaryGap: ['0', '100%'],
           min:0,
           max:100,
            scale:true,
            splitArea : {show : true},
            label: {
                 formatter: function(){
                 return 100 * value /$(this.axis.tickPositions).last()[0]
                 + '%';
                       }
                   }
            },
     series: [
            {
                name: 'Location1',
                type: 'bar',
                stack: 'one',
                label: {
                    normal: {
                        show: true,
                        position: 'insideRight'
                    }
                },
                data: [1100, 2050]
            },
            {
                name: 'Location2',
                type: 'bar',
                stack: 'one',
                label: {
                    normal: {
                        show: true,
                        position: 'insideRight'
                    }
                },
                data: [291064, 34789]
            }
        ]
        }

})

A: Set yAxis in below format
yAxis: [{
  type: "value",
  name: "%",
  axisLabel: {
    formatter: "{value} %"
  }
}]

A: you have to calculate maxValue first, then...
  yAxis: [
    {
      type: 'value',
      axisLabel: {
        formatter: (value) => {
          return Math.floor(100 * value / maxValue) + '%';
        }
      }
    }
  ],


text:
Q: How to change the orientation of the model itself? I downloaded a bullet model from TurboSquid.
But the bullet is pointing to the left (negtive X axis).
So the whole thing needed to be turned 90 degree on Y axis to face "forward" (Z axis).
I'm making a first-person shooting game so I needed the bullet to face exactly where the camera was facing.
So if I simply set
bullet.gameObject.transform.rotation = Camera.main.transform.rotation;

The bullet will just facing "left"!
I tried to do a additional rotation after the rotation assignment as follow:
bullet.gameObject.transform.Rotate(Camera.main.transform.up,90);

It worked fine if the view is parallel to the horizon.
But it will started to facing some weird ways if you're shooting up or down!
I also tried to create an empty parent GameObject and throw the bullet in as its child, and set the parent's rotation.
Now it "always" facing "forward" (Z axis)! No matter where I turned my camera!
Could somebody please be so kind and teach me how to fix this!?
Much appreciated!

A: Wrap your model in a parent object, like this:

Then you can rotate the BulletModel 90 degrees and attach the script that moves the object to the ParentBullet. This should do the trick.
It's usually considered good practice overall to separate your model and logic/actual object like this.

A: I fixed it by some weird ways!
I just set its forward to the camera's right, and its right to the camera's back.
bullet.gameObject.transform.forward = Camera.main.transform.right;
bullet.gameObject.transform.right = -Camera.main.transform.forward;

But I still don't know why the empty parent GameObject trick don't work!?


text:
Q: $R/(a)$ is torsion for any nonzero $a \in R$? Let $R$ be an integral domain and $a \in R$ be nonzero. The claim now is that $R/(a)$ is a torsion $R$-module, where $(a) = Ra = \{ ra: r \in R\}$ is a cyclic submodule.
I don't know why I still cannot formulate a proof. I've read Foote and Dummit and some notes I found online, all of which seems to regard it as trivial so there's got to be something small I've missed. Here's my attempt:
Attempt. We prove by contradiction. Suppose $R/(a)$ is not torsion. Then there exists $r + (a) \in R/(a)$, such that for any nonzero $s \in R$, we have
$$s \cdot (r + (a)) = sr + (a) \neq 0_R + (a).$$
Accordingly, this means that $sr \notin (a)$ and $sr \neq 0_R $. And here's where I am stuck.
I was thinking of putting it into a form where I can use that $R$ is an integral domain, but I have $rs \neq 0$ and not $rs = 0$. I have spent hours on this, so it would be helpful if someone could point me in the right direction.

A: Consider a typical element $r+(a)$. Then $a(r+(a)) = ra+(a) = 0$ as $ra \in (a)$.


text:
Q: rpart() inside a function doesn't show variable names I have the following problem: The goal is to put rpart () in a function so the set-up can be quickly done for different variables and datasets. Whenever rpart() is written in a function it seems to have some problems with different environments. Both for finding the assigned variables as in the names of the variables in the tree.
For instance if you look to the example below, the name 'parameter' is used at each splitting node.
I tried already solving the problem with get() (which gives the error 'Error in get(parameter) : invalid first argument'.
I also tried environment(research.parameter)<-environment() which makes the function work, but still isn't showing the assigned variable names in the splitting in the tree.
[Result function tree][1]
Example code:
  attach(Data.used)
  environment(research.parameter)<-environment()
  environment(parameter)<-environment()
  fit <- rpart(research.parameter ~ parameter,data=Data.used)
  printcp(fit)

  rpart.plot(fit, type=0, tweak=1.5,main= title.tree)

  File <- paste("Decisiontree_",research.parameter,"_",title.tree,"_",date,".png",sep = "")     #png voor cross-validation results
       png(File, units = "in", width = 15, height = 10, res=300)

  rpart.plot(fit, type=5, tweak=1.5, main= title.tree,cex.main=3)

  dev.off()
}

Plot.tree.2(Data.used = train.data, parameter=IT+RE,research.parameter = Mmean, title.tree = "test")```

  [1]: https://i.stack.imgur.com/8avE3.png


text:
Q: WordPress - Disable WP postrating on all pages except post I am using following code of wp postrating plugin on my all pages
if(function_exists('the_ratings')) { the_ratings(); } ?>

I do not want to allow users to rate on all pages except post page. I checked documentation faq and plugin author's forum page but I haven't got any clue how to disable rating for users.
Any hint or clue how to solve this problem?

A: By post page, do you mean the single post view page?
If so, then the easiest method would be to only include the call in you single.php template.


text:
Q: how to show amazon interstitials when app starts (android) I was wondering how to display amazon interstitial Ads right when the app starts on android devices.
I have tried...
AdRegistration.setAppKey(APP_KEY);
        this.interstitialAd = new InterstitialAd(this);
        this.interstitialAd.loadAd();
        this.interstitialAd.setListener(this);

under OnCreate but the ad won't appear

A: Make a launcher activity by declaring it as launcher in manifest in on create show your interestial
Make a handler and use postdelayed to start your main activity
@Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        // do not set contentView
        Your Interestial logic goes here

      //set up a handler to start main activity
    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {

        @Override
        public void run() {

                Intent intent = new Intent(Splash.this,HomeActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                        | Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                finish();

        }

    }, 4000);

}


text:
Q: SQL Server - Column for Time Since Last Row Was Created I have a table that is structured like this
CREATE TABLE log (
  id                 BIGINT            IDENTITY (1, 1) PRIMARY KEY,
  datetime_created   DATETIME NOT NULL DEFAULT (getdate()),
  message            VARCHAR(MAX)
)

I'd like to add a fourth column, time_since, that by default looks at the previous row's datetime_created field and gets the difference in time and saves this in the new row's time_since column.
Any ideas on how to accomplish this?
EDIT: As a note, I'm constrained to using SQL Server 2008

A: Instead of having a column for this, I recommend that you just calculate it on the fly using LAG.  That way if the dates ever change you won't need to change this 2nd field.
Example:
CREATE TABLE log (
  id                 BIGINT            IDENTITY (1, 1) PRIMARY KEY,
  datetime_created   DATETIME NOT NULL DEFAULT (getdate()),
  message            VARCHAR(MAX)
)

insert into log values ('2016-01-01', 'first');
insert into log values ('2016-01-02T12:21:23', 'second');

SELECT l.id, l.datetime_created, l.message, DATEDIFF(SECOND, LAG(l.datetime_created) OVER (ORDER BY l.id), l.datetime_created)
FROM log l

A: You can do this with an instead of trigger
create table log
(
    id bigint identity(1, 1) primary key,
    datetime_created datetime not null default (getdate()),
    message varchar(max),
    time_since int not null
)
go

create trigger is_log on log
instead of insert
as
    insert into log (datetime_created, message, time_since)
    select datetime_created, message,
        datediff(ss, isnull((select max(datetime_created) from log), getdate()), datetime_created)
    from inserted
go

insert into log (message)
values ('Message 1')

waitfor delay '00:00:02';

insert into log (message)
values ('Message 2')

waitfor delay '00:00:04';

insert into log (message)
values ('Message 3')

waitfor delay '00:00:06';

insert into log (message)
select message + 'multi insert'
from log
go

select *
from log

A: When inserting a new row, why not also insert a value that equals DATEDIFF(SECOND, (SELECT MAX(datetime_created) FROM log), CURRENT_TIMESTAMP)


text:
Q: How to get the dimension of a function return value without evaluating the function Assume I know that the function f returns a vector of unknown dimension. The function returns value of the form: np.array(list). Can I get the dimension of the return value without evaluating the function?
Consider for instance this function:
def f(x):
    f1 = x**2
    f2 = x
    return np.array([f1,f2]);

I want some something like: dim(f) that gives the answer 2.
Right now I get around the problem by evaluating the function for a random  number and then find the dimension: len(f(np.random.rand()))
but I want to avoid the evaluation of the function.
npis off course numpy

A: This is not possible. The output dimension of the function is dependent on that of its input, it's not static. You can reason about it yourself, in your example the function has an output dimension of [2, *x.ndim]. Sure, if x is a single scalar the dimension will be two, but if x is an array the dimension is gonna be different, et cetera.
In short, if you know your function always takes a scalar or some other value with static dimensions, just put its output dimension in the doc-string. If you take arguments that can be any dimension, you won't get around evaluating the function to find out the dimension of its result.

A: What Koen Dercksen said is correct, there is no way to determine the dimension of the result without evaluating the function. However, if you do evaluate the function, you should use the .shape property instead of len()
For example:
def f(x):
    f1 = x**2
    f2 = x
    return np.array([f1,f2]);

len = f(0).shape[0]

Also generating a new random number for the function call is unnecessary, you can pass a constant as the parameter and the result will be the same.


text:
Q: ObjectPool or similar for .NET already in a library? I don't want to write my own because i'm afraid i might miss something and/or rip off other people's work, so is there an ObjectPool (or similar) class existing in a library for .NET?
By object pool, i mean a class that assists caching of objects that take a long time to create, generally used to improve performance.

A: CodeProject has a sample ObjectPool implementation.  Have a look here.  Alternatively, there are some implementations here, here, and here.

A: In the upcoming version of .NET (4.0), there's a ConcurrentBag<T> class which can easily be utilized in an ObjectPool<T> implementation; in fact the there's an article on MSDN that shows you how to do precisely this.
If you don't have access to the latest .NET framework, you can get the System.Collections.Concurrent namespace (which has ConcurrentBag<T>) in .NET 3.5 from Microsoft's Reactive Extensions (Rx) library (in System.Threading.dll).

A: UPDATE:
I'd also put forward BufferBlock<T> from TPL DataFlow. IIRC it's part of .net now. The great thing about BufferBlock<T> is that you can wait asynchronously for items to become available using the Post<T> and ReceiveAsync<T> extension methods. Pretty handy in an async/await world.
ORIGINAL ANSWER
A while back I faced this problem and came up with a lightweight (rough'n'ready) threadsafe (I hope) pool that has proved very useful, reusable and robust:
    public class Pool<T> where T : class
    {
        private readonly Queue<AsyncResult<T>> asyncQueue = new Queue<AsyncResult<T>>();
        private readonly Func<T> createFunction;
        private readonly HashSet<T> pool;
        private readonly Action<T> resetFunction;

        public Pool(Func<T> createFunction, Action<T> resetFunction, int poolCapacity)
        {
            this.createFunction = createFunction;
            this.resetFunction = resetFunction;
            pool = new HashSet<T>();
            CreatePoolItems(poolCapacity);
        }

        public Pool(Func<T> createFunction, int poolCapacity) : this(createFunction, null, poolCapacity)
        {
        }

        public int Count
        {
            get
            {
                return pool.Count;
            }
        }

        private void CreatePoolItems(int numItems)
        {
            for (var i = 0; i < numItems; i++)
            {
                var item = createFunction();
                pool.Add(item);
            }
        }

        public void Push(T item)
        {
            if (item == null)
            {
                Console.WriteLine("Push-ing null item. ERROR");
                throw new ArgumentNullException();
            }
            if (resetFunction != null)
            {
                resetFunction(item);
            }
            lock (asyncQueue)
            {
                if (asyncQueue.Count > 0)
                {
                    var result = asyncQueue.Dequeue();
                    result.SetAsCompletedAsync(item);
                    return;
                }
            }
            lock (pool)
            {
                pool.Add(item);
            }
        }

        public T Pop()
        {
            T item;
            lock (pool)
            {
                if (pool.Count == 0)
                {
                    return null;
                }
                item = pool.First();
                pool.Remove(item);
            }
            return item;
        }

        public IAsyncResult BeginPop(AsyncCallback callback)
        {
            var result = new AsyncResult<T>();
            result.AsyncCallback = callback;
            lock (pool)
            {
                if (pool.Count == 0)
                {
                    lock (asyncQueue)
                    {
                        asyncQueue.Enqueue(result);
                        return result;
                    }
                }
                var poppedItem = pool.First();
                pool.Remove(poppedItem);
                result.SetAsCompleted(poppedItem);
                return result;
            }
        }

        public T EndPop(IAsyncResult asyncResult)
        {
            var result = (AsyncResult<T>) asyncResult;
            return result.EndInvoke();
        }
    }

In order to avoid any interface requirements of the pooled objects, both the creation and resetting of the objects is performed by user supplied delegates: i.e.
Pool<MemoryStream> msPool = new Pool<MemoryStream>(() => new MemoryStream(2048), pms => {
        pms.Position = 0;
        pms.SetLength(0);
    }, 500);

In the case that the pool is empty, the BeginPop/EndPop pair provide an APM (ish) means of retrieving the object asynchronously when one becomes available (using Jeff Richter's excellent AsyncResult<TResult> implementation).
I can't quite remember why it is constained to T : class... there's probably none.

A: How about System.Collections.Generic.Dictionary?

A: Sounds like you need a Factory pattern with caching.
You can try use .net reflector to look at the ThreadPool implementation.


text:
Q: select pages for pdf print I am printing the current page of a pdf file in evince. But I found that in evince, there are two different page numbers showing the current page. If I choose the one shown in an input box, that will print out the wrong page, but if I choose the one shown inside the parenthesis after the input box, that will be the correct one. I was wondering

*

*what is the difference between the
two numbers shown for the current
page?

*why selecting pages for printing
works that way?

Thanks and regards!

A: Tim,
Evince displays the page numbers in parenthesis based on the logical/actual sequence of pages; that is, the real page numbers if you used only 1 - n (instead of i, ii, iii, 1).
The numbers in the input box are the numbers (or "name") given to the page. For example i, ii, and so on.
This is an issue with any type of document/reader that uses mixed or after actual first page numbering.


text:
Q: Unique constraint without index let's say I have a large table.
This table not need to be queried, I just want to save the data inside for a while.
I want to prevent duplicates rows in the table, so I want to add an unique
constraint (or PK) on the table.
But the auto-created unique index is realy unnecessary.
I don't need it, and it's just wasting space in disk and require a maintenance
(regardless of the long time to create it).
Is there a way to create an unique constraint without index (any index - unique or nonunique)?
Thank you.

A: No, you can't have a UNIQUE constraint in Oracle without a corresponding index. The index is created automatically when the constraint is added, and any attempt to drop the index results in the error
ORA-02429: cannot drop index used for enforcement of unique/primary key

Best of luck.
EDIT
But you say "Let's say I have a large table". So how many rows are we talking about here? Look, 1TB SSD's are under $100. Quad-core laptops are under $400. If you're trying to minimize storage use or CPU burn by writing a bunch of code with minimal applicability to "save money" or "save time" my suggestion is that you're wasting both time and money. I repeat - ONE TERABYTE of storage costs the same as ONE HOUR of programmer time. A BRAND SPANKING NEW COMPUTER costs the same as FOUR LOUSY HOURS of programmer time. You are far, far better off doing whatever you can to minimize CODING TIME, rather than the traditional optimization targets of CPU time or disk space. Thus, I submit that the UNIQUE index is the low cost solution.

A:
But the auto-created unique index is really unnecessary.

In fact, UNIQUEness in an Oracle Database is enforced/guaranteed via an INDEX. That's why your primary key constraints come with a UNIQUE INDEX.
Per the Docs
UNIQUE Key Constraints and Indexes
Oracle enforces unique integrity constraints with indexes.

A: Maybe Index-Organized Tables is what you need ?.
But strictly the index organized table is the table stored in the structure of the index - one can say that there is the index alone without the table, while yor requirement is to have the table without the index, so this is the opposite :)
CREATE TABLE some_name
(
 col1           NUMBER(10)    NOT NULL,
 col2           NUMBER(10)    NOT NULL,
 col3           VARCHAR2(50)  NOT NULL,
 col4           VARCHAR2(50)  NOT NULL,
 CONSTRAINT pk_locations PRIMARY KEY (col1, col2)
)
ORGANIZATION INDEX


text:
Q: Maintenance mode for the Play Framework Is there any way to enable the display of a static HTML page to explain that a site is in maintenance during times such as when the Play Framework is compiling new code?
I can see how we could manually create a maintenance page for things such as while a long database or file change is undergoing (during which the application may be in an inconsistent state), but is there any built-in approach for the Play Framework?
I know that some other major server software like Nginx have a way to display a static resource here. Since the Play Framework is also the server software, does it have an equivalent?

A: Sure. Your best bet is to use request interceptors. This is using a request filter, lightly adapted from those docs:
import play.api.Logger
import play.api.mvc._

object MaintenanceModeFilter extends Filter {
  def apply(next: (RequestHeader) => Future[Result])(request: RequestHeader): Future[Result] = {
    if (/* check for trigger */) {
      Logger.info("Sending maintenance mode response")
      Ok(/* your maintenance page */)
    } else {
      next(request)
    }
  }
}

object Global extends WithFilters(AccessLoggingFilter)

You could probably make it work with onRouteRequest, also mentioned in those docs, if you prefer.


text:
Q: Using variables in PrometheusRule expr field instead of contant values I am trying to create a 'PrometheusRule' inside my cluster with some alert rules using promql expressions. However, I want these resources to be used and configurable for different services inside my same cluster. All I want to do is have Variable values inside my "expr" field, something like this:
expr: sum( nginx_ingress_controller_requests{status=~"5.+"} ) > VARIABLE_VALUE

Instead of:
expr: sum( nginx_ingress_controller_requests{status=~"5.+"} ) > 50

This is the PromethuesRule I am trying to make:
apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
  name: blablaname
  namespace: blablans
spec:
  groups:
  - name: {{ include "blabla.fullname" . }}-cache
    rules:
    - alert: TOOMANY5XXX
      annotations:
        description: too many 5XXs
        summary: blablabla
      expr: sum( nginx_ingress_controller_requests{status=~"5.+"} ) > VARIABLE_VALUE
      for: 5m
      labels:
        severity: critical

PS: I am using Helm charts as my package manager and would like the Variable to be present in my Values.yaml file

A: If you are using helm then use simple variable assignment:
expr: sum( nginx_ingress_controller_requests{status=~"5.+"} ) > {{ .Values.VariableValue }}


text:
Q: Problems with hurdle and truncated count model from statsmodels I want to use a hurdle model from statsmodels (https://www.statsmodels.org/dev/examples/notebooks/generated/count_hurdle.html).
Unfortunately, when following the manual, I am running into several problems:

*

*I am only able to load the discrete_model and count_model from discrete:

Hence, the following work
import statsmodels.discrete.discrete_model
import statsmodels.discrete.count_model

However, there is no module named 'statsmodels.discrete.truncated_model'
Furthermore, I am not able to run
get_diagnostic()

with
a poisson regression. I am running the same code as on the statsmodels website (see below), but it throughs the following error:
'PoissonResults' object has no attribute 'get_diagnostic'

Thanks for your help!
np.random.seed(987456348)
# large sample to get strong results
nobs = 5000
x = np.column_stack((np.ones(nobs), np.linspace(0, 1, nobs)))

mu0 = np.exp(0.5 *2 * x.sum(1))
y = np.random.poisson(mu0, size=nobs)
print(np.bincount(y))
y_ = y
indices = np.arange(len(y))
mask = mask0 = y > 0
for _ in range(10):

    print( mask.sum())
    indices = mask #indices[mask]
    if not np.any(mask):
        break
    mu_ = np.exp(0.5 * x[indices].sum(1))
    y[indices] = y_ = np.random.poisson(mu_, size=len(mu_))
    np.place(y, mask, y_)
    mask = np.logical_and(mask0, y == 0)

np.bincount(y)

mod_p = Poisson(y, x)
res_p = mod_p.fit()
print(res_p.summary())

dia_p = res_p.get_diagnostic()
dia_p.plot_probs();


text:
Q: Accessing R list elements through function parameters I have an R list which looks as follows
> str(prices)
List of 4
 $ ID   : int 102894616
 $ delay: int 8
 $ 47973      :List of 12
  ..$ id       : int 47973
  ..$ index        : int 2
  ..$ matched: num 5817
 $ 47972      :List of 12
..

Clearly, I can access any element by e.g. prices$"47973"$id.
However, how would I write a function which parametrises the access to that list? For example an access function with signature:
access <- function(index1, index2) { .. }

Which can be used as follows:
> access("47973", "matched")
5817

This seems very trivial but I fail to write such a function. Thanks for any pointers.

A: Using '[[' instead of '$' seems to work:
prices <- list(
    `47973` = list( id = 1, matched = 2))

access <- function(index1, index2) prices[[index1]][[index2]]
access("47973","matched")

As to why this works instead of:
access <- function(index1, index2) prices$index1$index2 (which I assume is what you tried?) it's because here index1 and index2 are not evaluated. That is, it searches the list for an element called index1 instead of what this object evaluates to.

A: You can take advantage of the fact that [[ accepts a vector, used recursively:
prices <- list(
    `47973` = list( id = 1, matched = 2))

prices[[c("47973", "matched")]]
# 2


text:
Q: How to define a sort function in Mongoose I'm developing a small NodeJS web app using Mongoose to access my MongoDB database. A simplified schema of my collection is given below:
var MySchema = mongoose.Schema({
    content:   { type: String },
    location:  {
         lat:      { type: Number },
         lng:      { type: Number },
    },
    modifierValue:  { type: Number }
});

Unfortunately, I'm not able to sort the retrieved data from the server the way it is more convenient for me. I wish to sort my results according to their distance from a given position (location) but taking into account a modifier function with a modifierValue that is also considered as an input.
What I intend to do is written below. However, this sort of sort functionality seems to not exist.
MySchema.find({})
        .sort( modifierFunction(location,this.location,this.modifierValue) )
        .limit(20)       // I only want the 20 "closest" documents
        .exec(callback)

The mondifierFunction returns a Double.
So far, I've studied the possibility of using mongoose's $near function, but this doesn't seem to sort, not allow for a modifier function.
Since I'm fairly new to node.js and mongoose, I may be taking a completely wrong approach to my problem, so I'm open to complete redesigns of my programming logic.
Thank you in advance,

A: You might have found an answer to this already given the question date, but I'll answer anyway.
For more advanced sorting algorithms you can do the sorting in the exec callback. For example
MySchema.find({})
  .limit(20)
  .exec(function(err, instances) {
      let sorted = mySort(instances); // Sorting here

      // Boilerplate output that has nothing to do with the sorting.
      let response = { };

      if (err) {
          response = handleError(err);
      } else {
          response.status = HttpStatus.OK;
          response.message = sorted;
      }

      res.status(response.status).json(response.message);
  })

mySort() has the found array from the query execution as input and the sorted array as output. It could for instance be something like this
function mySort (array) {
  array.sort(function (a, b) {
    let distanceA = Math.sqrt(a.location.lat**2 + a.location.lng**2);
    let distanceB = Math.sqrt(b.location.lat**2 + b.location.lng**2);

    if (distanceA < distanceB) {
      return -1;
    } else if (distanceA > distanceB) {
      return 1;
    } else {
      return 0;
    }
  })

  return array;
}

This sorting algorithm is just an illustration of how sorting could be done. You would of course have to write the proper algorithm yourself. Remember that the result of the query is an array that you can manipulate as you want. array.sort() is your friend. You can information about it here.


text:
Q: GGTS Convert to Grails fails with NoClassDefFoundError I've imported a Grails project and am attempting to "convert it to grails". When I do this, I"m getting a NoClassDefFound on the apache commons logging package. Where do I add the jar for this? Is this in the IDE's class path, the Grails class path or the app's class path? It does not appear to be in grails-2.2.4/lib. That is the first place I'd expect it. This appears to use Ivy, so should that come as a dependency? Below is the error I'm seeing:
Loading Grails 2.2.4
| Error java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
| Error     at org.codehaus.groovy.grails.io.support.PathMatchingResourcePatternResolver.<clinit>(PathMatchingResourcePatternResolver.java:136)
| Error     at org.codehaus.groovy.grails.cli.GrailsScriptRunner.getAvailableScripts(GrailsScriptRunner.java:813)
| Error     at org.codehaus.groovy.grails.cli.GrailsScriptRunner.executeScriptWithCaching(GrailsScriptRunner.java:423)
| Error     at org.codehaus.groovy.grails.cli.GrailsScriptRunner.executeScriptWithCaching(GrailsScriptRunner.java:417)
| Error     at org.grails.ide.api.impl.GrailsConnectorImpl.executeCommand(GrailsConnectorImpl.java:160)
| Error     at org.grails.ide.eclipse.longrunning.process.GrailsProcess.run(GrailsProcess.java:130)
| Error     at org.grails.ide.eclipse.longrunning.process.GrailsProcess.main(GrailsProcess.java:93)
| Error     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
| Error     at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
| Error     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
| Error     at java.lang.reflect.Method.invoke(Method.java:483)
| Error     at org.codehaus.groovy.grails.cli.support.GrailsStarter.rootLoader(GrailsStarter.java:234)
| Error     at org.codehaus.groovy.grails.cli.support.GrailsStarter.main(GrailsStarter.java:262)
| Error Caused by: java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory
| Error     at org.codehaus.groovy.tools.RootLoader.findClass(RootLoader.java:175)
| Error     at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
| Error     at org.codehaus.groovy.tools.RootLoader.loadClass(RootLoader.java:147)
| Error     at org.codehaus.groovy.grails.cli.support.GrailsRootLoader.loadClass(GrailsRootLoader.java:52)
| Error     at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
| Error     ... 13 more

A: Remove jdk1.8. I had both 1.7 and 1.8 jdks installed and 1.8 was my default runtime for osx. The project was specified as 1.7 but GGTS is looking at the default java runtime. After removing 1.8, it all works as expected.


text:
Q: changing route variable for a resource I just decided that the 'show' action of my 'users' controller should no longer render a page, but rather some json to be used by an ajax call.  Edit: I've already implemented this part.  My controller just has
def show
    render :json => myobject
end

My javascript in the views generate the url to do the AJAX, and all that works fine.  As for my question: I'm just looking to take a little shortcut; instead of going through all the places that I link to this action in a view, with something like
<%= link_to "Foobar" user_path(@user) %>

and replacing it with
Foobar

I'd like it if user_path instead just spit out my javascript URI.  Admittedly, this sounds like a terrible hack, but can it be done?

A: you can specify the format :
user_path( user, format: :json )

if you want your helper to throw an error, just override it in application_helper.rb :
def user_path( *args, options = {} )
  raise MyException
end

... or just use your favorite IDE / shell to find all occurences of the helper.

A: As a hack, you can go to helpers/application_helper.rb and insert there
def user_path(*args)
  "javascript:..."
end

This will do the trick. But I don't recommend it as a long-term solution, only as a quick workaround to check how your new code works, probably.
Besides, if you want to build the link for the right user you'll need to parse all possible combinations of user_path parameters. If you only call it in the user_path(@user) format then it's relatively easy.

A: You can specify a default format for a route in config/routes.rb:
resources :user, defaults: { format: 'json' }

If you only want to do this for show:
resources :user, only: [:show], defaults: { format: 'json' }


text:
Q: TSQL - Window function / Ranking I am trying to find all people that missed 3 or more consecutive appointments. I believe I can use a windowing function to accomplish this, but I am stuck and looking for some help.
Here is a sample of what I am looking for:
For the following PATID = x001 meets the criteria for missing 1/12,1/14,1/15
And PATID = x002 Will not meet the criteria.
PATID  DEPT   DATE       STATUS
x001   A002   1/1/2016   Missed
x001   A002   1/5/2016   Complete
x001   A002   1/8/2016   Missed
x001   A002   1/10/2016   Complete
x001   A002   1/12/2016   Missed
x001   A002   1/14/2016   Missed
x001   A002   1/15/2016   Missed
x001   A002   1/19/2016   Complete

x002   A003   1/1/2016   Missed
x002   A003   1/5/2016   Complete
x002   A003   1/8/2016   Missed
x002   A003   1/10/2016   Complete
x002   A003   1/12/2016   Missed
x002   A003   1/14/2016   Complete
x002   A003   1/15/2016   Missed
x002   A003   1/19/2016   Complete

This is what I have so far.
SELECT
PR.PATID
, PR.DEPT
, PR.DATE
, CASE WHEN PR.STATUS IN (3,4) THEN 'Cancel' WHEN PR.STATUS = 2 THEN 'COMPLETED' ELSE 'ERROR' END AS STATUS, ROW_NUMBER () OVER (PARTITION BY PR.PAT_ID,PR.DEPARTMENT_ID ORDER BY R.PAT_ID,PR.DEPARTMENT_ID,PR.CONTACT_DATE) AS RN  -- Just numbers the rows
, COUNT(*) OVER (PARTITION BY PR.PAT_ID,PR.DEPARTMENT_ID, CASE WHEN PR.APPT_STATUS_C IN (3,4) AND PR.CANCEL_REASON_C <> 4 THEN 'Cancel'                  WHEN PR.APPT_STATUS_C = 2 THEN 'COMPLETED' ELSE 'ERROR' END) AS RNC  -- Should have break at new statuses
FROM #PatsReturn AS PR

Once I figure out how to assign the correct breaks at the new status changes by dates, then I need to figure out a way to identify (possibly a new flag field??) the PATIDs that have missed 3+ consecutive....
Any help is greatly appreciated.
Thanks,

A: One method is just to use lag()/lead():
select distinct patid
from (select pr.*,
             lead(status) over (partition by patid order by date) as status_1,
             lead(status, 2) over (partition by patid order by date) as status_2
      from #PatsReturn pr
     ) pr
where status = 'Missed' and status_1 = 'Missed' and status_2 = 'Missed';

If you want information about each sequence, you can identify groups of similar appointments.  One method is a difference of row numbers:
select patid, count(*) as numMissed, min(date), max(date)
from (select pr.*,
             row_number() over (partition by patid order by date) as seqnum_p,
             row_number() over (partition by patid, status order by date) as seqnum_ps
      from #PatsReturn pr
     ) pr
where status = 'Missed'
group by patid, (seqnum_p - seqnum_ps)
having count(*) >= 3;

To understand how this works, run the subquery and you can see the pattern where the difference in the two "seqnum" values is constant for sequences of the same status.

A: If you go with Gordon's first solution you will want a POC index. Say this is your table:
CREATE TABLE #PatsReturn (PATID char(4), DEPT char(4), [date] date, [status] varchar(10));

You would want this index:
CREATE UNIQUE INDEX nc_PatsReturn  ON #PatsReturn(PATID, [date]) INCLUDE ([status]);

This will ensure a nice, linear sort-free query execution plan. The second solution would be a little trickier to index for.


text:
Q: Is Gandalf really to blame for Sauron's return? In The Hobbit, Gandalf assembles the party of 13 to retake the Misty Mountain and give Erebor back to Thorin.  However, along the way, Bilbo and company are captured by goblins and Bilbo meets Golum.  There's no indication that anyone or anything actually knew of Golum's existence or location until Bilbo met him.
Yes, Sauron was already beginning his return, even without the one ring, but had Bilbo never found the ring and stolen it from Golum, it never would have returned to the surface.  So, by that logic, since Gandalf was so adamant about Bilbo being the dwarves' burglar and basically guilted him into joining them he is responsible for the ring being found. Had Bilbo stayed home, the ring would have stayed hidden with Golum.
So, is Gandalf the person responsible for the events of the third age and Sauron's return to power?

A: No. In fact, it was Sauron's rising that prompted Gandalf to find a way to re-take Erebor and remove Smaug from the possible use by Sauron.
LOTR, Appendix A Annals of the Kings and Rulers:

    But at last there came about by chance a meeting between Gandalf and
  Thorin that changed all the fortunes of the House of Durin, and led to
  other and greater ends beside. On a time Thorin, returning west from a
  journey, stayed at Bree for the night. There Gandalf was also. He was
  on his way to the Shire, which he had not visited for some twenty
  years. He was weary, and thought to rest there for a while.    Among
  many cares he was troubled in mind by the perilous state of the North;
  because he knew then already that Sauron was plotting war, and
  intended, as soon as he felt strong enough, to attack Rivendell. But
  to resist any attempt from the East to regain the lands of Angmar and
  the northern passes in the mountains there were now only the Dwarves
  of the Iron Hills. And beyond them lay the desolation of the Dragon.
  The Dragon Sauron might use with terrible effect. How then could the
  end of Smaug be achieved?

If Bilbo had stayed home it's likely that the Ring would have been found by some Orc:
LOTR, Book I, Ch. 2 The Shadow of the Past:

   The Ring was trying to get back to its master. It
  had slipped from Isildur's hand and betrayed him; then when a chance
  came it caught poor Déagol, and he was murdered; and after that
  Gollum, and it had devoured him. It could make no further use of him:
  he was too small andmean; and as long as it stayed with him he would
  never leave his deep pool again. So now, when its master was awake
  once more and sending out his dark thought from Mirkwood, it abandoned
  Gollum. Only to be picked up by the most unlikely person imaginable:
  Bilbo from the Shire!

Sauron was already rising well before Gandalf joined up with Thorin. And the Ring had abandoned Gollum some time before Bilbo found it.


text:
Q: Traefik V2 & Cloudflare : SSL error subdomain ERR_SSL_VERSION_OR_CIPHER_MISMATCH I want to deploy a Traefik with SSL using a wildcard certificate.
My domain is: sub.domain.com
My applications are :
traefik.sub.domain.com
portainer.sub.domain.com

I want to create for each application an entry in the cloudflare dns.
For that I made :
A -> sub- > 177.171.8.109
CNAME -> portainer.sub -> sub.domain.com
CNAME -> traefik.sub -> sub.domain.com
Traefik starts normally without errors.
The nslookup command also returns a correct answer.
The problem is that when I access my portainer.sub.domain.com applications, I get an error like: ERR_SSL_VERSION_OR_CIPHER_MISMATCH
No certificate visible in the "Connection not secure" lock location
FYI: If I delete my two entries and do a CNAME:
CNAME -> *.sub -> sub.domain.com

then I have access to my applications, but I lose all the advantage of the cloudflare proxy which does not support proxification via *....
Thanks for your help!
Traefik logs :
time="2021-03-12T21:33:33Z" level=debug msg="legolog: [INFO] [sub.domain.com, *.sub.domain.com] acme: Validations succeeded; requesting certificates"
time="2021-03-12T21:33:38Z" level=debug msg="legolog: [INFO] [sub.domain.com] Server responded with a certificate."
time="2021-03-12T21:33:38Z" level=debug msg="Certificates obtained for domains [sub.domain.com *.sub.domain.com]" providerName=mydnschallenge.acme

Traefik configuration :
https://pastebin.com/4uGftcys

A: Due to cloudflare policy(free subscription), it is not possible to do sub.sub-domain.domain.fr
You can only do sub.domain.fr


text:
Q: Contained records only 1 level deep for afterFind? I have a Schedule which hasMany Events.  Each Event belongsTo a Room.
I set up my options for a Contain'd find::
    $options = array(
            'conditions' => array('Schedule.' . $this->Schedule->primaryKey => $id),
            'contain' => array(
                'Event' => array(
                    'Room'
            // Etc.

I find everything using:
$sched = $this->Schedule->find('first', $options);

I have an afterFind method defined on the Event's model;  In that I copy the Room's name into the event's displayname so that the event can clearly identify which room it's in.
The Problem: In the afterFind method Event has no subsidiary records.  Specifically, it has no Room record.  If I do a normal/non-Contain'd find (with the $this->Schedule->recursive field set to 3) then I DO see the Room's data.
Is there a way for Contain to fetch data of a related record before the afterFind method is called?

A: IMHO, I'm guessing the reason you want to copy the room name into the event's display name is for a view?
May I suggest an alternative approach to this problem?
I think it would be far simpler to create a view helper to assist on rendering the event with its associated room information. It doesn't have to be too complex, for example:
In your view:
echo $this->Event->displayName($eventRecord)

Given the depth of documentation relating to the containable behavior, it is pure black-magic how it works and I personally wouldn't want to modify any of its code to do what you propose. I totally appreciate what you're trying to achieve but sticking to the principles of KISS, this seems like the right advice to give.

A: In many situations, the Containable behavior will 'split' the find() query into separate queries and merge the results later on using PHP.
To force performing a single query, you may try to use joins in stead. However, because of the hasMany, using only joins will probably not be the most efficient query.
Joins-example;
$options = array(
        'conditions' => array('Schedule.' . $this->Schedule->primaryKey => $id),
        'contain' => array(
            'Event' => array(
                'joins' =>  array(
                    array(
                        'table' => 'rooms',
                        'alias' => 'Room',
                        'type' => 'INNER',
                        'conditions' => array(
                            'Room.id = Event.room_id',
                        )
                    )
                )
            )
        );

note
I am not sure if CakePHP accepts joins to be defined inside a Contain. More information on manually specifying joins can be found here: Joining Tables


text:
Q: How to set the revision Number to a file I am using the file upload in my project. I like to set the revision number for the file which I am uploading in the database. i.e. I will upload a sd.doc file for first time it will be saved as version 1. After I am downloading that file I will make some changes and I will save that it should be saved as version 2. While viewing it should show both the version and I should choose the file based on the version. Can any one help me to solve this issue.
Thanks in Advance.

A: If I right understand your problem, you need versioning system for docs.
One of the solutions that I can think off, is using of Mercurial DVS. You can create simple UI interafce to interact with it's command line "hg". It provides to you a huge potential, that most probabbly you will no need in your app, but saving "revision" number, enable others to query it, all this is already done +  you will given huge amount of options for future development.
But all depends on your project requirements. Keep an eye on that and make a choice.
Hope this helps.
Regards.


text:
Q: Is an article determained by the possessive 's? Today I came across the following sentence:

AI's decision-making process is usually too difficult for most people to comprehend.

It seemed weird to me because I thought that the word process required an article, since it is singular and countable. Then I noticed this 's with AI and assumed that there is no article because this AI's serves as a modifier that somehow takes the role of a determiner (and the word AI as such does not have to had an article).
So then, it should be AI's process, but the AI process, for instance in a sentence like The AI process is now optimised.
If I am correct, then it should work the other way round, too, for instance with proper nouns that aren't used with articles, so the sentences The London programme is now over and London's programme is now over should both be correct.
Am I right or I miss some point?

A: In English, it's not possible to have both a possessive "'s" and an article, so the "'s" takes the place of the article.
More info:
Articles are in a syntactic category called determiners. Beyond articles, this group includes "some", "no", "this", "that", and the possessive "'s", among others. For the most part, a noun can only have one determiner. In the case of your example, the determiner of "process" is "'s".

A: It is often useful to write out a "long form":
The process of decision making of artificial intelligence
BECOMES
AI's decision-making process
The purpose of game playing of children
Children's game-playing purpose
As for proper nouns:
The London program and London's program are both correct but the long form is not:
the program of London. And that's the difference between the phrases above and this phrase.


text:
Q: In mysql, why varchar require size and text does not? Why does varchar require a specific size but text does not?

A: Obviously columns of type text also require storage space, but there is one fundamental difference to columns of type char or varchar:
The content of columns of type text is not stored inside the table itself, but at a separate location. That way the table itself does not get bloated by the huge space text cells actually require.
In contrary to that the cells of column types char or varchar are store right inside the table. Thus their size is considered in things like maximum index length and the like.


text:
Q: PuTTY terminal behaviour differs between two accounts on same server I'm using PuTTY to connect to my server where I have two accounts.  One account gives me a colour terminal and responds correctly to the home/end keys, while the other account gives me a black-n-white prompt and the home/end keys produce ~s.
Both accounts have the same .bashrc file, and the PuTTY settings are identical except for the username specified.
Can someome please help me understand what is causing this?
Edit
To fix the Home/End keys, I needed to add /etc/inputrc and /lib/x86_64-linux-gnu/libreadline.so.* to the available files in the jail, thnx to grawity's pointers.
To fix the colour prompt problem, using the standard .bashrc, I needed to add /usr/bin/tput to the jail as well.

A: The terminal behaves the same way. But the keypresses are interpreted and prompts printed not by the terminal itself, but by programs running in it – primarily the shell.
Your two accounts might be set up to use different login shells – one uses bash (or maybe zsh), the other is likely set to plain /bin/sh.
Use getent passwd USERNAME to check the configured shell for that account, and chsh to set it.

Additionally, even in bash/zsh, the prompt format and key information are read from outside files.

*

*The prompt, as well as aliases which enable colors for 'ls', are configured in "profile" and "bashc" files. Namely /etc/bashrc (or similar) and ~/.bashrc.

*The keys are recognized by readline, which mainly uses the ncurses "terminfo" database /usr/share/terminfo but also has various custom settings in /etc/inputrc.
(Zsh uses its own zshzle, I don't know what all files it needs, but I'm sure it requires the terminfo DB anyway.)
For jailed accounts, make sure all these files are available. If necessary, use strace or similar tools (truss, etc.) to see what files are loaded by the shell.


text:
Q: CSS Mega Menus: How to target ul's except those in divs With CSS Mega Menus, there are many possibilities. But it also mean that I need to handle things like I want to style children
 as nav only if they are not in a div.
I created a jsFiddle http://jsfiddle.net/av5zr/ demonstrating the problem
The list in the 2nd menu should be a normal list. How can I style children ul's as lists only if they are not part of a div? 1 way might be to reset list styles with .megaMenu-hor div ul but I will need to duplicate "normal" list styles in 2 places, in the menu style and in the site's main style, which I prefer to keep separate

A: I think you can use it like this:
...

        Link 1

This is a div

...

Then all you need to select it in CSS is this:
.megaMenu-hor div.normal-list ul{
    display: none;
}

Hope it works..

A: As far as I know you can't.
Either you need to duplicate your styles to undo the menu
 style for normal
s within a menu OR  you need to add a class to the menu
s and target them specifically
EDIT
Just read other answerer's comment. My understanding is that you want to keep the main
 styles and menu
 styles separate. Otherwise an easier suggestion might be to write out your default
 styles like this:
ul,
.megaMenu-hor div ul {
/* whatever */
}