text:
Q: Which normed space have Fatou's property? There is tool in mathematics, more specifically  in Analysis, which has immense applications in handling delicates estimates, limiting arguments, etc... ; namely Fatou property.
Let $E$ be a normed space, continuously embedded into $\mathcal{S'}(\mathbb R)$(= The space of tempered distributions). We say that $E$ has a Fatou property if there exists a constant $C>0$ such that the following is true:
If $\{f_{j}\}_{j\geq 0}$ is any bounded sequence in $E,$ with limit $f\in \mathcal{S'}(\mathbb R),$ then $f$ belongs to $E$ and
$$\|f\|_{E}\leq C \sup_{j\geq 0} \|f_{j}\|_{E}.$$
My Question is:

Is Fatou property true for general normed space(Or Banach Space) ? If not,which kind of normed space(Or Banch space) have Fatou property and which normed space (Banach) fails for Fatou property ?

A: EDIT: A lot of what I said in my original post is wrong, as it turns out :(
The $L^1$ example below shows that your formulation of the Fatou property is not as useful as it first appears.
The Fatou property as you formulate it is not true in general. As a counterexample, consider
$$
C_0 := \{f : \Bbb{R} \to \Bbb{C} \mid f(x) \to 0 \text{ as } |x|\to\infty \}.
$$
This is a Banach space (if equipped with the sup norm), continuously embedded in $\mathcal{S}'$, but if you take something like
$$
f_n = \sum_{k=1}^n \chi_{[k - 1/k^2, k+1/k^2]},
$$
then (you have to replace the "squares" by "triangles" of course, to make everything continuous) $f_n \to f$ in $L^1$ (and hence in $\mathcal{S}'$) for some $f$ which no longer belongs to $C_0$ (check this).
One natural sufficient condition for what you want is the following. Assume that $E$ can be written as
$$
E = \{f \in \mathcal{S}' \mid \sup_{g\in F} |\langle f,g \rangle | < \infty \}
$$
with the corresponding norm, where $F$ is a suitable subset of $\mathcal{S}'$.
The problem is now that even the space $L^1$ does not satisfy your formulation of the Fatou property. To see this, take any function $f \in C_c$, $f \geq 0$ with $\int f \,dx =1$ and let
$$
f_n(x) := n \cdot f(nx).
$$
It is relatively easy to see that $f_n \to \delta_0$ (delta distribution at the origin) in $\mathcal{S}'$ and that $\Vert f_n \Vert = 1$ for all $n$. But of course $\delta_0 \notin L^1$.
The problem here seems to be that $L^1$ is not weak-$\ast$-closed in $\mathcal{S}'$.
An alternative formulation of the Fatou property (which holds in many interesting cases, especially for $L^1$) can be formulated in the context of so called Banach function spaces. These are spaces which continously embed into $L_\rm{loc}^1$. The Fatou property then states that if $f_n \to f$ pointwise a.e. and if $\Vert f_n \Vert_E$ is bounded, then $f \in E$ with
$$
\Vert f \Vert_E \leq \liminf_n \Vert f_n \Vert.
$$
Of course, this property fails as soon as smoothness-properties (like differentiability) enter.
BTW: Very interesting question.


text:
Q: single quote in file name - javascript,php How can I deal with a quote in data that has to be there?
This javascript statement works fine until city name is "ST JOHN'S".
We are not able to change the change the city name in database -or- use a more reliable key.
$('#map_output').html('
<img src="img/map/<?=$CITY_OUT?>_map.PNG" width="600">
')

A: Use htmlspecialchars().
EDIT: you use it (sorta) like json_encode:
<?=htmlspecialchars($CITY_OUT, ENT_QUOTES)?>

But htmlspecialchars is more semantic - json_encode is about generating JSON (internal, data representation), not about presentation.
Nick Craver is right though - it'll also work.
Edit: need ENT_QUOTES for rendering " ' " correctly...

A: You can use json_encode() to escape the quote,  like this:
<?=json_encode($CITY_OUT)?>

A: There are three levels of encoding needed:
You're creating a URL, so you need to URL-encode it:
$url = rawurlencode('img/map/'.$CITY_OUT.'_map.PNG');

You're creating an HTML attribute, so you need to HTML-encode it:
$html = '

';

That second step may not make a big difference, since you're not likely to have ', ", &, <, or > in your URL. But if you want to be strictly correct, you should encode all HTML attributes. It's a good habit to get into, so you can handle all special characters.
Finally, you're creating a JavaScript value, so you need to JSON-encode it:
$('#map_output').html(<?= json_encode($html) ?>)

(edited to add JSON-encoding)

A: In my quick tests, neither of the two answers worked:
<?php

  $string = "ST JOHN'S";
  $json = json_encode($string);
  $html =  htmlspecialchars($string);
  $escape = str_replace("'", "\'", $string);

  ?>

The only test which did not produce a javascript error was my usage of str_replace to actually escape the single quote.

A: "rawurlencode" is what you need to ensure the characters in the URL are interpreted the same on the "img/map/..." request the same way they are in this PHP script.
Incidentally, "rawurlencode" safely escapes all of the characters you need to worry about in XSS injections.
<?php
    $string   = "ST JOHN'S";
    $json     = json_encode($string);
    $html     = htmlspecialchars($string, ENT_QUOTES);
    $htmlent  = htmlentities($string, ENT_QUOTES);
    $escape   = str_replace("'", "\'", $string);
    $urlenc   = rawurlencode($string);
?>

A: You've said that none of the solutions given so far have worked for you, but I think actually they're fine (at least some of them). Let me demonstrate:
Here are the examples you listed:
$json:

$html:

$htmlent:

$escape:

$urlenc:

I don't see any problem with any of these (except the JSON one, which I'll explain in a moment).
And I've just tried all these examples, trying to simulate your scenario as closely as possible (even down to using the same file name).... All of them loaded the graphic correctly, again except the JSON example.
The JSON example needs a minor tweak to get it working, but it also does escape the string in a workable way. To get it working you need to take into account that JSON produces a fully-quoted Javasscript string rather than just escaping it as the others do, so you'd modify the output to close the quotes and add the strings together, like so:
$('#map_output').html('
<img src="img/map/"+<?=$json?>+"_map.PNG"/ width="600">
');

The other solutions don't need this. They all work as is. As I say, I tried them, and they all loaded the graphic into the page.
In the context, all three mechanisms (escaping \', entities &#039 and URL encoding %27) are valid:

*

*Escaping works because you're in the context of Javascript, so the backslash gets dealt with by Javascript and the final generated HTML that gets inserted into the page won't contain it.

*Entities work because HTML translates entities into the mapped character, so &#039 in a HTML page is the same as a single quote, even within an attribute value as in this case.

*URL Encoding works because browsers translate them when they load a URL.
I would suggest URL encoding is the correct solution in this case, since this is being used for a URL. The reason for that is that while all the solutions work for the given example, if you have any examples that contain a question mark or an ampersand (&) or a few other reserved characters, then URL encoding will be the only solution that will work in these cases. On the other hand, if you're displaying the output in your HTML page in another context, then entities are the way to go. And if it is going to be used just within Javascript, then JSON is the answer.
But you say none of them did the trick. My question is: Did you actually try them? Did you run the code and the graphic failed to load? It did for me. On the other hand, if they did work, but still don't "do the trick", then what is it you actually want?
My guess is that what you actually mean is that you want to end up with a simple quote character there, but have it magically work. That can't happen; the quote has to be escaped somehow or other in order for it to work, but they user will never see the escaped version, so there's no need to worry about it.
In fact, you should be escaping or encoding all the strings you input or output, so that invalid characters do work. Otherwise Mr O'Brien is going to have trouble entering his name into your site, and if he manages it, you'll have trouble displaying it afterward.

A: Unfortunately none of the above solutions did the trick.
<?
    $string   = "ST JOHN'S";
    $json     = json_encode($string);
    $html     = htmlspecialchars($string, ENT_QUOTES);
    $htmlent  = htmlentities($string, ENT_QUOTES);
    $escape   = str_replace("'", "\'", $string);
    $urlenc   = rawurlencode($string);
?>

$json:
<img src="img/map/<?=$json?>_map.PNG"/ width="600">
$html:
<img src="img/map/<?=$html?>_map.PNG"/ width="600">
$htmlent:
<img src="img/map/<?=$htmlent?>_map.PNG"/ width="600">
$escape:
<img src="img/map/<?=$escape?>_map.PNG"/ width="600">
$urlenc:
<img src="img/map/<?=$urlenc?>_map.PNG"/ width="600">

output:
$json:

$html:

$htmlent:

$escape:

$urlenc:

redpajama_set_name: RedPajamaStackExchange


text:
Q: Android dynamically add a menu item based on DB field I'm trying to show an extra menu item (contextual action bar) when the user selects one/multiple items in a ListView. Basically I'm checking if the selected item has a field in the DB set to true. If so, I add the extra menu item.
I tried to query the DB for the selected item in onItemCheckedStateChanged() and invalidate the menu. This will call onPrepareActionMode() where I could show the extra option if needed.
This does not work because the options that are already selected with the DB column set to true, are not remembered when an item with the special DB column set to false gets selected in onItemCheckedStateChanged() and when onPrepareActionMode() gets called the extra menu item is removed.
How can I approach this better? Essentially I need a way to remember all the selected ListView items that have the extra field in the DB set to true so I can show the extra menu item - and vice-versa remove the item when none of the selected ListView items has that DB field.

A: You have to decide how to handle a situation when both kind of items are selected at once (say, one with true in db and one with false). If you decide to allow it, track your button state somewhere in your activity. I'd add a private integer member to your activity and increase this number whenever the item with true in the database is selected and decrease it whenever such item is deselected. If it's zero in onPrepareActionMode - don't show your button.


text:
Q: Shell : What does this script do? #!/bin/bash
if test $# -ne 2
  then
  echo "Error : Invalid number of arguments"
else
  if [ -d $1 ]
    then
    if [[ $2 =~ ^[0-9]+$ ]]
    then
      ls -l $1 | while read line
      do
        eval "echo $line | cut -d' ' -f5" | while read ln
        do
          if [[ $ln -gt $2 ]]
          then
            echo $line
          fi
        done
      done
    else
      echo $2" is not a integer"
    fi
  else
      echo "The repertory "$1" does not exist "
  fi
fi

The question was to make cpp , that works like  the command cp . The script it's supposed  to react correctly if we don't give 2 argument. I don't understand what this script do from line 10 .
This code is the following of this post Explain me 2 lines of this shell script.
Thanks

A: Without working through the code line by line and explaining it, I would point you at http://explainshell.com, which takes lines of shell code and puts commentary from the manual on each parameter.
E.g, this is part of line 12 above: http://explainshell.com/explain?cmd=echo+%24line+%7C+cut+-d%27+%27+-f5
It should help you go through it line by line and work out what is going on.

A: In words: It selects the lines from ls -l from a directory $1 which have a size bigger than $2.
If that code is in a file called script.sh, it is called like:
$ ./script.sh /home/user 130000

And it will print all lines of ls -l /home/user which have a size bigger than 130000.
I do not know why the eval in:
eval "echo $line | cut -d' ' -f5" | while read ln

The line will work the same as:
echo $line | cut -d' ' -f5 | while read ln


text:
Q: Python for the absolute beginner 3rd edition Chapter 9 example 3 doesn't seem to work So I have been going through the book and have been retyping the code exactly from the book into Notepad++ and then running in the command line. There's a couple of things which are bugging me. For one the code does not seem to work and I am copying it pretty much exactly as it says in the book.
# example 3
# card game 2.0
# Aims: Learn about: Inheritance, Base Class, Derived Class

class Card(object):

    """ A playing card. """
    RANKS = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
    SUITS = ["c", "d", "h", "s"]

    def __init__(self, rank, suit):
        self.rank = rank
        self.suit = suit
    def __str__(self):
        rep = self.rank + self.suit
        return rep

class Hand(object):

    """ A hand of playing cards. """

    def __init__(self):
        self.cards = []

    def __str__(self):
        if self.cards:
            rep = ""
            for card in self.cards:
                rep += str(card) + "\t"
        else:
            rep = "<empty>"
        return rep

    def clear(self):
        self.cards = []

    def add(self, card):
        self.cards.append(card)

    def give(self, card, other_hand):
        self.cards.remove(card)
        other_hand.add(card)

class Deck(Hand):
    """ A Deck of Playing Cards"""
    def populate():
        for suit in Card.SUITS:
            for rank in Card.RANKS:
                self.add(Card(rank, suit)

    def shuffle(self):
        import random
        random.shuffle(self.cards)

    def deal(self, hands, per_hand = 1):
        for rounds in range(per_hand):
            for hand in hands:
                if self.cards:
                    top_card = self.cards[0]
                    self.give(top_card, hand)
                else:
                    print("Can't continue deal. Out of cards!")

# main
deck1 = Deck()

print("Created a new deck.")
print("Deck:")
print(deck1)

deck1.populate

print("\nPopulated the deck.")
print("Deck:")
print(deck1)

I have created 3 classes Card, Hand and Deck. In the main section of the programme when I try to call the method 'populate' the method should call and run through the list of class atrributes from the Card class and provide me with a list of possible cards when i print deck1, however I am always getting  back why is this the case?
My second question is that sometimes I seem to be getting a syntax error for 'def shuffle(self)' and I see no problem with this method.

A: deck1.populate is a function, so you need call it in this  way:
deck1.populate()

A: Your first problem

In the main section of the programme when I try to call the method 'populate' the method should call and run through the list of class atrributes from the Card class and provide me with a list of possible cards when i print deck1, however I am always getting back why is this the case?

You aren't calling populate, deck1.populate won't call it, use deck1.populate() instead.
And you haven't defined it correctly either, it should take a parameter:
# ...
def populate(self):
    # ...

As for your second problem

My second question is that sometimes I seem to be getting a syntax error for 'def shuffle(self)' and I see no problem with this method.

You have
            # ...
            self.add(Card(rank, suit) # <-- Syntax error

def shuffle(self):

The line with self.add is missing a closing parentheses


text:
Q: Solving $x^2 - 11y^2 = 3$ using congruences I'm looking to find solutions to $x^2 - 11y^2 = 3$ using congruences.
The question specifically asks "Can this equation be solved by congruences (mod 3)? If so, what is the solution? (mod 4) ? (mod 11) ?"
I know using (mod 4) I can show that there aren't any solutions:
$x^2 - 11y^2 \equiv 3 (mod 4)$
$x^2 - 11y^2 \equiv -1 (mod 4)$
This is unsolvable because of the fact that 11 is a prime, and it's congruent to 3 mod 4, and thus would follow that there are no solutions. Thus I know that the whole equation is unsolvable.
I'm curious because the back of the book said that this result could also be seen (mod 3), but I can't get the same result:
$x^2 - 11y^2 \equiv 3 (mod 3)$
$x^2 - 11y^2 \equiv 0 (mod 3)$
Thus x and y can both be congruent to 0 mod 3 to solve it.  Can someone help me understand why this equation is provably unsolvable mod 3?

A: $$-11 \equiv -11+16 \equiv 5 \equiv 1 \pmod 4$$
So,the congruence becomes:
$$x^2+y^2 \equiv 3 \pmod 4$$
$$x \equiv 0 \pmod 4 \Rightarrow x^2 \equiv 0 \pmod 4$$
$$x \equiv 1 \pmod 4 \Rightarrow x^2 \equiv 1 \pmod 4$$
$$x \equiv 2 \pmod 4 \Rightarrow x^2 \equiv 0\pmod 4$$
$$x \equiv 3 \pmod 4 \Rightarrow x^2 \equiv 1 \pmod 4$$
$$$$
$$y \equiv 0 \pmod 4 \Rightarrow y^2 \equiv 0 \pmod 4$$
$$y \equiv 1 \pmod 4 \Rightarrow y^2 \equiv 1 \pmod 4$$
$$y \equiv 2 \pmod 4 \Rightarrow y^2 \equiv 0\pmod 4$$
$$y \equiv 3 \pmod 4 \Rightarrow y^2 \equiv 1 \pmod 4$$
We can see that it cannot be $x^2+y^2 \equiv 3 \pmod 4$
EDIT:
$$-11 \equiv 1 \pmod 3$$
So,the congruence becomes:
$$x^2+y^2 \equiv 0 \pmod 3$$
$$x \equiv 0 \pmod 3 \Rightarrow x^2 \equiv 0 \pmod 3$$
$$x \equiv 1 \pmod 3 \Rightarrow x^2 \equiv 1 \pmod 3$$
$$x \equiv 2 \pmod 3 \Rightarrow x^2 \equiv 1 \pmod 3$$
$$$$
$$y \equiv 0 \pmod 3 \Rightarrow y^2 \equiv 0 \pmod 3$$
$$y \equiv 1 \pmod 3 \Rightarrow y^2 \equiv 1 \pmod 3$$
$$y \equiv 2 \pmod 3 \Rightarrow y^2 \equiv 1 \pmod 3$$
We can see that $x^2+y^2 \equiv 0 \pmod 3$,only if $x \equiv 0 \pmod 3 \text{ AND } y \equiv 0 \pmod 3$

A: The point is not that it is unsolvable mod $3$, but that every solution modulo $3$ must satisfy $x\equiv y\equiv0\pmod3$.
Indeed, as $-11\equiv1\pmod3$ we have $x^2+y^2\equiv0\pmod3$. Some case checking learns that squares are only congruent to $0$ or $1$ $\pmod3$ (and this is worth being remembered!), so $x^2+y^2\equiv0$ implies $x^2\equiv y^2\equiv0$.
Now here comes the contradiction: if $3\mid x,y$, then $9\mid x^2,y^2$ and hence $9\mid x^2-11y^2=3$.


text:
Q: Dart/Flutter - access private members of mixin or in derived class I want to outsource redundant class members into a separate class/mixin. For each class, which uses that class/mixin, I want to decide individually whether the members are gettable and/or settable from the outside.
I'd like to have something like the example below, but that doesn't compile, seemingly because private attributes are not visible when derived or added to a class via with.
So far, I haven't come to a reasonable solution yet. Any ideas?
mixin Person {
  String _firstName;
  String _lastName;
}

class Butcher with Person {
  Butcher({
    String firstName,
    String lastName,
  }) :
        _firstName = firstName,
        _lastName = lastName;

  final String tool = 'knife';

  String get firstName => _firstName;
  String get lastName => _lastName;
}

class SecretAgent with Person {
  SecretAgent({
    String firstName,
    String lastName,
  }) :
        _firstName = firstName,
        _lastName = lastName;

  final String tool = 'poison';

  String get firstName => _firstName;
  String get lastName => _lastName;

  set firstName(String value) => _firstName = value;
  set lastName(String value) => _lastName = value;

}

A: This has nothing to do with private members. Dart initializer lists can initialize only members of that class, not from any base classes (including mixins). (Member initialization from initializer list executes before base class constructors.)
It should work if you instead move initialization to the constructor body:
class Butcher with Person {
  Butcher({
    String firstName,
    String lastName,
  }) {
    _firstName = firstName;
    _lastName = lastName;
  }

  ...

class SecretAgent with Person {
  SecretAgent({
    String firstName,
    String lastName,
  }) {
    _firstName = firstName;
    _lastName = lastName;
  }

  ...


text:
Q: Oxyplot Polar Diagram with Categories I'd like to create a polar diagram with oxyplot. The circular axis should not consist of integers, but of categories.
Meaning instead of 1 ... 10 it should say Category A Category B ... around the plot.
Neither MagnitudeAxis nor AngularAxis provide the possibility to set "strings" for the axis.
CategoryAxis however cannot be used to plot a polar diagram, because it does not support angles.
My code so far:
var plotModel = new PlotModel { Title = "", };
plotModel.PlotType = OxyPlot.PlotType.Polar;
plotModel.Axes.Add(new OxyPlot.Axes.AngleAxis()
{
    MajorGridlineStyle = LineStyle.Solid,
    //MinorGridlineStyle = LineStyle.Dot,
    MajorStep = 1,
    CropGridlines = false,
    StartAngle = 450,
    EndAngle = 90,
    Minimum = 0,
    Maximum = 19
});

plotModel.Axes.Add(new OxyPlot.Axes.MagnitudeAxis()
{
    MajorGridlineStyle = LineStyle.Solid,
    Minimum = 0,
    Maximum = 5,
    MajorStep = 1,
    MinorStep = 1
});

var newValues = new OxyPlot.Series.LineSeries { Title = "New Values", StrokeThickness = 1 };

int i = 0;

foreach(var dataRow in details)
{
    newValues.Points.Add(new DataPoint(dataRow.NewValue, i++)); //instead of i++ I would like to put a string of the object dataRow, but this is not supported...
}

In lack of examples and documentation online, this is my last hope to find some help...

A: It looks to me like the LabelFormatter property is what you need.  The code below creates labels 'Category A', 'Category B'...'Category S' around the outside of the plot.  It does this because (char)65 is 'A', (char)66 is 'B' etc.
plotModel.Axes.Add(new OxyPlot.Axes.AngleAxis()
{
    MajorGridlineStyle = LineStyle.Solid,
    MajorStep = 1,
    CropGridlines = false,
    StartAngle = 450,
    EndAngle = 90,
    Minimum = 0,
    Maximum = 19,
    LabelFormatter = d => $"Category {(char)(d+65)}"
});

A: Based on the answer of Rich N I was able to find a (nasty) workaround by myself:
plotModel.Axes.Add(new OxyPlot.Axes.AngleAxis()
{
    MajorGridlineStyle = LineStyle.Solid,
    //MinorGridlineStyle = LineStyle.Dot,
    MajorStep = 1,
    CropGridlines = false,
    StartAngle = 450,
    EndAngle = 90,
    Minimum = 0,
    Maximum = 19,
    LabelFormatter = d => myCategoryList[Convert.ToInt32(d)] //myCategoryList is a list of strings
});


text:
Q: How to create a function to expand formulas? I am trying to convert formulas from Excel to Python.
For example, AVERAGE(D1:D4) can work in excel but not in Python. For python it would be np.mean([D1,D2,D3,D4]). May I know how to create a function that can convert from AVERAGE(D1:D4) to np.mean([D1,D2,D3,D4]) and work in all scenario.

A: Stop thinking in Excel and start thinking Python lists / arrays:
import numpy as np

d = [4, 8, 12, 18]
print("all elements", np.mean(d))
print("middle two", np.mean(d[1:3]))
print("last two", np.mean(d[-2:]))
print("all after 1st", np.mean(d[1:]))
# etc...
# output:
all elements 10.5
middle two 10.0
last two 15.0
all after 1st 12.666666666666666

A: Given AVERAGE(D1:D4) you can evaluate the argument of the Excel command D1:D4 with eval() in Python. Here is an example of how you could parse AVERAGE(D1:D4)
import numpy as np
import re

excel_command = "AVERAGE(D1:D4)"

D0, D1, D2, D3, D4, D5 = [i for i in range(2, 8)]

def excel_to_py(excel_command):
    if excel_command[:7] == 'AVERAGE':
        command = excel_command[7:][1:-1] # strip command of 'AVERAGE' and parenthesis
        # handle range (e.g. D1:D4)
        range_command = command.split(':')
        # determine the column id, in example it's 'D'
        column = range_command[0][0]
        if len(range_command) == 2: # if splitting by ':' gave two elements, it's a range
            # get range: e.g. for D245:D366 we need only numerical values 245 and 366 for rows
            complete_range = list(range(int(range_command[0][1:]), int(range_command[1][1:]) + 1))
            print(complete_range)
            argument = ', '.join([column+str(n) for n in complete_range])
            print(argument)
            average = np.mean(eval(argument)) # evaluating the
    return average

average = excel_to_py(excel_command)
print(average)

Output is:
[1, 2, 3, 4]
D1, D2, D3, D4
4.5

where 4.5 is equal to np.mean(D1, D2, D3, D4) = (3 + 4 + 5 + 6)/4 = 4.5
Of course this is a basic example, where:

*

*the range (D1:D4) is only applied over a single column (D).

*

*you could expand it with ranges over columns as well, with help from this post: range over character in python

*only the range is handled, and not simply multiple elements (AVERAGE(D1, D3, D4))

*

*you could easily implement that in a similar way to what I provided above.

*other commands are not handled (summing, subtracting, etc...).

*

*again, follow my example above and have fun implementing those too if needed.

*only a single AVERAGE operation is handled, instead of an entire, more complex, expression of multiple different operations.

*

*it's simply a matter of parsing the input command and handling the operations in the right order.

Good luck!


text:
Q: Filling a DataSet which contains a DateTime column with Sqlite Databases I am working on a C# WPF project which uses an SQLite database. I am trying retrieving the data from a table within the sqlite database and add to a data set so I can add the data set to the items source of the data grid. One of the columns is a DateTime column but I am getting the following error:
String was not recognized as a valid DateTime.

Below is how I am retrieving the data
private DataSet getAlarmsForSqlite()
        {
            DataSet ds = new DataSet();
            try
            {
                using (ConnectSQLiteDatabase db = new ConnectSQLiteDatabase(dbPassword))
                {
                    string query = "SELECT * FROM alarms ORDER BY date";
                    SQLiteDataAdapter da = new SQLiteDataAdapter(query, db.conn);
                    da.Fill(ds);
                }

            }
            catch (SQLiteException ex)
            {
                Console.WriteLine("Failed to get alarms. Sqlite Error: {0}", ex.Message);
                return null;
            }
            return ds;
        }

And below is the create statement for the table
CREATE TABLE `alarms` (`id` int(11) NOT NULL, `date` datetime NOT NULL,
`type` varchar(50) NOT NULL,
`message` mediumtext NOT NULL,
`level` varchar(45) NOT NULL,
`page` varchar(500) NOT NULL,
`acknowledged` char(1) DEFAULT '0', PRIMARY KEY (`id`))

Thanks for any help you can provide.

A: try this way
select *  from alarms order  by date(date) DESC

see the documentation.

A: There's some discussion regarding this issue here; sqlite throwing a "String not recognized as a valid datetime"
Apparently the SQLite datetime to C# DateTime serialization mapping doesn't exactly work. To me, it sounds like the datetime is coming back as a string so you need to do DateTime.Parse() in your code. In one of the answers to that question it suggests the datetime also needs to be cast to an nvarchar in order for it work.

A: It is one of two things:

*

*The data in your table is actually in a format which SQLite is not
capable of    turning into a datetime. For best results use the
ISO8601 date format    "yyyy-MM-dd HH:mm:ss.FFFFFFF". It requires
conversion before writing    the data to the database, but is
transparently handled when reading the data back to the dataset.

*The ORDER BY term in your query is for some reason preventing the
SQLiteDataAdapter from identifying the correct type for the
column. Even if you order by some other column, the result will be
the same. To avoid the problem, remove the ordering term (which will
then identify the column data type correctly) and sort your DataSet
after it has been filled.
EDIT: After looking into the recommendation of Ramesh, when using the "date" function with the Order By, the behavior outlined in my second point no longer happened.


text:
Q: How to receive images from a user using a GupShup Chatbot via Skype I am currently trying out Gupshup to develop a chatbot that is deployable on several platforms.
[The Situation]
One feature of this chatbot requires the user being able to send an image to the chatbot, so that the image can then be further processed on the backend. Looking at the Gupshup docs I have been able to provide this upload feature for a range of channels (Facebook, Slack, Telegram, Chat Widget).
[The Problem ]
As stated in the title, I am having trouble with receiving image messages when using the chatbot on Skype. After some testing, I was able to see the following problem:
When a user sends an image to the chatbot on Skype, there is NO EVENT that is being triggered, which means that my code will not even be executed. Looking at my logs, I simply cannot see any event generated by the user sending an image via Skype.
(Since no event is generated, the "onMessage" function is not called. It does work for text messages AND image messages on the channels listed above, but doesnt seem to work for image messages using skype).
[My setup]
 - I am using the in-browser Javascript Gupshup IDE
 - Logging is done via console.log();
 - For deploying I use the "deploy to prod" option
 - To use the chatbot, I am currently using the Gupshup proxy bot
[What I have tried so far]
I tried using different devices as the user (Skype on my Android phone, Skype on ubuntu 16.04, Skype on Win10) but there is no difference in the behavior. Since image messages do not generate an event that is dispatched, my code does not even get executed, which is why I am pretty limited in my possibilities. I have also browsed through the Gupshup Docs and could not find any special instructions for Skype as a channel.
Also, I could not find any helpful posts on SO or google.
[How to repeat my issue]
  1. Create a Gupshup Bot, using the Javascript IDE as development tool
  2. Add logging to the code, so that ANY incoming is logged
  3. Use the "deploy to prod" functionality
  4. Now open Skype, add the Gupshup proxy bot and use the "proxy YourBotName" functionality
  5. Send an image into the chat
  6. Now check the chatbot's logs and you will not be able to see any event that was generated by the message.
Has anyone else also experienced this problem? Did you find a solution, or is it simply not supported or maybe a bug on Gupshup? Maybe also Skype recently changed some APIs and Gupshup has not been able to keep up with these changes?
Any help is very welcome!
[Btw since this is my very first post, feedback on the post's overall form is very welcome as well!]


text:
Q: HTML doesn't read the CSS styling So I'm using XAMPP (if that matters) and every time I restart the local server, the styling stops working.
For example I have this style link right now:
<link href="style/mainstyling.css" rel="stylesheet" type="text/css"/>

Everytime when I restart the local server the styling is actually working, but when I make a change into the css file itself, it doesn't affect the page at all. The fix right now is  when I copy all the css code and put it into another file with completely different name and connect it again with the php (html) page itself.
I've been reading articles about it and I couldn't find any particular answer that could actually be the problem solver in this situations. It's either the cache of the browser or I don't know.
And yes, everything is in the right directory.

A: Open up Developer tools in Chrome (F12), go to your network tab and look at the HTTP response of
mainstyling.css Check that:

*

*Got a 200 OK and not a 404.

*The response Content-Type is "text/css"

*Check the response body has CSS in it.

*Run the CSS through a css format checker and check it is valid.


text:
Q: returning an array of bool in C I'm generating a 56bits string of 0 and 1.
so this is my code :
#include <time.h>
#include <stdlib.h>

#include "genkey.h"

static char * genkey()
{
    srand(time(NULL));
    int rr;
    char key[7];

    for(int ii = 0; ii < 7; ii++)
    {
    key[ii] = rand() % 255;
    }

    return *key;
}

int main()
{
    char truc[64] = genkey();
    printf("%s", truc);

    return EXIT_SUCCESS;
}

I can't compile it. And I don't understand why.

A: You are returning a pointer to a local variable. That variable goes out of scope once the function returns. This leads to undefined behavior when you try to dereference this pointer.
Not to mention that you will get compilation errors first because you don't actually returns a pointer (return *key returns the value that key is pointing to) and that you can't initialize an array in that way in the main function.
I would recommend that you instead of returning a pointer, you pass the array as an argument to the function for initialization. So e.g.
void genkey(bool *key)
{
    ...
}

int main(void)
{
    bool truc[64];
    genkey(truc);

    ...
}

A: This is very wrong. You are returning pointer to a local no longer existing array. Use
void genkey(bool* key, unsigned size)
... (of course without declaring key in the function)

bool key[64];
genkey(key, 64); // better to use #define instead

BTW bool is NOT one bit, but one byte.

A: First of all, you're declaring an array of 64 bytes each of them containing only one boolean information, 1 or 0. If you want to be memory efficient, use a bitmask on one or several bytes.
Then here's how to solve your problem:
#include <time.h>
#include <stdbool.h>
#include <stdlib.h>

#include "genkey.h"

bool* genkey(bool* key)
{
    srand(time(NULL));
    int rr;

    for(int ii = 0; ii < 64; ii++)
    {
    rr = rand();
    key[ii] = rr;
    }
}

int main()
{
    bool key[64];
    genkey(key);
    printf("%s", truc);

    return EXIT_SUCCESS;
}

please go read the K&R or even better that documentation http://www.chiark.greenend.org.uk/~sgtatham/cdescent/ that is aimed at people coming from higher abstraction languages. You need to learn about memory management and scope of variables!

A: In C, functions can only return simple types, not arrays.
static bool* genkey()
{
    bool key[64];
    ...
    return *key;
}

Here key is a bool*, yet you are trying to return *key, which dereferences key and therefore returns its first element. This is obviously not a pointer to a bool (i.e. a bool*) as the function declaration says.
Let's say you change it to what I think you meant:
static bool* genkey()
{
    bool key[64];
    ...
    return key;
}

This is still wrong, because key is a pointer to an array that was allocated on the stack. When the function exits, the contents of key[] will be lost. Returning a pointer to that key array is therefore always the wrong thing to do, because it may be undefined.
What you need to do is allocate the array on the heap, and free it in the caller after it has been used. Something like:
static bool* genkey()
{
    bool *key = malloc(64 * sizeof bool);
    ...
    return key;
}

int main()
{
    bool *truc = genkey();
    ...
    free (truc);

    return EXIT_SUCCESS;
}

As an alternative, allocate the array in main() (on the heap or the stack) and pass a pointer to genkey.
Remaining problems left for an exercise for the reader:

*

*Error handling.

*You cannot printf a pointer to an array of booleans and expect a sensible result.

*Using an array of bool is not an efficient way to store a bitfield; admittedly it is readable, and for 64 bytes, one might say 'who cares?'

A: There are lots of problems in your code. Besides what others have said, you're assigning a value to an array
char truc[64] = genkey();

which is forbidden in C. An array can only be initialized by values in { } pair. That's why the program didn't compile
Worse, the return value of the function is a byte in the array, not the address. Even if it's the address, you will face undefine behavior since it's a local array which ends its life after exitting the scope. Also, you generate 8 bytes in the program and then expect it to assign into 64 bytes in main
And the error list still isn't end. You call printf without including "stdio.h". Enable the warnings, you'll see a implicit declaration of function message.
One more thing, main in C is int main(void)

A: Here's a working example.
#include <time.h>
#include <stdio.h>
#include <stdlib.h>

/* allocates an array of random bits
 * char [0]{bit0, bit1, bit2, ... bit7}, char[1]{bit8, bit9 ... }
 */
unsigned char * genKey(int numberOfBits) {

    unsigned char *key = malloc((numberOfBits + 7) / 8);
    for (int i = 0; i < numberOfBits; i++) {

        int idx = i / 8;
        int mod = i % 8;
        unsigned char bit = (rand() & 1) << (7 - mod);

        key[idx] |= bit;
    }
    return key;
}

/* prints an array of bits.
 * Order: bitN, bitN-1, bitN-2, ...
 */
void printKey(unsigned char *key, int numberOfBits) {

    for (int i = numberOfBits - 1; i >= 0; i--) {

        int idx = i / 8;
        int mod = i % 8;
        unsigned char bit = 1 << (7 - mod);

        printf("%c", (key[idx] & bit) ? '1' : '0');
    }
    printf("\n");
}

int main() {

    srand(time(NULL));

    int bits = 56;
    unsigned char *key = genKey(bits);

    printKey(key, bits);
    free(key);

    return 0;
}


text:
Q: Setting up Brother HL-2240 printer I'm using Ubuntu 16.04 and can't print with my Brother HL-2240 printer.  I went through all the steps of setting it up through the Printers/System Settings, and chose all the recommended drivers/locations, but it still doesn't work.
This is a picture of how everything is set up right now:

Right now, I'll try to print something and then it disappears from the queue in seconds.
I tried downloading the driver from here as well: http://support.brother.com/g/b/downloadhowto.aspx?c=us&lang=en&prod=hl2240_us_eu&os=128&dlid=dlf006893_000&flang=4&type3=625
 Step1. Download the tool.(linux-brprinter-installer-*.*.*-*.gz)

The tool will be downloaded into the default "Download" directory.
(The directory location varies depending on your Linux distribution.)
e.g. /home/(LoginName)/Download

Step2. Open a terminal window and go to the directory you downloaded the file to in the last step.

Step3. Enter this command to extract the downloaded file:

Command: gunzip linux-brprinter-installer-*.*.*-*.gz

Step4. Get superuser authorization with the "su" command or "sudo su" command.

Step5. Run the tool:

Command: bash linux-brprinter-installer-*.*.*-* Brother machine name

Step6. The driver installation will start. Follow the installation screen directions.

 When you see the message "Will you specify the DeviceURI ?",

 For USB Users: Choose N(No)
 For Network Users: Choose Y(Yes) and DeviceURI.

The install process may take some time. Please wait until it is complete.

But I can't figure out how to do step 5 which is:
Command: bash linux-brprinter-installer-..- Brother machine name
I'm not sure what machine name is supposed to be.  I tried HL-2240, HL2240, HL 2240, and 2240 without result.

A: So I got it to work by downloading all the following drivers:
LPR printer driver (deb package)
CUPSwrapper printer driver (deb package)
Generic LPR printer driver (deb package)
Generic CUPSwrapper printer driver (deb package)
Then under Printer Properties my Make and Model is:
Brother HL2240 for CUPS
I have no idea which driver's worked, I just threw everything against the wall and hoped something sticked.  And now it works.

A: When adding the printer(Brother HL-2240D) I selected Brother HL-2142 and selected the recommended driver for that printer, and my Brother HL-2240D works perfectly. In my case the actual printer is on a Windows XP PC and thus I was adding a Network printer to Ubuntu.

A: Installed 16.04 then added Brother HL-2142 but just issued many blank pages on test.  Downloaded HL-2240 Brother linux-brprinter-installer-..- and followed command line install.  But had to use HL-2240DW model number at step 5 above and printer is now working correctly.
I had similar problem with 14.04.

A: I did the following to make it work (USB HL2240D configuration)

*

*Download driver from this link

*Open a Terminal window and go to Downloads

*Type command: gunzip linux-brprinter-installer-2.1.1-1.gz

*Type command: sudo sh linux-brprinter-installer-2.1.1-1
Input model name ->
HL2240D
-e
-e You are going to install following packages.
-e    hl2240dlpr-2.1.1-1.i386.deb
-e    cupswrapperHL2240D-2.0.4-2.i386.deb
-e -n OK? [y/N] ->
y
-e
............................
............................
is License.
=========================================
-e
-e -n Do you agree? [Y/n] ->
y
............................
............................
-e -n Will you specify the Device URI? [Y/n] ->
n
-e
-e -n Test Print? [y/N] ->
y
-e
wait 5s.
lpr -P HL2240D /usr/share/cups/data/testprint
-e -n Hit Enter/Return key.

and then it was installed succesfully and works ok.


text:
Q: Operação matemática em RecyclerView Quero saber como faço para somar determinados valores de uma RecyclerView..
no caso será o model.getQntd(), preciso somar todos seus respectivos resultado.
ATUALIZAÇÃO
Consegui fazer a contagem o problema agora é que quando acontece agulma mudança no servidor(firebase), a soma incrementa um novo numero ao invés de modificar...
Exemplo seu eu tenho 2 valores no servidor exemplo:.
}
 teste1:
   qntd:10
}
...
}
 teste2:
   qntd:10
}
se eu mudar a qntd do teste1 para 11 , o resultado será, 10+10+11=31 e não 21, já que o 10+10 já tinha sido adicionado a lista e o 11 vem como um novo dado... se eu sair e voltar pra atividade o resultado será 21...
Agradeço desde já.
              mFireAdapter = new FirebaseRecyclerAdapter<Afiliado, BlogViewHolder>(
            Afiliado.class,
            R.layout.row_afiliados,
            BlogViewHolder.class,
            mQuery
    ) {

        int total =0;
        int total1 =0;

        @Override
        protected void populateViewHolder(final BlogViewHolder viewHolder, final Afiliado model, final int position) {
            final String key = getRef(position).getKey();
            final int teste = model.getQntd();

            viewHolder.mNome.setText(model.getNome());
            viewHolder.mQntd.setText(String.valueOf(model.getQntd()));
            viewHolder.mRende.setText(String.valueOf(model.getQntd()/5));
            total += teste;
            total1 += teste/5;

            mTotal1.setText(String.valueOf(total));
            mTotal2.setText(String.valueOf(total1));

            Log.i("Resultado", String.valueOf(total));

            mData.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {

                    String cod = (String) dataSnapshot.child(users).child(mUser.getUid()).child("cod").getValue();
                    for(DataSnapshot snap : dataSnapshot.child(afiliados).child(cod).getChildren());
                    String resultado = dataSnapshot.child(afiliados).child(cod).getChildrenCount()+"";
                    String maxValue = (String) dataSnapshot.child(users).child(mUser.getUid()).child("maxAfiliados").getValue();

                    int valor1 = Integer.parseInt(resultado);
                    int resultado1 = valor1+total1;
                    mMeus.setText(String.valueOf(valor1));
                    mBruto.setText(String.valueOf("Resultado: "+resultado1));
                    mCircleView.setValue(resultado1);
                    mCircleView.setMaxValue(Float.parseFloat(maxValue));
                    mCod.setText(cod);
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
            //total+=mFireAdapter.get(position).getQntd();
            //f(position==mQuestLIst.size()-1)

        }
    };
    mFireAdapter.notifyDataSetChanged();
    mRecycler.setAdapter(mFireAdapter);

    // Update UI
    //firebaseRecycleAdapter.notifyDataSetChanged();
}

public static class BlogViewHolder extends RecyclerView.ViewHolder {
    View mView;
    private TextView mNome,mQntd,mRende;
    public BlogViewHolder(View itemView) {
        super(itemView);
        mView = itemView;

        mNome = mView.findViewById(R.id.nome);
        mQntd = mView.findViewById(R.id.qntd);
        mRende = mView.findViewById(R.id.rende);

    }
    }


text:
Q: Mathematics of symmetry in chaos I'm a neuroscience PhD student.
Recently I became so interested in the mathematical equations involving order and disorder and complex plane. I read a book named "Symmetry in chaos" by Martin Golubitsky. It's about the generation of symmetrical patterns using simple chaotic equations based like this
 equation
I'm really willing to learn about the mathematics of this kind, to understand what is done here because it's so related to my field and I just know some calculus, so I ask from you great guys to guide me by either introducing some books or
teaching me directly. Actually I would love to have a remote advanced math teacher and I'm willing to pay for the services. Thanks.


text:
Q: Intellij set module compile output as library I was wondering if this was possible in IntelliJ
I have 3 modules (Client, Server, and Protocol). My current way of doing things is to compile the Protocol module as a jar, and then use it as a library in my Client & Server module. However, this means that I have to refresh IntelliJ each time.
Is there a way for me to add a module as a library directly to my Server and Client modules? I have already tried going into libraries and adding the src/ folder for Protocol to my Client and Server modules.
I also looked at http://www.jetbrains.com/idea/webhelp/configuring-module-dependencies-and-libraries.html but couldn't get an answer.
Thanks in advance!

A: Have you tried this:

*

*Project Structure Ctrl+Alt+Shift+S (for Windows) or File - Project Structure

*Modules (on LHS)

*You should now see 3 modules in the middle list (provided you have set up the modules)

*Select the module to add a dependency to

*Dependencies Tab (Top Middle)

*Click + symbol on RHS to add a dependency

*Select Module Dependency

*Choose the module which it depends on.

This requires that all 3 modules are set up within the same project.


text:
Q: Does WSO 2 API Manager prevent to XSS and CRSF security error I'm researching WSO2 API Manager and I discover that if I use WSO2 API Publisher and API Store, I would meet XSS and CSRF security errors. With XSS, I see that WSO2 didn't encode HTML character input. With CSRF, I see that WSO2 didn't create token when I request from client to server and vise versa.
Does everyone know how to config WSO2 to prevent these security error or how to fix them.
Thanks in advanced.

A: On our side, there are a few things we do when publishing/consuming APIs via the API Publisher and API Store:

*

*Set the Transports property to just HTTPS so that we can limit API availability to just HTTPS.

*For each HTTP method, we set the Auth Type to either Application, Application User or both, but never none. This will force the client to utilize the WSO2 Access Token scheme to invoke the APIs hosted on the API Store.

*On the client side, we have been invoking the Token API to generate and renew user and application access token so that we don't have to manually re-generate keys in the API Store.

*Utilize API in-sequence to escape special characters.

A: We fix these type of security issues in our next release  AM V 1.7.1. You can expect it in 3rd week of September.


text:
Q: how to put product label on mysql product list I have a product list page and I am trying to figure out how to put product label on selected items. I have a category $bestseller and I want them to have a best seller image label on its upper right corner.
Any help? Thanks.
<?php
include "storescripts/connect_to_mysql.php";
$dynamicList = "";
$sql = mysql_query("SELECT * FROM products ORDER BY date_added DESC LIMIT 15");
$productCount = mysql_num_rows($sql); // count the output amount
$i = 0;

$dynamicList = '
';

     while($row = mysql_fetch_array($sql)){
     $id = $row["id"];
     $brand = $row["brand"];
     $product_name = $row["product_name"];
     $pdetails = $row["pdetails"];
     $bestseller = $row["bestseller"];
     $details = $row["details"];
     $date_added = strftime("%b %d, %Y", strtotime($row["date_added"]));
     if ($i % 3 == 0) { // if $i is divisible by our target number (in
this case "3")
         $dynamicList .= '

' . $brand . '
' . $product_name . '	';
    } else {

                $dynamicList .= '

' . $brand . '
' . $product_name . '	';
    }
    $i++;
}
$dynamicList .= '

';
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta content="text/html; charset=iso-8859-1" http-equiv="Content-Type"/>

<title>Product List</title>
<link rel="shortcut icon" href="icon.png" />
<link rel="icon" href="icon.png" type="image/x-icon" />
<link rel="stylesheet" type="text/css" href="../rustansstyle.css" />

<?php include_once("header.php");?>

Dresses

Short Dresses

Maxi Dresses

Cocktail Dresses

<?php echo $dynamicList; ?>

<?php include_once("footer.php");?>


text:
Q: Guardar imagens do servidor na minha aplicação Estou a desenvolver uma aplicação que depois de instalada, a primeira vez que é inicializada ela vai ao servidor buscar todas as imagens necessárias para o utilizador poder usar a aplicação.
Escolhi a biblioteca Picasso para manipular as minhas imagens mas não sei como posso descarregar o ficheiro e a seguir salvar a imagem na minha directoria /data/data/pt.MEU_PROJECTO/ para depois poder popular as minhas ImageView's mesmo que o utilizador não tenha ligação à internet.
Tenho a seguinte função criada para salvar as minhas imagens que construí a partir de um tutorial mas não sei que parâmetro da classe Picasso devo passar nem em que directoria é que está a ser utilizada para salvar as imagens.
public static void saveAssetImage(Context context, String assetName){
    File fileDirectory = context.getFilesDir();
    File fileToWrite = new File(fileDirectory, assetName);

    AssetManager assetManager = context.getAssets();
    try{
        InputStream in = assetManager.open(assetName);
        FileOutputStream out = new FileOutputStream(fileToWrite);

        in.close();
        out.close();
    }catch (IOException e){
        e.printStackTrace();
    }
}

saveAssetImage(getApplicationContext(), Picasso.with(this).load(urlImagem).fetch());

Preciso também de saber como posso ir buscar a imagem, depois de guardada, à directoria correcta para popular as minhas ImageView. Encontrei este código mas houve muitos utilizadores que comentarão não estar a funcionar.
Uri uri = Uri.parse("file:///data/data/pt.MEU_PROJECTO/file.jpg");
image.setImageURI(uri);

A: Para salvar a imgem:
    Picasso.with(context).load(URL IMAGEM).into(target);

 private Target target = new Target() {
        @Override
        public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    String pathImage = Environment.getExternalStorageDirectory().getPath() + "/PASTA ONDE ESTÁ A IMGEM";

                    File projDir = new File(dirPath);

                    if (!projDir.exists()) {
                        projDir.mkdirs();
                    }

                    File file = new File(dirPath + File.separator + "NOME DA IMAGEM");

                    try {
                        if (file.exists()) {
                            file.delete();
                        }
                        file.createNewFile();
                        FileOutputStream ostream = new FileOutputStream(file);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 75, ostream);
                        ostream.close();

                        user.setUrlPath(file.getAbsolutePath());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }).start();
        }

        @Override
        public void onBitmapFailed(Drawable errorDrawable) {
        }

        @Override
        public void onPrepareLoad(Drawable placeHolderDrawable) {
            if (placeHolderDrawable != null) {
            }
        }
    };

Para recuperar a imagem utilize o seguinte:
String pathImage = Environment.getExternalStorageDirectory().getPath() + "/PASTA ONDE ESTÁ A IMGEM/NOME DA IMAGEM";

File f = new File(pathImage);
Picasso.with(context).load(f).into(this.mUserPhoto);


text:
Q: Como fazer uma Grid com quadrados? Gostaria de fazer algo como esse aqui, uma Grid baseado em uma matriz(e que baseado no valor da matriz, defina uma cor a célula correspondente), e que eu possa manipular ela com o mouse.

A: Baseado num exemplo de tabuleiro de xadrez, fiz esse exemplo de grid preenchido com JLabels, onde ao clicar em algum deles, altera a cor de fundo para preto. Usando ele como uma base, você pode desenvolver melhor a sua ideia.
Esta classe criará um painel de JLabels populados num GridLayout:
class GridPane extends JPanel {

    private static final long serialVersionUID = 1L;
    private int rows;
    private int column;

    private JLabel[][] squares;

    public GridPane(int rows, int column) {
        this.rows = rows;
        this.column = column;
        this.setLayout(new GridLayout(rows, column));
        this.squares = new JLabel[this.rows][this.column];

        for (int r = 0; r < this.rows; r++) {
            for (int c = 0; c < this.column; c++) {
                SquareLabel square = new SquareLabel();
                this.squares[r][c] = square;
                this.add(square);
            }
        }
    }
}

Criei também uma classe, a parte chamada SquareLabel pro caso de você querer personalizar algo em cada quadrado:
class SquareLabel extends JLabel {

    private static final long serialVersionUID = 1L;

    public SquareLabel() {
        setOpaque(true);
        setBorder(BorderFactory.createLineBorder(Color.black, 1));
        addMouseListener(new ClickChangeColor());
    }
}

Separei também o listener, apesar de que para o exemplo nem seria necessário, mas com ele já criado, facilita adição de outras ações que podem estar relacionadas ao mouse:
class ClickChangeColor extends MouseAdapter {

    boolean clicked = false;

    @Override
    public void mouseClicked(MouseEvent e) {

        clicked = !clicked;
        JLabel square = (JLabel) e.getSource();
        Color color = clicked ? Color.black : square.getParent().getBackground();
        square.setBackground(color);
    }
}

Em execução:

Fiz exemplo executável que pode ser testado no Github.


text:
Q: Blank as last character in a monospace formatted text Writing a documentation, I have some small text examples to give, which should be formatted as monospace text by using backticks. Theses text snippes contains always as last character a blank, which must not be omitted, as it is significant. Unfortunately Asciidoctor omits them.
For example `: ` should be rendered as : . But instead it is readered as :.
So how does the markup look to get a colon and a blank rendered as preformatted?

A: There's the built-in attribute {nbsp} for non-breaking space in Asciidoctor, which can be used for a blank.
So `:{nbsp}` is rendered as : .


text:
Q: SQL Server - How to transform JSON to Relational database How can we use SQL to Convert a JSON statement into different tables?
For example we have JSON:
{"table1":
    {"Name":"table1","Items":
        [{"Id":1,"FirstName":"John",
         "LastName":"Wen","Country":"UK",
         "PostCode":1234,"Status":false,
         "Date":"2018-09-18T08:30:32.91",}]},
 "table2":
     {"Name":"table2","Items":
        [{"Id":1,"Name":"leo",
         "StudentId":102,"CreatedDate":"2018-09-18","Location":"USA"}]}}

In the relational database, we will get two tables once the JSON is converted
For example, schema 'Table1':
Id  FirstName  LastName  Country  PostCode  Status   Date
1   John       Wen       UK       1234      false    2018-09-18T08:30:32.91

And the 'Table2' will look like:
Id   Name   StudentId   CreateDate    Location
1    Leo    102         2018-9-18     USA

Could anyone please give any advices on it.

A: You can do this using openjson and json_value functions. Try the following:
Declare @json nvarchar(max),@table1Items nvarchar(max), @table2Items nvarchar(max)
set @json='{
    "table1": {
        "Name": "table1",
        "Items": [{
            "Id": 1,
            "FirstName": "John",
            "LastName": "Wen",
            "Country": "UK",
            "PostCode": 1234,
            "Status": false,
            "Date": "2018-09-18T08:30:32.91"
        }, {
            "Id": 2,
            "FirstName": "John1",
            "LastName": "Wen1",
            "Country": "UK1",
            "PostCode": 12341,
            "Status": true,
            "Date": "2018-09-15T08:30:32.91"
        }]
    },
    "table2": {
        "Name": "table2",
        "Items": [{
            "Id": 1,
            "Name": "leo",
            "StudentId": 102,
            "CreatedDate": "2018-09-18",
            "Location": "USA"
        }]
    }
}'

set @table1Items=(select value from OpenJSON((select value from OpenJSON(@Json) where [key]='table1')) where [key]='Items')
set @table2Items=(select value from OpenJSON((select value from OpenJSON(@Json) where [key]='table2')) where [key]='Items')
--select for table 1
select JSON_VALUE(val,'$.Id') as ID,
 JSON_VALUE(val,'$.FirstName') as FirstName,
JSON_VALUE(val,'$.LastName') as LastName,
JSON_VALUE(val,'$.Country') as Country,
JSON_VALUE(val,'$.PostCode') as PostCode,
JSON_VALUE(val,'$.Status') as Status,
JSON_VALUE(val,'$.Date') as Date
from
(
select value as val from openJSON(@table1Items)
) AS Table1JSON

--select for table 1
select JSON_VALUE(val,'$.Id') as ID,
 JSON_VALUE(val,'$.Name') as FirstName,
JSON_VALUE(val,'$.StudentId') as LastName,
JSON_VALUE(val,'$.CreatedDate') as Country,
JSON_VALUE(val,'$.Location') as PostCode

from
(
select value as val from openJSON(@table2Items)
) AS Table2JSON

It is working exactly as you wanted. At the end, the two select statements return the tables as you mentioned. Just add them to your desired table using insert into select. I have also tried adding another object to table1 array and verified that it is working fine i.e. returning two rows for two objects. Hope this helps

A: If SQL Version 2016+ use OPENJSON AND with_clause:
https://learn.microsoft.com/en-us/sql/t-sql/functions/openjson-transact-sql?view=sql-server-2017
    DECLARE @JsonData NVARCHAR(MAX);

    SET @JsonData = N'
    {
      "table1": {
        "Name": "table1",
        "Items": [
          {
            "Id": 1,
            "FirstName": "John",
            "LastName": "Wen",
            "Country": "UK",
            "PostCode": 1234,
            "Status": false,
            "Date": "2018-09-18T08:30:32.91"
          },
          {
            "Id": 2,
            "FirstName": "John1",
            "LastName": "Wen1",
            "Country": "UK1",
            "PostCode": 12341,
            "Status": true,
            "Date": "2018-09-15T08:30:32.91"
          }
        ]
      },
      "table2": {
        "Name": "table2",
        "Items": [
          {
            "Id": 1,
            "Name": "leo",
            "StudentId": 102,
            "CreatedDate": "2018-09-18",
            "Location": "USA"
          }
        ]
      }
    }
    ';

    --Table1
    SELECT [a].[Id]
         , [a].[FistName]
         , [a].[Lastname]
         , [a].[Country]
         , [a].[PostCode]
         , [a].[Status]
         , [a].[Date]
    FROM
           OPENJSON(@JsonData, '$.table1.Items')
               WITH (
                        [Id] INT '$.Id'
                      , [FistName] NVARCHAR(200) '$.FirstName'
                      , [Lastname] NVARCHAR(200) '$.LastName'
                      , [Country] NVARCHAR(200) '$.Country'
                      , [PostCode] NVARCHAR(200) '$.PostCode'
                      , [Status] NVARCHAR(200) '$.Status'
                      , [Date] DATETIME '$.Date'
                    ) [a];

    --Table2
    SELECT [a].[Id]
         , [a].[Name]
         , [a].[StudentId]
         , [a].[CreatedDate]
         , [a].[Location]
    FROM
           OPENJSON(@JsonData, '$.table2.Items')
               WITH (
                        [Id] INT '$.Id'
                      , [Name] NVARCHAR(200) '$.Name'
                      , [StudentId] INT '$.StudentId'
                      , [CreatedDate] DATETIME '$.CreatedDate'
                      , [Location] NVARCHAR(200) '$.Location'
                    ) [a];

A: Try using OPENJSON function in SQL Server:
ReferenceLink_1
ReferenceLink_2


text:
Q: How to pass output of one script as input of other script I need to pass output of bash shell to the python script.

*

*I am opening one emulator and once will get error message on terminal

*I want to parse some data from stdout and stderr using python script

*once parsing is done I want to terminate emulator(which is opened in bash script)

I tried using pipe-lining but here python script is not getting started until manually I'm not terminating emulator.
eg:
./start.sh | python file.py

I want to achieve automation.
I want to stream output of one script to input to python script.
Can you suggest a way to achieve streaming in the two scripts?
Regards,
Mann


text:
Q: Run time analysis of Dijkstra's algorithm, I am getting O(Vlog(V) + VE) I am trying to determine the run time of dijkstra's algorithm using
min-priority queue (which is implemented using a Fibonacci heap)
The code

Analysis:
I know that for Fibonacci heap insert is Decrease/Insert Key is O(1) and to extract min it's O(log(n))
Line 1 to 3: The run time is O(V), for every vertex
The loop in line 4 takes O(V), but the ExtractMin takes O(log(V)),
also the for loop from line 6-7 its O(E), for every edge
There for since the for loop is within the while loop,
I would have V(log(V) + E)
so I would get O(V + Vlog(V) + VE) which comes down to O( Vlog(V) + VE)
but most of the articles indicate it is  O( V*log(V) + E), is it because E>V or am I doing something wrong?

A: Each vertex will get pulled out by ExtractMin at most once, so that the inner for loop (across all iterations of the while loop) will select each edge at most once; hence the E, and not V*E, term.


text:
Q: Implementing Spring-like package scanning in Android I'm attempting to implement a package-scanning feature, similar to Spring's component-scan, for the Android framework I'm developing. Basically, I would like to be able to specify a base package, e.g. com.foo.bar and retrieve all Class instances that have a particular annotation. I don't want to have to register every component with my framework as that would defeat the purpose of the auto scanning.
Based on my research, it seems that it's not possible with Java to retrieve resources given a package name using reflection. However, I briefly looked into the Reflections framework, and I'm wondering if there is an Android-compatible equivalent. If not, perhaps there is a slightly less obvious way to accomplish what I want to do.
I looked into the Spring source a bit to see how they achieved this, but I don't think what they are doing would work within the Dalvik runtime.
Update
Currently, the below code has been the best I can do to retrieve all classes that contain a specific annotation, but frankly it's a pretty poor solution. It makes some really unsafe assumptions about the ClassLoader plus it scans (and loads) all application classes.
public Set<Class<?>> getClassesWithAnnotation(Class<? extends Annotation> annotation) {
    Set<Class<?>> classes = new HashSet<Class<?>>();
    Field dexField = PathClassLoader.class.getDeclaredField("mDexs");
    dexField.setAccessible(true);
    PathClassLoader classLoader = (PathClassLoader) Thread.currentThread().getContextClassLoader();
    DexFile[] dexs = (DexFile[]) dexField.get(classLoader);
    for (DexFile dex : dexs) {
        Enumeration<String> entries = dex.entries();
        while (entries.hasMoreElements()) {
            String entry = entries.nextElement();
            Class<?> entryClass = dex.loadClass(entry, classLoader);
            if (entryClass != null && entryClass.isAnnotationPresent(annotation)) {
                classes.add(entryClass);
            }
        }
    }
    return classes;
}

A: I wanted to find all the subclass at runtime.
So I've been looking for android class scanning.
This is my final code from what I gathered in web.
You will get the idea.
public static void findSubClasses(Context context, Class parent) {
    ApplicationInfo ai = context.getApplicationInfo();
    String classPath = ai.sourceDir;
    DexFile dex = null;
    try {
        dex = new DexFile(classPath);
        Enumeration<String> apkClassNames = dex.entries();
        while (apkClassNames.hasMoreElements()) {
            String className = apkClassNames.nextElement();
            try {
                Class c = context.getClassLoader().loadClass(className);
                if (parent.isAssignableFrom(c)) {
                    android.util.Log.i("nora", className);
                }
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            //              android.util.Log.i("nora", className);
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        try {
            dex.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

A: I share the opinion of Joop Eggen and find his approach a good one. In Android I try to avoid the usual web app features which lead to a long lasting application start. I do not use reflection or package scanning.
But if you want to .... if I understand it correctly you want to have an annotation for a class. Instead of using annotations you could also use marker interfaces (to just have more possibilites).
1) Look at

*

*Annotation: Java custom annotation and dynamic loading
Has an implementation in the question which just answers your question.

*Annotation: Scanning Java annotations at runtime

*Interface: Find Java classes implementing an interface

*Interface: Is something similar to ServiceLoader in Java 1.5?

*Interface: How can I get a list of all the implementations of an interface programmatically in Java?

*Interface: Since the approach is  expensive, maybe the ServiceLoader is a compromise between execution time and comfort, since it loads only the classes given in the services file. On the other hand if only classes with a certain interface are in your package then the ServiceLoader isn't that faster.

2) AndroidAnnotations
I would prefer the way AndroidAnnotations work (maybe an integration in AndroidAnnotations is the preferable way): It automatically adds an extra compilation step that generates source code, using the standard Java Annotation Processing Tool. So instead of runtime scanning you execute code based on the annotations generated during compile time.
I think the Bean/EBean annotation could work for you (only single class): https://github.com/excilys/androidannotations/wiki/Enhance%20custom%20classes
A scan-feature is not available, see this thread
3) Writing your own annotation processor

*

*See APT (Annotation Processing Tool). The idea would be to generate a static function which returns a list of classes which are annotated, so that no class scanning is needed.

*A very good ressource is http://javadude.com/articles/annotations/index.html

A: EDIT:
I found this issue in the Android issue tracker.  It appears that ClassLoader.getResource(String) is 'working as expected', in that it returns null.  This is expected because the DalvikVM does not keep the resources around after compiling.  There are workarounds listed in the issue, but there may be another way to access the classes you desire.
Use the PackageManager to get a hold of an instance of ApplicationInfo.  ApplicationInfo has a public field called sourceDir which is the full path (a String) to the location of the source directory for that application.  Create a File from this String, and you should be able to navigate to your package within the source directory.  Once there, you can use the method from my original answer to find the classes you are looking for.
String applicationSourceDir =
    getPackageManager().getApplicationInfo(androidPackageName, 0).sourceDir;

/EDIT
You should be able to use the ClassLoader.getResource(String) to get a URL to your specific package (the passed in String being the package name you are interested in delimited by path separators rather than periods).  With this URL you can then call getFile(), from which you can create a Java File to the package folder.  Call packageFile.listFiles() from there, and you have your classes/subpackages.
Be recursive with the subpackages, and with the classes find the Class object using the static Class.forName(String) method.

A: Take a look at Vogar's ClassPathScanner. It uses it to find test cases on the class path.

A: In your java build process incorporate the class path scanning, generating injection data/code. This could then be ported too to Dalvik. It is even more efficient that dynamic scanning.


text:
Q: Character Sets, Locales, Fonts and Code Pages? I can't figure out the relation between those terms. I actually need a brief explanation for each and eventually a relation between them.
Moreover, where do all these stuff reside? Where are they implemented? Is it the job of the operating system to manage the aforementioned terms? If not, then who is responsible for this job?

A: Character Sets describe the relationship between character codes and characters.
As an example, all (extended) ASCII character sets assign 41hex == 65dec to A.
Common character sets are ASCII, Unicode (UTF-8, UTF-16), Latin-1 and Windows-1252.
Code Pages are a a representation of character sets / a mechanism for selecting which character set is in use: There are the old DOS/computer manufacturer codepages and the legacy support for them in Windows, ANSI-Codepage (ANSI is not to blame here) and OEM-Codepage.
If you have a choice, avoid them like the plague and go for unicode, preferably UTF-8, though UTF-16 is an acceptable choice for the OS-facing part in Windows.
Locales are collections of all the information needed to conform to local conventions for display of information. On systems which neither use code pages nor have a system-defined universal character set, they also determine the character set used (e.g. Unixoids).
Fonts are the graphics and ancillary information neccessary for displaying text of a known encoding. Examples are "Times New Roman", "Verdana", "Arial" and "WingDings".
Not all Fonts have symbols for all characters present in any specific character set.


text:
Q: "Canonical" graph structure on $\text{Hom}(G, H)$ By a graph I mean a pair $G = (V, E)$ where $V$ is a set and $E \subseteq [V]^2 := \{\{a,b\}: a\neq b \in V\}$. A graph homomorphism between graphs $G, H$ is a map $f:V(G)\to V(H)$ such that $\{v, w\}\in E(G)$ implies $\{f(v), f(w)\} \in E(H)$.
Given graphs $G,H$, we denote by $\text{Hom}(G, H)$ the set of all graph homomorphisms $f: G\to H$. Note that for many $G, H$ the set $\text{Hom}(G,H)$ is empty (for instance when $\chi(G) > \chi(H)$).
For the edge set $E \subseteq [\text{Hom}(G,H)]^2$ I would like to pick the largest set such that the evaluation map $e: \text{Hom}(G,H)\times G \to H$, defined by $(f,v) \mapsto f(v)$ is a graph homomorphism.
Questions.
1) Is this construction always possible? Does it have a name?
2) If this works, how does it compare with $E'\subseteq [\text{Hom}(G,H)]^2$ where $E'$ is defined by $E'=\big\{\{f,g\}\in [\text{Hom}(G,H)]^2: \{f(v), g(v)\} \in E(H) \text{ for all } v\in V(G)\big\}$?
(For a more categorical description of this problem, see Todd Trimble's answer to a similar question in the category of topological spaces.)

A: It is trivial that such a maximal $E$ exists, and consists of pairs $\{f,g\}$ such that whenever $x$ and $y$ are adjacent, $f(x)$ and $g(y)$ are adjacent.  However, it does not make $\operatorname{Hom}(G,H)$ an exponential object, essentially because morally (according to the definition above) it should have a loop at every vertex.  For instance, when $G=H$, then for any graph $K$, there is a projection map $K\times G\to G$.  But the associated map $K\to \operatorname{Hom}(G,G)$ sends every point to the identity, and so is not a graph homomorphism unless $K$ has no edges.
Your $E'$ is adjoint not to the categorical product, but to the Cartesian product (which is rather unfortunately named from the perspective of category theory).


text: Q: Can I use the matrix of the object detected from Raycaster to calculate its vector in the face I intersected with? If so, how do I do it? I'm trying to calculate the angle between my direction of displacement and the wall(which is a THREE.Mesh), but I have no idea how to find the vector of the wall. Is there an easy way to do this?


text:
Q: Emergence of space from quantum mechanics Once talking to a visiting professor at my institute, I heard about some simple model that captures the emergence of space coordinates as the eigenvalues of some infinite-dimensional quantum mechanical Hamiltonian in $0+1$ dimensions.
Unfortunately, my attempts to find a reference or explanation inevitably end up in very complicated string theory papers that are far from what I am looking for and in which I am, to say the least, not an expert.
I would love to find some description of how this can be implemented. A toy model is more than enough.

A: I can offer up something similar to this, which is an isomorphism between something called the Tsirelson bound and the spacetime metric. This is not exactly the emergence of spacetime from quantum mechanics, but it does illustrate how spacetime could be seen as quantum mechanics in diguise.
Suppose we have four operators $A_1, A_2, B_1, B_2$  such that:
$$
A_i^2~=~B_i^2~=~1
$$
and
$$
[A_i , B_i ]=0
$$
These 4 operators correspond to the observables in Aspect's experiment. A single source of photons emits pairs of photons to the left and right measuring apparatuses. At the measurement station a rapidly moving mirror pushes the photons to be measured for polarization either on direction $A_1$ or $A_2$ for the left detectors, or $B_1$ or $B_2$ for the right detector. The outcomes are $+1$ or $-1$ (thus $A^2 = B^2 ~=~1$). The $A_i$ commute with $B_i$ because they are spatially separated. This set up is diagrammatically the same as used in the Bell theorem as diagrammed below

Now define an operator $C$ as follows:
$$
C~=~A_1 B_1 ~+~A_2 B_1 ~+~A_2 B_2 − A_1 B_2
$$
and it is not hard to show that:
$$
C^2~=~4~+~[A_1 ,A_2 ][B_1 ,B_2 ]
$$
By using the triangle inequality it is not hard to see that
$$
|C^2|~\le~4~+~4,~|C|~\le~ 2\sqrt{2}
$$
This is similar to the derivation by Peres for the Tsirelson bound.
The operator $C$ appears very similar to the Lorentz metric,
$$
x\cdot y ~=~ -x_0y_0 + x_1y_1 + x_2y_2 + x_3y_3,
$$
which is the metric distance with Lorentz geometry or $SO(3,1)$. In the case of the Riemann sphere $\sim \mathbb CP^1$ the set of conformal transformations are linear fractional transformations
$$
z~\rightarrow~\frac{az + b}{cz + d}
$$
where this transformation is isomorphic to $PSL(2,\mathbb C)$. The heavenly sphere is then the case of the null metric distance, or equivalently the projective light cone. The product space $V$ of $dim ~=~ n$ has the Jordan algebra is the $v^2 ~=~ \langle v, v \rangle$ ($v \in V$, $\langle u, v \rangle$ is the $\mathbb{R}^n$ inner product) so that a spin factor $J(V) ~\sim~ V\oplus\mathbb R$ (think of space plus time) such that
$$
(u, \alpha )◦(v, \beta ) ~=~ (\alpha v + \beta u, \langle u,v\rangle - \alpha \beta ).
$$
Then $J(V)$ is isomorphic to Minkowski spacetime. This Clifford algebra define on the right the spacetime metric $\langle u,v\rangle~ -~ \alpha\beta$.
So now suppose we let there be the spacetime $V_c$ with the basis elements
$$
u_1 ~=~ (A_1 , 0, 0), u_2 ~=~ (0, B_1 , 0), u_3 ~=~ (0, 0,A_2)
$$
$$
v_1 ~=~ (B_1 , 0, 0), v_2 ~=~ (0, A_2, 0), v_3 ~=~ (0, 0, B_2)
$$
and the real line R containing the two elements $(A_1 , B_2)$, it is then easy to see that the C operator can be expressed according to the Clifford algebra.
The connection between the null condition and the Tsirelson bound might be made by defining the elements of the real line $\mathbb R$ as $(i A_1  + \sqrt{2 \sqrt{2}}, i B_2 ~+~ \sqrt{2 \sqrt{2}})$ so that the product is the real valued part so that this is  $-B_2 A_1  ~+~ 2\sqrt{2}$. In that way the modified $|C|^2$ would be zero if it is at the Tsirelson bound, and similar to a choice of metric signature is negative if outside the Tsirelson bound.
This is a somewhat elementary or naive approach. We have though a monoid or magma connection between the Jordan algebra and the $W^*$ algebra. This might be an interesting topic to pursue. It is my thinking that spacetime physics and quantum physics are on a deep level identical. In effect spacetime is probably built up from quantum entanglements.

A: This probably refers to the BFSS matrix model. This is argued to arise in several equivalent ways: as the worldvolume theory of a large number of D0-branes in type IIA, as the KK-compactification of 10d SYM to zero space dimensions, or as a certain non-commutative limit of of the worldsheet action of the M2-brane in M-theory. In any case, it ends up being a quantum mechanical system whose degrees of freedom are a set of 9+1 large matrices. These play the role of of would-be coordinate functions and their eigenvalues may be in interpreted as points in a spacetime thus defined.
In the 90s there was much excitement about the BFSS model, as people hoped it might provide a definition of M-theory. It is from these times that Witten changed the original suggestion that "M" is for "magic, mystery and membrane" to the suggestion that it is for "magic, mystery and matrix". (See Witten's 2014 Kyoto prize speach, last paragraph). But these days it is more quiet around the BFSS model, a fate it shares with many of the ideas that were exciting in the 90s and now lay somewhat more dormant.
Notice that there is also the IKKT matrix model which takes this one step further by reducing one dimension further down (D(-1)-branes). There is a Japanese group who claims that a MonteCarlo computer simulation of the IKKT model which they have set up shows a spontaneous generation of a 10d spacetime with 3+1 large and 6 tiny dimensions (Kim-Nishimura-Tsuchiya 12).


text:
Q: How to make a border that touches the bottom of the nav on hover I am trying to style my menu, but I am having a small problem.
I want the red border on hover to touch the border-bottom of the nav. So it looks like this:

How can I get this effect? I have tried but my code below is doing this:

nav {
    display: flex;
    align-items: center;
    border-bottom: 1px solid #546478;
    padding: 5px 20px;
}

.nav__container {
    max-width: 93.75rem;
    margin: 0 auto;
}

li {
    list-style: none;
    margin: 20px;
}

li:hover {
    border-bottom: 1px solid red;
}

.hero__nav-items {
    margin-left: auto;
}

.hero_nav-list {
    display: flex;
}

Menu

Menu

Menu

A: Remove padding and margin from hero_nav-list and add padding in li

nav {
    display: flex;
    align-items: center;
    border-bottom: 1px solid #546478;
    padding: 0 20px;
}

.nav__container {
    max-width: 93.75rem;
    margin: 0 auto;
}

li {
    list-style: none;
    margin: 0 20px;
    padding: 20px 0;
    border-bottom: 1px solid transparent;
    transition: all 0.4s;
}

li:hover {
    border-bottom-color: red;
}

.hero__nav-items {
    margin-left: auto;
}

.hero_nav-list {
    display: flex;
    padding: 0;
    margin: 0;
}

Menu

Menu

Menu

A: The problem is that you are using margin instead of padding to create the space underneath the text. Borders apply to the outside including padding, but excluding the margin`.
See the working example at the end, and the changes you need are here:

*

*Change the margin to padding for your li: li { padding: 20px; /* change margin to padding */ }

*You also need to remove the margin from the ul as it is adding more space.
.hero_nav-list { margin: 0;}

*Remove the padding to the top & bottom of nav: nav { padding: 0px 20px; }

*To make the borders overlap, make the li bottom margin -1px: li { margin-bottom: -1px; }

*dd an "invisible" border that will be replaced by the red border  - this will stop the nav border jumping on hover: li { border-bottom: 1px solid transparent; }
Working Example:

nav {
  display: flex;
  align-items: center;
  border-bottom: 1px solid #546478;
  padding: 0px 20px;
}

.nav__container {
  max-width: 93.75rem;
  margin: 0 auto;
}

li {
  list-style: none;
  padding: 20px;
  border-bottom: 1px solid transparent;
  margin-bottom: -1px;
}

li:hover {
  border-bottom: 1px solid red;
}

.hero__nav-items {
  margin-left: auto;
}

.hero_nav-list {
  margin: 0;
  display: flex;
}

Menu

Menu

Menu

A: Just use padding rather than margin

nav {
  display: flex;
  align-items: center;
  border-bottom: 1px solid #546478;
  padding: 0px 20px;
}

.nav__container {
  max-width: 93.75rem;
  margin: 0 auto;
}

li {
  list-style: none;
  padding: 20px;
  border-bottom: 2px solid transparent;
  margin-bottom: -1px;
}

li:hover {
  border-bottom-color: red;
  transition: all .3s
}

.hero__nav-items {
  margin-left: auto;
}

.hero_nav-list {
  display: flex;
  margin: 0;
}

Menu

Menu

Menu


text:
Q: Is the space of convex functions a Polish space? I'm working with continuous, increasing, convex functions (call the set $\mathcal{U}$) and viewing them as a subspace of $\mathcal{C}=\mathcal{C}([0,1])$ (perhaps this is not the best topology, recommendations welcome). Since $\mathcal{C}$ is Polish I sense that $\mathcal{U}$ is as well. I have a proof sketch (follows) and I hope someone can either give me a reference, or tell me I'm wrong, before I get too far into it.
Sketch: These functions can be recovered by their subdifferentials, which perhaps can be viewed as cadlag functions since each point will have a closed, convex interval of subderivatives. So, if I can find a homeomorphism between $\mathcal{U}$ and the space of cadlag functions with the Skorokhod topology, I get my answer by showing that non-decreasing functions form a closed subset in the Skorokhod topology (hopefully true).
I'm aware that cadlag with Skorokhod is not a TVS, which seems to rule out finding an isomorphism, but it doesn't seem essential that the algebraic structure is mapped . . .
Thanks for any help.

A: New Answer:
As a closed subset of a Polish space, $\mathcal{U}$ is also Polish.
Note that the limit of a sequence of convex, nondecreasing functions will also be non-decreasing and (weakly) convex.
Aside:
Just trying to tie this off. I don't want to leave it hanging as unanswered.
Old Answer:
Obvious: $\mathcal{U}$ is closed.
Whoops. Thanks to "freakish" in comments above.


text:
Q: Simple show/hide gone wrong in Javascript I'm trying to create a show/hide function for data within a table populated with data from a mssql database. The function should look for rows with the same value in the "capability" column and onclick, hide all rows with the same value. After this, a row is inserted into the table with the same capability value, but summarizes the data in the hidden rows. This should work in the way that grouping cells together works in excel.
I've managed to get this to work, but it only works for the first click and I receive a "cannot read innerHTML property of NULL" for any of the function's calls after that.
function compactRows(thisrow) {
  var totalRows = document.getElementById("DataTable").getElementsByTagName("tr").length;

  var summaryVal1= [];
  var summaryVal2= [];

  for(var i = 1; i < totalRows;i++) {
    var trID = "capability" + i;
    if(thisrow.innerHTML == document.getElementById(trID).innerHTML) { //The error gets returned on this line
        summaryVal1.push(document.getElementById(trID).parentNode.children[5].innerHTML);
        summaryVal2.push(document.getElementById(trID).parentNode.children[14].innerHTML);
        document.getElementById(trID).parentNode.style.display = 'none';
    }
  }
  createNewRow(thisrow, summaryVal1, summaryVal2);
}

//I took out the logic for the data summarizing in the createNewRow function because I don't think its relevant to the issue I'm having. Also, I didn't want to crowd the area with unrelated code
function createNewRow(row, ibxMobile, overallStatus) {
var table = document.getElementById("DataTable");
var localRow = table.insertRow(row.parentNode.rowIndex);

var cell1 = localRow.insertCell(0);
cell1.setAttribute("id", "entry1");

var cell2 = localRow.insertCell(0);
cell2.setAttribute("id", "Capability");
cell2.innerHTML = row.innerHTML;

var cell3 = localRow.insertCell(0);
cell3.setAttribute("id", "entry3");
}

The function called at the bottom, createNewRow, handles making the row to be entered after all the rows are hidden. It also, handles the logic for summarizing the hidden rows.
All help is greatly appreciated! Thank you
Edit 1: example table set up

Entry1
Capability
Entry3

1.1
Lasers
stuff

1.2
Lasers
things

2.1
Beams
more things

//The Below table is what it looks like after clicking either of the first two entries

Entry1
Capability
Entry3

1
Lasers

2.1
Beams
more things

A: There is no "Capability1" id for any rows after the "CreateNewRow" is called. Therefore, the second time "CompactRows()" is called a null reference is thrown when accessing "document.getElementById("Capability1").innerHTML".  Rework the CreateNewRow to inlcude the increment for the Capability id value or test that "getElementById" actually returns an object before attempting to access the innerHTML method.


text:
Q: zsh grep pattern matching for ^ not working For git, I have many branches that I start off with temp, so to filter all the temporary branches, I tried:
git branch | grep "^temp"
However, I am not getting any result.
If I just run git branch, I get the following:
temp/github-fix
temp/mismatches
test/temp

I want to just match the first two, but not the last one.

A: as @WumpusQ.Wumbley pointed out, git branch output usually starts with whitespace, try this, git branch|grep '^\s*temp'

A: You can use --list followed by a pattern to list the branches you want.
git branch --list 'temp*'


text:
Q: How to establish PHP PDO connection with pooling I want to connect a Postgres database with pooling:true. Can we do it with PHP new PDO option? If not are there any reliable options?
I want to pass the below parameters(similar) while establishing the connection:
Pooling=true;Minimum Pool Size = 2;Internal Command Timeout = 0;Command Timeout = 0;
I cannot find any such details in https://www.php.net/manual/en/ref.pdo-pgsql.connection.php
Any help will be much appreciated.

A: As far as i remember from old days of programming in PHP, You cannot have pooling in PHP as php is not threded (most of times) and each requests goes line by line.  In JavaScript (node.js) you can do pooling, but not on PHP as each request is one thread.

A: We can use PgBouncer. This has been answered in another question.


text:
Q: While performing Authorization Http client call not working in Blazor application We are making a WebAPI call through HTTP client and this call is prevented when authorization is enabled in the Blazor application.
We just need to trigger the PostCount method in the controller. But it is not triggering when the authorization code is added to the Program.cs file.
https://github.com/Indhumathy-Loganathan/NewAuthorizationSample/blob/main/Program.cs#L14
If you remove that Authorization code, then the API call will trigger properly. For now, it will only throw an error since we don't make any customizations at the server end. All we need is to trigger the API PostCount method, so set the breakpoint in that method to test this issue.


text:
Q: What does the one in 'tk.wm_attributes("-topmost", 1) mean? I created a game and there is this part of the code I don't understand.tk.wm_attributes("-topmost", 1)
What does the number after "-topmost" mean? I changed the number to 0 and 255, yet there is no difference. Why is that?

*

*I also checked the tkinter documentation and I can't find the function.

A: Yeah, the function's quite well hidden and (I think) only works on Python.
tk.wm_attributes() sets settings for tkinter to use for drawing the app. -topmost is an option to make the window always be on top of all the other windows, and zero is considered false while all other numbers are true.
So in other words, tk.wm_attributes('-topmost', 1) means "Yes, do draw the window on top of all the others."

A: The topmost attribute requires a value that can be converted to True or False in the tcl language. 1 or any other number greater than zero evaluates to True. 0 will evaluate to False.
So, tk.wm_attributes("-topmost", 1) sets the topmost option on, and a value of 0 turns it off.


text:
Q: How to write to specific line of the file using PHP? I am generating some PHP source code files using PHP only :)
And I want to know if I have to write some line of text before closing brackets, how can I do that using PHP file functions.
e.g. below is my target file code. filename : project.php
Class project{
   public function get_project($id){
   ..... some code here
   }

   public function add_project(){
   ..... some code here
   }

   <--- add code here
}

I have a line of code which I want to add to the position pointed in the example. I can use file_put_content() method but it has option to Append the code on the end of the file like below
file_put_contents('project.php', 'Hello World', FILE_APPEND);

but it will not write to specific position. So how can I do that?


text:
Q: Why does macdeployqt give the error "can't open input file"? When I run macdeployqt on my .app, it adds the libraries ok, but then makes the application crash when you try to start it. This works fine on Mac OS X 10.7, but on Mac OS X 10.8 DP3 no joy. To install Qt I've used port install qt4-mac (however, I may have a much older version of Qt on my 10.7 machine from the Qt website).
Command: macdeployqt bin/Synergy.app -verbose=3
Enite log: http://pastebin.com/i37vadB7
Log: Using install_name_tool:
Log:  in "bin/Synergy.app/Contents/Frameworks//libcrypto.1.0.0.dylib"
Log:  change reference "/opt/local/lib/libz.1.dylib"
Log:  to "@executable_path/../Frameworks/libz.1.dylib"
ERROR: "install_name_tool: can't open input file: bin/Synergy.app/Contents/Frameworks//libcrypto.1.0.0.dylib for writing (Permission denied)
install_name_tool: can't lseek to offset: 0 in file: bin/Synergy.app/Contents/Frameworks//libcrypto.1.0.0.dylib for writing (Bad file descriptor)
install_name_tool: can't write new headers in file: bin/Synergy.app/Contents/Frameworks//libcrypto.1.0.0.dylib (Bad file descriptor)
install_name_tool: can't close written on input file: bin/Synergy.app/Contents/Frameworks//libcrypto.1.0.0.dylib (Bad file descriptor)
"
ERROR: ""
Log:
Log: Deploying plugins from "/opt/local/plugins"
Log: Created configuration file: "bin/Synergy.app/Contents/Resources/qt.conf"
Log: This file sets the plugin search path to "bin/Synergy.app/Contents/PlugIns"

A: Solved by downgrading to an old Qt SDK .dmg I had hanging around (qt-sdk-mac-opensource-2010.03.dmg). I also ran sudo port uninstall qt4-mac to remove the new SDK.
So looks like the newest version of Qt has a broken macdeployqt app.
So here's the Qt version I have now, which works:
$ qmake -version
QMake version 2.01a
Using Qt version 4.6.3 in /Library/Frameworks

A: I think there is a privilege issue in macdeployqt.
I solved by using sudo:
sudo -s -- 'macdeployqt myapp.app; chown -R $(USER) myapp.app'

A: From your error message it seems that the libcrypto that you are using is linked to libz on the local file system. What you need to do is make sure there is a copy of libz in the Frameworks directory of your bundle and then use install_name_tool to change the path to the version in the bundle.
install_name_tool -change /opt/local/lib/libz.1.dylib @executable_path/../Frameworks/libz.1.dylib bin/Synergy.app/Contents/Frameworks//libcrypto.1.0.0.dylib

If your binary is linked to missing libraries it usually results in a crash.
There have been some issues with macdeployqt changing over the last few releases of Qt so you do have to check linked paths.


text:
Q: Targeting the 3.5 Framework using MSBuild 4.0 Assembly Conflict I'm attempting to create a 3.5 build from a 4.0 set of code.  It almost works the following msbuild options: /tv:3.5 /p:targetframeworkversion=v3.5.  The issue is that I get a conflict for those classes that have moved to new assemblies in 4.0, for example:
error CS0433: The type 'System.Web.Security.RoleProvider' exists in both 'c:\Windows\Microsoft.NET\assembly\
GAC_MSIL\System.Web.ApplicationServices\v4.0_4.0.0.0__31bf3856ad364e35\System.W
eb.ApplicationServices.dll' and 'c:\Windows\Microsoft.NET\Framework\v2.0.50727\
System.Web.dll'

How do I tell msbuild to pickup the System.Web assembly?  Can I tell it to ignore the 4.0 directory?

A: sounds like a similar issue to what we had, ended up with Hf from Microsoft
TFS2008 to TFS2010 migration upgrade


text:
Q: When requesting post, there is no content in the request header body <body>
    <form action="/signup" method="post" enctype="text/plain">
        ID : <input type="text" name="signupID" id="signupID">
        PW : <input type="text" name="signupPW" id = "signupPW">
        <input type = "submit" value="signup">
    </form>
</body>

And I entered the value
I've seen request, but I can not find the value anywhere
Where is the value I entered?
request: POST /signup HTTP/1.1
request: Host: localhost:8080
request: Connection: keep-alive
request: Content-Length: 38
request: Cache-Control: max-age=0
request: Origin: http://localhost:8080
request: Upgrade-Insecure-Requests: 1
request: User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36
request: Content-Type: text/plain
request: Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q=0.8
request: Referer: http://localhost:8080/
request: Accept-Encoding: gzip, deflate, br
request: Accept-Language: ko-KR,ko;q=0.8,en-US;q=0.6,en;q=0.4


text:
Q: Orphelin transaction named 'offline index build' hang forever So I'm having a problem with SQL Server 2008 R2 that I didn't have in SQL Server 2005.
I backuped a database and restored it to SQL Server 2008 R2. It's a standard database of moderate size with some indexes and fulltext indexes.
The problem now is that I have an open transaction that never ends.
When I execute the query:
DBCC OPENTRAN;

I get as result:
Transaction information for database 'MediaTrunk2005'.
Oldest active transaction:
    SPID (server process ID): 34s
    UID (user ID) : -1
    Name          : offline index build
    LSN           : (4070767:241:144)
    Start time    : Jul 29 2014  2:16:35:867PM
    SID           : 0x0
    DBCC execution completed. If DBCC printed error messages, contact your system administrator.

If I look at the table 'syslockinfo' with my database I can see this:
                                                   rsc_text                         rsc_bin                            rsc_valblk                         rsc_dbid rsc_indid rsc_objid   rsc_type rsc_flag req_mode req_status req_refcnt req_cryrefcnt req_lifetime req_spid    req_ecid    req_ownertype req_transactionID    req_transactionUOW
-------------------------------- ---------------------------------- ---------------------------------- -------- --------- ----------- -------- -------- -------- ---------- ---------- ------------- ------------ ----------- ----------- ------------- -------------------- ------------------------------------
                             0x0000000000000000000000001E000200 0x00000000000000000000000000000000 30       0         0           2        0        3        1          1          0             0            252         0           4             0                    00000000-0000-0000-0000-000000000000
                             0x0000000000000000000000001E000200 0x00000000000000000000000000000000 30       0         0           2        0        3        1          1          0             0            -2          0           4             0                    00000000-0000-0000-0000-000000000000

(2 row(s) affected)
Ok, it's not very readable. What I want to show there is an empty UOW guid so I cannot kill it with the Guid.
How can I solve this problem? What information do you need more?
EDIT:
I also restored the database on SQL Server 2012 and the bug is not present there either. So it only fails on SQL Server 2008 R2.


text:
Q: Terminal only outputs last few lines and everything before is deleted I am using grep to find strings in multiple files. It outputs a lot of text which is what I need, but then terminal just deletes all the output while grep continues working and so I can see only last few results grep found.
How do I make grep work?
I am sorry for noob question but I literally searched whole internet and didn't find answer. What I need is to search for text in multiply binary files recursively and output line from those binary files containing searched text.
grep does that but I can't use it, if there is another app that can do that it would be great too.

A: You can pipe the output to a pager like less, or redirect it to a file, and then read the file using your favorite editor or pager.
For example:
grep -R foo ./DIR | less    # search for foo, view a screen full at a time

or:
grep -R foo ./DIR > outputs # search for foo, and output the results to a file

less outputs                # view the file one screen full at a time


text:
Q: Get all posts from Workflow in Channel I have a Slack channel at my workplace where every new member is prompted via workflow to enter some information, and then the workflow posts it to the channel (there is a Workflow tag next to it). I want to organize all of the responses to that workflow in a single space, either by exporting it from Slack or by consolidating into a single post.
I believe I could use the workflow_published event object to catch them moving forward (in fact, I could even just add an additional step to the existing workflow I believe), but how could I go back and scrape previous responses to this workflow?
Apologies, I do not have any pre-existing code as I need to request access through our security team, which is pretty strict, and I want to know what is the least amount of permissions I can request.

A: May be you can use the conversations.history api to fetch all the messages from then channel and then extract information by applying required filters (e.g. subtype, username, bot_id).