text:
Q: d3 tooltip and brush not working together I have a class with tooltip and brush, I am using d3 version 4 and my code follows
var allData = [{
        value: 10,
        time: 1613579385
    }, {
        value: 15,
        time: 1613492985
    }, {
        value: 20,
        time: 1613406585
    }, {
        value: 30,
        time: 1613320185
    }, {
        value: 10,
        time: 1613589385
    }, {
        value: 15,
        time: 1613482985
    }, {
        value: 20,
        time: 1613486585
    }, {
        value: 30,
        time: 1613380185
    }
]
var margin = {
    top: 20,
    right: 10,
    bottom: 50,
    left: 50
};
var width = 600, height = 600;
var colors = ['#c0485c', '#4682b4'];
var svg = d3.select("body")
    .append('svg')
    .attr('class', 'ellipse')
    .attr('width', width + margin.left + margin.right + 100)
    .attr('height', height + margin.top + margin.bottom);
var gElement = svg.append('g')
    .attr('transform', `translate(${margin.left},${margin.top})`);
var xScale = d3.scaleTime().range([margin.left, width]);
var yScale = d3.scaleLinear().range([height, margin.bottom]);

xScale.domain(d3.extent(allData, (d) => new Date(d.time * 1000)));
yScale.domain(d3.extent(allData, (d) => d.value));

var xAxis = gElement.append('g')
    .attr('class', 'axis axis--x')
    .attr('transform', 'translate(0,' + (height) + ')')
    .call(d3.axisBottom(xScale));

gElement.append('text')
.attr('transform', 'translate(' + (width / 2) + ' ,' + (height + margin.top + 20) + ')')
.style('text-anchor', 'middle').text('time');

var yAxis = gElement.append('g')
    .attr('class', 'axis axis--y')
    .attr('transform', 'translate(' + (margin.left) + ',0)')
    .call(d3.axisLeft(yScale));

// text label for the y axis
gElement.append('text')
.attr('transform', 'rotate(-90)')
.attr('x', 0 - (height / 2)).attr('dy', '1em')
.style('text-anchor', 'middle').text('Unit');

var circleCx = (d) => xScale(d && d.time ? new Date(d.time * 1000) : new Date(0));
var circleCy = (d) => yScale(d && d.value ? d.value : 0);

var clip = gElement.append("defs").append("svg:clipPath")
    .attr("id", "clip")
    .append("svg:rect")
    .attr("width", width)
    .attr("height", height)
    .attr("x", margin.left)
    .attr("y", margin.bottom);

var circles = gElement.append('g')
    .attr("clip-path", "url(#clip)");

var focus = gElement.append('g')
    .attr('class', 'tooltip')
    .style('display', 'none');
focus.append('rect')
.attr('class', 'tooltip-box')
.attr('width', 300)
.attr('height', 60);

focus.append('text').attr('class', 'tooltip-date');
focus.append('text').attr('class', 'tooltip-value');

focus.append('circle')
.attr('class', 'tooltip-point')
.style('stroke', 'white')
.style('stroke-width', '.5')
.attr('r', 6);

function onMouseOver(data) {
    if (!data || !data.time) {
        return;
    }
    focus.style('display', null);
    focus.select('circle.tooltip-point').attr('transform', `translate(${xScale(new Date(data.time * 1000))},${yScale(data.value)})`);
    const translateX = xScale(new Date(data.time * 1000));
    const translateY = yScale(data.value);

    focus.select('rect.tooltip-box')
    .attr('transform', `translate(${translateX},  ${translateY})`)
    .attr('x', 2)
    .attr('y', -2.5);

    focus.select('text.tooltip-date')
    .attr('transform', `translate(${translateX},  ${translateY})`)
    .attr('dx', 10)
    .attr('dy', 30)
    .text(`Date: ${new Date(data.time * 1000)}`);

    focus.select('text.tooltip-value')
    .attr('transform', `translate(${translateX},  ${translateY})`)
    .attr('dx', 10)
    .attr('dy', 45)
    .text(`Value: ${data.value}`);
}

function onMouseOut() {
    focus.style('display', 'none')
}

var points = circles.selectAll(`.circle-data`)
    .data(allData)
    .enter()
    .append('circle') // enter append
    .attr('class', `circle-data`)
    .attr('stroke', 'blue')
    .attr('r', '3') // radius
    .attr('cx', circleCx)
    .attr('cy', circleCy)

function applyZoom() {
    var brush = d3.brushX()
        .extent([[margin.left, margin.bottom], [width, height]])
        .on("end", () => {
        const extent = d3.event.selection;

        if (extent) {
            xScale.domain([xScale.invert(extent[0]), xScale.invert(extent[1])]);

            circles.select(".brush").call(brush.move, null) // This remove the grey brush area as soon as the selection has been done

        }

        xAxis.transition().duration(1000).call(d3.axisBottom(this.xScale))

        circles.selectAll('.circle-data')
        .transition()
        .duration(1000)
        .attr('cx', circleCx)
        .attr('cy', circleCy)

    });

    circles.append("g")
    .attr("class", "brush")
    .call(brush)

    svg.on("dblclick", () => {
        xScale.domain(d3.extent(allData, (d) => new Date(d.time * 1000)));
        xAxis.transition().call(d3.axisBottom(xScale));
        d3.selectAll('circle')
        .transition()
        .attr('cx', circleCx)
        .attr('cy', circleCy)
    });
}
applyZoom();

gElement.selectAll('.brush')
.on('mouseover', onMouseOver)
.on('mouseout', onMouseOut);

The tooltip is not displayed while I can zoom by selecting over svg. The zoom is working but not together with tooltip. If I remove zoom , then tooltip works properly. commenting out applyZoom method gives a working tooltip.
full code is available in fiddle: https://jsfiddle.net/edayan/9chrn536/1/


text:
Q: How can I find all items beginning with a or â? I have a list of items that are grouped by their first letter. By clicking a letter the user gets alle entries that begin with that letter.
This does not work for french. If I choose the letter a, items with â are not returned.
What is a good way to return items no matter if they have an accent or not?
                 <%  char alphaStart = Char.Parse("A");
                        char alphaEnd = Char.Parse("Z"); %>
                    <%  for (char i = alphaStart; i <= alphaEnd; i++) { %>
                        <% char c = i; %>
                        <% var abcList = Model.FaqList.Where(x => x.CmsHeader.StartsWith(c.ToString())).ToList(); %>
                        <% if (abcList.Count > 0 ) { %>

                                <a id="<%= i.ToString().ToUpper() %>" class="naviPktLetter" href="#<%= i.ToString().ToLower() %>"><%= i.ToString().ToUpper() %>

                            <ul id="menuGroup<%= i.ToString().ToUpper() %>" class="contextMenu" style="display:none;">
                                <% foreach (var info in abcList) { %>
                                    <li class="<%= info.CmsHeader%>">
                                        <a id="infoId<%= info.CmsInfoId%>" href="#<%= info.CmsInfoId%>" class="abcEntry"><%= info.CmsHeader%>

                                <% } %>

                        <% } %>

                    <% } %>

A: You can easily remove the diacritic signs (accents, umlaut, cedilla and so on) from the string to test only on the base character. This is done by normalizing the string to Unicode form D and removing the character of category "NonSpacingMark". The following extension method strips a string of its diacritic signs :
    public static string RemoveDiacritics(this string s)
    {
        if (s == null)
            throw new ArgumentNullException("s");
        string formD = s.Normalize(NormalizationForm.FormD);
        string noDiacriticsFormD = new string(
            formD.Where(c => CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark)
                 .ToArray());
        string noDiacritics = noDiacriticsFormD.Normalize(NormalizationForm.FormC);
        return noDiacritics;
    }

Using this method, your code becomes :
var abcList = Model.FaqList.Where(x => x.CmsHeader.RemoveDiacritics().StartsWith(c.ToString())).ToList();

A: Try using i.ToString().ToUpper(StringComparison.InvariantCultureIgnoreCase). It uses a culture neutral model for case conversion, which should eliminate accents.

A: In addition to LBushkin's answer (which I think will work), you can clean up your alphabet generation.
var A = Char.Parse("A");
var alphabet = Enumerable.Range(0, 26).Select(i => A + i);

Then you can use a foreach loop and forget the whole c = i thing. Also you don't need the .ToUpper() calls because you already have capital lettters.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ruby On Rails : how to show/hide related div of radio buttons is checked I am trying using JQuery, not able to proceed. please help me.
 radio_button_tag(:radio_btn, 1, true)=> if checked div -- 'abc' show else hide()

      "abc is executing"

 radio_button_tag(:radio_btn, 0)=> if checked div -- 'xyz' show else hide()

      "xyz is executing"

A: Basically with:
$("input[type=radio]").change(function(e){ // or whatever selector you want
   // do what you want with $(e.currentTarget)
});

Made a simple fiddle to demonstrate behavior.
http://jsfiddle.net/cc5twser/2/

A: $('input[name="radio_btn"]').change(function() {
    var selected = $('input:checked[name="radio_btn"]').val();
    if(selected == '1') {
        $('#xyz').hide();
        $('#abc').show();
    } else if(selected == '0') {
        $('#abc').hide();
        $('#xyz').show();
    }
});


text:
Q: Emacs set C-RET- to M- Pretty self explanatory, but I'd like for regular RET to be RET, while C-RET will act as M. I'd like to do this because I have caps lock set to C and pressing both pinkies would be a convenient M.
Thanks in advance.


text:
Q: Set HWND TXT Color I'm trying to give a color for 1 single HWND in my win32 api..
So far I managed to give color for txt/background but that's for all the static HWNDs I have as follows:
HWND txtview1
HWND txtview2

HDC hdcStatic = (HDC)wParam;

case WM_CTLCOLORSTATIC:
    SetTextColor(hdcStatic, RGB(0, 0, 150));
    SetBkColor(hdcStatic, RGB(0, 230, 0));
    return (INT_PTR)CreateSolidBrush(RGB(255, 0255, 255));
    break;

I know it gets applied to wParam which is the whole thing..
But I want to apply it to 1 single HWND called (txtview1) not to txtview2 too
I tried:
HDC hdcStatic = GetDC(txtview1);

but it doesn't take affect, any hint is much appreciated.

A: You need to handle this message with checking if lParam equals to HWND you need
if ( (HWND)lParam == txtview1 )

Otherwise, just fall back to DefWindowProc


text:
Q: Pipenv uses the wrong lib directory I have a project using Python 3.10.4, i. e., the Pipfile has,
[requires]
python_version = "3.10.4"

I installed Python 3.10.4 using pyenv install 3.10.4 and now pyenv versions returns,
* system (set by /home/username/.config/pyenv/version)
  3.10.4

Now when I run pipenv install I get,
Creating a virtualenv for this project…
Using /home/username/.config/pyenv/versions/3.10.4/bin/python3 (3.10.4) to create virtualenv…
⠋created virtual environment CPython3.10.4.final.0-64 in 82ms
  creator CPython3Posix(dest=/home/username/.local/share/virtualenvs/project-2ZeatEXR, clear=False, no_vcs_ignore=False, global=False)
  seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app_data_dir=/home/username/.local/share/virtualenv)
    added seed packages: pip==20.3.4, pkg_resources==0.0.0, setuptools==44.1.1, wheel==0.34.2
  activators BashActivator,CShellActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator

Virtualenv location: /home/username/.local/share/virtualenvs/project-2ZeatEXR
Pipfile.lock not found, creating…
Locking [dev-packages] dependencies…
  from . import utils
  File "/usr/lib/python3/dist-packages/pipenv/vendor/requests/utils.py", line 27, in <module>
    from .cookies import RequestsCookieJar, cookiejar_from_dict
  File "/usr/lib/python3/dist-packages/pipenv/vendor/requests/cookies.py", line 172, in <module>
    class RequestsCookieJar(cookielib.CookieJar, collections.MutableMapping):
AttributeError: module 'collections' has no attribute 'MutableMapping'

The line Using /home/username/.config/pyenv/versions/3.10.4/bin/python3 (3.10.4) indicates that pipenv has found the right Python version and is using it to create the virtual environment but then when creating the lock file, observe that it uses the lib: /usr/lib/python3/dist-packages/pipenv/vendor/requests/utils.py directory is of the system installation. Which then causes the error since the system's lib is for Python 3.9.
Maybe this is a bug or maybe I have missed some config. Could someone see what is going wrong here?


text:
Q: How to display a still image of a place seeked by Unity's EasyMovieTexture I am using EasyMovieTexture on Unity to play videos.And I'm seeking a video using the slider UI.
When seeking and calling Play (), I can play from the targeted position.
Well, when I seek, I want to display a still image of the target position without playing it.
However, I can not find the corresponding method in the MediaPlayerCtrl class of EasyMovieTexture.
Please let me know if you know how to display the still image in the seek position with EasyMovieTexture.
Thanks.


text:
Q: Efficient Use of Java Heap Memory The exact question I wanted to ask has already answered here. Still I just want to explore few more possibilities (if there are any).
Scenario: My application is thread based data centric web-app and the amount of data gets decided at run time by User. A user can request some data operation, which triggers multiple threads, each thread transport own data. Sometimes the data selection crash the application with OutOfMemoryError i.e. insufficient space to allocate new object in the Java heap. When there are multiple users using the application concurrently and most of them request big data operations this situation (OutOfMemoryError) is more likely to occur.
Question: Is there a way that I can prevent whole application being crashed? I can limit the amount of data being pulled in memory but if there is a better way than this? Even after limiting the amount of data per user, multiple concurrent user can generate OutOfMemoryError. One user can be put on hold or exit rather than all survive.

A: Consistently I have experienced the following point:

*

*Stream large data out. Combined with a GZIPOutputStream on Accept-Inflate (maybe as servlet filter). This can be done for the file system and the database. Also there exist (URL based) XML pipelines where parts of the XML can be streamed.

This lowers memory costs, a stream may be throttled (articially slowed down.

*

*PDF generation: optimize the PDF, repeated images only stored once, sensible font usage (ideally the PDF fonts, otherwise embedded fonts).

*Office documents: the OpenOffice or Microsofts xlsx/docx variants.
In your case:
Have every process be combinable and stream there result to one output stream: a branching pipeline of tasks. If such a task might be called with the same parameters, yielding the same data, you could use parametrized URLs and cache the results.
I am aware this answer might not fit.


text:
Q: How to get to the data in a cosmos DB document when using Function trigger on the change feed I am using a azure function cosmos DB trigger V1 to try and parse the document take some action based on some values but I am struggling in how to read properties from the document for some reason. I am reading this page to try and understand it but cannot get it to work properly.
Documentation for trigger function
I created this sample class and it gets hit and receives the change feed just fine but I dont get inside the if clause since I am not reading the property correct and I dont really see how to get deeper into the JSON using this method
 public static class Function1
    {
        [FunctionName("Function1")]
        public static void Run([CosmosDBTrigger(
            databaseName: "XXX",
            collectionName: "XXX",
            ConnectionStringSetting = "CosmosDb",
            LeaseCollectionName = "leases", LeaseCollectionPrefix = "local")]IReadOnlyList<Document> documents, TraceWriter log)
        {
            if (documents != null && documents.Count > 0)
            {
                log.Info("Documents modified " + documents.Count);
                log.Info("First document Id " + documents[0].Id);

                foreach(var document in documents)
                {
                    if(document.GetPropertyValue<string>("sourceSystem") == "YYYY")
                    {
                        log.Info("sourceSystem = YYYY");
                    }
                }

            }
        }
    }

How do I read data from the document when it is nested deep inside a JSON array? I am a little confused about the getPropertyValue as oppose to parsing the JSON using linq or similar, How can I get my values from the document?

A: JSON files are parsed into Document Object, which provides method GetPropertyValue<T>(string propertyName). We can use this method to search first level of JSON file. To get deeper, we need to parse JSON property as appropriate.
For example, to read this file.
{
    "id": "test1",
    "myJarray": [
        {
            "mydata1": "testout",
            "mydata2": "testout"
        }
    ]
}

Get inside using JArray.
foreach (var document in documents)
{
    var array = document.GetPropertyValue<JArray>("myJarray");
    if (array != null)
    {
        var data = ((JObject)array[0]).GetValue("mydata1");
        if (data != null)
        {
            log.Info(data.ToString());
        }
    }
}


text:
Q: What good are Python function annotations? I have gone through the first couple of sections in PEP 3107, but I still don't get what good they do for the language. It seems to me that you can add metadata to functions using decorators. e.g.
def returns(return_type):
  f.return_type = return_type  # <- adding metadata here
  return f

@returns(Foo)
def make_foo(): ...

You can add metadata to arguments too, and it can look pretty if you take advantage of default arguments, like so:
import inspect

def defaults_are_actually_metadata(f):
  names, args_name, kwargs_name, defaults = inspect.getfuncspec(f)
  f.parameter_metadata = dict(zip(names[-len(defaults):], defaults))
  f.__defaults__ = ()
  return f

@defaults_are_actually_metadata
def haul(load="Stuff to be carried.",
         speed_mph="How fast to move the load (in miles per hour)."): ...

At least my initial impression is that annotations are superfluous: decorators can do everything that annotations can (and more). Why are annotations better than decorators when it comes to adding metadata to functions?

A: I think that the first paragraph states it all:

Because Python's 2.x series lacks a standard way of annotating a function's parameters and return values

(emphasis mine)
Having a standard way to do this has the advantage that you know exactly where the annotations will be located.
As for your argument about there's another way to do it, you could make the same argument against list comprehensions:
out = []
for x in my_iterable:
    out.append(x)

A: They have two different roles.
Annotations are documentation / comment for arguments while decorator transform the function.

By itself, Python does not attach any particular meaning or significance to annotations.

Python Decorators page

Decorators dynamically alter the functionality of a function, method, or class without having to directly use subclasses or change the source code of the function being decorated.

A: As you mentioned, the relevant PEP is 3107 (linked for easy reference in case others encountering this question haven't read it yet).
For now, annotations are kind of an experiment, and kind of a work in progress. There is actually a recent thread in the python-ideas mailing list on the topic which may be helpful. (The link provided is just for the monthly archive; I find that the URL for specific posts tends to change periodically. The thread in question is near the beginning of December, and titled "[Python-ideas] Conventions for function annotations". The first post is from Thomas Kluyver on Dec 1.)
Here's a bit from one of Guido van Rossum's posts in that thread:
On 12/4/2012 11:43 AM, Jasper St. Pierre wrote:

Indeed. I've looked at annotations before, but I never understood the
  purpose. It seemed like a feature that was designed and implemented without
  some goal in mind, and where the community was supposed to discover the goal
  themselves.

Guido's response:

To the contrary. There were too many use cases that immediately looked
  important, and we couldn't figure out which ones would be the most
  important or how to combine them, so we decided to take a two-step
  approach: in step 1, we designed the syntax, whereas in step 2, we
  would design the semantics. The idea was very clear that once the
  syntax was settled people would be free to experiment with different
  semantics -- just not in the stdlib. The idea was also that
  eventually, from all those experiments, one would emerge that would be
  fit for the stdlib.

Jasper St. Pierre:

So, if I may ask, what was the original goal of annotations? The PEP gives
  some suggestions, but doesn't leave anything concrete. Was it designed to be
  an aid to IDEs, or static analysis tools that inspect source code? Something
  for applications themselves to munge through to provide special behaviors,
  like a command line parser, or runtime static checker?

Guido's response:

Pretty much all of the above to some extent. But for me personally,
  the main goal was always to arrive at a notation to specify type
  constraints (and maybe other constraints) for arguments and return
  values. I've toyed at various times with specific ways of combining
  types. E.g. list[int] might mean a list of integers, and dict[str,
  tuple[float, float, float, bool]] might mean a dict mapping strings to
  tuples of three floats and a bool. But I felt it was much harder to
  get consensus about such a notation than about the syntax for argument
  annotations (think about how many objections you can bring in to these
  two examples :-) -- I've always had a strong desire to use "var: type
  = default" and to make the type a runtime expression to be evaluated
  at the same time as the default.

And a tiny bit of humor from Ned Batchelder:

A telling moment for me was during an early Py3k keynote at PyCon (perhaps
  it was in Dallas or Chicago?), Guido couldn't remember the word
  "annotation," and said, "you know, those things that aren't type
  declarations?"  :-)


text:
Q: Converting JOIN to Subquery I am trying to figure out how to convert a JOIN to a subquery. I am using AdventureWorks2019 database and I am pulling data from two tables. My JOIN statement I created is:
SELECT FirstName, MiddleName, LastName, StateProvinceID
FROM Person.Person AS P
  JOIN Person.BusinessEntityAddress AS BEA
    ON P.BusinessEntityID = BEA.AddressID
  JOIN Person.Address AS A
    ON BEA.BusinessEntityID = A.AddressID
WHERE StateProvinceID = 79;

How do I turn this into a subquery? Do I create them in FROM or WHERE?


text:
Q: .x86 file not executing I've tracked down a game named superhot and downloaded zipped Linux version. I unzipped it and there was a directory named SUPERHOT-LINUX_Data and file with extension .x86. I went to properties and ticked "can execute". But the file still doesn't start. All i can see is bunch of processes starting upon clicking on that file. Their names starts with unity.
Should i install some libraries or something?
Thanks for advice
Edit: I've tried as damien said and mono installed successfully, but still nothing. Then i tried running that file from terminal:
$ ./SUPERHOT-LINUX.x86

and it returned:
./SUPERHOT-LINUX.x86: error while loading shared libraries: libGLU.so.1: cannot open shared object file: No such file or directory

I guess something is missing?

A: I solved by installing these libraries:
$ sudo apt-get install libglu1-mesa:i386 libxcursor1:i386

You can print shared library dependencies with:
$ ldd SUPERHOT-LINUX.x86

A: Yes, your system lacks that library (libGLU). In this case it is available in the repositories so you just need to run
$ sudo apt-get install libglu1-mesa

If you find similar errors you can try to find the needed package using apt-file. In this case, to search packages that have the file libGLU.so.1:
$ apt-file search libGLU.so.1
libglu1-mesa: /usr/lib/x86_64-linux-gnu/libGLU.so.1
libglu1-mesa: /usr/lib/x86_64-linux-gnu/libGLU.so.1.3.08000
libglu1-mesa: /usr/lib/x86_64-linux-gnu/libGLU.so.1.3.08004


text:
Q: Emulate limited resource device android I am trying to find a NullPointerException that I get when in my app the phone release memory. I was testing on a Samsung G3, but now that I have change for a GS2 which has more RAM memory, the variable is still there when I minimaze/maximize.
Is there any way to simulate my old phone and his limited RAM memory? A bit ironic,but now I miss it...In the SDK emulators I can set SD card size, but not the RAM, which I guess is the key problem here.

A: There is a program on the android market called CPU Master. You can set CPU speed so then you can test your program as in a phone with limited resources.


text:
Q: scikit learn - feature importance calculation in decision trees I'm trying to understand how feature importance is calculated for decision trees in sci-kit learn. This question has been asked before, but I am unable to reproduce the results the algorithm is providing.
For example:
from StringIO import StringIO

from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
from sklearn.tree.export import export_graphviz
from sklearn.feature_selection import mutual_info_classif

X = [[1,0,0], [0,0,0], [0,0,1], [0,1,0]]

y = [1,0,1,1]

clf = DecisionTreeClassifier()
clf.fit(X, y)

feat_importance = clf.tree_.compute_feature_importances(normalize=False)
print("feat importance = " + str(feat_importance))

out = StringIO()
out = export_graphviz(clf, out_file='test/tree.dot')

results in feature importance:
feat importance = [0.25       0.08333333 0.04166667]

and gives the following decision tree:

Now, this answer to a similar question suggests the importance is calculated as

Where G is the node impurity, in this case the gini impurity. This is the impurity reduction as far as I understood it. However, for feature 1 this should be:

This answer suggests the importance is weighted by the probability of reaching the node (which is approximated by the proportion of samples reaching that node). Again, for feature 1 this should be:

Both formulas provide the wrong result. How is the feature importance calculated correctly?

A: A single feature can be used in the different branches of the tree, feature importance then is it's total contribution in reducing the impurity.
feature_importance += number_of_samples_at_parent_where_feature_is_used\*impurity_at_parent-left_child_samples\*impurity_left-right_child_samples\*impurity_right

impurity is the gini/entropy value
normalized_importance = feature_importance/number_of_samples_root_node(total num of samples)

In the above eg:
feature_2_importance = 0.375*4-0.444*3-0*1 = 0.16799 ,
normalized = 0.16799/4(total_num_of_samples) = 0.04199

If feature_2 was used in other branches calculate the it's importance at each such parent node & sum up the values.
There is a difference in the feature importance calculated & the ones returned by the library as we are using the truncated values seen in the graph.
Instead, we can access all the required data using the 'tree_' attribute of the classifier which can be used to probe the features used, threshold value, impurity, no of samples at each node etc..
eg: clf.tree_.feature gives the list of features used. A negative value indicates it's a leaf node.
Similarly clf.tree_.children_left/right gives the index to the clf.tree_.feature for left & right children
Using the above traverse the tree & use the same indices in clf.tree_.impurity & clf.tree_.weighted_n_node_samples to get the gini/entropy value and number of samples at the each node & at it's children.
def dt_feature_importance(model,normalize=True):

    left_c = model.tree_.children_left
    right_c = model.tree_.children_right

    impurity = model.tree_.impurity
    node_samples = model.tree_.weighted_n_node_samples

    # Initialize the feature importance, those not used remain zero
    feature_importance = np.zeros((model.tree_.n_features,))

    for idx,node in enumerate(model.tree_.feature):
        if node >= 0:
            # Accumulate the feature importance over all the nodes where it's used
            feature_importance[node]+=impurity[idx]*node_samples[idx]- \
                                   impurity[left_c[idx]]*node_samples[left_c[idx]]-\
                                   impurity[right_c[idx]]*node_samples[right_c[idx]]

    # Number of samples at the root node
    feature_importance/=node_samples[0]

    if normalize:
        normalizer = feature_importance.sum()
        if normalizer > 0:
            feature_importance/=normalizer

    return feature_importance

This function will return the exact same values as returned by clf.tree_.compute_feature_importances(normalize=...)
To sort the features based on their importance
features = clf.tree_.feature[clf.tree_.feature>=0] # Feature number should not be negative, indicates a leaf node
sorted(zip(features,dt_feature_importance(clf,False)[features]),key=lambda x:x[1],reverse=True)

A: I think feature importance depends on the implementation so we need to look at the documentation of scikit-learn.

The feature importances. The higher, the more important the feature. The importance of a feature is computed as the (normalized) total reduction of the criterion brought by that feature. It is also known as the Gini importance

That reduction or weighted information gain is defined as :

The weighted impurity decrease equation is the following:
N_t / N * (impurity - N_t_R / N_t * right_impurity
                      - N_t_L / N_t * left_impurity)
where N is the total number of samples, N_t is the number of samples at the current node, N_t_L is the number of samples in the left child, and N_t_R is the number of samples in the right child.

http://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html#sklearn.tree.DecisionTreeClassifier
Since each feature is used once in your case, feature information must be equal to equation above.
For X[2] :
feature_importance = (4 / 4) * (0.375 - (0.75 * 0.444)) = 0.042
For X[1] :
feature_importance = (3 / 4) * (0.444 - (2/3 * 0.5)) = 0.083
For X[0] :
feature_importance = (2 / 4) * (0.5) = 0.25


text:
Q: BLE characteristic changed callback executed only for first change after write I try to subscribe to BLE characteristic notification using typical approach:
stCharacteristic = stService.GetCharacteristics(stCharacteristicGUID)[0];
await stCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);
stCharacteristic.ValueChanged += stData_ValueChanged;

The callback function has also standard form:
async void stData_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
{
    var values = (await sender.ReadValueAsync()).Value.ToArray();
}

The problem is that the callback is not always called when the BLE device changes characteristic's value. When I write something to the characteristic and the device writes something in reponse, then the callback is called. But if the devices writes to characteristic just by itself the callback is not called. The funny part is that the data are not lost. When I write something again, I get several calls to my callback with all the data sent by the BLE device in meantime. In other words it looks like Windows or .NET Framework caches subsequent incoming data until a write is made. After write only first characteristic change causes callback to be fired.

*

*incoming data - no callback

*sending data

*incoming data - two callbacks!

*sending data

*incoming data - one callback

*incoming data

*incoming data

*incoming data

*sending data - three callbacks!

Windows 10, VS2015

A: You don't have to read the value in the ValueChanged callback. The value is already present in the GattValueChangedEventArgs.
Other than that - your handler should really be called directly and not after a write. Can you see if your device is disconnected / connected between the notifications?

A: It turns out it was Windows 10 issue. And on Windows 10.0.15063 and newer, like 10.0.16251, it's even worse - there are no callbacks at all. Fortunately there is a simple workaround, two registry entries are needed to be added. Here is the .reg file:
Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\AppID\{C6BFD646-3DF0-4DE5-B7AF-5FFFACB844A5}]
"AccessPermission"=hex:01,00,04,80,9c,00,00,00,ac,00,00,00,00,00,00,00,14,00,\
  00,00,02,00,88,00,06,00,00,00,00,00,14,00,07,00,00,00,01,01,00,00,00,00,00,\
  05,0a,00,00,00,00,00,14,00,03,00,00,00,01,01,00,00,00,00,00,05,12,00,00,00,\
  00,00,18,00,07,00,00,00,01,02,00,00,00,00,00,05,20,00,00,00,20,02,00,00,00,\
  00,18,00,03,00,00,00,01,02,00,00,00,00,00,0f,02,00,00,00,01,00,00,00,00,00,\
  14,00,03,00,00,00,01,01,00,00,00,00,00,05,13,00,00,00,00,00,14,00,03,00,00,\
  00,01,01,00,00,00,00,00,05,14,00,00,00,01,02,00,00,00,00,00,05,20,00,00,00,\
  20,02,00,00,01,02,00,00,00,00,00,05,20,00,00,00,20,02,00,00

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\AppID\YOURAPP.exe]
"AppID"="{C6BFD646-3DF0-4DE5-B7AF-5FFFACB844A5}"

Change YOURAPP.exe to you exe file name. The GUID can be changed or left as it is. After applying this .reg file callbacks are called instantly every time and notifications are being received very well.
At the moment of writing this answer Microsoft was working on a permanent fix. The workaround and the discussion is here: https://social.msdn.microsoft.com/Forums/en-US/58da3fdb-a0e1-4161-8af3-778b6839f4e1/bluetooth-bluetoothledevicefromidasync-does-not-complete-on-10015063?forum=wdk


text:
Q: Custom Post Type and single-posttype template I created CPT topic
function wpse100_create_cpt() {
    register_post_type( 'topic', array(
        'labels' => array(
            //.....
            ),
        'public' => true,
        'publicly_queryable' => true,
        'capability_type' => 'post',
        'hierarchical' => false,
        'rewrite' => array(
            'slug' => '/topic',
            'with_front' => false
            ),
        'has_archive' => false,
        'query_var' => true,
        ) );
add_action( 'init', 'wpse100_create_cpt' );

I choose permalink /%postname%, but by default URL mysite.tld/topic/postname, then I remove slug from URL  mysite.tld/postname uses this code
function wpse100_remove_slug($post_link, $post) {
    if ( 'topic' != $post->post_type )
        return $post_link;

    return str_replace(get_bloginfo('url') . '/topic' , get_bloginfo('url'), $post_link);
}
add_filter( 'post_type_link', 'wpse100_remove_slugs', 10, 2 );

and then create template for CPT single-topic.php but I get 404 error. How I can to correct the error?
PS If I turn off function wpse100_remove_slug() it works fine, but I need use URL such as mysite.tld/postname
Thanks!

A: I found solution. Big Thanks @Scribu Alternative to query_posts for main loop? Now works fine and no more 404 error.
function wpse49295_alter_the_query( $request )
{
    $dummy_query = new WP_Query();
    $dummy_query->parse_query( $request );

    if ( $dummy_query->is_single() )
        $request['post_type'] = 'topic';

    return $request;
}
add_filter( 'request', 'wpse49295_alter_the_query' );


text:
Q: Bash - sed syntax with variables I've got two variables VAR1 and VAR2 that contain strings. What I want to do is go through a list of files that have a .txt extension and change all occurences of VAR1 to VAR2. So far, it looks like this:
for i in `find . -name "*.txt"`
do
 echo $i
 sed -i -E "s|\$VAR1|\$VAR2|g" $i
done

I think everything except the sed line is working well. I think it's a syntax issue, but I haven't been able to figure out what it is. Any help would be appreciated
Thanks

A: You shouldn't need to escape your $ variable. Also make sure to use the lower case -e and quote the filename in case it has spaces:
sed -ri -e "s|$VAR1|$VAR2|g" "$i"

A: Since sed's "find-and-replace" functionality is oriented to regular expressions rather than literal strings, you might wish to consider an alternative to sed, e.g. using awk as follows:
 awk -v from="$VAR1" -v to="$VAR2" '
   function replace(a,b,s,  n) {
     n=index(s,a);
     if (n==0) {return s}
     return substr(s,1,n-1) b replace(a,b, substr(s,n+length(a)));
   }
   {print replace(from, to, $0)} '

The above can easily be combined with the find ... | while read f ; do .... done pattern mentioned elsewhere on this page.
GNU awk supports the equivalent of sed's '-i' option, but it's probably better simply to direct the output of awk to a temporary file, and then mv it into place.

A: You managed to quote the dollar sign from the shell (which would not have been necessary if you had used single quotes instead of double) but this does not change the fact that dollar signs also have a meaning in regular expressions. Double the backslashes to escape from both the shell and sed, or use single quotes so the backslashes get through to sed.  Alternatively, use a notation which does not require backslashes.
sed -i -E 's|[$]VAR1|$VAR2|g' "$i"

Incidentally, your loop has a number of problems. Your for loop will not work correctly if there are file names with whitespace in them, and you need to quote the arguments inside the loop.  To completely cope with file names with special characters in them, you want to use find -exec instead.
find . -name "*.txt" -exec sed -i -E 's|[$]VAR1|$VAR2|g' {} \;

If your find supports \+ instead of \;, by all means use that.

A: (1) Using the idiom for i in $(find ....) ; do ...; done will often work as intended, but it is not robust.  Significantly better is the pattern:
find ... | while read i ; do ... ; done

(2) If $VAR1 and/or $VAR2 contain characters that have special significance in regular expressions, then some care will be required.  For example, parentheses ("(" and ")") have special significance, and so if VAR1 contains these, using the -r option (or on a Mac, the -E option) is probably asking for trouble.
(3) Chances are that sed -i -e "s|$VAR1|$VAR2|g" will do the trick if VAR1 does not contain any of the eight characters: ^$*[]\|. and if VAR2 does not contain "|", "\" or "&".
(4) If you want to prepare your strings ($VAR1 and $VAR2) programatically for use with sed, then see this SO page; it shows how to munge the strings -- using sed of course!


text:
Q: How to delete part of string from specific word? Below is my sql query :
select * from Table where col1 = @param1 and col2 = @param2

Now I want to delete everything from where clause so expected output is like below :
select * from Table;

Code:
string str = "select * from Table where col1 = @param1 and col2 = @param2";

var str = sqlQuery.Replace("where", ""); // select * from Table col1 = @param1 and col2 = @param2

A: One way would be to work with IndexOf and Substring.
var sql = "select* from Table where col1 = @param1 and col2 = @param2";
var index = sql.IndexOf("where", StringComparison.OrdinalIgnoreCase);
var newSql = sql.Substring(0, index);

You could use Trim as well to remove the white space at the end. This would look like.
var newSql = sql.Substring(0, index).Trim();

A: I created below extension method with the help of answer provided by @Mighty Badaboom.
 static public string Foo(this string original,string wordToFind, StringComparison stringComparision = StringComparison.OrdinalIgnoreCase)
        {
            var index = original.IndexOf("where", stringComparision);
            return original.Substring(0, index).Trim();
        }

string newSql = Foo(str, "where", StringComparison.OrdinalIgnoreCase);


text:
Q: Verify Linux FAT32 Support I apologize if this is a duplicate, but I could not find any related question.
How can I verify that my Linux 3.16.1 kernel supports FAT32?

Things to keep in mind:
I do not have /proc/config.gz available to me.  When I build the kernel I enabled the following config values:
# DOS/FAT/NT Filesystems
#
CONFIG_FAT_FS=y
CONFIG_MSDOS_FS=y
CONFIG_VFAT_FS=y
CONFIG_FAT_DEFAULT_CODEPAGE=437
CONFIG_FAT_DEFAULT_IOCHARSET="iso8859-1"
CONFIG_NTFS_FS=y
# CONFIG_NTFS_DEBUG is not set
# CONFIG_NTFS_RW is not set

However, when I plug in a USB drive formatted with FAT32 it is not automounted.  This is fine.  I'm not a complete Linux n00b.  I ran lsusb, and saw my device listed.  Fantastic!  Lets see what its listed under in /dev.  I ran sudo blkid, nothing but my HDD is the only disk listed.
Running modprobe vfat and restarting did not change the results from above.
Is there something else that I'm missing?
Edit
Kernel Messages when a USB device is connected and disconnected.
Dec 10 11:46:45 narrator kernel: [   20.164811] usb 2-1.8: new full-speed USB device number 5 using ehci-pci
Dec 10 11:46:45 narrator kernel: [   20.280044] usb 2-1.8: New USB device found, idVendor=0a5c, idProduct=5801
Dec 10 11:46:45 narrator kernel: [   20.280055] usb 2-1.8: New USB device strings: Mfr=1, Product=2, SerialNumber=3
Dec 10 11:46:45 narrator kernel: [   20.280061] usb 2-1.8: Product: 5880
Dec 10 11:46:45 narrator kernel: [   20.280067] usb 2-1.8: Manufacturer: Broadcom Corp
Dec 10 11:46:45 narrator kernel: [   20.280072] usb 2-1.8: SerialNumber: 0123456789ABCD
Dec 10 11:46:45 narrator kernel: [   20.280200] usb 2-1.8: config 0 descriptor??
Dec 10 11:46:45 narrator kernel: [   24.792805] usbcore: registered new interface driver usbhid
Dec 10 11:46:45 narrator kernel: [   24.792812] usbhid: USB HID core driver
Dec 10 11:46:45 narrator kernel: [   24.924891] input: Logitech USB-PS/2 Optical Mouse as /devices/pci0000:00/0000:00:1d.0/usb2/2-1/2-1.1/2-1.1:1.0/0003:046D:C03E.0001/input/input14
Dec 10 11:46:45 narrator kernel: [   24.925127] hid-generic 0003:046D:C03E.0001: input,hidraw0: USB HID v1.10 Mouse [Logitech USB-PS/2 Optical Mouse] on usb-0000:00:1d.0-1.1/input0
Dec 10 11:49:43 narrator kernel: [  209.720215] usb 2-1.3: USB disconnect, device number 4

/proc/filesystems:
$ cat /proc/filesystems
nodev   sysfs
nodev   rootfs
nodev   ramfs
nodev   bdev
nodev   proc
nodev   cgroup
nodev   cpuset
nodev   tmpfs
nodev   devtmpfs
nodev   debugfs
nodev   securityfs
nodev   sockfs
nodev   pipefs
nodev   devpts
nodev   hugetlbfs
    vfat
    msdos
    ntfs
nodev   pstore
nodev   mqueue
    ext4
nodev   autofs
    ext2
nodev   binfmt_misc
    fuseblk
nodev   fuse
nodev   fusectl

A: First check this  cat /proc/filesystems  if vfat is their or not.
and
sounds silly but work many time use some guitool FS tools like Gparted  sometimes its easy to troubleshoot with them.
To inspect all filesystem modules Check here also ls /lib/modules/$(uname -r)/kernel/fs


text:
Q: Why am I getting a babel errors from a .babelrc file in a parent directory I was recently trying to debug errors in a next.js getting started project and realized that it didn't like a .babelrc file in a parent directory.
My questions are:

*

*Why is the project throwing an error on a .babelrc configuration file in a parent directory that's not part of the project?  Does it recursively look for a babel configuration file in all parent directories or did I at some point configure babel to look at that config file?  How can I check what that configuration is?

*Is this a quirk of next.js that makes it look for a configuration file in a parent directory?
I forgot if I had added that .babelrc configuration in the parent directory - is that something that I needed?  What is the configuration?  How should I update it to make the error go away?
ERROR in ./pages/index.js

Module build failed: ReferenceError: [BABEL] /Users/me/Projects/foo/foo-web/pages/index.js:
 Using removed Babel 5 option: /Users/me/Projects/.babelrc.optional
 - Put the specific transforms you want in the `plugins` option

.babelrc
"optional": ["es7.classProperties"]

A: *

*babel is looking first .babelrc file is present in the root directory

*you have to create the .babelrc file

npm install  babel-plugin-transform-runtime
insert to .babelrc
{
  "plugins": [
    "transform-runtime"
  ]
}

more info


text:
Q: How can I get a unique list of rows where a certain field is X? With the table below, I want to get a id, form, value for each UNIQUE form from where value = 1.  I've tried select id, form, value from tableName group by form but the query returns ids 1 and 6, not ids 2 and 4 like I want.
EDIT 1&2: I am trying to use this in a subquery in a left outer join, but I am simply trying to get a list of all forms with value=1 if it exists, otherwise the value=0 result, in order to use in my join.  If I use select id, form, value from tableName where value=1 group by form I don't get the a2 or b1 forms.
id  form  value
---|-----|------------
1  | a1  | 0
2  | a1  | 1
5  | a2  | 0
3  | b1  | 0
4  | c1  | 1
6  | c1  | 0

The result I want is :
id  form  value
---|-----|------------
2  | a1  | 1
5  | a2  | 0
3  | b1  | 0
4  | c1  | 1

A: Are you looking for something like this?
SELECT t.id, q.form, q.value
  FROM (
  SELECT form, MAX(value) value
    FROM table1
   GROUP BY form
) q JOIN table1 t
    ON q.form = t.form
   AND q.value = t.value

Output:

| id | form | value |
|----|------|-------|
|  2 |   a1 |     1 |
|  5 |   a2 |     0 |
|  3 |   b1 |     0 |
|  4 |   c1 |     1 |

SQLFiddle


text:
Q: Prove that $E_{\lambda}(T)=E_{\lambda^{-1}}(T^{-1})$ if $T$ is an invertible linear operator on a finite dimensional vector space $V$ Let $T$ be an invertible linear operator on the finite dimensional $F$-vector space $V$.  Prove that if $\lambda$ is an eigenvalue of $T$, then $\lambda^{-1}$ is an eigenvalue of $T^{-1}$ and that the eigenspaces $E_{\lambda}(T)=E_{\lambda^{-1}}(T^{-1})$.
I have shown the first part of the proof, but it remains to show that $E_{\lambda}(T)=E_{\lambda^{-1}}(T^{-1})$ is true.  I'm thinking that this needs to be shown by proving the dimension of each of the eigenspaces, or can it be done through just by showing that all elements of one eigenspace are in the other, and vice versa.

A: How about $Tv = \lambda v $ iff $\frac{1}{\lambda} v = T^{-1} v$ (Multiply the first equation by $T^{-1}$ and divide through by $\lambda$. $T$ is invertible, so all eigenvalues are $\neq 0$).
Explicitly, if $v \in E_\lambda(T)$ then $Tv = \lambda v $, hence $v = \lambda T^{-1} v $ and $\frac{1}{\lambda} v = T^{-1} v$. Hence $v \in E_{\frac{1}{\lambda}}(T^{-1})$. This gives $E_\lambda(T) \subset E_{\frac{1}{\lambda}}(T^{-1})$.
Since the same applies to $E_{\frac{1}{\lambda}}$ (and $(T^{-1})^{-1} = T$), we also have $E_{\frac{1}{\lambda}}(T^{-1}) \subset E_\lambda(T)$.
Hence they are equal.


text:
Q: How can I obtain data from database with a specific DateTime range I want to calculate statistics based for data from DB. For example:
In 2019 you earned: XXXX
In January 2019 you earned: XXXX
Till now you earned: XXXX
etc...
Are there any build in (sorting) functions in EF to do that?
How to build a proper method?
My controller so far:
[HttpGet("GetStatistics/{From}/{To}")]
    public async Task<IActionResult> GetStatisticsByTime(DateTime From, DateTime To)
    {
      try
      {
        var guest = await _guestService.GetByTime(From, To);
        return Ok(guest);
      }
      catch (NullReferenceException e)
      {
        return NotFound("Can't found values in this time period");
      }
    }

My service and repository interface method declaration:
Task<IEnumerable<TEntity>> GetByTime(DateTime From, DateTime To);

And I should create an implementation of above
Edit1;
I've tried with "where" but I got null (In db exist values with year 2017, 2018).
I've changed controller for one attribute - int year, and my method is:
public async Task<IEnumerable<Guest>> GetByTime(int year)
    {
      var guests = await _bookingContext.Guests
        .Where(x => x.reservation.CheckOut.Year == year)
        .ToListAsync();

        return guests;
    }

But that gives me null
CheckOut is a field with DateTime type.

A: Ok SOLVED.
I've done it with a proper method in service layer - it was a reason of null:
var guests = await _iGuestRepository.GetByTime(year);
      return guests.ToList();

I was using additional mappers, which caused a problem.
Repository layer:
var guests = await _bookingContext.Guests
        .Where(x => x.reservation.CheckOut.Year == year)
        .ToListAsync();

        return guests;

A: I want to recommend you to use CompareTo method with DateTime type, which
 returns a signed number indicating the relative values of this instance and the value
    parameter. Value Description Less than zero This instance is earlier than value.
    Zero This instance is the same as value. Greater than zero This instance is later
    than value.


text:
Q: TabControl with current tabpage triangle I need to modify this tabcontrol i found online, if i change the item height, the triable does not adjust properly

The code doing the drawing is
G.SmoothingMode = SmoothingMode.HighQuality
                Dim p() As Point = {New Point(ItemSize.Height - 3, GetTabRect(i).Location.Y + 20), _
                           New Point(ItemSize.Height + 4, GetTabRect(i).Location.Y + 14), _
                           New Point(ItemSize.Height + 4, GetTabRect(i).Location.Y + 28)}
     G.FillPolygon(Brushes.White, p)
     G.DrawPolygon(New Pen(Color.FromArgb(170, 187, 204)), p)

I have made adjustments to the line New Point(ItemSize.Height + 4, GetTabRect(i).Location.Y + 14) without success.
i need the triangle albeit bigger and centered in the Tabpage rectangle if the size is adjusted, say by 3 points.
Any ideas

A: I was able to find a solution after futher tinkering
 Dim hlf As Integer = GetTabRect(i).Height \ 2
G.SmoothingMode = SmoothingMode.HighQuality
            Dim p() As Point = {New Point(ItemSize.Height - 6, GetTabRect(i).Location.Y + hlf), _
      New Point(ItemSize.Height + 4, GetTabRect(i).Location.Y + hlf - 7), _
      New Point(ItemSize.Height + 4, GetTabRect(i).Location.Y + hlf + 7)}


text:
Q: While redirecting to other pages, events in Current pages not firing until redirected page loads While redirecting to other pages, events in Current pages not firing until redirected page loads. How to handle the events during other page is processing in Asp.Net

A: by default, thread of current page stops after redirection. you can keep response active with:
Response.Redirect("url", false)


text:
Q: Godot: too few arguments every now and then I stumble over an error-message like the one in this case:
if "," in text.erase():
print ("comma erased")

error(109,1): Too few arguments for "erase()" call. Expected at least
2.

Whatever I try to put into those (), nothing seems to work. How can I find out what arguments I need in such a case?

A: At least some basic programming knowledge provided, the editor's Search Help offers some useful info in such a case:
void erase ( int position, int chars )
Erases chars characters from the string starting from position.


text:
Q: How disable InfiniteGallery from responding to user Interaction I'm trying to disable user interaction on com.blundell.tut.ui.view.InfiniteGallery, I've done everything,
  android:clickable="false"
  android:focusable="false"
  galleryOne.setClickable(false);

add click and focusable on layout to true, and all still not working. I just want to disable users from being able to interact with it. Any other idea would be welcomed. Thanks.
 <LinearLayout
    android:id="@+id/galLay"
    android:layout_width="fill_parent"
    android:layout_height="0dip"
    android:layout_marginBottom="10dip"
    android:layout_weight="1"
    android:padding="5dip"
    android:clickable="true"
    android:focusable="false">

    <com.blundell.tut.ui.view.InfiniteGallery
        android:id="@+id/cardgallery"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:spacing="0dp"
        android:clickable="false"
        android:focusable="false"/>
</LinearLayout>

A: Set an OnTouchListener on the InfiniteGallery instance, and just return true in the onTouch() method to signal that the event has been handled. For example:
galleryOne.setOnTouchListener(new OnTouchListener()
    {
        @Override
        public boolean onTouch(View view, MotionEvent event)
        {
            return true;
        }
    }
);


text:
Q: What does return &obj mean? What impact does it have on equality checks What is the difference in returning
func New(text string) error { return &errorString{text} }

or returning like
func New(text string) error { return errorString{text} }

errorString is defined as follow
type errorString struct { text string }

error is defined as follow
type error interface {
  Error() string
}

I especially want to know what the difference in the return value is:
return &errorString{text}
      vs.
return errorString{text}

I already read the guide but it didn't mentioned the difference. It only mentioned, that with one you are not able to use equal what you do not want with the error object.

A: errorString{text} is a struct and &errorString{text} is a pointer to a struct. See https://tour.golang.org/moretypes/1 for a more detailed explanation of what this means.
There is also this question which has specifics on when to return which: Pointers vs. values in parameters and return values. Returning errorText{text} returns a copy of the entire struct while &errorText{text} returns a pointer to a struct instead.
A struct S and a pointer to a struct of type S are two separate types in Go. For errorText to implement the error interface, errorText must implement the Error() string method but it also needs to have the correct receiver type.
For example, this is OK:
type errorText struct {
    text string
}

func (e errorText) Error() string { return e.text }

func SomethingThatReturnsYourError() error {
    return errorText{"an error"}
}

This is also OK:
type errorText struct {
    text string
}

func (e errorText) Error() string { return e.text }

func SomethingThatReturnsYourError() error {
    return &errorText{"an error"} // Notice the &
}

But this is not OK and the compiler will hit you with an error:
type errorText struct {
    text string
}

// notice the pointer receiver type
func (e *errorText) Error() string { return e.text }

func SomethingThatReturnsYourError() error {
    return errorText{"an error"}
}

Error message: cannot use errorString literal (type errorString) as type error in return argument:
    errorString does not implement error (Error method has pointer receiver)
In order to use a pointer receiver you have to return a pointer:
type errorText struct {
    text string
}

func (e *errorText) Error() string { return e.text }

func SomethingThatReturnsYourError() error {
    return &errorText{"an error"}
}


text:
Q: java nio socketChannel.write() missing bytes System.out.println(" @ bBuffer = " + bBuffer.capacity());

headerBuffer.rewind();
socketChannel.write(headerBuffer);

int writen = socketChannel.write(bBuffer);
System.out.println(" @ writen = " + writen);

bBuffer is an object of type ByteBuffer and it came from FileChannel.map() (it's an image file).  When I receive this image file on client, it wasn't a complete image--about half of image was missing.  So I checked how much bytes was written by printing some statistics to the console.  The output was:
 @ bBuffer = 319932
 @ writen = 131071

What happened to the rest of the bytes?   It seems that (319923 - 131071) bytes are missing.
Sometimes written is equals to bBuffer.capacity() and it's seems irrespective to file size or buffer capacity.

A: Your code makes an invalid assumption. read() and write() aren't obliged to transfer more than one byte per call. You have to loop. But you're doing this wrong anyway. It should be:
while (headerBuffer.position() > 0)
{
    headerBuffer.flip();
    socketChannel.write(headerBuffer);
    headerBuffer.compact();
}

or
headerBuffer.flip();
while (headerBuffer.hasRemaining())
{
    socketChannel.write(headerBuffer);
}
headerBuffer.compact();

If the SocketChannel is in non-blocking mode, it gets considerably more complex, but you haven't mentioned that in your question.
You also need to check your receiving code for the same assumption.


text:
Q: If $a_n(t) \to a(t)$ and $t \mapsto a_n$ is continuous, are the $a_j(t)$ in a compact subset independent of $t$? I have a sequence $a_n(t) \to a(t)$ in a Hilbert space $H$.  Furthermore, for each $n$, $a_n:[0,1] \to H$ is continuous. Is it possible to deduce that
$$\{a_n(t)\}_{n \in \mathbb{N}}$$
is contained in a compact subset $K$ of $X$, where $K$ is independent of $t$ as well as $n$???
I think the asnwer is no, since we only get inclusion in compact sets that either depend on $t$ or on $n$. Does anyone know if it holds under additional assumptions on the sequence?


text:
Q: Структура и архитектура набора компонентов UI В очередной раз приходится участвовать в строительстве набора UI компонентов компании и в очередной раз сталкиваюсь с дилеммой.
Например, у нас есть некий Some UI, состоящий из стандартного набора компонентов, включающего TextField, Checkbox, Radio и прочие. Все бы хорошо, но в большинстве случаев для сложных интерфейсов фундаментальных возможностей этих компонентов становится недостаточно и приходится их расширять.
Возьмем компонент TextField(input). Один из самых важных и часто используемых компонентов форм, позволяющих пользователю вводить текстовую информацию. С ним все хорошо, но со временем или сразу возникнет необходимость ограничивать тип вводимых в него данных, добавить иконку внутрь поля, показывать callout по клику на него и прочее. И вот тут и встает вопрос о стратегии расширения возможностей этого компонента.
Вот, например, есть задача: дать возможность пользователю ввести номер телефона в формате +(7) 123-45-67. Тут все предсказуемо, скорее всего вы бы добавите нашему TextField дополнительное свойство phone, принимающее boolean-значение, либо, если вы чуть более дальновидны, свойство type, принимающее значение "phone". Все просто.
Появляется следующая задача: добавить возможность вводить в поле сумму в рублях в формате 00,00, и запилить иконку валюты внутрь поля. Эта задача в реализации немного сложнее предыдущей и здесь возникает соблазн сделать её в виде отдельного компонента, например, MoneyField. Кажется, в этом есть смысл, так как это облегчит код основного компонента. В подобных ситуациях нужно принимать решение о стратегии расширения этого компонента, либо создавать отдельный компонент, либо расширять нынешний, например, через тоже свойство type.
Я сильно склоняюсь к варианту "прокачки" единственного компонента. Пусть лучше это будет монстр TextField с большим количеством параметров, чем множество мелких и легких компонентов, решающих точечные задачи. Знаю, что второй вариант многим, на первый взгляд, кажется более привлекательным, но поработав с таким решением пару лет, понимаю, что это не самая лучшая стратегия. С другой стороны я не уверен что вариант с прокачкой единственного компонента покажет себя лучше со временем, хотя в теории у меня все сходится :)
Короче, если бы вы создавали набор компонентов UI (вроде Material UI, Fabric, Kendo и пр.) какой подход в расширении базовых компонентов вы бы использовали? Круто, если у кого-то есть реальный опыт создания больших базовых компонентов. Поделитесь, пожалуйста.

A: В своих проектах решаю проблему через наследование. Есть базовый полу-абстрактный класс TextFieldAbstract содержащий основные методы и поля. Есть несколько отнаследованных классов в которых содержится реализация для всех специфических частей (TextFieldText, TextFieldMoney, TextFieldNumber, etc.). Это разумный баланс между дублированием кода и классом-монстром.
P.S. А TextFieldAbstract сам наследуется от ControlAbstract, в котором общие вещи для всех контролов (типа положения, Enabled/Disabled и т.п.). ControlAbstract, в свою очередь, наследован от базового Object.
Не знаю насколько это применимо в JS. Делайте поправку на то что описанный подход хорошо работает в C / Delphi / т.п.

A: Вы бросаетесь от крайности в крайность. Между множеством мелких и часто ненужных компонентов и одним компонентом, заточенным под миллион задач есть середина. Если компонент представляет собой низкую абстракцию, то его ни в коем случае не нужно раздувать. Компонент должен решать одну задачу и в нём не должно быть много абстракций.
Если есть Input и нужно его расширить под ввод телефона, не стоит его кастомизировать и вводить ему поля. Лучше создать компонент PhoneInput, который будет являться контейнером для компонента Input, но с надстройками. Это и есть компонентный подход, это и переписывается легче, и тестируется проще, и дебажится лучше, и рефакторить это потом не придётся с клоунами на вертолётах.

A: Говоря про компонентный подход, нельзя не упомянуть всеми известный React, который как раз продвигает философию компонентов, используя при этом функциональный подход. Можно конечно рассуждать на эту тему, хорошо ли подходит парадигма функционального программирования для написания UI-компонентов, но как по мне это идеальное решение. UI пишется за счет функциональных компонентов, а модель реализуется уже с помощью привычного нам ООП
Заданный вами вопрос в контексте функциональных компонентов решается за счет композиции компонентов, есть какие-то атомарные компоненты, типа Input, Button + есть составные, более сложные компоненты - комбинация атомарных компонентов.
Для примера, у нас есть кнопка (буду использовать синтаксис React компонентов, но там не очень сложно разобраться)
class Button extends Component {
    render() {
        // html компонента, который мы будем получать на выходе
        return (
            <button onClick={this.props.onClick}>
                {this.props.buttonText}
            </button>
        )
    }
}

Компонент рисует простую кнопку, которая принимает два параметра: текст и обработчик события click
Представим, что теперь нам нужна кнопка авторизации (любая другая кнопка), которая при этом используется в нескольких местах. Тут как раз встает ваш вопрос, каким именно образом реализовать компонент, как дочерний класс компонента Button, либо как отдельный компонент, React предлагает решение, которое близко ко второму варианту, а именно компоненты высшего порядка, либо композиция компонентов
class AuthButton extends Component {
    render() {
        return (
            <Button
                buttonText='Авторизоваться'
                onClick={this.handleAuth}
            />
        )
    }
    handleAuth() {
        // some code
    }
}

Мы создали новый компонент AuthButton, который использует компонент Button, передавая ему определенные параметры. Мы можем создать миллион таких вот кнопок, каждая из которых будет выполнять свою роль/роли, например мы можем как-то кастомизировать стили кнопки, не затрагивая саму кнопку, просто передавая параметры, мы можем создать PrimaryButton, ErrorButton и так далее.
Преимущество в том, что мы ни как не меняем компонент Button, соответственно нам не стоит заботиться, что где-то в другом месте из-за изменений Button может что-то сломаться + миллион параметров у одного компонента приводит к тяжелым последствиям в дальнейшей поддержке
Воспринимать компоненты в данном контексте можно, как простые функции. Поддерживать и тестировать маленькие функции (пусть их даже и много) легче, чем одну огромную.
Ничто не мешает вам разбить все на две папки, UI, где вот такие, почти что нативные компоненты + Составные компоненты, которые используют в себе стандартный UI.


text:
Q: How to transpose column into row? I have the following code that pulls a table from a mysql databse and turns it into a table in html.
$query = mysqli_query($link, "select * from timetable Where id = $id and subject != '' order by Day asc, Hour asc "  );
?>

    day
    hour
    subject

<?php
while ($row = mysqli_fetch_array($query)) {
    echo "
";
    echo "".$row['Day']."	";
    echo "".$row['Hour']."	";
    echo "".$row['Subject']."	";
    echo "
";
}

?>

Im trying to make it so the day column is transposed to be along the top of the table as the first row.
Here is an example of a table
day hour subject
0   5   Maths
0   7   Maths
1   0   Maths
1   11  Physics
2   0   Physics
2   9   Maths
3   0   Physics
3   4   Maths
3   6   Physics
3   10  Maths
4   3   Maths
4   8   Physics
5   0   Maths
5   9   Physics
6   1   Maths
6   6   Physics

(note that I removed null values to make the table smaller for this question)
here is what I would like the table to look like
       Day  0     1     2      3     4     5     6
  hour
     1   physics
     2
     3
     4                      maths
     5          ect
     6
     7
     8
     9
     10
     11
     12

A: you can create this template firsly

Hours\Days
1
2
3
4

after that
<?php
for($hour = 1;$hour < 13; $hour++){
    echo "
";
    echo "".$hour."	";
    for($day = 0; $day < 7; $day++){
        while ($row = mysqli_fetch_array($query)) {
            if($row['Day'] == $day && $row['Hour'] == hour)
                echo "".$row['Subject']."	";
            else
                echo "	";
        }
    }
    echo "
"
}
?>

maybe u can write shorter code than me but its simple way.


text:
Q: Android - Merge image files to a movie (but not using JMF) I'd like to write an app that merges multiple images into a movie on Android. JMF has a basic implementation (JpegImagesToMovie). But, JMF isn't supported on Dalvik.
Is there an alternative library that I can use for this ?  Or if there is no library available, does anyone have any pointers for what I need to research to implement myself.
Rgds, Kevin.

A: I'm not aware of any pure-Java video encoders, and the built-in video encoder in Android appears to be limited to capturing video from the camera alone, rather than a custom input source.
You could look at writing a multi-part JPEG (quite rare but well supported) writer, or even an MJPEG (used by many digicams) encoder.


text:
Q: django Keyerror password I am trying to create a edit user profile feature which allows users to edit their profile info. When I click on submit in the form it is showing as keyerror password at albums/profile/edit.
Error Screen Shot
Views.py:
from django.views import generic
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.core.urlresolvers import reverse_lazy
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from django.contrib.auth.models import User
from django.contrib.auth.forms import PasswordChangeForm
from django.views.generic import View
from albums.models import Album, Song

from .forms import Userforms, EditProfileForm

class Profile_edit(View):
    form_class = EditProfileForm
    template_name = 'accounts/edit_profile.html'

    def get(self, request):
        form = self.form_class(None)
        return render(request, self.template_name, {'form': form})

    def post(self, request):
        form = self.form_class(request.POST)

        if form.is_valid():
            form.save()
            return redirect('profile')
        return render(request, self.template_name, {'form':form})

forms.py:
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserChangeForm
from django import forms

class EditProfileForm(UserChangeForm):

    class Meta:
        model = User
        fields = {'email', 'first_name', 'last_name', 'password'}

urls.py
url(r'^profile/edit/$', views.Profile_edit.as_view(), name='Profile_edit'),

edit_profile.html:
{% extends 'albums/base.html' %}

{% block title %}Sign Up{% endblock %}

{% block albums_active %}active{% endblock %}

{% block body %}

{% extends 'albums/base.html' %}

{% block title %}Sign Up{% endblock %}

{% block albums_active %}active{% endblock %}

{% block body %}

<form class="form-horizontal" action="" method="post" enctype="multipart/form-data">

  {% csrf_token %}

  {% include 'albums/form-template.html' %}

<button type="submit" class="btn btn-success">Submit</button>

</form>

{% endblock %}

A: You need to pass a user instance to the form when initialising it, otherwise the form has no idea which user you are editing.
def get(self, request):
    form = self.form_class(instance=request.user)

def post(self, request):
    form = self.form_class(request.POST, instance=request.user)


text:
Q: Can't connect to Mysql server with Laravel 5.2 When i add a MySQL connection to my laravel installation it does not seem to work. I double checked every setting, also on the remote server. The credentials are correct and everything should work. Underneath I'll post my controler, view and the database.config files so you can see what's wrong. I've been trying to fix this for the past 2 hours and I just have no idea what is wrong :( When i test if there's data it doesn't say the table does not exist, it just returns null. (I do have select permissions)
Controller
    <?php

namespace App\Http\Controllers;

use DB;
use App\Log;

class DataController extends Controller
{
    public function index()
    {
        $logs = Log::distinct()->select(['device_name','device_id'])->get();

        return view('data.index', compact('logs'));
    }

    public function show($device_id)
    {
        $logs = DB::table('datalog_net_data')->take(100);
        return view('data.show', compact('logs'));
    }
    public function dashboard()
    {
        $pageTitle = "Dashboard";
        return view('data.dashboard', compact('pageTitle'));
    }
}

The database config file
<?php

return [

    /*
    |--------------------------------------------------------------------------
    | PDO Fetch Style
    |--------------------------------------------------------------------------
    |
    | By default, database results will be returned as instances of the PHP
    | stdClass object; however, you may desire to retrieve records in an
    | array format for simplicity. Here you can tweak the fetch style.
    |
    */

    'fetch' => PDO::FETCH_CLASS,

    /*
    |--------------------------------------------------------------------------
    | Default Database Connection Name
    |--------------------------------------------------------------------------
    |
    | Here you may specify which of the database connections below you wish
    | to use as your default connection for all database work. Of course
    | you may use many connections at once using the Database library.
    |
    */

    'default' => 'mysql',

    /*
    |--------------------------------------------------------------------------
    | Database Connections
    |--------------------------------------------------------------------------
    |
    | Here are each of the database connections setup for your application.
    | Of course, examples of configuring each database platform that is
    | supported by Laravel is shown below to make development simple.
    |
    |
    | All database work in Laravel is done through the PHP PDO facilities
    | so make sure you have the driver for your particular database of
    | choice installed on your machine before you begin development.
    |
    */

    'connections' => [

        'sqlite' => [
            'driver'   => 'sqlite',
            'database' => database_path('database.sqlite'),
            'prefix'   => '',
        ],

        'mysql' => [
            'driver'    => 'mysql',
            'host'      => '192.168.1.113',
            'database'  => 'gs_database',
            'username'  => 'laravel',
            'password'  => '1234',
            'charset'   => 'Pneunet44',
            'collation' => '',
            'prefix'    => '%',
            'strict'    => false,
            'engine'    => null,
        ],

        'pgsql' => [
            'driver'   => 'pgsql',
            'host'     => env('DB_HOST', 'localhost'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'charset'  => 'utf8',
            'prefix'   => '',
            'schema'   => 'public',
        ],

        'sqlsrv' => [
            'driver'   => 'sqlsrv',
            'host'     => env('DB_HOST', 'localhost'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'charset'  => 'utf8',
            'prefix'   => '',
        ],

    ],

    /*
    |--------------------------------------------------------------------------
    | Migration Repository Table
    |--------------------------------------------------------------------------
    |
    | This table keeps track of all the migrations that have already run for
    | your application. Using this information, we can determine which of
    | the migrations on disk haven't actually been run in the database.
    |
    */

    'migrations' => 'migrations',

    /*
    |--------------------------------------------------------------------------
    | Redis Databases
    |--------------------------------------------------------------------------
    |
    | Redis is an open source, fast, and advanced key-value store that also
    | provides a richer set of commands than a typical key-value systems
    | such as APC or Memcached. Laravel makes it easy to dig right in.
    |
    */

    'redis' => [

        'cluster' => false,

        'default' => [
            'host'     => env('REDIS_HOST', 'localhost'),
            'password' => env('REDIS_PASSWORD', null),
            'port'     => env('REDIS_PORT', 6379),
            'database' => 0,
        ],

    ],

];

The return when i var_dump the first log row
http://puu.sh/nJLtV/028b2b5192.jpg
I hope you guys know, because i have no idea.

A: You also need to grant rights, so your Laravel app could connect remote MySQL server.
Example:
mysql> CREATE DATABASE foo;
mysql> GRANT ALL ON foo.* TO bar@'202.54.10.20' IDENTIFIED BY 'PASSWORD';

A: Change the DB_HOST in you .env file from:
DB_HOST=localhost

to
DB_HOST=127.0.0.1


text:
Q: How to convert seconds to minutes after 60 secs passed in Angular 8?   @Input() maxSeconds = 60;
  @Input() startSeconds = 0;
  @Output() alarmSnooze: EventEmitter<number> = new EventEmitter<number>();
  seconds: number;
  private everySecond$: Observable<number> = timer(0, 1000);
  private stopTimer$: Subject<{}> = new Subject();
  private alarms: Array<number>;
  constructor(private ref: ChangeDetectorRef) {
    this.alarms = [29, 59];
  }

  ngOnInit() {
    this.everySecond$.pipe(takeUntil(this.stopTimer$))
      .subscribe((seconds) => {
        this.seconds = (this.startSeconds + seconds);
        if (this.alarms.includes(this.seconds)) {
          this.alarmSnooze.emit(this.seconds);
        }
        this.ref.markForCheck();
      });
  }
}```

This is what i wrote as of now it just continues as seconds and keeps counting, but i want it to count to minutes.

A: ok here are some changes ive done
  @Input() startSeconds = 0;
  minutes = 0;
  @Input() secs = this.startSeconds - this.minutes * 60;
  // @Output() alarmSnooze: EventEmitter<number> = new EventEmitter<number>();
  seconds: number;

  private everySecond$: Observable<number> = timer(0, 1000);
  private stopTimer$: Subject<{}> = new Subject();
  private alarms: Array<number>;
  constructor(private ref: ChangeDetectorRef) {
    this.alarms = [29, 59];
  }

  ngOnInit() {
    this.everySecond$.pipe(takeUntil(this.stopTimer$))
      .subscribe((seconds) => {
        this.seconds = seconds;
        // if (this.alarms.includes(this.seconds)) {
        //   this.alarmSnooze.emit(this.seconds);
        // }
        if (this.seconds === 10){
          this.seconds = 0;
          this.minutes++;
        }
        this.ref.markForCheck();
      });
  }
}

i now can get 60 secs to 1:00 but after that it starts counting seconds again, i belive that i am missing something in the "if" statement


text:
Q: Installing PuppyLinux disables my Ubuntu install I had been using Lubuntu on this laptop of mine for quite some time. In order to install Lubuntu I had to use the --forcepae command. That is my processor has PAE support but must be force started. Below is the output of hardware-info regarding my processor.
-Processor-
Name      : Intel(R) Pentium(R) M processor 1.80GHz
Family, model, stepping      : 6, 13, 6 (Pentium III/Pentium III Xeon/Celeron)
Vendor      : Intel
-Configuration-
Cache Size      : 2048kb
Frequency      : 1800.00MHz
BogoMIPS      : 3590.92
Byte Order      : Little Endian
-Features-
FDIV Bug      : no
HLT Bug      : no
F00F Bug      : no
Coma Bug      : no
Has FPU      : yes
-Cache-
Cache information not available
-Capabilities-
fpu      : Floating Point Unit
vme      : Virtual 86 Mode Extension
de      : Debug Extensions - I/O breakpoints
pse      : Page Size Extensions (4MB pages)
tsc      : Time Stamp Counter and RDTSC instruction
msr      : Model Specific Registers
pae      : Physical Address Extensions
mce      : Machine Check Architeture
cx8      : CMPXCHG8 instruction
sep      : Fast System Call (SYSENTER/SYSEXIT)
mtrr      : Memory Type Range Registers
pge      : Page Global Enable
mca      : Machine Check Architecture
cmov      : Conditional Move instruction
clflush      : Cache Line Flush instruction
dts      : Debug Store
acpi      : Thermal Monitor and Software Controlled Clock
mmx      : MMX technology
fxsr      : FXSAVE and FXRSTOR instructions
sse      : SSE instructions
sse2      : SSE2 (WNI) instructions
ss      : Self Snoop
tm      : Thermal Monitor
pbe      : Pending Break Enable
bts      : Branch Trace Store
est      : Enhanced SpeedStep
tm2      : Thermal Monitor 2

Now I wanted to install puppylinux on the same system and dual boot both. I downloaded the PAE version of puppylinux but it failed to load informing me that I do not have PAE support. So I downloaded and installed the noPAE version and it ran as expected, after installing puppylinux, I ran GRUB4DOS so that it detects my other Ubuntu installations and I can dual boot.
The thing is that when I select Ubuntu 15.04 from the grub4dos screen at start i get the message that PAE is disabled or non-existant and that I should install the version suitable for my system.
When Ubuntu was installed with forcepae, why did it get disabled with the noPAE install of puppy? Cant I keep both? or am I forced to choose only one?
P.S. I installed this version of PuppyLinux: http://bkhome.org/news/?viewDetailed=00097

A: Right, I managed to sort this out. I booted from the Ubuntu Live CD`using the forcepae flag (which I believe enabled the pae on my processor). I then installed and ran boot repair, It repaired GRUB and detected puppy as well.
So now I can use both installations.


text:
Q: jquery ui tooltip wierd behaviour when word is in different line I am implementing the jquery ui tooltip. It works very well however, when the element that I am hovering over is in 2 different lines it is going to the middle of the them....Is there any way to customize this behaviour?
I know one possibility is to use  track:true  I do not want to use this...
Here is my jsfiddle,
"Spice Girls" is the tooltip with weird behaviour.
$(function () {
$(document).tooltip({
    items: ".oolinks",

    tooltipClass: "tooltip-position",
    content: function () {
        return "
Hi There.
";
    },
    position: {
        my: "bottom-20",
        at: "top",
        using: function (position, feedback) {
            $(this).css(position);
            $("
")
                .addClass("arrow")
                .addClass(feedback.vertical)
                .addClass(feedback.horizontal)
                .appendTo(this);
            $('.ui-tooltip-content').click(function (e, ui) {

            });
        }
    },
});});

A: Why not relocate br tag in like here:
The
<culink class="oolinks" lang="en" href="http://undefined/en/topic/Spice Girls" style="color:rgb(34, 34, 34)!important;font-size:15px!important;font-weight:bold!important;border-bottom-color:#4de3ce!important">Spice Girls</culink> about going on a joint
international tour.

A: I think the best thing you can do is apply two tooltips for each word ie., 'Spice' and 'Girls'.
The <culink class="oolinks" lang="en" href="http://undefined/en/topic/Spice Girls" style="color:rgb(34, 34, 34)!important;font-size:15px!important;font-weight:bold!important;border-bottom-color:#4de3ce!important">Spice </culink> <culink class="oolinks" lang="en" href="http://undefined/en/topic/Spice Girls" style="color:rgb(34, 34, 34)!important;font-size:15px!important;font-weight:bold!important;border-bottom-color:#4de3ce!important">Girls </culink>

Here is the fiddle.


text:
Q: Can compilers and interpreters have bugs, and what can we (as users) do to deal with them? If a compiler's work is essentially translating source code into machine level code, can there be any glitch in a compiler, i.e. a faulty "translation?"
The same goes for an interpreter: can it fail to output the required content sometimes?
I have not heard of any bugs in compilers/interpreters, but do they exist?

A: Compilers and interpreters are software too, and thus they aren't free from any of the problems of other software.
This is an example from a compiler as recent as MSVC 11 (2012), and here's an article on how they test the backend.

A: Yes
You tend to find them more in languages that are actively being developed than in those that are relatively mature (and thus don't see a lot of change on a frequent basis). This is probably why most languages are released at various 'stages' of stability. A nightly build is far less likely to be stable than a release candidate, which itself is less likely to be stable than a fully released and actively used version.
Luckily most of these languages (especially those that are open source) will have a public bug tracking system that you can submit reports to.
In my own experience, I ran into a fairly obscure but severe bug in Scala on Windows. I submitted my findings to the bug tracker and the issue was fixed fairly quickly. In that case, the language developers were smart enough to include a helpful note in the error log output, suggesting that what I'd run into was in fact a compiler error, and said where to submit the report.

A: Of course, because compilers are software.
In 2005, I had a piece of code fail in a highly critical piece of software I had written for a large company.   Since it cost the company literally millions of dollars to rectify, they of course launched a big-ass investigation.
Thankfully (from my perspective), the issue turned out to be a compiler issue in Delphi.   In the try finally block, the return value of a function was destroyed, and resulted in absolutely random results back to the caller.   This was documented, and acknowledged by Borland.
.NET was well known to have literally hundreds of different memory leaks, particularly in its early implementations.
I would contend that there is no such thing as bugless software.   Compilers are no exception.   They are, though, tested more thoroughly than most business software, and are consumed by smart, critical, contentious people, so their track record has actually, on the whole, been pretty good.

A: There can bugs even in hardware; a famous example is the Pentium FDIV bug.
Without doubt there is the possibility that the compilers contain bugs.

A: Not only bugs, but also deliberate malware.

The "login" trojan implemented by Brian Kernighan to the original Unix C compiler is the most well-known of these; the article http://cm.bell-labs.com/who/ken/trust.html has some background on this.

A: In layman's words:
All programs can have bugs.
Compilers are programs.
Ergo, compilers can have bugs.

A: Yes of course like any software compilers have bugs, for example the gcc bug list is here

A: Yes.
Also, not only with compilers, but also with Interpretors/debuggers, and any 3rd party software tool.
We are currently using some 3rd party software, and have been having some of the issue.
Sometimes they thank us, for finding and reporting a bug. :)
Some of them have some memory leaks too, which leads to crash. The important question here could be, how to determine if the 3rd party tool, or the compiler has bugs for your application to work correctly?

A: Compiler is a program that reads a program written in one language (the source language) and translates it into an another equivalent program in another language (the target language), mostly machine language.
There are different phases of compiler through which your source language code is scanned line by line. There is a symbol table which keeps the track of all Keywords which are scanned for in source language code.
Phase 1 : Lexical Analyzer - reads all the character in source program and forms the
          logical separation of tokens (int, char, float, if-else,for,while etc.)
Phase 2 : Syntax Analyzer  - analyze the structure of stream of tokens. Hierarchical
          parsing of expressions which includes postfix/prefix etc.
          (a=b+c*d)
Phase 3 : Semantic Analyzer - Type checking of tokens (integer to real, float etc.) and
          many things like operator precedence etc..
Phase 4 : Intermediate Code Generator -
          a=b+c*d-e(temp1=c*d, temp2=temp1+b, temp3=temp2-e)
Phase 5 : Code Optimization - Various Analysis (control flow, data flow, transformations)
          which eleminates : Redundancy code, Constants propogation, Partial dead code,
          common subexpression, Loop invariant code
Phase 6 : Code Generation - Generation of target code (Mostly Assembly Language) putting
          values in Registers
All these phases are nothing but well written programs and there could be N number of flaws in that..

A: Of course, compilers are just programms and their authors are idiots too :). Even language specification can have a bug. Example: c# + foreach + lambda.
Or in Python, bug in interpreter: Compiling evil ast crashes interpreter.
Well, if you want to look on bugs in compiler/interpeter -> look at php. There is a famous bug with integer overflow. First fix started from if (size > INT_MAX) return NULL;. Continuation of the story.


text:
Q: Using of "Tens hundreds" vs "Thousands" I've noticed recently that many people from the US used to count hundreds instead of thousands although thousands do exist there. For example the number 2618 would be called: "twenty six hundreds and eighteen" instead of "two thousand, six hundreds and eighteen" (see an example here: at 45:31).
Then my question if it's common in the UK as well as in the US?
I am afraid to use it in the UK and to be sounded weird.

A: This isn't a case where there are strict rules, but you could use the following:

*

*increasing number makes counting in hundreds less likely. Counting in hundreds from 1000 to  2000 is very common. 2000-5000, is less common but not unusual. 5000-9900 is unusual but still acceptable. 10000+ should never be used.

*it's never used for multiples of  1000. E.g. "ten-hundred" is incorrect, but "eleven-hundred" is normal.

*It is normally only used for multiples of 100, but this rule is sometimes broken, especially from 1000-2000.

*there's an implication that when counting in hundreds that you're giving an approximate figure, not an exact one.

*this system is for verbal communication and is rarely, if ever, written.

*this is common in both English and US-English.

A: Not sure why the lecturer used twenty-six hundred.
This can happen in AmE when the speaker wants to emphasize the number by making it sound large "twenty-six" sounds larger than "two"
In some cities, this also happens for house addresses where the first two digits can signify the cross street 2618 = the twenty six hundred block (coincidentally, this occurs in NYC where Columbia is located)
Maybe this video will help

British Numbers confuse Americans - Numberphile


text:
Q: Chaves duplicadas ** Melhorando o Post para melhor entendimento do ocorrido.
Pessoa, boa tarde.
Eu criei uma tabela 'cliente' no sql server e coloquei o campo e-mail como vachar(50), unique e aceita null
pq pela lógica, não existe 2 e-mails iguais...
Só que agora quando eu vou fazer um insert no banco e o valor do e-mail é null ele me retorna falando que não posso ter essa chave duplicada.

"Violation of UNIQUE KEY constraint 'UQ__CLIENTE__161CF72400F78D67'.
  Cannot insert duplicate key in object 'dbo.CLIENTE'. The duplicate key
  value is (). The statement has been terminated."

Como que eu privo para não deixar e-mails "validos" cadastrar duplicado e aceitar mais de 1 cliente com email = null?
Exemplificando o problema.
Criado a tabela
CREATE TABLE TEST(
ID_TEST INT NOT NULL IDENTITY,
NOME VARCHAR(50) NOT NULL,
EMAIL VARCHAR(20)
PRIMARY KEY(ID_TEST),
constraint VALOR_NULO UNIQUE(EMAIL)
)
Depois insiro meu primeiro valor com o campo de e-mail nulo
INSERT INTO TEST
VALUES('LUIZ', NULL)

Depois tento o segundo valor:
INSERT INTO TEST
VALUES('JUCA', NULL)

Quando eu tento inserir este valor que ele me acusa que os valores chaves não pode ser duplicado, não pode ter 2 valores(por que está com a constraint 'unique')

A: Na criação do índice deve usar esta cláusula:
WHERE email IS NOT NULL;

Coloquei no GitHub para referência futura.

A: Você deve ter criado a tabela com a declaração do email assim:
email varchar(max) unique
Coloquei max apenas como exemplo. Isso vai gerar uma constraint que não permitirá valores duplicados, incluindo null.
Como você marcou a tag sql-server-2012, para versão você tem uma alternativa (da versão 2008 em diante na verdade):

*

*Remova o unique da coluna email;

*Crie um índice unique que aceite nulls, assim:
CREATE UNIQUE NONCLUSTERED INDEX idx_clienteemail
   ON cliente(email) WHERE email IS NOT NULL
Isso vai validar o valor único para email e vai permitir nulos.


text:
Q: Merging an IObservable and IObservable to one observable that OnErrors when there is an exception I'm trying to create a single Observable which OnNext stream comes from one observable and which OnError stream comes from another observable.
The reason why I'm doing this is because I'm trying to wrap a class that is outside of my control and uses events to communicate its state. It has two events, one that indicates its done (bool) and one that indicates that an Exception occurs.
IObservable<Exception> error = Observable.FromEventPattern<ExceptionRoutedEventArgs>(foo, "Failed")
               .Select(x => x.EventArgs.ErrorException);

IObservable<bool> opened = Observable.FromEventPattern<RoutedEventArgs>(foo, "Opened")
               .Select(x => ((Bar)x.Sender).IsOpen);

Now I cannot use the standard Observable.Merge since both observable have a different generic parameter. But In pseudo code I would like to accomplish this:
Observable.Merge(opened, error, (op, err) =>
{
    if(op) { return op;}
    if(err != null){return Observable.Throw(err);}
}

Now there are a lot of reasons why the code above doesn't remotely resemble anything that can exist but I hope the intent is clear.
I think a way to make this work is to use a Subject<> but I've heard that those should be avoid that since it introduces state in a functional concept. And I have the idea that combining two observables into one observables OnNext and OnError stream seems like it should exist :)

A: You could use Observable.Create:
var combined = Observable.Create<bool>(o =>
{
    var openSub = opened.Subscribe(o);
    var errorSub = error.Subscribe(o.OnError);
    return new CompositeDisposable(openSub, errorSub);
});

Or you could project each Exception to an IObservable<bool> that just throws the errors, and merge the resulting sequences:
var combined = opened.Merge(error.SelectMany(Observable.Throw<bool>));

Though just because your source uses Exceptions for control flow doesn't mean you have to - why not just project the Exception to false, then you just get true on success and false on failure:
var combined = opened.Merge(error.Select(_ => false));

A: Try this:
var combined =
    opened
        .Materialize()
        .Merge(error.Select(e => Notification.CreateOnError<bool>(e)))
        .Dematerialize()
        .Synchronize();


text:
Q: Ошибка при распаковке GZIP Вылазит ошибка при распаковке функцией gzinflate(),подскажите в чем проблема!
$url = "http://capitalcity.combats.com/logs.pl?log=1392725194.42632";
$log = file_get_contents($url);

echo gzinflate($log);

Warning: gzinflate() [function.gzinflate]: data error in C:\xampp\htdocs\analyzer\index.php on line 6

A: Уже взял ради интереса отправил заголовок header("Content-Encoding: gzip"); Страница отображается корректно,но если пользуюсь функцией strpos пытаюсь найти позицию искомого текста то ничего не происходит.Объясните пожалуйста в чем проблема,хочу разобраться в этом теме!


text:
Q: Am I understanding the UIActivityViewController wrong? from my opinion, I can pass text, images etc. to the UIActivityViewController and it will show exactly these apps, that can handle the file types I´m passing in. But it isn´t behaving like that! It´s just showing the standard apps Mail, Messages, Twitter, Facebook and Copy. These are not changing at all, regardless of what I´m passing to UIActivityViewController.
I read that you have to subclass UIActivity to be able to support other Apps, but this renders the whole concept useless to me, as I have to know, which apps could do what.
Am I the only one that´s frustrated with this? Or am I just doing something wrong?
And to have some code:
NSArray *items = @[@"sometext", @"some longer text", [NSURL urlWithString:@"http://www.apple.com/"]];

controller = [[UIActivityViewController alloc] initWithActivityItems:items applicationActivities:nil];

Expected: to have apps like Evernote, Instagram etc. in the ActivityViewController

A: I think your question is related to this one. It doesn't seem anyone has an answer for either of them. Seems like if you create a UIActivity, you can only use it in your app within your own UIActivityViewController.


text:
Q: Docker connection refused on all ports except 5000 I have just started with Docker. I have installed Docker Toolbox for Windows. I was trying out a sample Flask app to understand how things work. But I am stuck!. I am trying to access my app like this http://docker-machine-ip : port number but every time I do, I get '{docker-machine ip} refused to connect.'
I get no exceptions during the building and deploying stages. I also did docker ps to see that container is running. I even tried to access it via Kitematic but still no luck. Below are details related to the app
app.py
from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello():
    return "Flask inside Docker shakel!!"

if __name__ == "__main__":
    app.run(debug=True,host='0.0.0.0')

requirements.txt
flask

Dockerfile
FROM python:2.7
MAINTAINER Shekhar Gulati "shekhargulati84@gmail.com"
COPY . /app
WORKDIR /app
RUN pip install -r requirements.txt
ENTRYPOINT ["python"]
CMD ["app.py"]

The docker commands I used for building and running are:
docker-machine ip default //To get docker machine ip
docker build -t flask-app .
docker run -d -p 6000:6000 flask-app

I have Windows 7 64 bit. Please let me know if any more info is required.
P.S. However I noticed that if I map my container to 5000 port it will run fine but on any other port I get connection refused
I don't know what am I missing here. This is my first attempt at Docker and I have googled for 4 hrs to find a solution but nothing is working. So it might be a very dumb mistake I am doing somewhere :).anyhow any help is very much appreciated. Thanks in advance.

A: That's because you didn't set the port for your flask application, which is port 5000 by default.
From flask documentation:

port – the port of the webserver. Defaults to 5000 or the port defined in the SERVER_NAME config variable if present.