text:
Q: How do I restore windows back to their original screen when re-connecting external monitor? Imagine you do this...

*

*Connect your external monitor.

*Start some apps, some on each monitor.

*Disconnect the external monitor.

*

*All good because all the apps move the primary monitor.

*Re-connect the external monitor.

*

*The apps stay on the primary monitor, but it'd be very nice if they moved back to the external monitor they were on before.

Using Windows 10.  Are there any solutions or workarounds to this to moving the apps back to the external monitor automatically?

A: Win Redock has worked best for me. Redock is automatic - saves and restores windows without any intervention. Magic! Its open source too!

A: I have, in the past, used an Autohotkey tool called Windowpad for this. Apparently this has now been replaced with a new, enhanced version called WindowPadX. Scroll down to see the readme. Full documentation is here.
This was crucial to me on multiple monitors. I loved to be able to easily switch a window between the two.
You can set hotkeys for the following (from the readme):

Possible actions to be configured on hotkeys
Window actions
Multi-Monitor
WPXA_MoveWindowToMonitor: Move window between screens, preserving
  relative position and size.
WPXA_MinimizeWindowsOnMonitor: Minimize
  all windows on the given Screen
WPXA_GatherWindowsOnMonitor: "Gather"
  windows on a specific screen.
WPXA_FillVirtualScreen: Expand the
  window to fill the virtual screen (all monitors).
General
WPXA_MaximizeToggle:
  Maximize or restore the window.
WPXA_TopToggle:
  Toogles "AlwaysOnTop" for given window
WPXA_RollToggle: Toggles
  "Roll/Unroll" for given window WPXA_Move: move and resize window based
  on a "pad" concept.
WPXA_TileLast2Windows: Tile active and last window
Multi-Monitor Mouse actions
WPXA_MoveMouseToMonitor: Moves mouse to center of given monitor
WPXA_ClipCursorToCurrentMonitorToggle: Toogles clipping mouse to
  current monitor
WPXA_ClipCursorToMonitor: Clips (Restricts) mouse to given monitor
General Mouse actions
WPXA_MouseLocator: Easy find the mouse

You can find it and other tools among a "A curated list of awesome AutoHotkey libraries, library distributions, scripts, tools and resources" here

A: Some gpu's have support for this such as Nvidia control panel which allows you to apply settings for this and a lot of other features.
Or you could just set the multiple display settings to mirror the desktop (instead of extend) on all monitors if that works for you.

A: I use UltraMon (I believe it is Open Source) and in certain circumstances, it can do this, if configured correctly.
First get the program UltraMon installed.  Then, when it is running, lets say right now you only have one monitor plugged in (doesn't matter the number), create a profile:

*

*Right Click the icon in the systray

*Left Click Display profiles

*Left Click new Display Profile, Name it (for example, what I do is give it a number reflecting how many monitors you are using, like Profile 1).

*Now you have one. Cool, you can create wallpaper for each monitor, screensavers, etc. Get all of your icons just the way you want.

*Right Click the systray Icon.

*Left Click Desktop Icons Left Save Positions

Now connect/disconnect other displays. Create a profile for this new setup. Maybe call it "Profile 7" for having 7 monitors plugged in. Now save the icon positions when they are the way you want them.
You can easily use this tool to switch back and forth between profiles. You can easily place desktop shortcuts to quick-switch between profiles.
Lastly, in the advanced options, you can tell UltraMon to do this all the time, automatically for you, but that may require a paid version (one time lifetime fee).
I bought UltraMon back in 2009 for $19.99 and it was totally worth it.

A: Windows programs - called app(lication) nowadays - can save the position of their window in a file or the registry.
If one knows where this data is, it can be edited manually in the notepad or registry editor.
(incorrect registry entries may cause Windows instability or errors)
The creation of an automated way should be easy for someone with a bit of coding skills and it can be started as needed (i.e. after the monitor is re-attached).
This could be done by an action script, .bat file or a native app.
The applications in question will need to be closed previous to this though in order for the desired positions to become implemented.
Another possibility with "online" capability (no app restart needed) would be if Windows allows accessing a window of one process by another.
An approach could be the SendMessage and WindowProc functions.
(I'm unsure at this point if this only applies to threads of the parent application or can be done by threads of other applications as well...and of course requires good knowledge in programming for Windows)
https://msdn.microsoft.com/en-us/library/windows/desktop/ms644950%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396

Sends the specified message to a window or windows.
  [...]
  If the specified window was created by the calling thread, the window procedure is called immediately as a subroutine. If the specified window was created by a different thread, the system switches to that thread and calls the appropriate window procedure.

WM_Move message
https://docs.microsoft.com/en-us/windows/desktop/winmsg/wm-move

Sent after a window has been moved.

A window receives this message through its WindowProc function.
https://msdn.microsoft.com/en-us/library/ms633573%28v=VS.85%29.aspx?f=255&MSPPError=-2147217396

An application-defined function that processes messages sent to a window.
  [...]

A: You can do this, if you're an old "keyboard guy" like me ;-]
I figured this out ages ago, being that I've been multi-mon since the early 90's, it's been a very longtime issue, amongst slightly differing UIs.
The easiest way I've found for offscreen/border apps, is:

*

*Simply select the app, via the taskbar or Alt-Tab

*Hold the Alt key down, and press the spacebar (Alt-Spacebar)

*You'll see a menu, on your main screen(s), one option of which will be "Move", with the M underlined.

*As such, press the "M" key, while the menu is still on-sceen

*At this point, don't point/click/etc, as you're now "re-positioning" the active window (the offscreen one).

*You can drag the mouse around (NO BUTTON PUSHES FOR NOW), and you should see the app sort of come in/out of the main screens, enough for you to place it somewhere more convenient for use.

*Alternatively, you can use the arrow-keys to move the app around, works just as well, but a bit slower, to figure out where the windows is and which way it's heading.

*Once you have the Window in a "good place", where can actively size/move it, either click the main-mouse-button, or if using the keyboard method, hit the "enter" key.

*The window/app should now be easy to move/adjust.

*Repeat for all windows/apps that are off-screen.

A: If you shift+right click the icon on the taskbar, then press move, you can use the arrow keys to move the window and the enter key to set the position. I had the same issue a few years ago.
Another solution is to use DisplayFusion to snap the window to the closest monitor (the only one connected) with the "Move all windows to current monitor" hotkey.

A: There aren't any solutions to do this, you must use the windows key on the keyboard with the left right arrows, to move in between screens, or windows key+shift+left/right in order to move to portions of the screen.
Windows key + P also helps in multi monitor situations to aid with mirroring/extending etc.
But again, once you disconnect your screen, if those windows had any metadata on them, they are gone afterwards


text:
Q: Как отрефакторить данный код, чтобы не было повторений и много строк? this.a = obj.a;
this.b = obj.b;
this.c = obj.c;
this.d = obj.d;
this.e = obj.e;

A: Вы можете использовать деструктуризацию для присвоения множественных значений за один раз:

obj = {
  a: 'a',
  b: 'b',
  c: 'c',
  d: 'd',
  e: 'e'
}

let { a, b, c, d, e } = obj

console.log(a, b, c, d, e)

A:

const obj = {
  a: 1,
  b: 2,
  c: 3,
  d: 4,
  e: 5
};

function create(source) {
  Object.assign(this, source);
}

const d = new create(obj);
console.log(d);

const obj = {
  a: 1,
  b: 2,
  c: 3,
  d: 4,
  e: 5
};

function create(source) {
  ['a', 'b', 'c', 'd', 'e'].forEach(i => this[i] = source[i]);
}

const d = new create(obj);
console.log(d);

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to specify useFetch data return type in Nuxt I am fetching data from an API in Nuxt3. I am using typescript and I wish to define the type of data that I will get. How do I specify this?
<script lang="ts" setup>
  interface APIBody {
    /* properties defined here */
  }

  const {data} = await useFetch("api_url here")
</script>

<template>
 {{ data.name.officialName }}
<template>

I get an error in the template where I am displaying data.name.officialName

Property 'name' does not exist on type 'never'

However, while running the code in the browser, the website works fine.
Edit
I tried the following code but I am receiving a different error now.
<script lang="ts" setup>
  interface APIBody {
    /* properties defined here */
  }

  const typedData = ref<APIBody[]>()
  const {data} = await useFetch("api_url here")
  typedData.value = data as APIBody[] // -> error here
</script>

<template>
 {{ data.name.officialName }}
<template>

The error in this case is:

Conversion of type 'Ref<Pick<unknown, never>>' to type 'APIBody[]' may be a mistake because neither type sufficiently overlaps with the other.

A: You can give a type to useFetch to define the return type
Like:
  interface APIBody {
    /* properties defined here */
  }

  const {data} = await useFetch<APIBody>("api_url here")


text:
Q: Tensorflow back_prop ValueError: setting an array element with a sequence I'm getting this value error:ValueError: setting an array element with a sequence, when doing back_prop in tensorflow. I'm using large IMDB dataset and glove 50d pre-trained vectors. I have tried everything converting multi-dimensional list into np.array, converting individual lists into np.array and also did reshape operation x = x.reshape((batch,time_steps,embedding))
on x but it gave me value error ValueError: total size of new array must be unchanged. I think something is wrong with my input but don't know what? You could run this code on your pc by downloading IMDB dataset and 50d glove vectors. Please Help!
Traceback (most recent call last):
  File "nlp.py", line 109, in <module>
    sess.run(minimize_loss,feed_dict={X : x, Y : y})
  File "/home/indy/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 372, in run
    run_metadata_ptr)
  File "/home/indy/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 619, in _run
    np_val = np.array(subfeed_val, dtype=subfeed_dtype)
ValueError: setting an array element with a sequence.

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import tensorflow as tf
import numpy as np
import math
import os
from nltk.tokenize import TweetTokenizer
batch = 500
start = 0
end = batch - 1
learning_rate = 0.2
num_classes = 8
path = "/home/indy/Downloads/aclImdb/train/pos"
time_steps = 250
embedding = 50

def get_embedding():
    gfile_path = os.path.join("/home/indy/Downloads/glove.6B", "glove.6B.50d.txt")
    f = open(gfile_path,'r')
    embeddings = {}
    for line in f:
        sp_value = line.split()
        word = sp_value[0]
        embedding = [float(value) for value in sp_value[1:]]
        embeddings[word] = embedding
    return embeddings

ebd = get_embedding()

def get_y(file_name):
    y_value = file_name.split('_')
    y_value = y_value[1].split('.')
    return y_value[0]

def get_x(path,file_name):
    file_path = os.path.join(path,file_name)
    x_value = open(file_path,'r')
    for line in x_value:
        x_value = line.replace("

","")
        x_value = x_value.lower()
    tokeniz = TweetTokenizer()
    x_value = tokeniz.tokenize(x_value)
    padding = 250 - len(x_value)
    if padding > 0:
       p_value = ['pad' for i in range(padding)]
       x_value = np.concatenate((x_value,p_value))
    x_value = [ebd['value'] for value in x_value]

    return x_value

def  batch_f(path):
     directory = os.listdir(path)
     y = [get_y(directory[i]) for i in range(len(directory))]
     x = [get_x(path,directory[i]) for i in range(len(directory))]
     return x,y

X = tf.placeholder(tf.float32, [batch,time_steps,embedding])
Y = tf.placeholder(tf.int32, [batch])

def build_nlp_model(x, _units, lstm_layers,num_classes):

     x = tf.transpose(x, [1, 0, 2])
     x = tf.reshape(x, [-1, embedding])
     x = tf.split(0, time_steps, x)

     lstm = tf.nn.rnn_cell.LSTMCell(num_units = _units, state_is_tuple = True)

     multi_lstm = tf.nn.rnn_cell.MultiRNNCell([lstm] * lstm_layers, state_is_tuple = True)

     outputs , state = tf.nn.rnn(multi_lstm,x, dtype = tf.float32)

     weights = tf.Variable(tf.random_normal([_units,num_classes]))
     biases  = tf.Variable(tf.random_normal([num_classes]))

     logits = tf.matmul(outputs[-1], weights) + biases
     return logits

logits = build_nlp_model(X,400,4,num_classes)
c_loss = tf.nn.sparse_softmax_cross_entropy_with_logits(logits,Y)
loss = tf.reduce_mean(c_loss)

decayed_learning_rate = tf.train.exponential_decay(learning_rate,0,10000,0.9)
optimizer= tf.train.AdamOptimizer(decayed_learning_rate)
minimize_loss = optimizer.minimize(loss)

correct_predict = tf.nn.in_top_k(logits, Y, 1)
accuracy = tf.reduce_mean(tf.cast(correct_predict, tf.float32))

init = tf.initialize_all_variables()

with tf.Session() as sess:
     sess.run(init)
     for i in range(25):
         x, y = batch_f(path)
         sess.run(minimize_loss,feed_dict={X : x, Y : y})
         accu = sess.run(accuracy,feed_dict = {X: x, Y: y})
         cost = sess.run(loss,feed_dict = {X: x,Y: y})
         start = end
         end = (start + batch)
         print ("Minibatch Loss = " + "{:.6f}".format(cost) + ", Training Accuracy= " + "{:.5f}".format(accu))

EDIT: The other error that I'm getting, when I run the code.
(500, 250, 50)
(500,)
Traceback (most recent call last):
  File "nlp.py", line 115, in <module>
    accu = sess.run(accuracy,feed_dict = {X: x, Y: y})
  File "/home/indy/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 372, in run
    run_metadata_ptr)
  File "/home/indy/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 636, in _run
    feed_dict_string, options, run_metadata)
  File "/home/indy/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 708, in _do_run
    target_list, options, run_metadata)
  File "/home/indy/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 728, in _do_call
    raise type(e)(node_def, op, message)
tensorflow.python.framework.errors.InvalidArgumentError: targets[0] is out of range
     [[Node: InTopK = InTopK[T=DT_INT32, k=1, _device="/job:localhost/replica:0/task:0/cpu:0"](add, _recv_Placeholder_1_0)]]
Caused by op u'InTopK', defined at:
  File "nlp.py", line 102, in <module>
    correct_predict = tf.nn.in_top_k(logits, Y, 1)
  File "/home/indy/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/ops/gen_nn_ops.py", line 890, in in_top_k
    targets=targets, k=k, name=name)
  File "/home/indy/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/ops/op_def_library.py", line 704, in apply_op
    op_def=op_def)
  File "/home/indy/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 2260, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "/home/indy/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 1230, in __init__
    self._traceback = _extract_stack()


text:
Q: If Page is idle for sometime any postback leads to whole page refresh in UpdatePanel Within the solution there are two webparts, second is being shown within a modal dialog in first webpart.
In second webpart everything is inside update panel(bad practice).
When I open the second webpart first time and perform any postback(either by button click or dropdown index change)
Page.IsPostBack is true and ScriptManager.GetCurrent(Page).IsInAsyncPostBack is also true (Which is good because within page load I have added check for these two condition)
but when I keep the modal popup static for lets say 3 minutes and then perform any postback operation both the Page.IsPostBack and ScriptManager.GetCurrent(Page).IsInAsyncPostBack are false hence instead of firing the event handler for the control causing the postback the whole page within the modal refreshes.
Update panel is used like this
<asp:UpdatePanel ID="up1" runat="server">
<ContentTemplate>
....contents
</ContentTemplate>
</asp:UpdatePanel

Triggers are not used.
tried these attribute as well
ChildrenAsTriggers="true" UpdateMode="Conditional"

still the same behavior

A: As it turns out this was the problem with SharePoint 2013 and update panel
You can read about the exact problem and available workarounds in the following technet forum:
https://social.technet.microsoft.com/Forums/systemcenter/en-US/c33d4a46-87d6-4dbc-a24c-cb8e5f9eb1ea/page-refresh-after-postback-from-updatepanel-in-sharepoint-2013?forum=sharepointdevelopment
among the multiple workaround suggested the one works for me is the following script:
ExecuteOrDelayUntilBodyLoaded(function () {
    try {
        if (Sys.WebForms.PageRequestManager.getInstance().digestFixed !== true) {
            Sys.WebForms.PageRequestManager.getInstance().digestFixed = true;
            Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(function () {
                if (typeof (UpdateFormDigest) === "function" && typeof (_spPageContextInfo) === "object")
                    UpdateFormDigest(_spPageContextInfo.webServerRelativeUrl, 3 * 60 * 1000);
            });
        }
    }
    catch (e) { }
});

Thanks @Shai Petel (From the forum)


text:
Q: Что не так с этим кодом Решил сделать программу которая ищет TODO: в файлах
Вот код:
#include <iostream>
#include <fstream>
#include <cstdlib>

using namespace std;

ifstream inFile;

const int SIZE = 60;
int  i,d;

string todo[200];

int main()
{
    char filename[SIZE];
    string filecontents;
    cout <<"Place this executable to source folder" << endl
         <<"and enter filename to start search" << endl
         <<"filename can't start from space" << endl
         <<"Maximum count of TODOs is 200."<< endl
         <<"Maximum size is 60 symbols. Enter q to quit." << endl;
    while (cin.getline(filename, SIZE))
    {
        if (filename[0] == 'q')
        {
            cout << "Terminating...\n";
            exit(EXIT_SUCCESS);
        }
        else if (filename[0] != ' ')
        {
            if (filename[0] != '\n')
            {
                inFile.open(filename);
                if (!inFile.is_open())
                {
                    cout << "Can't open file called " << filename << endl;
                }
                else
                {
                    int count = 1;
                    string temp;
                    cout << "Opened file called " << filename << endl <<
                         "Searching for todos..." << endl;
                    while (getline(inFile, temp))
                    {
                        filecontents += temp + '\n';
                    }
                    while (i < filecontents.size())
                    {
                        if (filecontents[i] == 'T')
                        {
                            if (filecontents[i+1] == 'O')
                            {
                                if (filecontents[i+2] == 'D')
                                {
                                    if (filecontents[i+3] == 'O')
                                    {
                                        if (filecontents[i+4] == ':')
                                        {
                                            string temp = "";
                                            char temp2;
                                            int temp3 = i + 5;
                                            while (temp2 != '\n')
                                            {
                                                temp += filecontents[temp3]; //TODO: test todo m8
                                                temp2 = filecontents[temp3+1];
                                                ++temp3;
                                            }
                                            ++d;
                                            todo[d] = temp;
                                            temp = "";
                                            cout << "Found todo: " << todo[d] << endl;
                                        }
                                    }
                                }
                            }
                        }
                        i++;
                    }
                }

            }
            else
                cout << "Please enter correct filename according to rules:\n"; // TODO: another todo as always
        }
        else
            cout << "Please enter correct filename according to rules:\n";
        inFile.close();
        d = 0;

        cout<< "Please enter filename: ";
    }
    return 0;
}

Когда запускаю эту скомпилированную программу на собственном исходном коде, он читает только первый TODO и только один раз. Как это можно исправить? Или я просто слепой и не вижу очевидного?
Компилятор: Clang++ LLVM Compiler
Система: Fedora 23

A: С этим кодом всё не так. Начиная с глобальных переменных. С того, что он ищет неправильные TODO (во-первых, двоеточие не нужно, во-вторых, найдёт и SOMETODO: в комментариях, и TODO: как метку, и переменную, заканчивающуюся на TODO в тернарном операторе, и т.д.) С непонятного ограничения на количество найденых строк. И заканчивая лапшой.
Но даже с учётом поиска только подстрок без учёта контекста всё это можно написать покрасивше, попонятней и попригодней для отладки:
const char TODO[] = "TODO:";

static size_t substring_count(const char * where, const char * what,
        size_t what_length) {
    size_t count = 0;
    const char * ptr = strstr(where, what);
    while (ptr) {
        count++;
        ptr = strstr(ptr + what_length, what);
    }
    return count;
}

int main() {
    size_t todos = 0;
    std::vector<std::string> lines;
    std::ifstream inFile;
    std::string temp;

    inFile.open("123.txt");
    while (std::getline(inFile, temp)) {
        size_t todo_count = substring_count(temp.c_str(), TODO,
                sizeof(TODO) - 1);
        if (todo_count) {
            todos += todo_count;
            lines.push_back(temp);
        }
    }
    inFile.close();
    std::cout << "Found " << todos << " TODO in " << lines.size() << " lines."
            << std::endl;
}


text:
Q: How can I fit this table in landscape orientation? \begin{landscape}
\begin{table}[htbp]
  \centering
  \caption{Add caption}
    \begin{tabular}{ccllcc}
    \hline
    \multicolumn{1}{l}{\textbf{Amount(INR Cr)}} & \multicolumn{1}{l}{\textbf{Round}} & \textbf{Stage} & \textbf{Investors} & \multicolumn{1}{l}{\textbf{Pre Money Valuation (INR Cr)}} & \multicolumn{1}{l}{\textbf{Post Money Valuation (INR Cr)}} \\
    \hline
    417   & 8     & Growth-PE & IIFL VC, Sequoia Capital India &       & 30496 \\
    1001.82 & 7     & Late  & Wellington Management, Faering Capital, TVS Capital, Others & 25971.15 & 26972.97 \\
    1492.2 & 6     & Growth-PE & IIFL VC, Faering Capital, TVS Capital, Sequoia Capital India, Others &       & 26078.5 \\
    135   & 5     & Growth-PE & A91 Partners, Faering Capital, TVS Capital & 14049.7 & 14184.7 \\
    654.58 & 4     & Growth-PE & A91 Partners, Faering Capital, TVS Capital, Others & 5471.74 & 6126.32 \\
    165   & 3     & Growth-PE & Fairfax Holdings &       &  \\
    315   & 2     & Growth-PE & Fairfax Holdings &       &  \\
    384.44 & 1     & Growth-PE & Fairfax Holdings &       &  \\
    \hline
    \end{tabular}%
  \label{tab:addlabel}%
\end{table}%
\end{landscape}

A: I would not try to typeset this table in landscape mode, since doing so would be treating the symptoms rather than the cause of the table's underlying problem. The problem is that you're not allowing line breaks in columns 4, 5, and 6.
To fix this problem, I suggest you switch from a tabular to a tabularx environment and allow line breaking in all cells of column 4 and in headers of columns 5 and 6. I would also (a) align the numbers in columns 1, 5, and 6 on their explicit or implicit decimal markers and (b) move the unit legend (INR Cr) to separate lines.

\documentclass{article}
\usepackage{tabularx,ragged2e,siunitx}
\newcolumntype{L}{>{\RaggedRight}X}  % flush-left, not justified
\newcommand\mC[1]{\multicolumn{1}{L}{#1}}
\sisetup{group-four-digits=true} % show thousands separator for 4-digits numbers

\begin{document}

\begin{table}
\setlength\tabcolsep{3.5pt}    % default: 6pt
\setlength\extrarowheight{2pt} % for a less-cramped look

\caption{Add caption}
\label{tab:addlabel}

\begin{tabularx}{\textwidth}{@{}
    S[table-format=4.2] c l L *{2}{S[table-format=5.2]} @{}}
    \hline
    {\bfseries Amount} &
    \bfseries Round &
    \bfseries Stage &
    \bfseries Investors &
    \mC{\bfseries Pre Money Valuation} &
    \mC{\bfseries Post Money Valuation} \\
    {(INR Cr)} & & & & {(INR Cr)} & {(INR Cr)} \\ % units on separate line
    \hline
    417     & 8 & Growth-PE & IIFL VC, Sequoia Capital India &       & 30496 \\
    1001.82 & 7 & Late      & Wellington Management, Faering Capital, TVS Capital, Others          & 25971.15 & 26972.97 \\
    1492.2  & 6 & Growth-PE & IIFL VC, Faering Capital, TVS Capital, Sequoia Capital India, Others &          & 26078.5  \\
    135     & 5 & Growth-PE & A91 Partners, Faering Capital, TVS Capital         & 14049.7 & 14184.7 \\
    654.58  & 4 & Growth-PE & A91 Partners, Faering Capital, TVS Capital, Others & 5471.74 & 6126.32 \\
    165     & 3 & Growth-PE & Fairfax Holdings &       &  \\
    315     & 2 & Growth-PE & Fairfax Holdings &       &  \\
    384.44  & 1 & Growth-PE & Fairfax Holdings &       &  \\
    \hline
    \end{tabularx}
\end{table}

\end{document}

A: Similar to @Mico answer (+1) but with tabularray package. For table rules is employed booktabs package and for page layout geometry package:
\documentclass{article}
\usepackage{geometry}
\usepackage{tabularray}
\UseTblrLibrary{booktabs, siunitx} % load corresponding packages

\begin{document}
    \begin{table}
\caption{Add caption}
\label{tab:addlabel}
\sisetup{group-four-digits=true,

\begin{tblr}{colsep=4pt,
             colspec={@{} S[table-format=4.2] c l
                          X[2.2, l]
                     *{2}{X[c, si={table-format=5.2}]} @{}},
            row{1} = {font=\small\bfseries},
            row{1,2} = {guard}
            }
    \toprule
Amount  & Round & Stage & Investors & Pre Money Valuation   & Post Money Valuation  \\
(INR Cr) &      &       &           & (INR Cr)              & (INR Cr)              \\
    \midrule
417     & 8     & Growth-PE & IIFL VC, Sequoia Capital India
                                    &                       & 30496                 \\
1001.82 & 7     & Late      & Wellington Management, Faering Capital, TVS Capital, Others
                                    & 25971.15              & 26972.97              \\
1492.2  & 6     & Growth-PE & IIFL VC, Faering Capital, TVS Capital, Sequoia Capital India, Others
                                    &                       & 26078.5               \\
135     & 5     & Growth-PE & A91 Partners, Faering Capital, TVS Capital
                                    & 14049.7               & 14184.7               \\
654.58  & 4     & Growth-PE & A91 Partners, Faering Capital, TVS Capital, Others
                                    & 5471.74               & 6126.32               \\
165     & 3     & Growth-PE & Fairfax Holdings
                                    &                       &                       \\
315     & 2     & Growth-PE & Fairfax Holdings
                                    &                       &                       \\
384.44  & 1     & Growth-PE & Fairfax Holdings
                                    &                       &                       \\
    \bottomrule
\end{tblr}
    \end{table}
\end{document}


text:
Q: jQuery how to select  node I have an XML document that looks someting like this:
<event>
    <foo.bar>content</foo.bar>
</event>

I use jQuery to read this xml document as follows:
var $xml = $( $.parseXML(xmlStr) );

When i try to select the foo.bar node, it will search for a node with the name foo and the class bar. How can i select this node by tagname?
$xml.find( "foo.bar" ) //returns nothing, searches for tag foo with class bar

A: You need to escape the . in the selector:
$xml.find("foo\\.bar")

A: You could try to use this:
$xml.find( "foo\\.bar" )

You need an escape character for the ..


text:
Q: Sunspot Rails - Can user change what fields to search? I started using Sunspot to perform searches in my Rails 3 app and I ran into a doubt. Is there a way that I can let the user choose in what fields he/she wants to search. For example, in my app we have:
class Project < ActiveRecord::Base
    searchable do
      text :name, :content, :keyword
    end
end

And in the View the default search bar:
<%= form_tag projects_path, :method => :get do %>
  <p>
    <%= text_field_tag :search, params[:search] %>
    <%= submit_tag "Search", :name => nil %>
  </p>
<% end %>

Can I add a radio button or something like that so the user can mark it in order just to search by name, or content or keyword? If yes, how can I make it?
Thanks a lot.

A: Watch the railscasts on the subject: http://railscasts.com/episodes/278-search-with-sunspot .. in it, Ryan lets user's query optionally by month.
So, if month was sent in:
def index
  @search = Article.search do
    fulltext params[:search]
    with(:publish_month, params[:month]) if params[:month].present?
  end
  @articles = @search.results
end


text:
Q: Run Time Error 13 - compare to true Have simply this line of code as shown below:
If Cells(L, i).Value = True

Then i receive following error message:
Run Time Error 13. Type mismatch.

Could someone tell me why i get this error message?
This column L has either empty cells or some formulas like:
=IF(OR($O11="";$CJ11=0;AH$6<$CJ11);"";IF($CJ11=AH$6;TRUE;IF($O11="S";TRUE;IF(OR(AND(RIGHT($O11;1)="M";$O11<>"M");RIGHT($O11;1)="S");IF(MOD(AH$6-$CJ11;LEFT($O11;LEN($O11)-1)*IF(RIGHT($O11;1)="M";4;1))=0;TRUE;FALSE);IF($O11="M";IF(MOD(AH$6-$CJ11;4)=0;TRUE;FALSE);IF(RIGHT($O11;1)<>"A";MOD(AH$6-$CJ11;$O11)=0;FALSE))))))

A: Two possible reasons (that I know of) why a Type mismatch error might occur here.

*

*L or i are not natural numbers. Fix: make sure the arguments are natural numbers. (for example if L is a range, use L.Row)

*The cell contains an error. Fix (if you can't remove the error):
If Not IsError(Cells(L, i).Value) Then
    If Cells(L, i).Value = True Then 'you could also omit the "= True"
        'do stuff
    End If
End If

Since VBA has no lazy evaluation, it is necessary to split the tests up.
The reason you can't find the error might be that you are looking at the wrong cell. In your question you wrote "column L" but the cell you reference is in row L and column i.


text:
Q: Get alias names form stored procedure in Oracle Is there any way to get only the alias name that is used in a select statement of an stored procedure? I want to create entities using that select statement.
Example:
procedure Getnames(namerecords out Sys_refcursors)
as
begin
open namerecords for
select
  N.First_name    FirstName,
  N.SecondName    Secondname
from  Names
End Getnames;

I want to get only the Firstname ,secondname as a result by passing only the stored procedure names.
Are there any system tables which store this information?

A: CREATE OR REPLACE PROCEDURE dummy_proc
AS
    CURSOR dummy_cur is
        SELECT  dummy AS dummy_alias1, dummy AS dummy_alias2,dummy dummy_alias3
        ,       dummy AS dummy_alias4
        ,   dummy  dummy_alias5
        ,dummy  dummy_alias6
        ,dummy  dummy_alias7
        FROM    DUAL;
BEGIN
    NULL;
END;
-- PROCEDURE DUMMY_PROC compiled

WITH all_src AS
(
        SELECT  owner, name, type, line, text
        FROM    all_source
        WHERE   owner = USER
        AND     type  = 'PROCEDURE'
        AND     name  = 'DUMMY_PROC'
)
, conditions AS
(
        SELECT  line AS con_start
        ,       LEAD(line) OVER (PARTITION BY name ORDER BY line) AS con_end
        FROM    all_src
        WHERE   (INSTR(UPPER(text), 'SELECT') > 0 OR INSTR(UPPER(text), 'FROM') > 0)
)
, one_line AS
(
        SELECT  LISTAGG(text, ' ') WITHIN GROUP (ORDER BY line) AS select_line
        FROM    all_src
        WHERE   EXISTS
                (
                    SELECT  1
                    FROM    conditions
                    WHERE   line >= con_start
                    AND     line <  con_end
                )
)
SELECT  REGEXP_REPLACE
        (
            REGEXP_SUBSTR(select_line, '\w+(\s+\,|\,|$)', 1, 1) || ' ' ||
            REGEXP_SUBSTR(select_line, '\w+(\s+\,|\,|$)', 1, 2) || ' ' ||
            REGEXP_SUBSTR(select_line, '\w+(\s+\,|\,|$)', 1, 3) || ' ' ||
            REGEXP_SUBSTR(select_line, '\w+(\s+\,|\,|$)', 1, 4) || ' ' ||
            REGEXP_SUBSTR(select_line, '\w+(\s+\,|\,|$)', 1, 5) || ' ' ||
            REGEXP_SUBSTR(select_line, '\w+(\s+\,|\,|$)', 1, 6) || ' ' ||
            REGEXP_SUBSTR(select_line, '\w+(\s+\,|\,|$)', 1, 7)
         -- REGEXP_SUBSTR(select_line, '\w+(\s+\,|\,|$)', 1, 8)
         -- REGEXP_SUBSTR(select_line, '\w+(\s+\,|\,|$)', 1, 9)
        ,   '\s+\,\s+'
        ,   ', '
        ) AS r_substr
FROM    one_line
;

-- dummy_alias1, dummy_alias2, dummy_alias3, dummy_alias4, dummy_alias5, dummy_alias6, dummy_alias7

A: I guess the answer is
select * from all_source where name='YOUR_SP'.
But you should do some text processing to find the aliases, and the procedures should have the same format.


text:
Q: MySQL Error - Cannot add foreign key constraint I know this question has been asked several times but it seemed like the problem was due to different data types between parent and child rows.
In my case, the data types are the same but I'm still getting the error. Here's my code
CREATE TABLE STUDENT_2(
    StudentNumber       INT                 NOT NULL AUTO_INCREMENT,
    StudentName         VARCHAR(50)         NULL,
    Dorm                VARCHAR(50)         NULL,
    RoomType            VARCHAR(50)         NOT NULL,
    CONSTRAINT          STUDENTPK           PRIMARY KEY(StudentNumber)
);

CREATE TABLE DORM_COST(
    RoomType            VARCHAR(50)         NOT NULL,
    DormCost            DECIMAL(7,2)        NULL,
    CONSTRAINT          DORM_COSTPK         PRIMARY KEY(RoomType),
    CONSTRAINT          DORM_COST_FK        FOREIGN KEY(RoomType)
        REFERENCES      STUDENT_2(RoomType)
                ON UPDATE CASCADE
                ON DELETE CASCADE
);

Where DORM_COSTS' foreign key cannot be added.
Thanks!

A: You want the foreign key reference on the table that has the foreign key, not the primary key.  So, that would be:
CREATE TABLE DORM_COST (
    RoomType            VARCHAR(50)         NOT NULL,
    DormCost            DECIMAL(7,2)        NULL,
    CONSTRAINT          DORM_COSTPK         PRIMARY KEY(RoomType)
);

CREATE TABLE STUDENT_2(
    StudentNumber       INT                 NOT NULL AUTO_INCREMENT,
    StudentName         VARCHAR(50)         NULL,
    Dorm                VARCHAR(50)         NULL,
    RoomType            VARCHAR(50)         NOT NULL,
    CONSTRAINT          STUDENTPK           PRIMARY KEY(StudentNumber),
    CONSTRAINT fk_student2_roomtype FOREIGN KEY (RoomType) REFERENCES DORM_COST(RoomType)
);

Here is a db<>fiddle that shows that this works.
That said your data model seems quite strange.

*

*I would expect a table called RoomTypes to have a primary key of RoomTypeId.

*I would expect dorm_cost to have dates, because costs can vary from year to year.

*I would expect different dorms to have similar room types -- singles, doubles, and so on.

*I would expect those room types to vary, perhaps, by dorm.


text:
Q: Codeigniter join multiple times same table and same column name I'm having a problem, i have this table named IMOVEIS and another table named CARACTERISTICAS.
IMOVEIS must do at least 10 joins with CARACTERISTICAS, to get different caracteristics (this is a real state project).
Now I know how to make multiple joins in same table, the problem is: the column name of CARACTERISTICAS table (CT_NOME it's the column's name).
So how to change column name to each join result?


text:
Q: web.config transform not working correctly We have a website created in VS 2012.  We've right-clicked our web.config file and selected 'Add Config Transform' and created Release and Debug versions of web.config.
In them we've added some new entries to the <appSettings> section in both our Debug and Release versions of web.config:
  <appSettings>
    <add key="username" value="user" xdt:Transform="Insert" xdt:Locator="Match(key)"/>
    <add key="password" value="pwd" xdt:Transform="Insert" xdt:Locator="Match(key)"/>
    <add key="GET" value="https://somewhere.com/url1" xdt:Transform="Insert" xdt:Locator="Match(key)"/>
    <add key="POST" value="https://somewhere.com/url2" xdt:Transform="Insert" xdt:Locator="Match(key)"/>

  </appSettings>

We have experimented with the various transform types, including 'Insert' and 'SetAttribute'.  None so far have produced the desired result of adding those new appSettings entries to web.config after a build.
Do we need to put placeholder entries for them in web.config, or is there another step(s) to this we're missing?
[Edit] the appSettings above are contained in the <configuration> element in the Debug and Release versions of web.config.

A: My guess is that the Insert and the Locator don't work together. If you are doing an Insert, you aren't trying to match it on anything. If you are trying to do a replace, or set some attributes, you would need to do a Locator match. If you are doing an insert, you don't need to look for something (using Locator) as it is net-new.
In a nutshell, if this is a new entry, leave Insert, drop Locate.
Make sense?


text:
Q: Indices on Commuting Matrices Suppose the matrices $A$ and $B$ commute, then
$$(A B)_{i k} = \sum_j A_{i j} B_{j k} = \sum_j B_{i j} A_{j k} .$$
That is, upon commuting the matrices, their indices are interchanged. But, this was easy, because in the above I was multiplying A by B. What if the indices aren't so easy. For example,
$$A_{a b} B_{c d} \stackrel{?}{=} B_{a b} A_{c d} .$$
What are the rules here?
Also, suppose they don't commute. Maybe $AB = BA^\ast$, then
$$A_{a b} B_{c d} \stackrel{?}{=} B_{a b} (A^\ast)_{c d} .$$


text:
Q: How to refer to Gauge Pointer's value from the expression for another Pointer's property? In SSRS Report, I would like to set Hidden property of a Gauge Pointer when specific condition is met. How can I refer to Gauge Pointer's current value from the expression for Hidden property so that I do not have to duplicate the whole expression for Value?
This is what I mean (pseudo-code):
Hidden: =Code.GetHiddenPropertyBasedOnPointerValue(this.Value)

What should I use instead of "this.Value"?

A: In the Properties of the Gauge Panel, go to the visibility section. Put the expression where it says "Show or hide based on an expression". Use an expression that evaluates to True for Hidden and False for Show.


text:
Q: supermartingale which is closable on the right Let $\{X_t\}$ be a supermartingale (right continuous) which is bounded from below, i.e. $X_t\ge -a$ for all $t$. Now let $Y_t:=X_t+a$ which is therefore a positive supermartingale. Convergence theorems tells us, that $Y_t\to Y_\infty$ almost surely and $Y_\infty\in L^1$. This is the convergence theorem as I know it. Now why is the following true:
$$E[Y_\infty|\mathcal{F}_t]\le Y_t$$
for all $t\ge 0$, i.e. $\{Y_t\}$ is closable from the right. We would then conclude that the same is true for $\{X_t\}$. It would be appreciated if someone could give me proof why this is true, for simplicity, in the discrete case.


text:
Q: Can a recursive function have a different call stack limit when it is called by another function? With this functions
var a = function(s) { s = s+1; console.log(s); a(s); }
var bz = function() { a(1) }

In the web console of my browser (Mozilla Iceweasel 38.6.1)

*

*if I run a(1), I get a result that varies around 18000 results

*if I run bz(), I get something that varies around 4000 results

Try it. Is it the same for you? Do you know why bz() would give 4000 instead of 18000 results?


text:
Q: MYSQL connector.net connection lost after long time I have mysql connection to remote server with connector.net 6.7.4
like this:
public MySqlConnection conn;
public MySqlCommand com;

public onStart()
{
   conn = new MySqlConnection("Server=xx.xx.xx.xx;Port=3306;Database=kbindb;Uid=collector; Pwd=xxx;");
   conn.Open();
   com = new MySqlCommand("SELECT * FROM blabla;", conn);
   timer.Interval=1000;
   timer.Enabled=True;

}

public onTimerTick(bla bla)
{
    // timer.Enabled=False;
     MySqlDataReader dr = com.ExecuteReader();
     while(dr.Read()){
            //blabla
      }
     dr.Close();
     //timer.Enabled=True;
 }

Code is running succesfully but after 1-2 hours lock timer on this line : com.ExecuteReader();
It can  not handling with try catch.
What can I do?

A: I wouldn't keep a connection to the database open any longer than you need it.. certainly not for hours. I assume you're getting a timeout of some sort.
Try creating the connection inside the tick event, get your data, and dispose of the connection. (The using statements in the following code will take care of disposing your resources.)
public onStart()
{
   timer.Interval = 1000;

   timer.Enabled = true;
}

public onTimerTick(...)
{
    timer.Enabled = false;

    using (var conn = new MySqlConnection("Server=xx.xx.xx.xx;Port=3306;Database=kbindb;Uid=collector; Pwd=xxx;"))
    {
        conn.Open();
        using (var com = new MySqlCommand("SELECT * FROM blabla;", conn))
        {
            var reader = com.ExecuteReader();

            while (dr.Read())
            {
                //blabla
            }
        }
    }

    timer.Enabled = true;
}


text:
Q: i have written a programm in tkinter and sqlite3 but i am unable to update a specific column database using my primary key def update():
    z = cname.get()

    print(z)
    j = ver.get()
    print(j)
    c.execute(
        "CREATE TABLE IF NOT EXISTS case_d(name TEXT PRIMARY KEY,crime TEXT,location TEXT,dt_of_arrest TEXT,officer TEXT,judge TEXT,defendant TEXT,prosecution TEXT,evidence TEXT,verdict TEXT)"
    )
    c.execute("UPDATE case_d SET verdict=? WHERE  name=?", (j, z))
    conn.commit()
    mb.showinfo(title="case ID", message="UPDATED SUCCESSFULLY")

r5 = Button(
    root, width=10, text="UPDATE", bd=5, relief="raised", bg="coral", command=update
).place(x=460, y=500)

in my above program I am getting my print statement work properly, but my database is not getting updated.


text:
Q: Why "Datanucleus-maven-plugin" in not recognising "ExtenssionMetaData" and "ObjectValueGenerator"? I am upgrading java 8 to java 11. My project uses datanucleus-maven-plugin (4.0.0-release) and I am importing its features( ExtensionMetaData, ObjectValueGenerator) like below
import org.datanucleus.metadata.ExtensionMetaData;
import org.datanucleus.store.objectvaluegenerator.ObjectValueGenerator;

but when i try to ugrade its version to  5.2.(source) it is not recognising above imports and showing error "can't find symbol".
** plugin-config (written in java 8)**
                <groupId>org.datanucleus</groupId>
                <artifactId>datanucleus-maven-plugin</artifactId>
                <version>4.0.0-release</version>
                <configuration>
                    <api>JDO</api>
                    <verbose>true</verbose>
                    <fork>false</fork>
                </configuration>
                <executions>
                    <execution>
                        <phase>process-classes</phase>
                        <goals>
                            <goal>enhance</goal>
                        </goals>
                    </execution>
                </executions>
                <dependencies>
                    <!-- override the default dependency -->
                    <dependency>
                        <groupId>org.datanucleus</groupId>
                        <artifactId>datanucleus-core</artifactId>
                        <version>4.1.0-release</version>
                    </dependency>
                </dependencies>
            </plugin>

** Plugin-config updated (for java 11) **
                <groupId>org.datanucleus</groupId>
                <artifactId>datanucleus-maven-plugin</artifactId>
                <version>5.2.1</version>
                <configuration>
                    <api>JDO</api>
                    <verbose>true</verbose>
                    <fork>false</fork>
                </configuration>
                <executions>
                    <execution>
                        <phase>process-classes</phase>
                        <goals>
                            <goal>enhance</goal>
                        </goals>
                    </execution>
                </executions>
                <dependencies>
                    <!-- override the default dependency -->
                    <dependency>
                        <groupId>org.datanucleus</groupId>
                        <artifactId>datanucleus-core</artifactId>
                        <version>5.2.1</version>
                    </dependency>
                </dependencies>
            </plugin>

I have tried other version of plugins and "datanucleus-core" but nothing worked.
I am not sure if those imports are deprecated or not. if deprecated what is substitute of that ?
github repo of datanucleus-core
Thanks.


text:
Q: LINQ GroupBy a List according to a key inside dictionary inside dictionary inside List C# I am Creating a list that has dictionaries of dictionaries for creating Json with it from a wcf service.
im creating like this:
List<Dictionary<string, Dictionary<string, Object>>> superduperList = new List<Dictionary<string, Dictionary<string, Object>>>();

Im filling it with data and the Json Looks like this:
[
{
DepartureJ: {},
ReturnJ: {},
pricesDepartureJ: {},
pricesReturnJ: {},
DepartureSegmentsJ: {},
ArrivalSegmentsJ: {}
},
...,
...,
...,
...,
...,
]

the starting Array is the List
the first Object is the Dictionary of Dictionaries
and the Objects Within the First Dictionary are again Dictionaries with Key/Value Pairs String/object
(i use object because the type could be bool or int or string)
now a dictionary in the last level looks like this:
   "DepartureJ": {
        ArrivalDateTime: "2013-09-27T12:15:00",
        ArrivalDateTime_str: "12:15",
        StopQuantity: 0,
        StopQuantity_str: "Direct",
        TotalDuration: "50",
        TotalDuration_str: "0h 50mins",
        SeatsRemaining_str: "2",
        NoBag_str: "",
        NonRefundable: true,
        NonRefundable_str: "Non Refundable",
        FareBasisCode: "xxx-",
        RoutingId: "",
        GroupCompStr: "ATH-SKG-1xxxxxx-UOWA3--0",
        LineCompStr: "-2013-09xxxxxxxxxxxxxxxxxxxxxA3--3,0000000-1-0--",
        TotalAmount_From_Prices: 136.64
    }

Now My Question is how do i Sort the Outer List From the Key TotalAmount_From_Prices which lies inside the dictionary of each dictionary of each item of the list?
i tried with groupby with LINQ but not working or don't know how :s
superduperList.GroupBy(each_result=> each_result["DepartureJ"]["TotalAmount_From_Prices"]);

its ok if i create a new list or change the existing.

A: Well actually i did it in a different manner.
I created a custom Class to hold the data as following:
public class each_flight
{
    public Dictionary<string, object> DepartureJ = new Dictionary<string, object>();
    public Dictionary<string, object> ReturnJ = new Dictionary<string, object>();
    public Dictionary<string, object> pricesDepartureJ = new Dictionary<string, object>();
    public Dictionary<string, object> pricesReturnJ = new Dictionary<string, object>();
    public Dictionary<string, object> DepartureSegmentsJ = new Dictionary<string, object>();
    public Dictionary<string, object> ArrivalSegmentsJ = new Dictionary<string, object>();

    public double total_price;

}

and then i created:
List<each_flight> flights = new List<each_flight>();

and then i populated the objects in the list and then with the extra double total_price i sorted them like this:
List<each_flight> Fligths_sorted = flights.OrderBy(o => o.total_price).ToList();

so its ok now :)


text:
Q: Xamarin forms UWP tooltips I would like to add tooltips in Xamarin for UWP by using a native view and the Windows.UI.Xaml Nuget package. I have added the following reference to the xaml page to get the windows native view:
<ContentPage

             xmlns:win="clr-namespace:Windows.UI.Xaml.Controls;assembly=Windows, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime;targetPlatform=Windows"

</ContentPage>

I can successfully access native windows controls, e.g. a TextBlock:
<    win: TextBlock Text="S"/>

However, when I try to add the tooltip to the control:
<win:TextBlock Text="S" ToolTipService.ToolTip="Service agreement"/>

I get the following exception during compilation:

"Xamarin.Forms.Xaml.XamlParseException: 'Position 56:45. Type
  ToolTipService not found in xmlns
  http://xamarin.com/schemas/2014/forms'"

Is the system getting confused between the standard Windows.UI.Xaml.Controls namespace and the extended one from the Nuget package?

A: ToolTipService is attached property, and it will not find ToolTipService assembly in Forms client, the better way is use Effect to create your own tip service and render it in UWP platform. You could refer the following steps.

*

*
Create a subclass of the PlatformEffect class.

*
Override the OnAttached method and write logic to customize the control.

*
Override the OnDetached method and write logic to clean up the control customization, if required.

*
Add a ResolutionGroupName attribute to the effect class. This attribute sets a company wide namespace for effects, preventing collisions with other effects with the same name. Note that this attribute can only be applied once per project.

*
Add an ExportEffect attribute to the effect class. This attribute registers the effect with a unique ID that's used by Xamarin.Forms, along with the group name, to locate the effect prior to applying it to a control. The attribute takes two parameters – the type name of the effect, and a unique string that will be used to locate the effect prior to applying it to a control.

UWP Code Part
[assembly: ResolutionGroupName("Microsoft")]
[assembly: ExportEffect(typeof(UWPToolTipEffect), nameof(TooltipEffect))]

namespace NativeSwitch.UWP
{
    public class UWPToolTipEffect : PlatformEffect
    {
        protected override void OnAttached()
        {
            var control = Control ?? Container;

            if (control is DependencyObject)
            {
                ToolTip toolTip = new ToolTip();
                toolTip.Content = TooltipEffect.GetText(Element);
                switch (TooltipEffect.GetPosition(Element))
                {
                    case TooltipPosition.Bottom:
                        toolTip.Placement = Windows.UI.Xaml.Controls.Primitives.PlacementMode.Bottom;
                        break;
                    case TooltipPosition.Top:
                        toolTip.Placement = Windows.UI.Xaml.Controls.Primitives.PlacementMode.Top;
                        break;
                    case TooltipPosition.Left:
                        toolTip.Placement = Windows.UI.Xaml.Controls.Primitives.PlacementMode.Left;
                        break;
                    case TooltipPosition.Right:
                        toolTip.Placement = Windows.UI.Xaml.Controls.Primitives.PlacementMode.Right;
                        break;
                    default:
                        return;
                }
                ToolTipService.SetToolTip(control, toolTip);
            }

        }

        protected override void OnDetached()
        {

        }
    }
}

Forms code part
public static class TooltipEffect
{

    public static readonly BindableProperty TextProperty =
      BindableProperty.CreateAttached("Text", typeof(string), typeof(TooltipEffect), string.Empty, propertyChanged: OnTextChanged);

    public static readonly BindableProperty PositionProperty =
      BindableProperty.CreateAttached("Position", typeof(TooltipPosition), typeof(TooltipEffect), TooltipPosition.Bottom);

    public static string GetText(BindableObject view)
    {
        return (string)view.GetValue(TextProperty);
    }

    public static void SetText(BindableObject view, string value)
    {
        view.SetValue(TextProperty, value);
    }

    public static TooltipPosition GetPosition(BindableObject view)
    {
        return (TooltipPosition)view.GetValue(PositionProperty);
    }

    public static void SetPosition(BindableObject view, TooltipPosition value)
    {
        view.SetValue(PositionProperty, value);
    }

    static void OnTextChanged(BindableObject bindable, object oldValue, object newValue)
    {
        var view = bindable as View;
        if (view == null)
        {
            return;
        }

        string text = (string)newValue;
        if (!string.IsNullOrEmpty(text))
        {
            view.Effects.Add(new ControlTooltipEffect());
        }
        else
        {
            var toRemove = view.Effects.FirstOrDefault(e => e is ControlTooltipEffect);
            if (toRemove != null)
            {
                view.Effects.Remove(toRemove);
            }
        }
    }

}

public enum TooltipPosition
{
    Bottom,

    Right,

    Left,

    Top
}

class ControlTooltipEffect : RoutingEffect
{
    public ControlTooltipEffect() : base($"Microsoft.{nameof(TooltipEffect)}")
    {

    }
}

Usage
// forms project namesapce
xmlns:effects="clr-namespace:ToolTipTestApp"
......

<win:TextBlock
    effects:TooltipEffect.Position="Right"
    effects:TooltipEffect.Text="Hello"
    Text="Hello Wrold"
    />


text:
Q: Alignment of rows in nested CSS grid I have nested CSS grids with auto columns (fixed heights are no solution) and want the rows of the inner grids of the same row of the outer grid to align with each other - see the example below for illustration:

ol ol{list-style:lower-alpha;}

ol{display:grid;grid-template-columns:auto auto;}

li{display:grid-item;}

li.x1y1{grid-area:1/1;}
li.x1y2{grid-area:2/1;}
li.x2y1{grid-area:1/2;}
li.x2y2{grid-area:2/2;}

1. Single Grid

The basic case of a grid layout:

Top Left

      Extra text.

Top Right

Bottom Left

Bottom Right

Note how <q>4. Bottom Right</q> is aligned with <q>3. Bottom Left</q>.

Now, let's see what happens when nesting grids.

2. Nested Grid

Top Left

            Extra text.

Top Right

Bottom Left

Bottom Right

Top Left

Top Right

Bottom Left

Bottom Right

Top Left

Top Right

Bottom Left

Bottom Right

Top Left

Top Right

Bottom Left

Bottom Right

As before, <q>1.d Bottom Right</q> is aligned with <q>1.c Bottom Left</q>.

However, <q>2.c Bottom Left</q> and <q>3.d Bottom Right</q> aren't aligned with the aforementioned - because they're not in the same grid.

3. HTML "Solution"

The code below alters the HTML to show what it's supposed to look like.

Top Left (1.a)

      Extra text.

Top Right (1.b)

Bottom Left (1.c)

Bottom Right (1.d)

Top Left (2.a)

Top Right (2.b)

Bottom Left (2.c)

Bottom Right (2.d)

Top Left (3.a)

Top Right (3.b)

Bottom Left (3.c)

Bottom Right (3.d)

Top Left (4.a)

Top Right (4.b)

Bottom Left (4.c)

Bottom Right (4.d)

However, the altered HTML not only breaks the numbering but also the Javascript relying on the HTML to figure out what belongs where (it's 2x2 elements only for the sake of the example - in practice it can be more or less in either dimension).

Therefore the appearance below needs to be achieved using CSS on the HTML from section 2, not by altering the HTML as in section 3.

So, how do I do that?

A: Putting display:contents on all the elements between the topmost display:grid and the bottom display:grid-item seems to do the trick.
Of course, the script that creates the list needs to generate adjusted grid-area values.
And the rest of the CSS also changes (e.g. the numbering).
But at least the Javascript doesn't need to be modified.

.container{display:grid;grid-template-columns:auto auto auto auto;}
.container>li{display:contents;}
ol ol{display:contents;}
ol ol li{display:grid-item;}

Top Left

            Extra text.

Top Right

Bottom Left

Bottom Right

Top Left

Top Right

Bottom Left

Bottom Right

Top Left

Top Right

Bottom Left

Bottom Right

Top Left

Top Right

Bottom Left

Bottom Right


text:
Q: How can I run gtk.main() asynchronsly in pygtk? The basic code that I have so far is below. How do I thread gtk.main() so that the code after Display is initialized runs asynchronously?
import pygtk
pygtk.require("2.0")
import gtk

class Display():

    def __init__(self):
        self.fail = "This will fail to display"
        window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        window.connect("destroy", lambda w: gtk.main_quit())
        window.show()
        self.main()

    def main(self):
        gtk.main()

class Test():

    def __init__(self, display):
        print display.fail

d = Display()
t = Test(d)

A: Just put the gtk.main call after everything else.
If you need to have the controller in a separate thread, make sure you do all gtk related function/methods by doing gobject.idle_add(widget.method).
import pygtk
pygtk.require("2.0")
import gtk

class Display(object):

    def __init__(self):
        self.fail = "This will fail to display"
        window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        window.connect("destroy", lambda w: gtk.main_quit())
        window.show()

class Test(object):

    def __init__(self, display):
        print display.fail

d = Display()
t = Test(d)

gtk.main()

A: You could use Twisted with the gtk2reactor.
http://twistedmatrix.com/documents/current/core/howto/choosing-reactor.html


text:
Q: Passing SQL query as system argument in Python I am trying to pass SQL query as an argument and store it into a Variable, so It can pick the query from the variable and execute SQL Statement. Is there any way? Appreciate your help in advance!
For example, I have a SQL query like;
Select column1, column2 from Table where Column3 = 'America' and column2 = %s

I need to pass this as a string to python file from Commandline and in the Python file I have;
state = 'NY'

conn = pyodbc.connect()
Query = sys.argv[1]
cur.execute(Query,[state])

When I am trying to do this way, I am getting the following error
 format_operation_with_parameters operation = operation % tuple(tlist) TypeError: not all arguments converted during string formatting


text:
Q: how to call MvxDialogViewController as a popover I am trying to display MxxDialogViewController from a popover and am getting an exception

18.35 Request is null - assuming this is a TabBar type situation where ViewDidLoad is called during construction... patching the request now
  - but watch out for problems with virtual calls during construction

while calling base.ViewDidLoad()
here is what I did to demonstrate the problem as a small sample:
I took N-23 example and added to the first section a new element with the Tapped command
new StringElement("test Popover", Tapped),

here is Tapped(), as a test I am trying to display the same FirstView in a popover.
    private void Tapped()
    {
        var dvc = new FirstView();
        var nc = new UINavigationController(dvc);
        _ardlViewPopover = new UIPopoverController(nc);

        _ardlViewPopover.PresentFromRect(this.View.Frame, this.View, UIPopoverArrowDirection.Any, true);
    }

Should MvxDialogViewController work inside of a popover controller?
Thank you
Mark

A: The error message is Request is null
Try setting the Request property for the FirstView - e.g. if there are no parameters then use:
var dvc = new FirstView();
dvc.Request = MvxViewModelRequest<FirstViewModel>.GetDefaultRequest();


text:
Q: Number of fragments into which a fixed triangle is cut in the 3d version of the binary space partitioning algorithm You can scroll down the question, if you're familiar with the construction of a 3d binary space partition as presented in the book Computational Geometry: Algorithms and Applications by Mark de Berg et al..

Let

*

*$S$ be a set of $n$ non-overlapping line segments in the plane

*$\ell(s)$ be the line which contains $s\in S$

*$\ell^+$ and $\ell^-$ be the half-plane above and below of a line $\ell$, respectively

Consider the following algorithm, called $\text{2dBSP}(S)$:

*

*Randomly shuffle the elements of $S$ such that each possible permutation of those elements has equal probability of appearance

*If $S$ contains at most one element, create a tree $T$ with value $S$

*Otherwise, pick the first element $s_1\in S$ and use $\ell:=\ell(s_1)$ to split the plane:

*

*Let $S^\pm:=\left\{s\cap l^\pm:s\in S\right\}$ and $T^\pm:=\text{2dBSP}(S^\pm)$

*Create a tree $T$ with left subtree $T^-$, right subtree $T^+$ and value $\left\{s\in S:s\subseteq\ell\right\}$

*Return $T$

Suppose we have chosen the first few splitting lines. These lines induce a subdivision of the plane whose regions correspond to nodes in the built tree. Consider one such region $r$. There can be segments $s$ in $S$ that cross $r$ completely (i.e. the fragment $f$ of $s$ contained in $f$ doesn't cut any segments inside $r$). Picking $f$ to split $r$ is called a free split.

Now, we want to use a set of $n$ non-intersecting triangles $t_1,\ldots, t_n$ in the space instead of $S$. Let $h_i$ be the plane which contains $t_i$. Since we cannot use the literal translation of $\text{2dBSP}$ if we want to be able to analyze the resulting algorithm, we use the following modification, called $\text{3dBSP}$:

*

*Randomly shuffle the elements of $S$ such that each possible permutation of those elements has equal probability of appearance

*for $i=1$ to $n$:

*

*Use $h_i$ to split every region where the split is "useful" and make all possible free splits

The definition of a free split can be translated literally to the 3d case.

You can find $\text{3dBSP}$ in the book above Lemma 12.3. A $2d$ example of its behavior, in contrast to $\text{2dBSP}$, is shown in the next image

where (a) is the result of $\text{2dBSP}$ and (b) is the result of a $2d$ variant of $\text{3dBSP}$.

Question: Let $k\in\left\{1,\ldots,n\right\}$ and $N$ be the number of fragments into which $t_k$ is cut. What's the expecation of $N$?

In the book they do the following:

*

*Let $\ell_i:= h_i\cap h_k$ for $i\in\left\{1,\ldots,k-1\right\}$ be the intersection line of the plane $h_i$ with $h_k$ and $L:=\left\{\ell_1,\ldots, \ell_{k-1}\right\}$

*Let $I:=\left\{i\in\left\{1,\ldots,k-1\right\}:\ell_i\cap t_k\ne\emptyset \right\}$ be the index set of those $\ell_i$ which intersect $t_k$ and $s_i:=\ell_i\cap t_k$ for $i\in I$ be the segment of $\ell_i$ which intersects $t_k$

Now, they state that $N$ is not the number of faces in the arrangement that $\left\{s_i:i\in I\right\}$ induces on $t_k$. Why?

They state the following: Consider the moment where $t_{k-1}$ is treated and assume that $\ell_{k-1}$ intersects $t_k$. The segment $s_{k-1}$ can intersect several faces of the arrangement that $\left\{s_i:i\in I\right\}$ induces on $t_k$. But if such a face $r$ is not incident to one of the edges of $t_k$ (i.e. $r$ is an interior face) then a free split already has been made through this part of $t_k$.

Why is that the case? I absolutely don't understand it.

A: Their formulation "through this part" is a bit confusing – what they mean is "using this part". Such an interior face doesn't cut anything in the plane outside of itself because it's shielded on all sides by interior edges, and it doesn't cut anything itself because the triangles are non-intersecting; so the moment it's created it would be used for a free split.


text:
Q: How is cardinality exactly defined as a function and why is it different from the ordinals Once we construct the definition of the ordinals:
$$0=\{\} \, \, 1=\{0\} \,\, 2=\{0,1\} \,\,3= \{0, 1,2\} \,\, ...$$
And we want to describe the cardinality of the set $S$:
$$S=\{3,2,4\}$$
Intuitively we know that:
$$|S|=3$$
However, how do we describe the function of $\mathbb{card}(x)$?
This function must map the Von-Neumann ordinals to the cardinality of the set. How does this function do that? If the cardinality of the set can be described by an ordinal, why do we denote:
$$|\mathbb{N}| = \aleph_0$$
And not:
$$|\mathbb{N}| = \omega_0$$
What would be the ordinal number that would be associated with $\aleph_1$. I thought that it could be $\omega_0 + 1$ since it is the next size of infinity. Like the next size in cardinal arithmetic is always just adding one. Or the idea of the next. However, if it is not that what would it be? Would the construction of the cardinality function help, or not?
If this is not clear, please let me know and I'll edit this a bit more.
Thanks.

A: As the Wikipedia page notes, there are two ways to approach cardinality. One, which is what you are getting at here, is to construct the cardinal numbers and have a procedure that assigns each set $S$ a unique cardinal $Card(S)$. This construction is somewhat involved and is mostly the domain of set theorists and the like. Most ordinary mathematicians think of cardinality through the relations "$A$ has the same cardinality as $B$" denoted by $|A| = |B|$ and "$A$ has cardinality less than or equal to $B$", denoted by $|A| \leq |B|$.
We define $|A| = |B|$ as $\exists \phi:A \to B, \phi$ is a bijection. And we define $|A| \leq |B|$ by $\exists \phi: A \to B, \phi$ is an injection.
Then the Schroder-Bernstein theorem gives that $|A| \leq |B|$ and $|B| \leq |A| \implies |A| = |B|$.
Now if we just consider finite sets, we can alternatively define a "function" (note it won't be a true set function, since there is no set of all finite sets) $Card(S)$ that assigns a finite set $S$ a unique natural number that is its number of elements. We then can note that $Card(A) = Card(B) \iff |A| = |B|$ and $Card(A) \leq Card(B) \iff |A| \leq |B|$, so these two approaches are the same for finite sets.
Edit: Defining the $Card$ "function" for finite sets. Since $Card$ cannot be a set function as noted above, we are really looking for a predicate $\Phi(A,n)$ s.t. $A$ is finite implies $\exists! n \in \mathbb{N}, \Phi(A,n)$.
Denote $set(n) = \{0,...,n-1\}$. Define $\Phi(A,n) \iff n \in \mathbb{N} \land \exists \phi : A \to set(n), \phi$ is a bijection.
Then to show $\Phi$ has the properties we want, we note that uniqueness comes directly from the nonexistence of bijections between $set(n)$ and $set(m)$ for $n \neq m$ and since $A$ is finite can be defined to mean $\exists n \in \mathbb{N} \exists \phi : A \to set(n), \phi$ is a bijection, we get existence of some $n$ s.t. $\Phi(A,n)$ provided $A$ is finite.
Thus $\Phi$ defines a function, since to each finite $A$, we get a unique $n \in \mathbb{N}$.


text:
Q: Convert json data for google chart I am trying to convert this json into the correct format for a google chart:
var jsonData =  {"Battery Voltage, (A)":
                    {"2017-11-11T00:00:00.000Z":12.3
                    ,"2017-11-11T00:01:00.000Z":12.35
                    ,"2017-11-11T00:02:00.000Z":12.6
                    ,"2017-11-11T00:03:00.000Z":12.7
                    ,"2017-11-11T00:04:00.000Z":12.8}
                ,"Battery Current, (A)":
                    {"2017-11-11T00:00:00.000Z":1.3
                    ,"2017-11-11T00:01:00.000Z":1.4
                    ,"2017-11-11T00:02:00.000Z":1.5
                    ,"2017-11-11T00:03:00.000Z":1.6
                    ,"2017-11-11T00:04:00.000Z":1.7}};

I can use this code, as used here:
var chartData = [];
Object.keys(jsonData).forEach(function (column) {
  chartData.push(['Datetime', column]);
  Object.keys(jsonData[column]).forEach(function (dateValue) {
    chartData.push([new Date(dateValue), jsonData[column][dateValue]]);
  });
});

But I get a c.getTimezoneOffset is not a function error.
How do I correctly format this data into a googe datatable?


text:
Q: svelte - run code with side effects inside of for loop I have the following Svelte component:

    {#each tests as test}

{test.txt}

    {/each}

Is there way to make test defined so, I can call foo?
This is closer, but it renders the null:

    {#each tests as test}
        {
            test.foo() || null
        }

{test.txt}

    {/each}

A: I think use:action might be what you are looking for REPL

    {#each tests as test}

{test.txt}

    {/each}


text:
Q: How to copy the background view of the actual Navigation Bar? How can I copy the actual UINagivationBar background appearance? I would like to have the exact background appearance to use on another view.

A: I don't think there's a direct way to access the gradient background of the UINavigationBar. You can, however, play around with mockup versions of the background here and create your own version using Photoshop.


text:
Q: Can I make Android Studio show errors immediately, like Eclipse used to do? There is one thing I really miss about Eclipse and it was that if I commented out a public field, for instance, the project immediately turned red and all the classes that use this field, also turn red, so I know what I broke.
In Android Studio, I comment out a public field and nothing changes, and if I want to find which are the affected classes I either have to try to remember where I used it, or run a rebuild, wait for a minute, until the error appears.
Can I make Android Studio do this kind of check in real time like Eclipse did?

A: It works in Android Studio as well. But only for the current visible class.
Make sure Power Save Mode is not enabled. You can uncheck it at 'File > Power Save Mode'


text:
Q: Imgur API won't remove image from album I'm using the Imgur API to create an album under a users account, and then add or remove images from that album.
I can authenticate successfully, create the album, and add images to the album without a problem.
When I go to remove an image from the album, I get this response:
{'success': True, 'data': True, 'status': 200}

However, the image remains in the album. As far as I can tell, I'm correctly sending the request using an HTTP delete.
The Imgur album page also seems to have gone a little screwy. After having attempted to remove and re-add the same image to the album a few times, the albums page of my account lists the album as having 3 images. But if I go into the actual album, it says it only has one image.
Does anyone have any ideas what might be going on here?

A: I was mistakenly using the DELETE call wrong. I was including the ids I wanted to remove as parameters in the request, as if it was a POST request.
Instead I needed to include the ids in the URL like this:
https://api.imgur.com/3/album/{album}/remove_images/?ids={theid}


text:
Q: Gorilla websocket with google app engine I am getting following error when I am running "goapp serve myapp/" from Myproject folder inside src.

go-app-builder: Failed parsing input: parser: bad import "unsafe" in
  github.com/gorilla/websocket/client.go from GOPATH

my file structure is some something like this
$GOPATH/src
|-github.com/gorilla/websocket
|-MyProject
   |-myapp
      |-app.yaml
      |-mainApp.go (which contain init function and part of app package)

Please let me know how to correct this.
on a related subject, I read that google app provide websocket support only in paid app. Is there a way for me to test my website before getting into payment mode? Or is there a better option that google app engine?


text:
Q: Lua - Most resource efficient way to compare a variable to a fixed list of values So I have a variable, let's call it 'ID'. I need to check this value relative to a fixed amount of values. The ID, of course, can only match one of the values so there isn't an issue with stopping on the first matching value as none of the others would match. There is also a chance that the variable does not match any of the given values, too. My question is then, what is the most resource efficient way to do this? I can think of two easy ways of tackling the problem. Since I know the values at the time of programming I can setup a conditional with 'or' that just checks each value, like so:
if (ID == "1" or ID == "16" or ID == "58") then
    --do something--
end

The problem with this is that it's quite verbose and tedious to write. The other option involves a foreach loop where I define a table beforehand.
values = {"1", "16", "58"}
for _, value in ipairs(values) do
    if(ID == value) then
        return true
    end
end

The upside to this is it's reusable which is good since I'll need to do this exact check with a different set of values at least 10 times, the downside is I suspect it takes more resources.
Any help would be greatly appreciated.

A: Tables can be used as sets:
interesting = {
   ["1"] = true, ["16"] = true, ["58"] = true
}

if interesting[ID] then
   -- ...
end

While it eats more memory (80 bytes per empty table plus 32 bytes (IIRC, on x86_64) per entry (while rounding the number of entries up to the next power of two) vs. 16 bytes per comparison plus storage for the value that you compare) the chain of comparisons happens in C and is therefore faster than a chain of comparisons as a sequence of Lua instructions (at least once things get larger).
For small numbers of values, this doesn't really matter.  (If you are CPU-bound and this is very important in your case, measure in the context of your program and see what performs better.  Don't put too much weight on micro-benchmarks with this – cache behavior in particular might produce funny effects here.)
For large numbers of comparisons, this is the right approach.  It's also more flexible than if-then-else chains.  (You can change things at runtime without reloading code.)
Also note that the value you use to anchor an element in the set doesn't really matter, so a relatively common idiom (especially for input handling) is putting the action as a function into the table:
keybindings = {
   left = function()  Player:move_left( )  end,
   right = function()  Player:move_right( )  end,
   up = function()  Player:jump( )  end,
   -- ...
}

function onKey( k )
   local action = keybindings[k]
   if action then  action( )  end
end

While this certainly is slower than a direct comparison and inline code, speed is essentially irrelevant here (generally happens much less often than ~100x per second) and flexibility is of high value.


text:
Q: RxJava as replacement for parallel calculating big factorials with StreamAPI I created a function that counts the time needed to calculate a factorial using many threads.
It is created using StreamAPI.
static Long streamParallelFactorial(int number) {

        long czasRozpoczecia = System.currentTimeMillis();
        IntStream.range(1, number).parallel().mapToObj(BigInteger::valueOf).reduce(BigInteger.ONE,
                BigInteger::multiply);
        long czasZakonczenia = System.currentTimeMillis();

        return czasZakonczenia - czasRozpoczecia;
    }

Now I'm trying to do the same but using RxJava. During work, this monster came out.
static Long rxJavaParallelFactorial(int number) {
    long czasRozpoczecia = System.currentTimeMillis();

    Observable<Integer> vals = Observable.range(1,number);
    vals.flatMap(val -> Observable.just(val)
            .subscribeOn(Schedulers.computation())
            .scan(BigInteger.ONE, (big,cur) ->
            big.multiply(BigInteger.valueOf(cur))));

    long czasZakonczenia = System.currentTimeMillis();
    return czasZakonczenia - czasRozpoczecia;
}

Someone would be nice and advise me what should I do to make it work?
Thank you in advance.

A: You can do parallel computation similary to Stream in RxJava 2+:
Flowable.range(1, number)
.parallel()
.runOn(Schedulers.computation())
.map(BigInteger:valueOf)
.reduce(() -> BigInteger.ONE, BigInteger::multiply)
.reduce(BigInteger::multiply)
.subscribe();


text:
Q: First Unity Android game - Weird/unknown In App Purchasing error I'm currently building an Android game using Unity 2019.3.0f6.
I'm trying to enable some in-app purchases for some in-game currencty using the Unity Plugin "Easy IAP" and following the video tutorial series on YouTube (https://youtu.be/kMAkYXYL84U). But no matter what I do, I can't get the purchases to go through. I've added them in the Google Play Console and activated them, so I don't understand what is happening.
I've created an entirely empty scene in the project, made a build and uploaded it to the Google Play console (I've tried building driectly to my phone, going through Google's internal app sharing, and even full on releasing it) and using the plugin's debug script, it tells me that the consumables exist and are ready to purchase. Except that when I press the actual button, the Google Pay pop-up comes up and declares that the purchaseable is not available. And even less helpful is the plugin debugger returns that the purchase failed due to an "Unknown" error.
Note, when I do this in the Unity editor, it goes through a fake purchase fine, so I'm inclined to think something is wrong in my Google Play console hence why I'm posting here and not a Unity dedicated forum. I've seen other people ask similar questions and tried following those answers but nothing has worked so far.

A: Google Play does not allow publishers to buy their own products. So you need to sign up a new Google play account and add it as your test account in Google play developer console.
Try that way

A: I feel really dumb, but it seems to be working now and I haven't touched anything since I posted the question several days ago. I'm guessing that the servers didn't immediately recognize the product activations on the Console so I just had to wait.


text:
Q: Html.DisplayFor with Generic Class I have a class like this with a generic type:
Document<T>
This class is part of a view model
public class MyViewModel
{
   public IEnumerable<Document<T>> Documents {get;set;}

}

I'd like to use DisplayFor to dispatch to the appropriate template in the view.cshtml
@model MyViewModel
foreach(var vm in Model.Documents)
{
   @Html.DisplayFor(vm)
}

But I don't know how to create templates in Shared/DisplayTemplates that have a name of the class, but the C# name omits the generic parameters:
 Document`1

But this is insufficent, as it doesn't identify the full type structure.
Is there a way to use DisplayFor with DisplayTemplates and Generic Types?

A: You can do something like this:
@foreach(var vm in Model.Documents)
{
    Type type = vm.GetType().GetGenericArguments()[0];
    var templateName = "Document_" + type.Name;
    @Html.DisplayFor(model => vm, templateName)
}

And, then, your DisplayTemplates will be named like "Docuement_Entity1.cshtml", "Document_Entity2.cshtml",... where Entity1 and Entity2 are your generic argument types.
Alternatively, you can create a TemplateName property for the Document class, set it just like in the code above, and use it in your View like this:
@foreach(var vm in Model.Documents)
{
    @Html.DisplayFor(model => vm, vm.TemplateName)
}

UPDATE:
If you want to use an Html Helper, you can do something like this:
public static MvcHtmlString DisplayGenericFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression)
{
    var modelType = helper.ViewData.Model.GetType();
    if (!modelType.IsGenericType)
        throw new ArgumentException();

    Type genericType = modelType.GetGenericArguments()[0];
    var templateName = modelType.Name.Split('`').First() + "_" + genericType.Name;
    return helper.DisplayFor<TModel, TValue>(expression, templateName);
}


text:
Q: VirtualBox VM settings between different CPUs (Processor/Acceleration) I have 2 PCs, 1 with a INTEL-Q9550 (YES-VT-x) and another with INTEL-E2160 (NO-VT-x)
I will be using the Q9550 first to create a new VM, install XP and install stuff I'll need. Once this VM is golden, I plan on migrating this VM over to the E2160 machine.
The question is, while creating/preparing this VM on the Q9550, should I disable all the following settings below to make sure the E2160 can start this VM without errors?
Q9550 Default VM Settings
=========================

PROCESSOR
  [X] Enable PAE/NX

ACCELERATION
  [X] Enable VT-x/AMD-V
  [X] Enable Nested Paging

A: So I built a VM on the Q9550 with the above settings all enabled and then later migrated it to the E2160, so far the E2160 is running the VM without problems.
To answer my own question: no, it's not necessary to disable any of the ACCELERATION settings to successfully boot the VM on the E2160 CPU.


text:
Q: Using Javascript to add a span around a decimal value var value = 2.00

How can I add a span tag around the '.00', so that on my page I would end up with:
2.00

Please note that the '00' can be a different value. Depends on the data being injected.

A: You can use String#replace

var value = '2.00';
console.log(
  value.replace(/\.(\d+)/, '.<sapn>$1')
);

If variable holds a Number then convert it to 2 decimal format string using Number#toFixed and do the same.

var value = 2.00;
console.log(
  value.toFixed(2).replace(/\.(\d+)/, '.<sapn>$1')
);

Refer : Specifying a string as a parameter in replace method.

A: split it into the two parts and add a span to the second part.not sure if you want the decimal place inside the span or not, but this will do it.

var value = '2.00';
var valueParts=value.split(".");
var newValue=valueParts[0] +"."+valueParts[1]+ "";
alert(newValue);

A: Use the toFixed function
var num = 5.56789;
var n = num.toFixed(2);

if you need back the string to number you can use parseFloat function
var num = parseFloat(n)

A: You are specifically asking for a "span tag", so here is a JQuery approach:
$(document).ready(function () {
    var value = 2.00
  value = value.toFixed(2);

  $('body').append(value.split('.')[0] + '.' + value.split('.')[1] + '');
});

See this jsfiddle example: https://jsfiddle.net/fictus/tj7df8qh/


text:
Q: Thread re-runs the run() method I am learning about MultiThreading concepts. I just worked on a simple POC and found a little weird behaviour. Kindly help me
Goal :- To run 2 threads, one is "Tortoise" and other is "Hare". Making the Hare to sleep for 2 secs and allowing only tortoise to complete the thread before Hare.
My Runnable Class
package com.learn;

public class ThreadLearn implements Runnable{

    @Override
    public void run() {
        // TODO Auto-generated method stub
        //Thread.currentThread().interrupt();
        boolean flag = false;
        System.out.println("Running : " +Thread.currentThread().getName());
        if(Thread.currentThread().getName().equalsIgnoreCase("Hare")){

            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        System.out.println("Flag before Setting : " +flag);
        if(!flag){
        System.out.println("Winner  : " +Thread.currentThread().getName());
        flag = true;
        System.out.println("Flag after Setting : " +flag);
        }

    }

}

and My main method class
package com.learn;

public class ThreadExecutor {

    public static void main(String args[]){

        ThreadLearn l1 = new ThreadLearn();
        ThreadLearn l2 = new ThreadLearn();

        Thread t1 = new Thread(l1,"Tortoise");
        Thread t2 = new Thread(l2,"Hare");
        System.out.println("Thread STATE : " +Thread.currentThread().getState());

        t1.start();
        t2.start();

        System.out.println("END STATE : " +t1.getState());
    }

}

This is the output I got

Thread STATE : RUNNABLE
END STATE : RUNNABLE
Running : Tortoise
Running : Hare
Flag before Setting : false
Winner  : Tortoise
Flag after Setting : true
Flag before Setting : false
Winner  : Hare
Flag after Setting : true

If you see the output, I have set the "flag" as false in the run(), after making the hare therad  to sleep for 2 secs, Tortoise thread runs and sets the flag value as "true", so when the hare comes after 2 secs, my expectation was flag will be true and Winner sysout will not be printed at all. but the flag is again set as "false' and running the Winner sysout for Hare also. :( Please help me what is happening here.

A: each thread has own "flag" because you created 2 instances of ThreadLearn. both flags are independent. if you need to share 'flag' => you have to move 'flag' declaration from method to class body and mark it as static and volatile


text:
Q: DataFrame with multiple semi-colon separated variables in each column. How to one-hot encode? I have a DataFrame with multiple variables within each column - the datatype of these are strings not lists. I am unable to One-Hot Encode the data within each column.
Out:

        A                     B                             C
Ella    Red; Blue; Yellow     Circle; Square; Triangle      Small; Medium; Extra big
Mike    Yellow; Red; Blue     Oval; Triangle; Circle        Medium; Big; Extra big
Dave    Yellow; Red; Green    Circle; Square; Triangle      Extra small; Medium; Big

I am looking to create it with multi-tiered column headings to look like the below:
       A                                 B                                     C
       Red    Blue   Green   Yellow      Circle   Triangle  Square   Oval      ....
Ella   1      1      0       1           1        1         1        0         ....
Mike   1      1      0       1           1        1         0        1         ....
Dave   1      0      1       1           1        1         1        0         ....

I tried this, and it helped me but only works when all the columns have the same variables:
https://stackoverflow.com/a/67110743/15646168
df = df.stack().str.get_dummies(sep=',')
df.columns = df.columns.str.strip()
df = df.stack().groupby(level=[0,1,2]).sum().unstack(level=[1,2])

Thank you so much!

A: Use concat in dict comprehseion with Series.str.get_dummies - only is changed separator to ; :
df = pd.concat({x: df[x].str.get_dummies(sep='; ') for x in df.columns}, axis=1)
print (df)
        A                       B                        C            \
     Blue Green Red Yellow Circle Oval Square Triangle Big Extra big
Ella    1     0   1      1      1    0      1        1   0         1
Mike    1     0   1      1      1    1      0        1   1         1
Dave    0     1   1      1      1    0      1        1   1         0

     Extra small Medium Small
Ella           0      1     1
Mike           0      1     0
Dave           1      1     0


text:
Q: ES6 import/export modules I have the following file structure:
src
  ...
  ListBox
    index.js
    ListBox.jsx
    ListBoxItem.jsx
  ...
  index.js

where
src/ListBox/ListBox.jsx
class ListBox extends React.Component {
  ...
}

export default ListBox

src/ListBox/ListBoxItem.jsx
class ListBoxItem extends React.Component {
  ...
}

export default ListBoxItem

src/ListBox/index.js
export { default as ListBox } from './ListBox'
export { default as ListBoxItem } from './ListBoxItem'

src/index.js
import ... from '...'
import { ListBox, ListBoxItem } from './ListBox'

export {
  ...
  ListBox,
  ListBoxItem
}

I'm using webpack as a bundler and here is an error

As you can see webpack is trying to find ListBox module in src/ListBox/index.jsx instead of src/ListBox/ListBox.jsx. If I change export { default as ListBox } from './ListBox' to export { default as ListBox } from './ListBox.jsx' it works. It is the same with ListBoxItem.
Here is my webpack.config.js
module.exports = (env) => {
const config = {
    devServer: {
        contentBase: path.join(__dirname, 'docs'),
        historyApiFallback: true,
        hot: true
    },
    devtool: env.development ? 'cheap-module-eval-source-map' : false,
    entry: {
        bundle: [
            'babel-polyfill',
            './docs/index.jsx'
        ]
    },
    output: {
        path: path.join(__dirname, 'docs'),
        filename: '[name].min.js'
    },
    module: {
        rules: [
            {
                test: /\.less$/,
                exclude: [
                    path.resolve(__dirname, 'node_modules')
                ],
                use: [
                    'style-loader',
                    {
                        loader: 'css-loader',
                        options: {
                            minimize: env.production,
                            sourceMap: env.development
                        }
                    }, {
                        loader: 'postcss-loader',
                        options: {
                            plugins: [
                                autoprefixer({
                                    browsers: ['last 2 versions']
                                })
                            ],
                            sourceMap: env.development ? 'inline' : false
                        }
                    }, {
                        loader: 'less-loader',
                        options: {
                            sourceMap: env.development,
                            sourceMapContents: env.development
                        }
                    }
                ]
            },
            {
                test: /\.(?:jsx?)$/,
                use: 'babel-loader',
                exclude: [
                    path.resolve(__dirname, 'node_modules'),
                    /.*example\.jsx$/
                ]
            },
        ]
    },
    plugins: [
        new webpack.HotModuleReplacementPlugin(),
        new webpack.optimize.CommonsChunkPlugin({
            name: 'vendor',
            minChunks: (module) => {
                return module.context && module.context.indexOf('node_modules') !== -1;
            }
        }),
        new HtmlWebpackPlugin({
            template: 'docs/index.html'
        }),
    ],
    resolve: {
        alias: {
            ui: path.resolve(__dirname, './src')
        },
        extensions: ['.js', '.jsx']
    }
};

return config

};

A: If you look closely at the error message, you can read that webpack expects ListBox\index.jsx, while you called it ListBox\index.js. You can either fix it by renaming your file or to adjust your webpack configuration so that it accepts .js, you can do that by adjusting your resolve directive.
resolve: {... extensions: ['.js','.jsx'] }

A: Looks like the error is due to your syntax in src/ListBox/index.js, as the error is saying that's the thing that's failing to build.  Looking at your example, you may be exporting incorrectly:
// src/ListBox/index.js

export { default as ListBox } from './ListBox'
export { default as ListBoxItem } from './ListBoxItem'

Try changing to
// src/ListBox/index.js

import ListBox from './ListBox'
import ListBoxItem from './ListBoxItem'

export { ListBox, ListBoxItem }

I know there's an export...from syntax, but I could not find an example of doing that from multiple sources.  You could try just removing the 'default' from your lines, but my example will work as well if slightly more verbose.


text:
Q: How to hide a product in magento2 rest api? I want the product not to appear on the site, but not delete ?
How to do it through the REST API ?

A: Simply change the status of your product to disabled through Rest Api. That will make in hidden from appearing in website.
Hope it finds you helpful.


text:
Q: What do you call the small cabin on top of roof of certain buildings? What do you call the small cabin on top of roof of certain buildings?

The small cabin with something on top of it and with pipes running to the top of it. Is there a word for it? What are some standard ways of referring to that thing?

A: If it contains air conditioning, lift (elevator) motors and similar equipment then it could be called the "plant room". Although a plant room is not confined to the roof of a building, it may be anywhere, such as the basement.

A: The technical term for these structures seems to be either house or bulkhead (e.g. stair/elevator house or stair/elevator bulkhead), but satisfactory online definitions are hard to find.

bulkhead

*a boxlike structure built over an opening, as at the head of a staircase, elevator shaft, etc.

Your Dictionary

Elevator house or bulkhead Structures with elevators may have an equipment or motor room located on the roof. Elevator houses vary in size according to the number of elevators that they service...

Fire Engineering's Handbook for Fire Fighter I and II
The term elevator house may well be more understandable than elevator bulkhead to the average person.

A: Roof tower, this is just a stair well with a small landing at top of stairs inside.

A: Or Stair tower, can be used to name the structure.


text:
Q: Neural Network learns better at high output values I'm training a feed forward neural network
(stochastic gradient descent, 3 small hidden layers, elu activation, inputs scaled between 0 and 1, weights initialized according to TiRune from
https://stats.stackexchange.com/questions/229885/whats-the-recommended-weight-initialization-strategy-when-using-the-elu-activat)
on a function that outputs values from about 0 to 55.000. I'm satisfied with the result, it learns to approximate the function pretty well.
But when I scale the outputs to be between 0 and 1 (just outputs divided by 55.000) it stops learning pretty early, it performs much worse. I tried various learning rates, of course.
Is there a reason it learns much better when the output values are between 0 and 55.000 than when they are between 0 and 1? Or does it not make any sense and my problem is somewhere else?

A: If I understand correctly, the only difference between the networks is the output scaling (target scaling). For complete answer, I will give a list of possible reasons and include the learning rate you mentioned:
How scaling the outputs can effect my learning?

*

*You may have a bug. If you scale the networks output, make sure you scale both predictions and real outputs that you feed during the training, validation and test.

*Your output activation function cannot output at the target range. For instance, sigmoids can output values between 0 and 1. Scaling output values between 0 and 10 will reduce performance since the targets cannot be produced.

*Make sure you use correct data types. Normalization can be good, but if normalization causes loss of information due to data types, you should normalize to a larger range. Truncation and rounding errors will cause information loss.

*Adjust the learning rate - normalization changes the derivatives values, and therefore the propagated gradients all the way to the updates.

Good luck!


text:
Q: Using GeoPandas with rasterstats for zonal statistic gives error I'm trying to use GeoPandas and zonal statistic from rasterstats together.
I run this code
import geopandas as gpd
from rasterstats import zonal_stats

geodf = gpd.read_file("SHP/shape.shp")
zonal_stats(geodf, "raster.tif")

but I get this error:

ParseException: Unknown type: 'FID'
ParseException: Unexpected EOF parsing WKB
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/IPython/core/interactiveshell.py", line 2820, in run_code
exec code_obj in self.user_global_ns, self.user_ns
File "", line 1, in
zonal_stats(geodf,"raster.tif",stats='mean')
File "/usr/local/lib/python2.7/dist-packages/rasterstats/main.py", line 21, in zonal_stats
return list(gen_zonal_stats(*args, **kwargs))
File "/usr/local/lib/python2.7/dist-packages/rasterstats/main.py", line 128, in gen_zonal_stats
for i, feat in enumerate(features_iter):
File "/usr/local/lib/python2.7/dist-packages/rasterstats/io.py", line 107, in
features_iter = (parse_feature(x) for x in obj)
File "/usr/local/lib/python2.7/dist-packages/rasterstats/io.py", line 70, in parse_feature
raise ValueError("Can't parse %s as a geojson Feature object" % obj)
ValueError: Can't parse FID as a geojson Feature object

The GeoDataFrame looks like this:
    In[43]: geodf
    Out[42]:
         FID                                      geometry

    0     0  POLYGON ((7.662965420348624 45.05600185397847,...
    1     1  POLYGON ((7.665210146514162 45.05607590098681,...
    2     2  POLYGON ((7.663353281768154 45.05601113630467,...
    3     3  POLYGON ((7.660229137844505 45.0570570693801, ...
    4     4  POLYGON ((7.660047499767138 45.0572381357898, ...
    ....

Any suggestion how to solve this problem?

A: For anyone else that stumbles upon this you can do:
To get just one stat:
gdf['mean'] = pd.DataFrame(
    zonal_stats(
        vectors=gdf['geometry'],
        raster='raster.tif',
        stats='mean'
    )
)['mean']

To get all computed stats:
gdf = gdf.join(
    pd.DataFrame(
        zonal_stats(
            vectors=gdf['geometry'],
            raster='raster.tif',
            stats=['max','min']
        )
    ),
    how='left'
)

A: For some reason @Taras's solution did not work for me, I got the error:

TypeError: 'list' object is not callable

However, I bypass the problem with the following.
Not the best solution, but I got the same result.
origShp = gpd.read_file(r'E:\...\myshapefile.shp')

zonal_stats = zonal_stats(r'E:\...\myshapefile.shp',
            r'E:\...\myRaster.tif',
            stats="min mean max")

df = pd.DataFrame(zonal_stats)
df_redux = pd.concat([df, origShp], axis=1)

cols_at_end = ['min', 'mean', 'max']
final_gf = df_redux[[c for c in df_redux if c not in cols_at_end]
        + [c for c in cols_at_end if c in df_redux]]

Out[328]:
           min       mean        max
0    -0.035565  17.707176  34.366177
1    -0.156580  16.005182  32.490967
2    -0.256113  13.957398  31.997578
3    -0.032301   7.868770  23.284115
4    -0.172403  14.436392  32.300911

Or more compact:
import geopandas as gpd
from rasterstats import zonal_stats

def ZonalStats(shape, raster, stats):
    # shape - shapefile path
    # raster - raster path
    # stats - stats as list, f.e. 'min mean max' ; 'min'
    # the result is final_gdf as GeoDataFrame

    shape_gdf = gpd.read_file(shape)
    zonalSt = zonal_stats(shape, raster, stats = stats)
    df = pd.DataFrame(zonalSt)
    df_concat = pd.concat([df, shape_gdf], axis=1)
    final_gdf = gpd.GeoDataFrame(df_concat, geometry=df_concat.geometry)
    return final_gdf

new_df = ZonalStats(shpfile, myraster,'mean')