text:
Q: Object  has no method 'methodeX' i get an error in chrome:
Uncaught TypeError: Object s1A has no method 'applyToSelection'
in Firefox(firebug) i get this:
TypeError: val.applyToSelection is not a function
i use the rangy-core and the rangy-cssclassappliere
my Code:
<script type="text/javascript">
    window.onload = function() {
    rangy.init();
      s1A = rangy.createCssClassApplier("css_1", true);
    };

   //this is the Problem.
   function dosome (el) {
      var val = el.value;
      val.applyToSelection();
   }
</script>

<body>
  <button value="s1A" onclick="dosome(this);">test</button>
</body>

if id do this:
<script type="text/javascript">
    window.onload = function() {
    rangy.init();
      s1A = rangy.createCssClassApplier("css_1", true);
    };
   function s1() {
      s1A.applyToSelection();
   }
</script>

<body>
  <button onclick="s1();">test</button>
</body>

it works fine. But i need it for an option field and i want to get the value

A: I suggest storing appliers in an object where each property name corresponds to an input value:
window.onload = function() {
    var appliers = {};
    rangy.init();
    appliers.s1A = rangy.createCssClassApplier("css_1", true);
};

function dosome(el) {
    var val = el.value;
    appliers[val].applyToSelection();
}


text:
Q: indenting exercises I am typing up homework problems and I would like a very specific format but I'm not sure where to begin.  I'd like the exercise numbers to line up in a column and then have the questions and the answers flush left with another "column" so to speak.  To get an idea of what I mean this simple code works:
\documentclass{article}

\begin{document}
\begin{tabular}{l l}
    5.  & This is the question          \\
        & This is where the answer goes \\

    11. & Another Questions             \\
        & Another Answer
\end{tabular}
\end{document}

This looks like what I want, but its annoying to put my whole assignment in a tabular environment and worry about alignment characters, ect.  What I would really like is an environment where I can specify the exercise number and it will create the proper layout for the question and answer.  Is this possible?  Thanks!

A: You can use an enumerate environment; the optional argument of \item allows you to assign the desired label:
\documentclass{article}
\usepackage[nopar]{lipsum}% just to generate text for the example

\begin{document}

\begin{enumerate}
\item This is the question.

And this is where the question goes. \lipsum[2]
\item[11.] This is another question.

And this is where the question goes. \lipsum[4]
\end{enumerate}

\end{document}

A: There are lots of ways to do this. A simple way using just an enumerate environment
\begin{enumerate}
  \item[5] This is the question.
  \item[] This is where the answer goes
\end{enumerate}

or perhaps you want your own environment; I've posted a few different options below- take your pick, or perhaps build one based off one of them.
\documentclass{article}
\usepackage{calc}

\newcommand{\question}[1]{\item[#1]}
\newcommand{\answer}{\item[]}
\newenvironment{questionandanswer}[2]{\enumerate\setcounter{enumi}{#2-1}\item#1\item[]}{\endenumerate}
\newenvironment{anotherapproach}{\enumerate}{\endenumerate}

\begin{document}

\begin{questionandanswer}{This is the question.}{5}
  This is where the answer goes
\end{questionandanswer}

\begin{anotherapproach}
  \question{5} This is the question.
  \answer This is where the answer goes
\end{anotherapproach}

\begin{enumerate}
  \item[5] This is the question.
  \item[] This is where the answer goes
\end{enumerate}
\end{document}

If you want to change the indentation of the enumerate environment, then the enumitem package is the most sensible way to go:
\documentclass{article}
\usepackage{calc}
\usepackage{enumitem}
\setlist[enumerate]{leftmargin=*}

A: If you're particular about having the spacing between the label, the following code, copied from Gonzalo's answer and modified suitably looks good to me:
\documentclass{article}
\usepackage{enumitem}%provides the key labelsep

\begin{document}

\begin{enumerate}[labelsep=*]
\item[5.] This is the question.

And this is where the question goes. I use \texttt{labelsep}=*
\item[11.] This is another question.

And this is where the question goes. I use \texttt{labelsep}=*
\end{enumerate}

\begin{enumerate}
\item[5.] This is the question.

And this is where the question goes. No \texttt{labelsep}=*
\item[11.] This is another question.

And this is where the question goes. No \texttt{labelsep}=*
\end{enumerate}

\end{document}

An Output:

redpajama_set_name: RedPajamaStackExchange


text:
Q: Php random number generate My task:
Generate random numbers between 1 and 20, to 1 decimal place.
However my issue as simple as mt_rand. I want most of the numbers generated to be lower around 0.5 - 4.5 with the occasional number being between 4.5-10 and very rarely say once every 12-20 hours being between 10-20.
I've been using the following but have no idea where to go from. I am a very basic self-taught programmer.
$min = 1;
$max = 20;
$suisse_interest = mt_rand ($min*10, $max*10) / 10

Maybe if I briefly explain why I want this it may help..
I own an online game and want to add 3 "banks" with each bank generating different interests each hour. Most of the time I want it low, but sometimes higher and very rarely very high (15-20%).
With the above code the random number goes too high to often.
Any help with this is greatly appreciated!

A: You need an exponential calculation. If you use a function similar to the following function, the probability for low numbers increases. Of course you need to adapt the numbers a bit to provide an output suiting your needs.
$i = 0;
while($i<30) {
    $i++;
    $rand = mt_rand(0, 7000) / 100; // 0.0 ~ 70.0
    // This is the most important line:
    $output = round( 20*(pow(0.95,$rand)) , 1);
    echo "$output ";
}

Sample output:

1.8  4.3  2.6  5.5  3.7  15.5  1.6  0.6  0.6  1.6  5.8
1.3  6.1  3.2  0.8  1.7  14.7  7.9  1.3  10.3  5.5  12.6
1.5  8.4  1.5  0.9  13.3  5.8  7.5  1.7
As you see, mostly smaller number are printed.

The probability to get 20 is around 1.4% in my code whereas the probability to get a number smaller than 5 is around 78%

A: Try this.The probability to 1.0~4.5 is around 96%, 4.5~10.0 is around 2%, and 10.0~20.0 is around 2%.
<?php
    // 1.0~4.5    96%
    // 4.5~10.0   2%
    // 10.0~20.0  2%

    function fun() {
        $num = mt_rand(1, 100);
        if ($num > 0 && $num <= 96) {
            $return = mt_rand(10, 45) / 10;  // 96%
        } else if ($num > 96 && $num <= 98) {
            $return = mt_rand(45, 100) / 10;  // 2%
        } else {
            $return = mt_rand(100, 200) / 10;  // 2%
        }
        return sprintf("%01.1f",$return);
    }

    echo fun();
?>

A: This is not a PHP-specific problem.
What you need is a non-linear probability law, that you can then implement in PHP.
If you want something centered around an average value, the ideal would be a gaussian aka normal distribution, but computing it requires various complicated tricks, most of them being optimized for rapid generation at the cost of increasing complexity.
If you generate only a few values each hour, performance will not be an issue.
A reasonable approximation would be to sum 3 or 4 random variables, taking advantage of the central limit theorem.
Summing random values between 0 and twice your middle rate will create an approximation of a gaussian centered around your middle value.
You can then clamp values inferior to the middle point if you don't want low rates. The net result would be 50% chances of getting middle rate and a steadily decreasing chance to get up to twice that value.
An increasing number of sums will "narrow" the curve, making it less likely to get a high value.
for instance:
define ("INTEREST_MEAN", 10);
define ("INTEREST_SPREAD", 5);
function random_interest ()
{
    $res = 0;
    for ($i = 0 ; $i != INTEREST_SPREAD ; $i++) $res += mt_rand(0, 2*INTEREST_MEAN);
    $res /= INTEREST_SPREAD; // normalize the sum to get a mean-centered result
    $res = max ($res, INTEREST_MEAN); // clamp lower values
}


text:
Q: Conditional navbar based on a user authentication status I'm trying to conditionally display navbar elements of a navigation component based on the onAuthStateChanged Firebase function.
<template>
    <navbar dark position="top" class="default-color" scrolling>
        <mdb-navbar-brand href="#/" style="font-weight: bolder;">
            Test
        </mdb-navbar-brand>
        <navbar-collapse>
            <navbar-nav left>
                <navbar-item href="#/" waves-fixed>Home</navbar-item>
                <navbar-item href="#/css" waves-fixed>About</navbar-item>
                <navbar-item href="#/jobs" waves-fixed>Jobs</navbar-item>
                <navbar-item href="#/advanced" waves-fixed>Profile</navbar-item>
            </navbar-nav>
            <navbar-nav right>
                <router-link to="/signup"><button v-if="!user" type="button" class="btn btn-primary">Signup</button></router-link>
                <router-link to="/login"><button v-if="!user" type="button" class="btn btn-primary">Login</button></router-link>

Logout

            </navbar-nav>
        </navbar-collapse>
    </navbar>
</template>

Unfortunately, for some reason, the onAuthStateChanged is not working. I also tried to simply display the user in the console from the component perspective, but it's not working as well:
console.log(firebase.auth().currentUser);

Thanks in advance for any hints.

A: I just wanted to point out another option.  Renaud Tarnec's answer is correct but there is a second solution.
You can use the arrow function syntax. With arrow functions the context doesnt change so there is no need to set vm = this before the function since this will still work inside the function.  I'm a huge fan of lambda/arrow functions and see no reason not to use them.
Renaud Tarnec's should be the accepted answer but just wanted to offer a second option :)
export default {
  name: 'Navigation',
  data() {
    return {
      user: null,
    };
  },
  components: {
    Navbar,
    NavbarItem,
    NavbarNav,
    NavbarCollapse,
    mdbNavbarBrand
  },
  methods: {
    ....
    }
  },
  created: function () {
      firebase.auth().onAuthStateChanged(user => {
        if (user) {
          this.user = user;
        } else {
          this.user = null;
        }
      });
   }
};

A: If you want to call firebase.auth().onAuthStateChanged() in the created lifecycle hook you should do as follows:
export default {
  name: 'Navigation',
  data() {
    return {
      user: null,
    };
  },
  components: {
    Navbar,
    NavbarItem,
    NavbarNav,
    NavbarCollapse,
    mdbNavbarBrand
  },
  methods: {
    ....
    }
  },
  created: function () {
      var vm = this;
      firebase.auth().onAuthStateChanged(function(user) {
        if (user) {
          vm.user = user;
        } else {
          vm.user = null;
        }
      });
   }
};

The way you do it, you are declaring created as a "standard" component method.


text:
Q: What can cause a .NET Core binary to load a native library, then throw a DllNotFoundException? I'm trying to run an SFML.NET game on MacOS having ported the game to .NET Core.
I have been unable to get SFML to load its native dependencies correctly at runtime, so I set up a minimal test example to try to isolate the issue, and still get the following error output (I have set DYLD_PRINT_LIBRARIES):
dyld: loaded: /System/Library/Frameworks/CoreData.framework/Versions/A/CoreData
dyld: loaded: /System/Library/Frameworks/ServiceManagement.framework/Versions/A/ServiceManagement
dyld: loaded: /System/Library/PrivateFrameworks/BackgroundTaskManagement.framework/Versions/A/BackgroundTaskManagement
dyld: loaded: /usr/lib/libxslt.1.dylib
dyld: loaded: /usr/local/share/dotnet/shared/Microsoft.NETCore.App/2.2.0/libclrjit.dylib
dyld: loaded: /usr/local/share/dotnet/shared/Microsoft.NETCore.App/2.2.0/System.Globalization.Native.dylib
dyld: loaded: /usr/local/share/dotnet/shared/Microsoft.NETCore.App/2.2.0/System.Native.dylib
Hello World!
dyld: loaded: /Users/ashley/RiderProjects/SFML.NET Test/SFML.NET Test/bin/Debug/netcoreapp2.2/libcsfml-window.dylib
dyld: unloaded: /Users/ashley/RiderProjects/SFML.NET Test/SFML.NET Test/bin/Debug/netcoreapp2.2/libcsfml-window.dylib
dyld: loaded: libcsfml-window.dylib
dyld: unloaded: libcsfml-window.dylib

Unhandled Exception: System.DllNotFoundException: Unable to load shared library 'libcsfml-window.dylib' or one of its dependencies. In order to help diagnose loading problems, consider setting the DYLD_PRINT_LIBRARIES environment variable: dlopen(liblibcsfml-window.dylib.dylib, 1): image not found
   at SFML.Window.VideoMode.sfVideoMode_getDesktopMode()
   at SFML.Window.VideoMode.get_DesktopMode() in /Users/ashley/SFML.Net/src/Window/VideoMode.cs:line 86
   at SFML.NET_Test.Program.Main(String[] args) in /Users/ashley/RiderProjects/SFML.NET Test/SFML.NET Test/Program.cs:line 12
dyld: unloaded: /usr/local/share/dotnet/shared/Microsoft.NETCore.App/2.2.0/libhostpolicy.dylib

The code I am trying to run is as follows:
using System;
using SFML.Graphics;
using SFML.Window;

namespace SFML.NET_Test
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            RenderWindow window = new RenderWindow(VideoMode.DesktopMode, "Test");
            while (true)
            {
            }
        }
    }
}

I have copies of the relevant native libraries in the running directory and the executable bin (this isn't a permanent set-up -- just while experimenting) and it seems to try to load both in sequence, before giving up and unloading them.
Given this, I'm basically wondering what can lead to this occurring?
I suspect it might indicate my library is the wrong version? (I've tried CSFML 2.2, 2.3, 2.5, so for my sanity's sake I hope this isn't the case) Or maybe there are missing dependencies that it's trying and failing to load? Is there any way to get further debug information out of dyld?
I've tried searching around about this, but it's quite difficult to find any useful resources so I'd appreciate pointers from people who understand the runtime linking system better.
I'm not entirely sure what extra information will be useful for helping answer this. My hope is that there's a specific, well-defined set of scenarios in which this behaviour can surface, which I can apply to fix my specific problem. Otherwise, I'm very happy to provide any additional information that helps.
My .NET Core version is 2.2.101

A: After the discussion in the comments it appears the pre-built binaries for SMFL have incorrect paths and filenames set within them. These type of issues can generally be solved by otool and install name tool utilities to inspect the binaries and then change the paths/name of the libraries that need to be loaded.
An example with otool -l might look like this:
$ otool -l /path/to/binary
Load command 2 <-- OLD
          cmd LC_ID_DYLIB
      cmdsize 40
         name libtest.dylib (offset 24)
   time stamp 1 Wed Dec 31 18:00:01 1969

To change the path you could do:
$ install_name_tool -id "@loader_path/../libtest.dylib" libtest.dylib

which would give you a new path such as:
Load command 2 <-- NEW
          cmd LC_ID_DYLIB
      cmdsize 64
         name @loader_path/../libtest.dylib (offset 24)

If you wanted to use rpath instead you could do:
$ install_name_tool -id "@rpath/libtest.dylib" libtest.dylib

I answered a previous question regarding rpath and loader_path which goes into more detail on the subject. Every scenario is potentially different in the case of loading dynamic libraries, so it really comes down to what you find out by investigating via otool -l.


text:
Q: Why am I get a warning "Dead code"?     if (myCondition1 && myCondition2 && myCondition3)
    {
    ...
    }

I wrote this code and run successfully. but I got warning about part of (...). The warning is "Dead code". It is just interesting to me. Do u have any idea?
thank u

A: "Dead code" is code that will never be executed. Most likely one of your conditions is hard-coded to false somewhere, making the conditional inside the if always false.

A: Dead code means it is never going to execute. E.g.
void someMethod() {
    System.out.println("Some text");
    return;
    System.out.println("Another Some text"); // this is dead code, because this will never be printed
}

Same in case of your condition checking e.g.
String obj = "";
if(obj == null && obj.equals("")) { // here you get warning for Dead code because obj is not null and first condition is false so obj.equals("") will never evaluate

}

A: Your code inside the block is never reached. The reason is most likely that one of the conditions is always false.

A: If one or more of myCondition1, myCondition2 and myCondition3 are always false (like private const bool myCondition1 = false;) then that code inside the if will never be executed.

A: This could occur for a number of reasons. Either the whole of the if block is dead, caused by something like the following:
boolean condition1 = true;
boolean condition 2 = !condition1;

if(condition1 && condition2) {
    //This code is all dead
    Foo f = fooFactory();
    f.barr(new Bazz());
}

Or you unconditionally leave the if block using something like return, break or continue, as shown below:
for(Foo f : foos) {
    if(true) {
        f.barr(new Bazz());
        break;
        //Everything after here is dead
        System.out.println("O noes. I won't get printed :(");
    }
}


text:
Q: Threading reading a serial port in Python (with a GUI) I want to trigger an event whenever there is data to be read from a serial port while running a GUI. The pySerial module apparently has experimental functionality for that, but it isn't particularly well documented (I couldn't find any useful examples in the API).
This question appears to deal with the same or at least very similar task, but doesn't provide instructions to replicate it or working code examples.
I came up with this code:
import tkinter as tk
import serial
import threading

# Create GUI window
window = tk.Tk()

# Initialize the port
myPort = serial.Serial('/dev/ttyUSB0')

# Function to call whenever there is data to be read
def readFunc(port):
    port.readline()
    print('Line read')

# Configure threading
t1 = threading.Thread(target = readFunc, args=[myPort])
t1.start()

# Main loop of the window
window.mainloop()

Running it does indeed trigger the event, but only once. Why is that? Is there a "recommended" way to do this as by using the functionality of pySerial itself?
Alternatively, I would also run the function to read and process data on an event like you can with GUI elements. If that is the better solution, how would that be done?
Related question (unanswered), probably makes this question a duplicate
Edit: Here is a minimal example derived from the answer below that changes the text of a label whenever data is read to the incoming data:
import tkinter as tk

from serial import Serial
from serial.threaded import ReaderThread, Protocol

app = tk.Tk()
label = tk.Label(text="A Label")
label.pack()

class SerialReaderProtocolRaw(Protocol):
    port = None

    def connection_made(self, transport):
        """Called when reader thread is started"""
        print("Connected, ready to receive data...")

    def data_received(self, data):
        """Called with snippets received from the serial port"""
        updateLabelData(data)

def updateLabelData(data):
    data = data.decode("utf-8")
    label['text']=data
    app.update_idletasks()

# Initiate serial port
serial_port = Serial("/dev/ttyACM0")

# Initiate ReaderThread
reader = ReaderThread(serial_port, SerialReaderProtocolRaw)
# Start reader
reader.start()

app.mainloop()

A: Your main concern is to be thread safe, when You are updating GUI from another running Thread.
To achieve this, we can use .after() method, which executes callback for any given tk widget.
Another part of Your request is to use Threaded serial reader.
This can be achieved by using ReaderThread accompanied with Protocol.
You can pick two protocols:

*

*raw data reader protocol, which reads data as they come

*line reader protocol, which enables us to read lines of data

Here is working code example, with two protocols mentioned above, so You can pick which one suits You. Just remember, that all data coming from serial port are just raw bytes.
import tkinter as tk

from serial import Serial
from serial.threaded import ReaderThread, Protocol, LineReader

class SerialReaderProtocolRaw(Protocol):
    tk_listener = None

    def connection_made(self, transport):
        """Called when reader thread is started"""
        if self.tk_listener is None:
            raise Exception("tk_listener must be set before connecting to the socket!")
        print("Connected, ready to receive data...")

    def data_received(self, data):
        """Called with snippets received from the serial port"""
        self.tk_listener.after(0, self.tk_listener.on_data, data.decode())

class SerialReaderProtocolLine(LineReader):
    tk_listener = None
    TERMINATOR = b'\n\r'

    def connection_made(self, transport):
        """Called when reader thread is started"""
        if self.tk_listener is None:
            raise Exception("tk_listener must be set before connecting to the socket!")
        super().connection_made(transport)
        print("Connected, ready to receive data...")

    def handle_line(self, line):
        """New line waiting to be processed"""
        # Execute our callback in tk
        self.tk_listener.after(0, self.tk_listener.on_data, line)

class MainFrame(tk.Frame):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.listbox = tk.Listbox(self)
        self.listbox.pack()
        self.pack()

    def on_data(self, data):
        print("Called from tk Thread:", data)
        self.listbox.insert(tk.END, data)

if __name__ == '__main__':
    app = tk.Tk()

    main_frame = MainFrame()
    # Set listener to our reader
    SerialReaderProtocolLine.tk_listener = main_frame
    # Initiate serial port
    serial_port = Serial("/dev/ttyUSB0")
    # Initiate ReaderThread
    reader = ReaderThread(serial_port, SerialReaderProtocolLine)
    # Start reader
    reader.start()

    app.mainloop()


text:
Q: Simplify multiple occurrences of the same formula Is it possible to simplify a SEDE query that has the same formula written multiple times?
For instance, this query is writing rtrim(LOWER(Title)) five times:
select
    rtrim(LOWER(p.Title)),
    count(rtrim(LOWER(p.Title)))
from Posts p
group by rtrim(LOWER(p.Title))
having (count(rtrim(LOWER(p.Title))) > 1)
order by count(rtrim(LOWER(p.Title))) desc

In answers, please specify if your factorisation is purely cosmetic or if it also has a performance impact.

A: Based on the link for your query, it looks like you're using the LOWER() and RTRIM() functions for the sake of comparison.
TSQL by default is case-insensitive, and trailing spaces to the right are ignored.  You can get the same results via the following:
Select      Lower(P.Title), Count(P.Title)
From        Posts   P
Group By    Lower(P.Title)
Having      Count(P.Title) > 1
Order By    Count(P.Title) Desc

A: First - the permanent solution here is to clean up your data. Using functions like LTRIM, RTRIM, UPPER, LOWER makes your not SARGEable. In other words your queries can slow to a crawl because it's impossible for SQL Server to retrieve the data you need from an index without scanning all rows.

For instance, this query is writing rtrim(LOWER(Title)) five times:

Enter the APPLY + VALUES inline aliasing trick
This is something I came up with some time ago at first to simplify my code but I later discovered some occasional performance benefits which I'll demonstrate. First some sample data:
use tempdb;
go

create table dbo.sometable(someid int identity, somevalue decimal(10,2));
insert dbo.sometable(somevalue) values (100),(1050),(5006),(111),(4);

Let's say we have a query that takes a few variables or parameters, performs a calculation on them and uses that value throughout a query. Note the case statement below.
declare @var1 int = 100, @var2 int = 50, @var3 int = 900;

select
  someid,
    somevalue,
    someCalculation =
      case when @var3 < somevalue then (@var1 / (@var2*2.00))+@var3 else @var3+somevalue end,
  someRank = dense_rank() over (order by
      case when @var3 < somevalue then (@var1 / (@var2*2.00))+@var3 else @var3+somevalue end)
from dbo.sometable
where case when @var3 < somevalue then (@var1 / (@var2*2.00))+@var3 else @var3+somevalue end
  between 900 and 2000
order by case when @var3 < somevalue then (@var1 / (@var2*2.00))+@var3 else @var3+somevalue end;

We can simplify this query like this:
select
  someid,
  somevalue,
  someCalculation = i.v,
  someRank = dense_rank() over (order by i.v)
from dbo.sometable
cross apply (values
(
  case when @var3 < somevalue then (@var1/(@var2*2.00))+@var3 else @var3+somevalue end)
) i(v)
where i.v between 900 and 2000
order by i.v;

Each query returns identical results. Now the execution plans:

Not only have we simplified our query, we've actually sped it up. In my original query the optimizer had to calculate the same value twice and perform two sorts. Using my inline aliasing trick I was able to remove a sort and a calculation


text:
Q: Grouping with TRUE/FALSE in Tidyverse I have a dataset with the following layout (random example):
set.seed(1)

data <- tibble(A = sample(c(TRUE, FALSE), 10, replace = T), B = sample(c(TRUE, FALSE), 10, replace = T), C = sample(c(TRUE, FALSE), 10, replace = T), value = sample(1:100, 10))

For each combination of A, B and C I want to calculate the mean(value). Ideally, I want a new tidy tibble with these combinations of A, B and C and the result (including A, AB, ABC, AC, etc - all possible combinations of A/B/C if).
Here, rows 1,3 and 4 are all ABC which would result in
ABC - mean(89, 79, 33)
For row 2,5
B,C - mean(44,84)
How would I go about this?

A: A simple solution is to use dplyr: group_by the variables A, B, C, then summarise the mean of the values:
library(dplyr)
dat2<-dat%>%
  group_by(A,B,C)%>%
  summarise(Mean = mean(value))


text:
Q: Two different domain for specific languages pointing to one site I am developing a blog for a client and he needs it to be bilingual (English and Spanish). Now what he wants is that the users can get to the content with correct language based on the domain; e.g. John enters www.domain.com and he gets the English version and Juan enters www.elsenordominio.com to get the Spanish version.
All content will be validated by PHP so the users and search engines only reads the domain related language.
What do I need to use header re-direct or 301? Is it bad for SEO? Will google penalize me?


text:
Q: How to open .ccproj in VS2010? How to open .ccproj projects types in VS2010, ccproj file type is a Cloud project i suppose.
Please provide inputs.

A: Download and install Windows Azure SDK and Windows Azure Tools for Microsoft Visual Studio (March 2011)

A: The link above is good but points to a specific version of the SDK. As such, it is subject to obsolescence. The following seems to be a generic page for the Azure SDK, which should not be bind to a specific version:
http://www.microsoft.com/windowsazure/sdk/
You can get from there a link to the latest download (button "Get the SDK").


text:
Q: Regex : Find a number between space I am trying to extract a zip code of six numbers starting with the number 4 from a string. Right now I am using [4][0-9]{5}, but it is also matching starting from other numbers, like 020-25468811 and it's returning 468811. I don't want it to search in the middle of a number, only full numbers.

A: Try to use the following:
(?<!\d)4\d{5}(?!\d)

I.e. find 6-digit number starting with 4 and not preceded or followed by digit.

A: Your expression right now tries to match any six numbers consisting of a 4 with five numbers between 0 and 9. To fix this behavior you should add word boundaries as per Jon's suggestion.
\b[4][0-9]{5}\b

More on word boundaries here: http://www.regular-expressions.info/wordboundaries.html

A: You could simply add a space to the beginning of your regular expression " 4[0-9]{5}". If you need a more universal way of finding the beginning of the number (could it maybe be also be tabulator, a newline, etc?) you should have look at the predefined character class \s. Also have a look at boundary matchers. I dont know which language you are using, but regex work very similar in most languages. Check this Java regex documentation.

A: There is a start of line character in regex: ^
You could do:
^4[0-9]{5}

If the numbers are not always in the beginning of a line, you can more generally use:
\<4[0-9]{5}\>

To match only whole words.
Both examples work with egrep.


text:
Q: Category of $\mathcal{D}$-modules on a singular variety Take $X\to V$ a closed embedding, where $X$ is not necessarily smooth, $V$ is affine and smooth. Define the category $\mathcal{C}$ of $\mathcal{D}$ modules on $X$ to be the full subcategory of $\mathcal{D}$ modules on $V$ with support on $X$.
I want to ask if the inclusion $D(\mathcal{C})\to D_\mathcal{C}(\mathcal{D}_V\text{-mod})$ is an equivalence (where $D_\mathcal{C}(\mathcal{D}_V\text{-mod})$ is the full subcategory of $D(\mathcal{D}_V\text{-mod})$ consisting complexes with cohomologies in $\mathcal{C}$). I believe it is. In fact for what I really need, I only need the inclusion to be fully faithful, but nevertheless it should be an equivalence. The derived category is the one with either quasi-coherent or coherent objects, and should be bounded. Note when $X$ is smooth, this is just a version of Kashiwara's Theorem.
What we know: $\mathcal{C}$ is thick/Serre, $\mathcal{C}$ and $\mathcal{D}_V\text{-mod}$ are Grothedieck (so has enough injectives).
There is a potential useful theorem in Kashiwara-Schapira Category and Sheaves, Theorem 13.2.8, but I don't know how to show the conditions. Also, these overflow questions can be useful: Equivalence between a derived subcategory and a subcategory of the derived category
Derived category of $\mathcal{D}_X$ modules
Edited later: Actually there is more to ask: similar to Derived category of $\mathcal{D}_X$ modules, is the same result still true for singular $X$, because normally Kashiwara's theorem is stated using 'the other' version of derived category instead of the version I am using (and they turn out to be the same in the smooth case), but I probably don't need this...

A: I'm going to assume that we're dealing with bounded-below complexes, as I'm most familiar with those.
Denote by $\Gamma_X$ the sections-supported-on-$X$ functor, i.e.
$$\Gamma(U, \Gamma_X(\mathcal{F})) = \ker\left(\Gamma(U; \mathcal{F}) \xrightarrow{\text{restriction}} \Gamma(U\setminus X; \mathcal{F})\right).$$
Let $\mathcal{M}^\bullet$ be a bounded-below complex of $\mathcal{D}_V$-modules whose cohomology is supported on $X$. It suffices to show that $\mathcal{M}^\bullet$ is quasi-isomorphic to a complex of objects in $\mathcal{C}$.
I claim that the inclusion $i^\bullet\colon \Gamma_X(\mathcal{M}^\bullet) \hookrightarrow \mathcal{M}^\bullet$ is a quasi-isomorphism. I do this by induction on the cohomological degree $p$.
When $p\ll 0$, both complexes vanish, so $H^p\Gamma_X(\mathcal{M}^\bullet) = H^p(\mathcal{M}^\bullet) = 0$, and therefore $H^p(i^\bullet)$ is trivially an isomorphism.
Assume we know that $H^{p-1}(i^\bullet)$ is an isomorphism. Consider the short exact sequence
$$0 \to \Gamma_X(\mathcal{M}^\bullet) \to \mathcal{M}^\bullet \to \mathcal{M}^\bullet/\Gamma_X(\mathcal{M}^\bullet) \to 0.$$
This gives rise to an exact sequence
$$  H^{p-1}(\mathcal{M}^\bullet) \to  H^{p-1}(\mathcal{M}^\bullet/\Gamma_X(\mathcal{M}^\bullet)) \to H^{p-1}(\mathcal{M}^\bullet/\Gamma_X(\mathcal{M}^\bullet)) \to H^p(\Gamma_X(\mathcal{M}^\bullet)) \to H^p(\mathcal{M}^\bullet) \to  H^p(\mathcal{M}^\bullet/\Gamma_X(\mathcal{M}^\bullet)).\tag{1}
$$
By the induction hypothesis, the first map is an isomorphism, so (1) gives the exact sequence
$$
0\to H^{p-1}(\mathcal{M}^\bullet/\Gamma_X(\mathcal{M}^\bullet)) \xrightarrow{a} H^p(\Gamma_X(\mathcal{M}^\bullet)) \xrightarrow{H^p(i^{\bullet})} H^p(\mathcal{M}^\bullet) \xrightarrow{b}  H^p(\mathcal{M}^\bullet/\Gamma_X(\mathcal{M}^\bullet)).\tag{2}
$$
For each $q$, no non-zero section of $\mathcal{M}^q/\Gamma_X(\mathcal{M}^q)$ vanishes outside of $X$ (prove this!), so the same is true of each $H^q(\mathcal{M}^\bullet/\Gamma_X(\mathcal{M}^\bullet))$. On the other hand, every non-zero section of $H^q(\mathcal{I}^\bullet)$ and $H^q(\Gamma_X(\mathcal{I}^\bullet))$  vanishes outside of $X$ (the first by hypothesis and the second because by the definition of $\Gamma_X$). Therefore, $a$ and $b$ must be the zero map. Hence, $H^p(i^{\bullet})$ is an isomorphism.
Edit 1: To see fully faithfulness: $\Gamma_X\colon \mathcal D_V\text{-mod} \to \mathcal{C}$ preserves injectives (because it is right adjoint to the inclusion functor, which is fully faithful). Therefore, the hom sets in $D^+(\mathcal C)$ and $D^+_X(\mathcal D_V)$ are computed in the same way.
Edit 2 (2019/10/06): Using the following fact, along with the non-crossed-out part of Edit 1, I am going to prove fully faithfulness.

Fact. Although in general, a morphism $u$ between bounded below complexes with $H^n(u)=0$ for all $n$ is not necessarily $0$ in the derived category, if such a morphism $u$ maps between complexes of injectives, then it is $0$. (See, e.g., the proof of Prop. 1.7.10 from Kashiwara and Schapira's Sheaves on Manifolds).

Let $\mathcal{M}^\bullet, \mathcal{N}^\bullet$ be bounded below complexes of objects of $\mathcal{C}$. Choose $\mathcal{D}_V$-injective resolutions $\mathcal{I}^\bullet,\mathcal{J}^\bullet$ of $\mathcal{M}^\bullet, \mathcal{N}^\bullet$, respectively. Because $\Gamma_X(\mathcal{M}^\bullet)=\mathcal{M}^\bullet$ (as $\mathcal{M}^\bullet$ is a complex of guys in $\mathcal{C}$), the resolving quasi-isomorphism $\mathcal{M}^\bullet \to \mathcal{I}^\bullet$ factors through the natural inclusion $\Gamma_X(\mathcal{I}^\bullet) \hookrightarrow \mathcal{I}^\bullet$. Hence, because by the above, the natural inclusion $\Gamma_X(\mathcal{I}^\bullet) \hookrightarrow \mathcal{I}^\bullet$ is a quasi-isomorphism, we get a quasi-isomorphism (i.e. a resolution) $\mathcal{M}^\bullet\to \Gamma_X(\mathcal{I}^\bullet)$. But $\Gamma_X(\mathcal{I}^\bullet)$ is a complex of $\mathcal{C}$-injectives, so we in fact have a $\mathcal{C}$-injective resolution
$$ \mathcal{M}^\bullet\to \Gamma_X(\mathcal{I}^\bullet)$$
of $\mathcal{M}^\bullet$. Similarly,
$$\mathcal{N}^\bullet\to \Gamma_X(\mathcal{J}^\bullet)$$
is a $\mathcal{C}$-injective resolution of $\mathcal{N}^\bullet$.
Replacing $\mathcal{M}^\bullet$ and $\mathcal{N}^\bullet$ with $\Gamma_X(\mathcal{I}^\bullet)$ and $\Gamma_X(\mathcal{J}^\bullet)$, resp., it is enough to show that

*

*for every morphism $u^\bullet\colon \Gamma_X(\mathcal{I}^\bullet)\to \Gamma_X(\mathcal{J}^\bullet)$, there exists a unique (in $D^+_X(\mathcal{D}_V)$) morphism $v^\bullet\colon \mathcal{I}^\bullet\to \mathcal{J}^\bullet$ extending $u^\bullet$; and

*if $u^\bullet=0$ in $\mathcal{D}^+(\mathcal{C})$, then $v^\bullet=0$ in in $D^+_X(\mathcal{D}_V)$.
Let $i^\bullet,j^\bullet$ be, resp., the inclusions $\Gamma_X(\mathcal{I}^\bullet) \hookrightarrow \mathcal{I}^\bullet$ and $\Gamma_X(\mathcal{J}^\bullet) \hookrightarrow \mathcal{J}^\bullet$. The existence of $v^\bullet$ is because everything in town is injective. Then 2. and the remaining part of 1. follow from the Fact together with the equation
$$ v^\bullet\circ i^\bullet = j^\bullet\circ u^\bullet.$$


text:
Q: UndefVarError st not defined. I have no variable called st in my code Homework question to return path tupples of path of least weight in a matrice. However the code gives me an error as: UndefVarError st not defined?
I have tried running the program without the for loops, and returning just s, and that works.
function backtrack(pathweights)
    s = size(pathweights)[1]
    bestpath = []
    a = argmin(pathweights[:, s])
    push!(bestpath, (size(pathweights)[1]-1,a))

    for j = size(pathweights)[1]:-1:1
        b = argmin(pathweights[:, j])
        for i = 1: size(pathweights)
            if isdefined[pathweights[b+1,j-1]] &&
            isdefined[pathweights[b-1,j-1]]
                push!(bestpath, (min(pathweights[b, j-1],
                pathweights[b-1,j-1], pathweights[b+1, j-1]), j))
            else if isempty[pathweights[a+1,j-1]]
                push!(bestpath, (min(pathweights[b-1, j-
                1],pathweights[b, j-1]), j))
            else
                push!(bestpath, (min(pathweights[b, j-1],
                pathweights[b+1,j-1]), j))
            end
        end
    end
    return bestpath
 end

Iinput:
pathweights = [3  6  8  6  3
              10 9  11 10 6
              13 19 13 7  12
              23 17 10 8  9
              23 11 15 11 17]
Expected output:
bestpath = [(5,2), (4,3), (3,4), (2,5), (1,5)]

A: It looks like you're using Juno and are trying to evaluate a file which contains an error.
This bug was reported here and fixed by this commit, so please update to Atom.jl 0.11.1 (with using Pkg; Pkg.update() and try again.


text:
Q: How to rectify 'Index was outside the bounds of the array (Microsoft.sqlserver.Express.smo)' in SQL Server 2012? I am using SQL Server 2012 Management Studio Express.
I installed this few days back. when i try to create a new database or new table, I am getting the below error message:

Cannot show requested dialog.
ADDITIONAL INFORMATION:
Cannot show requested dialog. (Microsoft.SqlServer.Express.SqlMgmt)
Index was outside the bounds of the array. (Microsoft.SqlServer.Express.Smo)

I tried installing some service packs. But nothing worked.
Can you please help me out of this issue.
Thanks in advance.

A: if you are using the interface of the Management Studio to create a database or a table then try writing the query by clicking New Query on the top left corner of the management studio.
for creating a new database use :
   CREATE DATABASE database_name

to use the database after creating it :
   USE database_name


text:
Q: How to pass multiple enum types as method arguments and then call common methods on them? Our issue is like this:
We want to pass different enum types to a method and call the values() method on the type.
public enum Testing {
    A, B, C, D
}

public enum Retesting {
    E, F, G, H
}

public static Object[] getValues(Enum e) {
    return e.values(); // ! Compilation Error
}

public static void main(String[] args) {
    Testing t = Testing.A;
    getValues(t);
}

Does anyone know if how something like this should be achieved or if it's possible at all?
Thank you

A: Try using:
e.getClass().getEnumConstants()

A: Here is a solution using reflection.  But I like @korifey's answer better.  :)
@SuppressWarnings("unchecked")
public static <T extends Enum<T>> T[] getValues(Class<T> e) throws IllegalArgumentException, SecurityException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    return (T[]) e.getMethod("values").invoke(null);
}

public static void main(String[] args) throws IllegalArgumentException, SecurityException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    System.out.println(Arrays.asList(getValues(Testing.class)));
}

A: Both @korifey and @Matt McHenry are right (+1 to each one).
I personally think that in your case korifey's way is preferable.
I just wanted to add that your method signature may be:
getValues(Enum e) {
....
}
because all enums are ordinary classes that extend class Enum;


text:
Q: Tensorflow Neural Network for Regression I am using tensor flow library to build a pretty simple 2 layer artificial neural network to perform linear regression.
My problem is that the results seem to be far from expected. I've been trying to spot my mistake for hours but no hope. I am new to tensor flow and neural networks so it could be a trivial mistake. Could anyone have an idea what i am doing wrong?
from __future__ import print_function

 import tensorflow as tf
 import numpy as np
 # Python optimisation variables
 learning_rate = 0.02

data_size=100000
data_length=100
train_input=10* np.random.rand(data_size,data_length);
train_label=train_input.sum(axis=1);
train_label=np.reshape(train_label,(data_size,1));

test_input= np.random.rand(data_size,data_length);
test_label=test_input.sum(axis=1);
test_label=np.reshape(test_label,(data_size,1));

x = tf.placeholder(tf.float32, [data_size, data_length])
y = tf.placeholder(tf.float32, [data_size, 1])

W1 = tf.Variable(tf.random_normal([data_length, 1], stddev=0.03), name='W1')
b1 = tf.Variable(tf.random_normal([data_size, 1]), name='b1')

y_ = tf.add(tf.matmul(x, W1), b1)

cost = tf.reduce_mean(tf.square(y-y_))
optimiser=tf.train.GradientDescentOptimizer(learning_rate=learning_rate)
.minimize(cost)

init_op = tf.global_variables_initializer()

correct_prediction = tf.reduce_mean(tf.square(y-y_))
accuracy = tf.cast(correct_prediction, tf.float32)

with tf.Session() as sess:
  sess.run(init_op)
  _, c = sess.run([optimiser, cost],
                     feed_dict={x:train_input , y:train_label})
  k=sess.run(b1)
  print(k)
  print(sess.run(accuracy, feed_dict={x: test_input, y: test_label}))

Thanks for your help!

A: There are a number of changes you have to make in your code.
First of all, you have to perform training for number of epochs and also feed the optimizer training data in batches. Your learning rate was very high. Bias is supposed to be only one input for every dense (fully connected) layer. You can plot the cost (loss) value to see how your network is converging.
In order to feed data in batches, I have made the changes in placeholders also. Check the full modified code:
from __future__ import print_function

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
# Python optimisation variables
learning_rate = 0.001

data_size=1000  # Had to change these value to fit in my memory
data_length=10
train_input=10* np.random.rand(data_size,data_length);
train_label=train_input.sum(axis=1);
train_label=np.reshape(train_label,(data_size,1));

test_input= np.random.rand(data_size,data_length);
test_label=test_input.sum(axis=1);
test_label=np.reshape(test_label,(data_size,1));

tf.reset_default_graph()
x = tf.placeholder(tf.float32, [None, data_length])
y = tf.placeholder(tf.float32, [None, 1])

W1 = tf.Variable(tf.random_normal([data_length, 1], stddev=0.03), name='W1')
b1 = tf.Variable(tf.random_normal([1, 1]), name='b1')

y_ = tf.add(tf.matmul(x, W1), b1)

cost = tf.reduce_mean(tf.square(y-y_))
optimiser=tf.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(cost)

init_op = tf.global_variables_initializer()

EPOCHS = 500
BATCH_SIZE = 32
with tf.Session() as sess:
    sess.run(init_op)

    loss_history = []
    for epoch_no in range(EPOCHS):
        for offset in range(0, data_size, BATCH_SIZE):
            batch_x = train_input[offset: offset + BATCH_SIZE]
            batch_y = train_label[offset: offset + BATCH_SIZE]

            _, c = sess.run([optimiser, cost],
                     feed_dict={x:batch_x , y:batch_y})
            loss_history.append(c)

    plt.plot(range(len(loss_history)), loss_history)
    plt.show()

    # For running test dataset
    results, test_cost = sess.run([y_, cost], feed_dict={x: test_input, y: test_label})
    print('test cost: {:.3f}'.format(test_cost))
    for t1, t2 in zip(results, test_label):
        print('Prediction: {:.3f}, actual: {:.3f}'.format(t1[0], t2[0]))


text:
Q: NSInternalInconsistencyException while adding Core Data into an application I am adding Core Data into an existing application, I am following these steps:

*

*Importing the framework

*Creating the model
In addition to set up the stack, I'm using the following code:
- (NSManagedObjectContext *) managedObjectContext {
    if (managedObjectContext != nil) {
        return managedObjectContext;
    }
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) {
        managedObjectContext = [[NSManagedObjectContext alloc] init];
        [managedObjectContext setPersistentStoreCoordinator: coordinator];
    }

    return managedObjectContext;
}

- (NSManagedObjectModel *)managedObjectModel {
    if (managedObjectModel != nil) {
        return managedObjectModel;
    }
    managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain];

    return managedObjectModel;
}

-(NSPersistentStoreCoordinator *)persistentStoreCoordinator {

    if (persistentStoreCoordinator != nil) {
        return persistentStoreCoordinator;
    }

    NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"xxxxx.sqlite"]];

    NSError *error = nil;
    persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: [self managedObjectModel]];
    if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:nil error:&error]) {
       // Handle error
    }

    return persistentStoreCoordinator;
}

- (NSString *)applicationDocumentsDirectory {
    return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}

But when I am trying to save data I get the following execption

Terminating app due to uncaught exception
  NSInternalInconsistencyException, reason: 'This
  NSPersistentStoreCoordinator has no persistent stores.  It cannot
  perform a save operation.'

A: This problem could be do to the fact you have run the application and then you have changed the model.
The simplest solution is to delete the application from the simulator/device, then performing a Clean, and trying again.
The more correct solution is to deal with light migration as suggested in I keep on getting "save operation failure" after any change on my XCode Data Model.
A simple suggestion is to enable Core Data logs as suggested in XCode4 and Core Data: How to enable SQL Debugging and see what is going under the hood.
Hope that helps.


text:
Q: Rails with nginx not serving CSS or JS with HTTPS I have a rails 4 application configured to use passenger and nginx. The application works as expected over HTTP, however when I use HTTPS the CSS and JS files are not served (although the images and text are).
My nginx config file is as follows:
server {
        listen       80;
        listen 443 ssl;
        server_name  divvyup.com.au;
        root /home/duroot/www/rails/DivvyUp/current/public;
        ssl_certificate      divvyup.com.au.chained.crt;
        ssl_certificate_key  divvyup.com.au.key;
        ssl_protocols       TLSv1 TLSv1.1 TLSv1.2;
        ssl_ciphers         HIGH:!aNULL:!MD5;
        passenger_enabled on;
        location /assets/ {
                gzip_static on;
                expires max;
                add_header Cache-Control public;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }

My production.rb file contains:
config.cache_classes = true
  config.eager_load = true
  config.consider_all_requests_local       = false
  config.action_controller.perform_caching = true
  config.serve_static_assets = false
  config.assets.js_compressor = :uglifier
  config.assets.compile = false
  config.assets.precompile << /(^[^_\/]|\/[^_])[^\/]*$/
  config.assets.digest = true
  config.assets.version = '1.0'
  config.force_ssl = false

Any help would be great...

A: I found the answer to this.
I had set the asset_host directive to include http: forcing the assets to be served as HTTP.
Updating the directive as follows resolved the issue:
config.action_controller.asset_host = 'www.divvyup.com.au'


text:
Q: Sending in-app email I need to send an email without exiting the application as the subject and body are already set by the application. I already know how to send an email but I need to exit the application to the email application and click on send to go back to my application. Can't I just send the email without exiting or at least without needing to click on send button, can't there be some sort of a framework that auto-sends the email?
Kind Regards,
Heba

A: Here's the code:
(Don't forget to add the messageUI framework to your project!!!)
First import the message framework:
#import <MessageUI/MessageUI.h>

then mark your self as a delegate like this
@interface MYViewController () <MFMailComposeViewControllerDelegate>

then to pull up the composer:
- (IBAction)supportPressed:(id)sender
{
    if ([MFMailComposeViewController canSendMail]) {
        MFMailComposeViewController *composeViewController = [[MFMailComposeViewController alloc] initWithNibName:nil bundle:nil];
        [composeViewController setMailComposeDelegate:self];
        [composeViewController setToRecipients:@[@"example@email.com"]];
        [composeViewController setSubject:@"example subject"];
        [self presentViewController:composeViewController animated:YES completion:NULL];
    }
}

Then to handle the delegate callback and dismiss the composer:
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
{
    //Add an alert in case of failure
    [self dismissViewControllerAnimated:YES completion:nil];
}

A: You can use MFMailComposeViewController to send in-app email. You can use this code inside one of your view controllers (for example, in response to a button press). Note that you will need to add the MessageUI framework to your app.
#import <MessageUI/MessageUI.h>

The code to present the mail view controller:
MFMailComposeViewController *mail = [[[MFMailComposeViewController alloc] init] autorelease];

mail.mailComposeDelegate = self;

[mail setToRecipients:[NSArray arrayWithObject:@"email@example.com"]];
[mail setSubject:@"Set The Subject Here"];

[self presentModalViewController:mail animated:YES];

See the documentation for how to implement the mailComposeDelegate - you can use this to dismiss the modal view controller when the email is sent or the user has canceled the task.

A: Look for MFMailComposeViewController . Also refer this post

A: To send email within the app you can use the MFMailComposeViewController class.
Like this:
if( [MFMailComposeViewController canSendMail] ) {
    MFMailComposeViewController *mailViewController = [[MFMailComposeViewController alloc] init];
    [mailViewController setRecipients:[NSArray arrayWithObject:@"mail@address.com"]];
    [self.navigationController presentModalViewController:mailViewController animated:YES];
    [mailViewController release];
}

A: Use this short code if you are not able to hard code: < a href="mailto:example@example.com" >Send Mail< /a >


text:
Q: qobject_cast always returns NULL? I'm trying to cast from QObject* to QSlider* with qobject_cast, but through debugging, the variable cObj is not NULL, but vNumSlider is NULL.
here is some related snippet in .cpp
int main(int argc, char *argv[]) {
    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    QQmlComponent component(&engine,QUrl(QStringLiteral(MAIN_FORM)));
    QObject *obj = component.create();
    QObject *cObj = obj->findChild<QObject*>("vNumSlider");
    QSlider *vNumSlider = qobject_cast<QSlider*>(cObj);
    delete obj;
    return app.exec();
}

and .qml
Slider {
    id: vNumSlider
    objectName: "vNumSlider"
    maximumValue: 130
    x: 85
    y: 12
}


text:
Q: Change angular-material for a $mdDialog I want to remove the gray background when you hover over the 'yes' and 'no' buttons of my $mdDialog.  I have managed to change the color of the text by changing it in the angular-material.css.  Any ideas?
Here is a pic of the 'NO' and 'YES' buttons I am referring to:

A: First of all, do not modify original sources of the library. Once you decide to update it to a newer version, all of your changes will be lost. Much better practice is to override original styles with your own. In order to do that, create a separate css file and add it to your site after angular-material.css.
To modify background color of buttons in a dialog, you need the following code:
md-dialog .md-button:not([disabled]):hover {
    background-color: transparent !important;
}

.md-button:not([disabled]):hover is a class responsible for styling hover color of md-button controls. In this case, !important is needed to override original color of buttons. Finally, md-dialog at the beginning ensures that your styles will be applied only inside dialogs.
Update 1 - Alternative solution
Another but more complicated solution is creating a custom confirmation dialog. This way you can completely change appearence of the dialog by using your own template. You can find more about custom dialogs in the Angular Material documentation:
https://material.angularjs.org/latest/demo/dialog


text:
Q: Installing Ruby in AIX 7.2 using YUM Issue : After successful installation of Ruby in AIX 7.2 using YUM, the error below show after running gem search puppet. Google does not provide any details for the error below, but I'm suspecting it is related to OpenSSL.
SERVER DETAILS :
Operating System : AIX
bash-4.4# oslevel
7.2.0.0
bash-4.4# ruby -v
ruby 2.4.4p296 (2018-03-28 revision 63013) [powerpc-aix6.1.0.0]
bash-4.4# gem -v
2.6.14.1

ERROR DETAILS :
bash-4.4# gem search puppet

REMOTE GEMS
/opt/freeware/lib64/ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require': load failed - /opt/freeware/lib64/ruby/2.4.0/powerpc-aix6.1.0.0/openssl.so. Please issue below command for detailed reasons: (LoadError)
        /usr/sbin/execerror ruby "30 /opt/freeware/lib64/ruby/2.4.0/powerpc-aix6.1.0.0/openssl.so" "36 X509_REVOKED_dup 475 /usr/lib/libcrypto.a[libcrypto64.so.1.0.0]" "36 X509_STORE_CTX_get0_store 633 /usr/lib/libcrypto.a[libcrypto64.so.1.0.0]" "36 SSL_is_server 796 /usr/lib/libssl.a[libssl64.so.1.0.0]" "36 SSL_get0_alpn_selected 837 /usr/lib/libssl.a[libssl64.so.1.0.0]" "36 SSL_CTX_set_alpn_select_cb 838 /usr/lib/libssl.a[libssl64.so.1.0.0]" "36 SSL_CTX_set_alpn_protos 839 /usr/lib/libssl.a[libssl64.so.1.0.0]" "2 /opt/freeware/lib64/ruby/2.4.0/powerpc-aix6.1.0.0/openssl.so" "6 8"
        from /opt/freeware/lib64/ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require'
        from /opt/freeware/lib64/ruby/2.4.0/openssl.rb:13:in `<top (required)>'
        from /opt/freeware/lib64/ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require'
        from /opt/freeware/lib64/ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require'
        from /opt/freeware/lib64/ruby/2.4.0/net/https.rb:23:in `<top (required)>'
        from /opt/freeware/lib64/ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require'
        from /opt/freeware/lib64/ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require'
        from /opt/freeware/lib64/ruby/2.4.0/rubygems/request.rb:49:in `configure_connection_for_https'
        from /opt/freeware/lib64/ruby/2.4.0/rubygems/request/https_pool.rb:6:in `setup_connection'
        from /opt/freeware/lib64/ruby/2.4.0/rubygems/request/http_pool.rb:39:in `make_connection'
        from /opt/freeware/lib64/ruby/2.4.0/rubygems/request/http_pool.rb:20:in `checkout'
        from /opt/freeware/lib64/ruby/2.4.0/rubygems/request.rb:132:in `connection_for'
        from /opt/freeware/lib64/ruby/2.4.0/rubygems/request.rb:187:in `perform_request'
        from /opt/freeware/lib64/ruby/2.4.0/rubygems/request.rb:156:in `fetch'
        from /opt/freeware/lib64/ruby/2.4.0/rubygems/remote_fetcher.rb:368:in `request'
        from /opt/freeware/lib64/ruby/2.4.0/rubygems/remote_fetcher.rb:251:in `fetch_http'
        from /opt/freeware/lib64/ruby/2.4.0/rubygems/remote_fetcher.rb:292:in `fetch_path'
        from /opt/freeware/lib64/ruby/2.4.0/rubygems/remote_fetcher.rb:327:in `cache_update_path'
        from /opt/freeware/lib64/ruby/2.4.0/rubygems/source.rb:190:in `load_specs'
        from /opt/freeware/lib64/ruby/2.4.0/rubygems/spec_fetcher.rb:263:in `tuples_for'
        from /opt/freeware/lib64/ruby/2.4.0/rubygems/spec_fetcher.rb:227:in `block in available_specs'
        from /opt/freeware/lib64/ruby/2.4.0/rubygems/source_list.rb:98:in `each'
        from /opt/freeware/lib64/ruby/2.4.0/rubygems/source_list.rb:98:in `each_source'
        from /opt/freeware/lib64/ruby/2.4.0/rubygems/spec_fetcher.rb:223:in `available_specs'
        from /opt/freeware/lib64/ruby/2.4.0/rubygems/spec_fetcher.rb:148:in `detect'
        from /opt/freeware/lib64/ruby/2.4.0/rubygems/commands/query_command.rb:175:in `show_gems'
        from /opt/freeware/lib64/ruby/2.4.0/rubygems/commands/query_command.rb:117:in `block in execute'
        from /opt/freeware/lib64/ruby/2.4.0/rubygems/commands/query_command.rb:117:in `each'
        from /opt/freeware/lib64/ruby/2.4.0/rubygems/commands/query_command.rb:117:in `execute'
        from /opt/freeware/lib64/ruby/2.4.0/rubygems/command.rb:310:in `invoke_with_build_args'
        from /opt/freeware/lib64/ruby/2.4.0/rubygems/command_manager.rb:169:in `process_args'
        from /opt/freeware/lib64/ruby/2.4.0/rubygems/command_manager.rb:139:in `run'
        from /opt/freeware/lib64/ruby/2.4.0/rubygems/gem_runner.rb:55:in `run'
        from /usr/bin/gem:21:in `<main>'

Output of  ruby -v -ropenssl -rfiddle -e 'puts Fiddle::Function.new(Fiddle.dlopen(nil)["SSLeay_version"], [Fiddle::TYPE_INT], Fiddle::TYPE_VOIDP).call(0)'
ruby 2.4.4p296 (2018-03-28 revision 63013) [powerpc-aix6.1.0.0]
/opt/freeware/lib64/ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require': load failed - /opt/freeware/lib64/ruby/2.4.0/powerpc-aix6.1.0.0/openssl.so. Please issue below command for detailed reasons: (LoadError)
        /usr/sbin/execerror ruby "30 /opt/freeware/lib64/ruby/2.4.0/powerpc-aix6.1.0.0/openssl.so" "36 X509_REVOKED_dup 475 /usr/lib/libcrypto.a[libcrypto64.so.1.0.0]" "36 X509_STORE_CTX_get0_store 633 /usr/lib/libcrypto.a[libcrypto64.so.1.0.0]" "36 SSL_is_server 796 /usr/lib/libssl.a[libssl64.so.1.0.0]" "36 SSL_get0_alpn_selected 837 /usr/lib/libssl.a[libssl64.so.1.0.0]" "36 SSL_CTX_set_alpn_select_cb 838 /usr/lib/libssl.a[libssl64.so.1.0.0]" "36 SSL_CTX_set_alpn_protos 839 /usr/lib/libssl.a[libssl64.so.1.0.0]" "2 /opt/freeware/lib64/ruby/2.4.0/powerpc-aix6.1.0.0/openssl.so" "6 8"
        from /opt/freeware/lib64/ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require'
        from /opt/freeware/lib64/ruby/2.4.0/openssl.rb:13:in `<top (required)>'
        from /opt/freeware/lib64/ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require'
        from /opt/freeware/lib64/ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require'


text:
Q: Icons available for ExtJS's Panel's "tool" buttons How can I set icon used in my Panel's "Title Bar"? Maybe I need to add an image myself, but if so I suppose I need to define or configure that somewhere?
{
    xtype: 'treepanel',
    title: 'Projects',
    width: 200,
    store: Ext.data.StoreManager.lookup('projects'),
    tools: [
        {
            type: 'add', // this doesn't appear to work, probably I need to use a valid class
            tooltip: 'Add project',
            handler: function() {
                console.log('TODO: Add project');
            }
        },
        ...
    ]
},

A: according to the ExtJS documentation, these predefined types are available:
collapse, expand, maximize, minimize, resize, restore, move, close

minus, plus, prev, next, pin, unpin, search, toggle, refresh

save, print, gear, help

right, left, up, down

one can enter whatever type one wants:
{type: 'YOURTYPE'}

while providing a 15px icon - or preferably icon sprites
(the background-position certainly not applies for single icons, but icon sprites):
.x-tool-img.x-tool-YOURTYPE{
   background: url('../images/custom_tool_sprites.png') no-repeat 0 0;
}

sources: Ext.panel.Tool-cfg-type, codefx.biz.

A: There are a set of 25 icons that can be specified by using the type config.
check http://docs.sencha.com/ext-js/4-0/#!/api/Ext.panel.Tool-cfg-type
To get add symbol use
tools:[{
    type:'plus',
    tooltip: 'Add project',
    // hidden:true,
    handler: function(event, toolEl, panel){
        // Add logic
    }
}]

the specified type:'add' is not in the list

A: If you want to add your own tool type and be able to assign it an image of your own, you can do the following:
Add a css class in your css file:
.x-tool-mytool { background-image: url(path_to_your_image_file) !important; }

Then in your tools, simply use 'mytool' as the type:
            {
                type:'mytool',
                tooltip: 'This is my tool',
                handler: function(event, toolEl, panel){
                    // my tool logic
                }
            }

Make sure that you use the same name in tool's type as you used for the css class suffix.

A: I think you mean "set buttons used in my Panel's Title Bar", not "set icon". You can use buttons config of Panel, not tools:
buttons: [{
   text: 'Add',
   tooltip: 'Add project',
   handler: function() {
      console.log('TODO: Add project');
   }
}]

You can use other configurations like bbar (bottom bar), fbar (footer), tbar (top), lbar (left), rbar (right) for position the toolbar. One small notice is the config objects in buttons have the default xtype as button, so you don't need to explicitly specify them.


text:
Q: Repeat binary number to be the same length as another number in python Say I have a binary number message of 0100110101100101 and a binary key of 001.
How can I repeat the key to be the same length as the message? As in take the length of the message and then repeat the pattern of the key till the length of the message is reached?
In the example the output should be 0010010010010010
Thanks.

A: You can use python's list slicing:
In [1599]: a = '0100110101100101'
In [1602]: key = '001'

In [1608]: factor = len(a) // len(key)
In [1606]: remainder = len(a) % len(key)

In [1625]: if factor == 0:
      ...:     print("pattern greater than the string")
      ...: else:
      ...:     answer = (key * factor) + key[:remainder]
      ...:

In [1614]: answer
Out[1614]: '0010010010010010'


text:
Q: Replacing integers in array with different strings using numpy I have an array of 75 integer values, and I'm trying to replace values in the array with strings if they are within a certain range of values.
All values in the array are between 0 and 75. I want to replace all values between 0-24 with a particular string, all values between 25-49 with a different string, and all values 50+ with a third string.
I'm trying to do this with numpy,
setosa = 'Iris-setosa '
versicolor = 'Iris-versicolor '
virginica = 'Iris-virginica '
arr_predicted1 = np.array(arr_indices).reshape(1, 75)

arr_predicted2 = np.where(arr_predicted1 < 25, setosa, arr_predicted1)
arr_predicted2 = np.where((arr_predicted1 > 24) & (arr_predicted1 < 50),
versicolor, arr_predicted1)
arr_predicted2 = np.where(arr_predicted1 > 49, virginica, arr_predicted1)

Issue I'm facing is that it only does the third np.where command, where it replaces all values that are > 49 with the virginica string like I wanted, but it seems to ignore the previous two commands where I want to replace the other two ranges with their respective strings (setosa and versicolor).
Is there a way to do this? Or perhaps create a new array where the strings correspond to the value ranges I want, essentially replacing the values with strings but creating a new array?

A: try numpy.select:
import numpy as np

conditions = [arr_predicted1 < 25, (arr_predicted1 > 24) & (arr_predicted1 < 50), arr_predicted1 > 49]
choice = [setosa, versicolor, virginica]

arr_predicted2 = np.select(condtions, choice)

A: You overwrite the arr_predicted2 every time, that is why it only does the last one:
setosa = 'Iris-setosa '
versicolor = 'Iris-versicolor '
virginica = 'Iris-virginica '
arr_predicted1 = np.array(arr_indices).reshape(1, 75)

arr_predicted2 = np.where(arr_predicted1 < 25, setosa, arr_predicted1)
arr_predicted3 = np.where((arr_predicted2 > 24) & (arr_predicted2 < 50),
    versicolor, arr_predicted2)
arr_predicted4 = np.where(arr_predicted3 > 49, virginica, arr_predicted3)


text:
Q: colorBars not working in BarChat react.js Bars are not showing in colors. Here is my code.
 <BarChart
      colorBars
       data={this.state.data}
       width={350}
       height={400}
       margin={{top: 10, bottom: 50, left: 50, right: 10}}
       />

Here is my output :-
click Here


text:
Q: Could not load type 'WingTipToys.Global_asax' I used to be a hobby programmer and still am. But, now I am trying to learn web application development and have been going through the first steps of Wingtiptoys project on MS site. After having done what was asked of me by the site and running the project for the first time...I get the below error on my browser.
QUOTE
Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.
Parser Error Message: Could not load type 'WingTipToys.Global_asax'.
Source Error:
Line 1:  <%@ Application Codebehind="Global.asax.vb" Inherits="WingTipToys.Global_asax" Language="vb" %>
Source File: /global.asax    Line: 1
UNQUOTE
Can anyone help?
Thanks & Best Regards
Rajeev

A: Thanks Michelle for trying to help and please accept my appology for not realizing that you were looking for the code as I assumed this was a common error for biginners. Anyways...below is the code from Global.asax.vb and at the very bottom is the code  from Global.asax
Namespace WingTipToys
Public Class [Global]
Inherits HttpApplication

Private Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
RouteConfig.RegisterRoutes(RouteTable.Routes)
BundleConfig.RegisterBundles(BundleTable.Bundles)
Database.SetInitializer(New ProductDatabaseInitializer)
End Sub
End Class
End Namespace

Here is the code from Global.asax
<%@ Application Codebehind="Global.asax.vb" Inherits="WingTipToys.Global.asax" language="vb" %>


text:
Q: Should I be seeing a symlink to kernel in root directory? My root shows symlinks to linux kernel are they necessary?
root@NAS1:/# ls -l
total 94
drwxr-xr-x   3 root root  4096 Dec 15  2011 ~
drwxr-xr-x   2 root root  4096 Mar 19 01:37 bin
drwxr-xr-x   4 root root  2048 Mar 19 22:27 boot
drwxr-xr-x  23 root root  4920 Mar 19 22:31 dev
drwxr-xr-x 140 root root 12288 Mar 19 22:07 etc
drwxr-xr-x   6 root root  4096 Aug  1  2015 home
lrwxrwxrwx   1 root root    32 Mar 19 22:05 initrd.img -> boot/initrd.img-4.8.0-41-generic
drwxr-xr-x  22 root root  4096 Mar 19 01:35 lib
drwxr-xr-x   2 root root  4096 Mar 19 01:34 lib64
lrwxrwxrwx   1 root root    36 Jun  6  2015 libnss3.so -> /usr/lib/x86_64-linux-gnu/libnss3.so
drwx------   2 root root 16384 Dec 11  2011 lost+found
drwxr-xr-x  15 root root  4096 Nov 26  2014 media
drwxr-xr-x   2 root root  4096 Jul 29  2016 mnt
drwxr-xr-x   4 root root  4096 Oct 10 20:42 opt
dr-xr-xr-x 206 root root     0 Mar 19 22:31 proc
drwx------  26 root root  4096 Nov 10 22:34 root
drwxr-xr-x  37 root root  1200 Mar 19 22:55 run
drwxr-xr-x   2 root root 12288 Mar 19 01:37 sbin
drwxr-xr-x   3 root root  4096 Mar 16  2012 srv
dr-xr-xr-x  13 root root     0 Mar 19 23:38 sys
drwxrwxrwt   9 root root  4096 Mar 19 23:42 tmp
drwxr-xr-x  10 root root  4096 Dec 11  2011 usr
drwxr-xr-x  16 root root  4096 Feb 14  2015 var
lrwxrwxrwx   1 root root    29 Mar 19 22:05 vmlinuz -> boot/vmlinuz-4.8.0-41-generic


text:
Q: Visual Studio 2012 no longer debugs unmanaged C++ Recently my Visual Studio 2012 lost the ability to debug unmanaged code.  What I have is a C# project which references a C++ COM module.  It uses a interop library that I created using tlbimp.exe.  The COM module is registered, and the C# project has 'Enable native code debugging' checked.  I'm using Windows 7 (current on updates) as the operating system and this project is set to x86 for both the C# and C++.  This is a practice that I've been doing for years, and debugging has never been a problem.
When the project loads, the breakpoints are disabled with the message 'The breakpoint will not currently be hit.  No symbols have been loaded for this document.'  When I load the Modules window the COM module is not in the list and I cannot find how to add it.
Is there a recent update or something that could have caused this problem?  What can I do to make this work again?


text:
Q: Double integral over annulus
Evaluate $$\iint_D\ e^{-x^2 - y^2}\ dA,$$
  where $D$ is annulus $a \le x^2 + y^2 \le b$

My understanding is it involves polar coordinates but I don't understand how to convert it.

A: Since $r^2 = x^2 + y^2$ (do you see why?), we're considering the annulus $\sqrt{a} \le r \le \sqrt{b}$. Then the integral is
$$\iint_D\ e^{-r^2}\ dA,$$
The area element is $dA = r\ dr\ d\theta$ in polar coordinates. Now what do you make the limits of integration?


text:
Q: increase /home size from root folder The following is my partition in linux (ubuntu)
Filesystem      Size  Used Avail Use% Mounted on
/dev/sda7        42G   11G   29G  29% /
udev            2.0G  4.0K  2.0G   1% /dev
tmpfs           2.0G   80K  2.0G   1% /tmp
tmpfs           802M  920K  801M   1% /run
none            5.0M  8.0K  5.0M   1% /run/lock
none            2.0G  5.0M  2.0G   1% /run/shm
cgroup          2.0G     0  2.0G   0% /sys/fs/cgroup
/dev/sda8       9.2G  8.4G  319M  97% /home

I need to increase my /home folders size. As I already have a lot of space (29G) in "/" . Is there any way to transfer / use that space in /home directory ?

A: There is a convenient utility called gparted that can do that for you with a minimum hassle. You will have to copy a live distro, like Ubuntu, to a USB stick, boot from it, choose Try Ubuntu without installing it, and install gparted:
  sudo apt-get install gparted
  sudo gparted

which will open the GUI of the program. The reason why you have to do it from a stick is that you cannot alter a live partition (or you can, under special circumstances, but it safer to do it this way). Then you will have to:
1) first, shrink /dev/sda7 to your intended size, which will leave some room free;
2) second, expand /dev/sda8 to include the newly liberated space.
Reboot from HDD, you are done.
Should you have any problem with rebooting, use the USB stick one again to boot from it, install Boot-Repair as per the instructions here, and follow these instructions to the end.


text:
Q: Failed to download packages from Maven repository for Maven project in the IntelliJ I've tried to download package in pom.xml file in the Maven but it is always failed to download.
Got the error message:
Could not transfer artifact org.sonatype.oss:oss-parent:pom:5 from/to central (https://repo.maven.apache.org/maven2): Transfer failed for https://repo.maven.apache.org/maven2/org/sonatype/oss/oss-parent/5/oss-parent-5.pom
I've tried to check the issue, go to the: File > Settings > Build, Execution, Deployment > Build Tools >Maven >Repositories
URL: https://repo.maven.apache.org.maven2
Type: Remote
Updated: Error
I am not sure if the issue in the Repositories causes issue that can't download package from maven.
Could you show me to fix it?
I'm using IntelliJ Idea 2021.1.1, created maven project.


text:
Q: Complexity after Arrays.sort and for loop In java, if I sort using Arrays.sort() (n log n) and then use a for loop o(n) in the code, what will be the new complexity ? is it n^2 log n or n log n

A: If you perform the for loop after, you have an O(nlog(n)) operation followed by an O(n) one. Since O(n) is negligible compared to O(nlog(n)), your overall complexity would be O(nlog(n)).

A: Answer: O(nLog(n))
non nested complexities can be simply added. i.e. O(n) + O(nLog(n))
For large n, nLog(n) is significantly greater than n. Therefore, O(nLog(n)) is the answer.
Read this: https://en.wikipedia.org/wiki/Big_O_notation
Note:
if the complexities are nested then the complexities are multiplied, for example:
Inside a loop of order n, you are doing a sort of order nLog(n).
Then complexity will be O(n * nLog(n)). i.e. O(n²Log(n))


text:
Q: In pimpl idiom, if without destructor, compiler would bring out error: can't delete an incomplete type I am using visual studio on windows10 using C++.
And I'm learning about pimpl idiom, what confuses me is that if without destructor of employee, compiler would bring out error: can't delete an incomplete type. I don't understand why I need a destructor for employee, isn't it enough having a destructor for struct impl because of unique_ptr.
this is the website which introduce pimpl idiom, it says:
"Since std::unique_ptr is a complete type it requires a user-declared destructor and copy/assignment operators in order for the implementation class to be complete." But I still don't understand and didn't get much information about the definition of complete type it says.
https://www.geeksforgeeks.org/pimpl-idiom-in-c-with-examples/
employee.h
#pragma once
#include<iostream>
#include<string>
using std::string;
using std::unique_ptr;

//pimple idiot
namespace employee {
    class employee {
    public:
        employee(const string& s);
        //~employee();//if without this line, compiler would bring out error: can't delete an incomplete type
        employee(const employee& e);
        employee& operator=(employee e);

        void setSalary(float s);
        float getSalary();
    private:
        struct impl;
        unique_ptr<impl> pimpl;
    };
}

employee.cpp
#include"employee.h"

namespace employee {
    struct employee::impl {//
        impl(const string& s) :name(s),salary(0){}
        ~impl(){}//for unique_ptr

        string name;
        float salary;
    };
    employee::employee(const string& s):pimpl(new impl(s)){
    }
    //employee::~employee() = default;
    employee::employee(const employee& e) : pimpl(new impl(*e.pimpl)) {
    }
    employee& employee::operator=(employee e) {
        std::swap(this->pimpl, e.pimpl);
        return *this;
    }

    void employee::setSalary(float s) {
        pimpl->salary = s;
    }
    float employee::getSalary() {
        return pimpl->salary;
    }
}

A: You need to know how to delete the class once the scope exits. If definition is hidden then there is no knowledge how to call destructor. You can do so without defining impl by writing a custom deleter for unique_ptr.
Simply add class impl_deleter having operator ()(impl *) that calls delete - needs to defined where impl is fully defined. And use unique_ptr<impl, impl_deleter>.
Seek C++ reference for details on unique_ptr.
Or just write full declaration of struct impl in the header.

A: The reason it need the destructor  is essentially so that the template code get instanciated.
As te type is defined is defined in the source file and the destructor of employee need to destroy the unique_ptr it need to know how to do it.
Compiler know know to do this if impl is a complete type. So you only need to define the destructor after the definition of impl.
Thus the correct way is to define the destructor as defaulted in source file if you don't need it otherwise.
employee.cpp
namespace employee
{
    struct employee::impl { .... };
    employee::~employee() = default; // If you need only for pimpl idiom
}


text:
Q: SQL - Calculate weighted students grades based on grade type I am having trouble calculating student grades based on a specific grade type.
I have the following tables
Subject
-------------------
Subid [PK]
subjectTitle

Topic
----------------
Tid (TopicID) [PK]
SubId (Subjectid) [FK]
Designation
WeightOfSubject

Marking
-------------------
pid (PersonID) [PK][FK]
Tid (TopicID) [PK][FK]
Points

Person
------------------------
pid (PersonId) [PK]
firstname
lastname
Sex

Paired with the following data.
Subject Data

Subid

AA001       Arts
AA002       Crafts

Topic Data

Tid      Subid      Designation WeightOfSubject
001      AA001          S1        30
002      AA001          S2        30
003      AA001          S3        40
004      AA002          S1        50
005      AA002          S2        50

Marking DATA

Pid Tid Points(out of 100)
P01 001 33
P01 002 62
P01 003 81
P01 004 85
P01 005 63
P02 001 74
P02 002 72
P02 003 45
P02 004 63
P02 005 88

Person DATA

pid firstname   lastname    sex
P01 Josh        Draxler     M
P02 John        Doe         M

What i'd like to do with this is to multply the markings by their weight, and then add all of the weighted scores together to get the average overall weighted for each subject they did (with the final result displaying the subject ids, the person, and their overall weighted average mark as a percentage.)
Although my MYSQL is mediocre at best, I gave it a go, and exprimented with the following (I know its wrong by a mile, dont worry.)
SELECT Topic.Designation, Subject.Subid, Subject.subjectTitle, Person.firstname, Person.lastname, AVG(Topic.WeightOfSubject/100*Marking.Points)
FROM Topic, Subject, Person, Marking
WHERE Person.pid = 'P01'
AND Marking.Points = 33
AND Topic.WeightOfSubject = 30

Which is fine for just one person, but I'm unsure on how to construct such a query for more than one person, and more than one subject, I've search up JOINS and the such but it really didnt guide me on how I could construct a query for my particular problem. This is the output I would like to expect:
Pid  Firstname  Lastname  subjectTitle  Result(WeightedAverage)
001  Josh       Draxler   Arts         (Weighted Average Here)

Any help is welcome.

A: I locally (re)created the tables in MySQL 8.0 as shown below:
create table subject (
  subid int,
  subjecttitle varchar(10)
);

create table topic (
  tid int,
  subid int,
  designation varchar(10),
  weightofsubject int
);

create table marking (
  pid int,
  tid int,
  points int
);

create table person (
  pid int,
  firstname varchar(20),
  lastname varchar(20),
  sex varchar(1)
);

Then, I ran the query shown below. It produces the weighted average for every person and subjects he/she has:
select
  p.pid as pid,
  max(p.firstname) as firstname,
  max(p.lastname) as lastname,
  max(p.sex) as sex,
  s.subid, -- you can remove this column, if you wish
  max(s.subjecttitle) as subjecttitle,
  1.0 * sum(m.points * t.weightofsubject) /
    sum(t.weightofsubject) as weighted_average
from subject s
join topic t on t.subid = s.subid
join marking m on m.tid = t.tid
join person p on p.pid = m.pid
group by p.pid, s.subid
order by p.pid, s.subid


text:
Q: ajax call return 406 not acceptable for non logged users only I wrote an ajax call to retrieve some info to print markers on a map:
if(jQuery('#mapa_general').length){
    var url_marcadores = 'http://localhost/rutaVino/wp-content/plugins/establecimientos/assets/img/';
    var url = jQuery('#mapa_general input').val();

    jQuery.ajax({
        url: url,
        type: 'POST',
        dataType: 'JSON',
        data: {funcion: 'obtener_coordenadas_establecimientos'},
    })
    .done(function(res) {

        var LeafIcon = L.Icon.extend({
            options: {
                iconSize:     [20, 28],
                iconAnchor:   [10, 20],
                popupAnchor:  [0, -35]
            }
        });
...

It works great but only when I'm logged in, if I visit the page as a visitor browser console shows:

XHRPOSThttps://vinos.islascanariasturismoactivo.com/wp-content/plugins/establecimientos/inc/base/establecimientos-main.php
[HTTP/2 406 Not Acceptable 207ms]

Don't know what can be happening


text:
Q: Node.js Devices not found I installed Appc studio on MBP with C2D, OSX 10.9.5, XCode 6.2, can't update to newest Sierra and XCode, because MBP is not longer supported.
I have problem, I don't see any iOS simulators/devices connected to MBP. I tried to uninstall, install, reinstall, downgrade and upgrade node.js and also TiSDK(6.0.2&5.1.1), but after
appc ti info -t ios
it throws error:
Cannot read property "devices" of undefined
When I open Xcode, I see my connected iPhone and iOS simulators.
Can please somebody help me?
Thank you

A: If from Xcode you can see al the devices and you can start them, the problem is probably that Appcelerator "lost" the path to Xcode.
Check with appc setup if it's everything right and have a look also at the platform iOS properties.


text:
Q: Continuity of a definite integral Let $f : \mathbb{R} \to \mathbb{C}$ be an absolutely integrable function, and let $F: \mathbb{R} \to \mathbb{C}$ be the definite integral $$F(x):=\int_{-\infty}^x f(t)\,\mathrm{d}t.$$ I need to show that $F$ is continuous, i.e., that for every $x_0 \in \mathbb{R}$ and $\epsilon >0$ there exists $\delta > 0$ such that $|F(x)-F(x_0)|=|\int_{[x,x_0]} f(t) dt|<\epsilon$ whenever $|x-x_o|< \delta$. Is there a simple way to do this?

A: We can show that it is sequentially continous. Consider a sequence $(x_n)$ convergning to $x\in \mathbb{R}$ and  the associed sequence of functions $f_n(x) = \chi_{[-\infty,x_n]}f(t)$. We have $|f_n|(t) \leq |f|(t)$ which is integrable. By the Lebesgue's dominated convegrence theorem, we get $$\lim_{n\to \infty}F(x_n) = \lim_{n\to \infty}\int_{\mathbb{R}}f_n(t) \mathrm{d}t =  \int_{\mathbb{R}}\chi_{[-\infty,x]}f(t)\mathrm{d}t = F(x).$$
A function is sequentially continous iff it is continous in «$\epsilon-\delta$»


text:
Q: Trigger two tables from two different databases to insert data (SQL Server) What the title says, I want to insert data from a database to another database. The first database "DB1" is the source and the second database "DB2" is the target.
The relevant tables are defined as follows:
DB1 => tbl_Target
==================================
Id | Date | Name | Age | Num_Aucts
==================================

DB2 => tbl_Source
======================
Name | Age | Num_Aucts
======================

Well, tbl_Source contains 40 rows of data. I need to transfer these rows into tbl_Target. But how you can see tbl_Target has two additional columns Idand Date. Id will set automatically. The important column is Date. In this column I want to set the currently date. In this case from today. How can I define this in a trigger frunction in SQL Server with T-SQL?
I have begun in this direction:
USE DB1
GO

CREATE TRIGGER trg_Insert_tblSource ON tbl_Source
FOR INSERT AS
BEGIN
    INSERT INTO DB2.dbo.tbl_Target ([Date], [Name], [Age], [Num_Aucts])
        SELECT ??? // How to get the current date?

Can anyone help me? Do I need a stored procedure?

A: I don't know if I fully understood your question. But if you just want to transfer the data from one table to another, you don't need a trigger. You could achieve this with a simple INSERT...SELECT:
INSERT INTO DB2.dbo.tbl_Target (
   [Date],
   [Name],
   [Age],
   [Num_Aucts]
)
SELECT GETDATE(), [Name], [Age], [Num_Aucts]
FROM yourDB.dbo.tbl_Source

If you want to use a trigger, write the following in the BEGIN block:
INSERT INTO DB2.dbo.tbl_Target (
   [Date],
   [Name],
   [Age],
   [Num_Aucts]
)
SELECT GETDATE(), [Name], [Age], [Num_Aucts]
FROM inserted

The trigger gets fired each time you insert data into tbl_Source. But the existing data doesn't get inserted into tbl_Target with your trigger.

A: you can use GetDate() to get current date of server
USE DB1
GO

CREATE TRIGGER trg_Insert_tblSource ON tbl_Source
FOR INSERT AS
BEGIN
    INSERT INTO DB2.dbo.tbl_Target (
       [Date],
       [Name],
       [Age],
       [Num_Aucts]
    )
    SELECT GETDATE(), [Name], [Age], [Num_Aucts]
    FROM inserted;
END
GO


text:
Q: Motherboard ID - WMI C++ - Reliable? I'm using WMI in C++ classes to retrieve the serial number of my motherboard.
The query is the following :
"SELECT SerialNumber FROM Win32_BaseBoard"

I wrote the query myself so i'm not certain it is correct, but it does return something :
/9637CW1/CN1296131Q0BA8/. The returned string is in the same format on multiple computers so i assume the query is correct.
My question is : am i really querying the motherboard serial number here ? Because i saw another class called "Win32_MotherboardDevice" (which has no "serial number" property). Would it be a good idea to use this as a computer identifier ? I am currently using the HDD serial number, but i thought using the serial number of a more reliable component such as the motherboard would be better since a disk is more likely to be changed than a motherboard.
Thank you :)

A: What I have found is that retrieving the serial number of the mother board can result in very different results depending on the manufacturer and the distribution channel. Some manufacturers who sell to the end customer and have good support processes with equipment repair will be consistent about setting the serial number information for WMI. Other manufacturers providing OEM type equipment will depend on the OEM to set the serial number.
Since the serial number is within a particular domain or name space based on manufacturer, it is possible though improbable that different manufacturers may have used the same serial number so you would really need to know both manufacturer as well as serial number.
Some point of sale terminals are consistent about the serial number and part of the procedure for mother board replacement in the case of a failed mother board is to set the serial number of the replacement board to the serial number of the board being replaced. This implies that someone could have the same serial number for several pieces of equipment similar to doing LAN NIC MAC spoofing.
The WMI query will make a difference as to the serial number provided. In addition to the serial number there is also an asset tag property as well.
Looking at the documentation for Win32_MotherboardDevice and trying a few properties, there does not seem to be much useful data there, certainly not something similar to a unique serial number.
On a Dell laptop With Windows XP when I run a C++ application that uses WMI to see the results of several different Select WMI queries for several different properties I get the following results:
Connected to ROOT\CIMV2 WMI namespace

Query for SELECT * FROM Win32_SystemEnclosure
  SMBIOS SerialNumber: 49495G1
  SMBIOS Name: System Enclosure
  SMBIOS SMBIOSAssetTag:
  SMBIOS Manufacturer: Dell Inc.

Query for SELECT * FROM Win32_BaseBoard
  SMBIOS SerialNumber: .49495G1.CN486438441035.
  SMBIOS Product: 0UY141
  SMBIOS Name: Base Board
  SMBIOS Manufacturer: Dell Inc.

Query for SELECT * FROM Win32_BIOS
  SMBIOS SerialNumber: 49495G1
  SMBIOS Name: Phoenix ROM BIOS PLUS Version 1.10 A10
  SMBIOS Manufacturer: Dell Inc.

Query for SELECT * FROM Win32_ComputerSystem
  SMBIOS Name: CIT-31204E1FF03
  SMBIOS Manufacturer: Dell Inc.

Query for SELECT * FROM Win32_ComputerSystemProduct
  SMBIOS Name: Latitude D830
  SMBIOS IdentifyingNumber: 49495G1
  SMBIOS UUID: 4C4C4544-0039-3410-8039-B4C04F354731

Looking on the bottom of this laptop I see a sticker that has a bar code along with printing that says "SERVICE TAG 49495G1" so for this laptop the serial number retrieved is the service tag identifier. I can go to the Dell website and look up this service tag in the support area.
A new point of sale terminal meant for resale with POS Ready 7 version of Windows provides the following output with the same C++ WMI application. This is similar to the output from a PC I constructed myself from purchased parts which also did not have serial numbers That PC is running Windows 8.1.
Connected to ROOT\CIMV2 WMI namespace

Query for SELECT * FROM Win32_SystemEnclosure
  SMBIOS SerialNumber: None
  SMBIOS Name: System Enclosure
  SMBIOS SMBIOSAssetTag: None
  SMBIOS Manufacturer: To Be Filled By O.E.M.

Query for SELECT * FROM Win32_BaseBoard
  SMBIOS SerialNumber: None
  SMBIOS Product: EIN70-SAM
  SMBIOS Name: Base Board
  SMBIOS Manufacturer: INTEL Corporation

Query for SELECT * FROM Win32_BIOS
  SMBIOS SerialNumber: None
  SMBIOS Name: BIOS Date: 10/15/13 20:06:15 Ver: 04.06.05
  SMBIOS Manufacturer: American Megatrends Inc.

Query for SELECT * FROM Win32_ComputerSystem
  SMBIOS Name: GENPOSA-1
  SMBIOS Manufacturer: To be filled by O.E.M.

Query for SELECT * FROM Win32_ComputerSystemProduct
  SMBIOS Name: EIN70-SAM
  SMBIOS IdentifyingNumber: None
  SMBIOS UUID: 03000200-0400-0500-0006-000700080009


text:
Q: AttributeError: module 'moviepy.audio.fx.all' has no attribute 'audio_fadein' After converting my code to exe either via auto-py-to-exe or pyinstaller, I get the following errors in relation to moviepy. The reason I need moviepy is that I cannot convert to mp4 when using a variable name although I can when set as a string in the code seen below. I have all the necessary libraries installed as far as I am aware btw and I have the same error even when running through Anaconda CMD.exe Prompt. I have tried using the solutions from the internet but they seem to involve modifying certain init files that didn't fix the problem or importing submodules from moviepy which doesn't work anymore with my code. I have tried everything I have seen on the internet with no luck. Any help would be greatly appreciated. Oh and btw, it works just fine as a .py file. It only breaks when converted to exe. So maybe missing dependency when converting to exe involving moviepy? Below is my error message:
Traceback (most recent call last):
  File "cdn_python_script.py", line 3, in <module>
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
  File "PyInstaller\loader\pyimod03_importers.py", line 531, in exec_module
  File "moviepy\editor.py", line 87, in <module>
  File "<string>", line 1, in <module>
AttributeError: module 'moviepy.audio.fx.all' has no attribute 'audio_fadein'
[11968] Failed to execute script cdn_python_script

Here is my source code:
# libraries imported for usage within the written code.
import requests
import moviepy.editor as moviepy
import os

# shows menu of options for the user to select from in range of 1-4.
print("Type 1 to Download a video of the Earth")
print("Type 2 to Download a video of an animated Rabbit")
print("Type 3 to Download a video of an Ocean")
print("Type 4 to Download a video of Sea Life")

# starts a loop so that the message is continuously repeated if necessary due to try and except functions.
while True:
    try:
        # user input saves to variable name message for future use in functions.
        message = int(
            # user is prompted to enter a value on their keyboard which is checked against requirements and rules.
            input(
                "Choose a video from the above menu, then enter the corresponding number and press enter: "
            )
        )
    # checks for value of user input as to ensure number is selected otherwise repeats question.
    except ValueError:
        print("Sorry, please enter a number.")
        # if the input is a number then the loop continues instead of looping back to the start.
        continue

    # part of the loop that makes sure the variable message isn't 0 or below as to ensure it is within the range of 1-4.
    if message <= 0:
        print("Sorry, your response was not within the range of 1-4.")
    # part of the loop that makes sure the variable message isn't above 4 as to ensure it is within the range of 1-4.
    elif message > 4:
        print("Sorry, your response was not within the range of 1-4.")
        continue
    # if input is a number within the correct range then it makes it to this code where the loop breaks.
    else:
        # selected number was successfully parsed, and we're happy with its value.
        # we're ready to exit the loop.
        break

# checks the value saved in the variable message is eitehr 1, 2, 3 or 4 and if so prints video selected.
if message in range(1, 5):
    print("Video Selected")
# checks the variable message is eitehr 1, 2, 3 or 4 and if not prints video not seelcted and will run previous loop.
else:
    print("Video not selected.")

# runs the correct block of code depending on if user selected 1, 2, 3 or 4 based on user input saved to the variable.
if message == 1:
    # saves the below string (URL) to variable name file_url.
    file_url = "https://myawsbuckettest12321.s3.eu-west-2.amazonaws.com/file_example_MP4_1920_18MG.mp4"
    # requests.get function saved to variable r and uses the saved file_url for the download later on.
    # requests library is used here within this code.
    r = requests.get(file_url, stream=True)

elif message == 2:
    file_url = (
        "https://myawsbuckettest12321.s3.eu-west-2.amazonaws.com/sample-mp4-file.mp4"
    )
    r = requests.get(file_url, stream=True)

elif message == 3:
    file_url = (
        "https://myawsbuckettest12321.s3.eu-west-2.amazonaws.com/sample_1280x720.mp4"
    )
    r = requests.get(file_url, stream=True)

elif message == 4:
    file_url = "https://myawsbuckettest12321.s3.eu-west-2.amazonaws.com/sample_960x400_ocean_with_audio.mp4"
    r = requests.get(file_url, stream=True)

# prompts the user to enter a name for the file and the input is then saved to file_name.
# the prompt from the user is to avoid overwriting files if the user downloads multiple videos because of a set string.
file_name = input("Please give the video a name to save as, then press enter: ")
print("Please wait while your video is downloading...")

# takes the file_name value depending on number selected earlier, opens file in binary mode and attempts to save as mp4.
with open(file_name, "wb") as mp4:
    for chunk in r.iter_content(chunk_size=1024):

        # writing one chunk at a time to mp4 file.
        if chunk:
            mp4.write(chunk)

# file_name variable above does not save as mp4 while it does if set as a string instead of a variable.
# therefore, moviepy library is used here to convert the file after downloaded to mp4 format to view the video.
clip = moviepy.VideoFileClip(file_name)
# saves the video as file_name (what the user named the file) plus .mp4 to ensure it always has the correct file format.
clip.write_videofile(file_name + ".mp4")

# os library is imported here because the converted mp4 and original file still exist.
# this line simply deleted the original file leaving the mp4 as it looks for the file_name without the mp4 on the end.
os.remove(file_name)

# startfile function from within the os library is used here to autoplay the downloaded and converted mp4 for the user.
from os import startfile

# file_input meaning what the user named the file as plus .mp4 is found once downloaded so as to play the mp4.
startfile(file_name + ".mp4")

Thank you!

A: You have to use
from moviepy.audio.io.VideoFileClip import VideoFileClip

Replace
import moviepy.editor as moviepy

A: from moviepy.video.VideoClip import VideoClip
is working for me.
Source/doc: https://moviepy.readthedocs.io/en/latest/_modules/moviepy/video/io/VideoFileClip.html


text:
Q: Javascript to get class or Id of that div which is largest in number? I want javascript to get id of that div which has largest number. Here is example.

now it should get the largest id or class of the div means function have to determine which is largest and save it in a variable.
var id = largestdivnumber

Thanks

A: window.onload = function (){
    var elements = document.getElementsByTagName("div");
    var maxId = 0;
    var max = 0;
    for (var i =0; i < elements.length; i++)
    {
        var id = parseInt(elements[i].id);
        if (id > maxId)
        {
            maxId = id;
            max = i;
        }
    }

    // Element with max id.
    console.log(elements[max]);
};

Here is working fiddle: http://jsfiddle.net/vyshniakov/kdGCm/

A: try this:
$('div').map(function(){
    return this.id;
}).get().sort(function(a, b) {
    return b - a;
})[0];

Here is JSfiddle

A: window.onload = function (){
  max_id = 0
  $.each($("div"), function(i, e){
    id_val  = $(e).attr("id")
    id_num = parseInt(id_val)
    if (!isNan(id_num)){
      if (id_num > max_id){
         max_id = id_num
      }
    }
  })
  element_you_need = $("#"+max_id)
}

You will need Jquery for this to work


text:
Q: itext: Textextracting example not working I want to extract text from an PDF document page wise and I am using itext. I used the example code from their website:
PdfReader reader = new PdfReader(pathToFile);
PdfReaderContentParser parser = new PdfReaderContentParser(reader);
TextExtractionStrategy strategy = parser.processContent(page, new SimpleTextExtractionStrategy());

The method processContent gives me a NullPointerException. What did I do wrong?
This is the stacktrace I get when using version 5.5.0 with this file:
java.lang.NullPointerException
at com.itextpdf.text.pdf.parser.PdfReaderContentParser.processContent(PdfReaderContentParser.java:82)
at com.itextpdf.text.pdf.parser.PdfReaderContentParser.processContent(PdfReaderContentParser.java:105)
at org.languageresources.PDFExtraktor.extractTextFromPage(PDFExtractor.java:100)

A: Given the code sniplet and sample document you gave I tried to reproduce the issue but to no avail, text extraction worked fine.
Furthermore, the stacktrace given:
java.lang.NullPointerException
at com.itextpdf.text.pdf.parser.PdfReaderContentParser.processContent(PdfReaderContentParser.java:82)
at com.itextpdf.text.pdf.parser.PdfReaderContentParser.processContent(PdfReaderContentParser.java:105)
at org.languageresources.PDFExtraktor.extractTextFromPage(PDFExtractor.java:100)

does not match the alleged version 5.5.0 because PdfReaderContentParser.java:82 in that version is an empty line and PdfReaderContentParser.java:105 does not exist: Back then that file was only 85 lines in size.

Assuming, though, that you use the current version 5.5.9, the stacktrace makes sense, in that version PdfReaderContentParser.java:82 is the second of these lines:
PdfDictionary pageDic = reader.getPageN(pageNumber);
PdfDictionary resourcesDic = pageDic.getAsDict(PdfName.RESOURCES);

and pageDic indeed can be null if there is no page pageNumber.
Thus, please check that page, the page number in question, is between 1 and reader.getNumberOfPages() inclusive.


text:
Q: Definite integral $\int_{-2}^{2} \frac{x^2}{1+5^x}\,\mathrm{d}x$ The question is to find the value of the definite integral: $$I=\int_{-2}^{2} \frac{x^2}{1+5^x}\,\mathrm{d}x.$$
This question appeared in this year's CBSE board exam.
Attempts:

*

*Replace $x\to-x$ and we get $$I=\int_{-2}^{2} 5^x \frac{x^2}{1+5^x}\,\mathrm{d}x.$$ Now what?? Probably integration by parts? But I get stuck there too.

*Substitute $5^x=\tan^2\theta$, and then I get (after calculation):
$$I=\left(\frac2{\log5}\right)^3\int_{\tan^{-1}(1/5)}^{\tan^{-1}(5)}\frac{(\log\tan\theta)^2}{\tan\theta}\,\mathrm{d}x.$$ But I still dont get the answer. It has become too complicated.

*Wolfram|Alpha gives me the value
$$I=\frac83,$$ But I don't have a pro account so I can't see the steps.
So how do I solve it?

A: After substituting $x$ as $-x$ , add the two equations.

A: After point 1) integrate by parts using
$$f'(x) = \frac{5^x}{5^x + 1} ~~~~~~~~~~~ \to ~~~~~ f(x) = \frac{\ln(5^x + 1)}{\ln(5)}$$
$$g(x) = x^2 ~~~~~~~~~~~ \to ~~~~~ g'(x) = 2x$$
Then again by parts once.