text:
Q: Postgres Delete records from table keeping a minimum and maximum value I have a Postgres table like so:
|scanID|scandatetime     |eventcode|state|
------------------------------------------
|12345 |2020-07-28 1:00  |123      |WA   |
|12345 |2020-07-28 2:00  |156      |WA   |
|12345 |2020-07-29 10:00 |200      |OR   |
|34678 |2020-07-20 4:00  |123      |TX   |
|34678 |2020-07-20 8:00  |156      |AR   |
|34678 |2020-07-22 1:00  |200      |MS   |

and essentially I want to delete every row such that I only keep 2 rows per scan ID. I want to retain the scan IDs with the minimum time and with the maximum time.
The current workflow is that data gets aggregated and written to this table every day, so after it's written there may be a bunch of new scan events, but I only want to keep the max and min. How would I go about doing that?
EDIT: The desired result table would look like this
|scanID|scandatetime     |eventcode|state|
------------------------------------------
|12345 |2020-07-28 1:00  |123      |WA   |
|12345 |2020-07-29 10:00 |200      |OR   |
|34678 |2020-07-20 4:00  |123      |TX   |
|34678 |2020-07-22 1:00  |200      |MS   |

A: You can use using:
delete from t
    using (select scanId, min(scandatetime) as min_sdt, max(scandatetime) as max_sdt
           from t
           group by scanid
          ) tt
    where tt.scanId = t.scanId and t.scandatetime not in (tt.min_sdt, tt.max_sdt);

You could also phrase this as:
delete from t
    where scandatetime <> (select min(t2.scandatetime) from t tt where tt.scanid = t.scanid) and
          scandatetime <> (select max(t2.scandatetime) from t tt where tt.scanid = t.scanid) ;

A: A record is in the middle if there is (at least) one above it, and (at least) one below it:

DELETE FROM ztable d
WHERE EXISTS ( SELECT *
        FROM  ztable x
        WHERE x.scanId = d.scanId
        AND x.scandatetime < d.scandatetime
        )
AND EXISTS ( SELECT *
        FROM  ztable x
        WHERE x.scanId = d.scanId
        AND x.scandatetime > d.scandatetime
        );

Similar trick, using row_number():

DELETE FROM ztable d
USING ( SELECT scanId, scandatetime
        , row_number() OVER
                (PARTITION BY scanId ORDER BY scandatetime ASC) rn
        , row_number() OVER
                (PARTITION BY scanId ORDER BY scandatetime DESC) rrn
        FROM  ztable
        ) x
        WHERE x.scanId = d.scanId
        AND x.scandatetime = d.scandatetime
        AND x.rn <> 1 AND x.rrn <> 1

        ;

A: You can use a NOT IN with a sub-select:
delete from the_table t1
where (scanid, scandatetime) not in (select scanid, min(scandatetime)
                                     from the_table
                                     group by scanid
                                     union all
                                     select scanid, max(scandatetime)
                                     from the_table
                                     group by scanid);

But I assume the solution using exists will be faster.


text:
Q: How can i get single document from Firestore with query (I'm using Ionic 4 ) Good morning , I have database in firestore below :
**collections**       **documents**     **fields**
123                     news1           title:{some data}
                        news2           content:{some data}

for example i want to get the all data of the (news1) in the page of my ionc4 app , how can i do that please help me

A: You can achieve this by querying specific document id:
firestore.collection(collectionName).doc(documentId).valueChanges()
.subscribe(singleDoc =>{
console.log(singleDoc)
});

For you the query will look like this:
firestore.collection('123').doc('news1').valueChanges()
.subscribe(news1=>{
console.log(news1)
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a `Split` equivalent to torch.nn.Sequential? A sample code for a Sequential block is
self._encoder = nn.Sequential(
        # 1, 28, 28
        nn.Conv2d(in_channels=1, out_channels=32, kernel_size=3, stride=3, padding=1),
        # 32, 10, 10 = 16, (1//3)(28 + 2 * 1 - 3) + 1, (1//3)(28 + 2*1 - 3) + 1
        nn.ReLU(True),
        nn.MaxPool2d(kernel_size=2, stride=2),
        # 32, 5, 5
        nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, stride=2, padding=1),
        # 64, 3, 3
        nn.ReLU(True),
        nn.MaxPool2d(kernel_size=2, stride=1),
        # 64, 2, 2
)

Is there some construct like nn.Sequential that puts modules in it in parallel?
I would like to now define something like
self._mean_logvar_layers = nn.Parallel(
    nn.Conv2d(in_channels=64, out_channels=64, kernel_size=2, stride=1, padding=0),
    nn.Conv2d(in_channels=64, out_channels=64, kernel_size=2, stride=1, padding=0),
)

Whose output should be two pipes of data - one for each element in self._mean_logvar_layers which are then feedable to the rest of the network. Kind of like a multi-headed network.

My current implementation:
self._mean_layer = nn.Conv2d(in_channels=64, out_channels=64, kernel_size=2, stride=1, padding=0)
self._logvar_layer = nn.Conv2d(in_channels=64, out_channels=64, kernel_size=2, stride=1, padding=0)

and
def _encode(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
    for i, layer in enumerate(self._encoder):
        x = layer(x)

    mean_output = self._mean_layer(x)
    logvar_output = self._logvar_layer(x)

    return mean_output, logvar_output

I would like to treat the parallel construct as a layer.
Is that doable in PyTorch?

A: Sequential split
What you can do is create a Parallel module (though I would name it differently as it implies this code actually runs in parallel, probably Split would be a good name) like this:
class Parallel(torch.nn.Module):
    def __init__(self, *modules: torch.nn.Module):
        super().__init__()
        self.modules = modules

    def forward(self, inputs):
        return [module(inputs) for module in self.modules]

Now you can define it as you wanted:
self._mean_logvar_layers = Parallel(
    nn.Conv2d(in_channels=64, out_channels=64, kernel_size=2, stride=1, padding=0),
    nn.Conv2d(in_channels=64, out_channels=64, kernel_size=2, stride=1, padding=0),
)

And use it like this:
mean, logvar = self._mean_logvar_layers(x)

One layer and split
As suggested by @xdurch0 we could use a single layers and split across channels instead, using this module:
class Split(torch.nn.Module):
    def __init__(self, module, parts: int, dim=1):
        super().__init__()
        self.parts
        self.dim = dim
        self.module = module

    def forward(self, inputs):
        output = self.module(inputs)
        chunk_size = output.shape[self.dim] // self.parts
        return torch.split(output, chunk_size, dim=self.dim)

This inside your neural network (notice 128 channels, those will be split into 2 parts, each of size 64):
self._mean_logvar_layers = Split(
    nn.Conv2d(in_channels=64, out_channels=128, kernel_size=2, stride=1, padding=0),
    parts=2,
)

And use it like previously:
mean, logvar = self._mean_logvar_layers(x)

Why this approach?
Everything will be done in one swoop instead of sequentially, hence faster, but might be too wide if you don't have enough GPU memory.
Can it work with Sequential?
Yes, it is still a layer. But next layer has to work with tuple(torch.Tensor, torch.Tensor) as inputs.
Sequential is also a layer, quite simple one, let's see forward:
def forward(self, inp):
    for module in self:
        inp = module(inp)
    return inp

It just passes output from previous model to the next and that's it.

A: Following @Szymon Maszke's great answer(s), here is the full relevant code, after all augmentations:
class Split(torch.nn.Module):
    """
    https://stackoverflow.com/questions/65831101/is-there-a-parallel-equivalent-to-toech-nn-sequencial#65831101

    models a split in the network. works with convolutional models (not FC).
    specify out channels for the model to divide by n_parts.
    """
    def __init__(self, module, n_parts: int, dim=1):
        super().__init__()
        self._n_parts = n_parts
        self._dim = dim
        self._module = module

    def forward(self, inputs):
        output = self._module(inputs)
        chunk_size = output.shape[self._dim] // self._n_parts
        return torch.split(output, chunk_size, dim=self._dim)

class Unite(torch.nn.Module):
    """
    put this between two Splits to allow them to coexist in sequence.
    """
    def __init__(self):
        super(Unite, self).__init__()

    def forward(self, inputs):
        return torch.cat(inputs, dim=1)

And the usage:
class VAEConv(VAEBase):
    ...
    ...
    ...

    def __init__():
        ...
        ...
        ...
        self._encoder = nn.Sequential(
        # 1, 28, 28
        nn.Conv2d(in_channels=1, out_channels=32, kernel_size=3, stride=3, padding=1),
        # 32, 10, 10 = 16, (1//3)(28 + 2 * 1 - 3) + 1, (1//3)(28 + 2*1 - 3) + 1
        nn.ReLU(True),
        nn.MaxPool2d(kernel_size=2, stride=2),
        # 32, 5, 5
        nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, stride=2, padding=1),
        # 64, 3, 3
        nn.ReLU(True),
        nn.MaxPool2d(kernel_size=2, stride=1),
        Split(
                # notice out_channels are double of real desired out_channels
                nn.Conv2d(in_channels=64, out_channels=128, kernel_size=2, stride=1, padding=0),
                n_parts=2,
        ),
        Unite(),
        Split(
                nn.Flatten(start_dim=1, end_dim=-1),
                n_parts=2
        ),
    )

    def _encode(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
        for i, layer in enumerate(self._encoder):
            x = layer(x)

        mean_output, logvar_output = x
        return mean_output, logvar_output

This now allows to subclass the VAE and define a different encoder on init time.


text:
Q: PHP - take data from html textarea row after row into variables I have a HTML form and there is a textarea let's say like this:
link1
link2
link3

I would like to take the text from the text area row after row through PHP file so it will in the end be like this:
$var1 will be "link1"
$var2 will be "link2"
$var3 will be "link3"

important - this variables must be saved in php - whole form is in html file
EDIT: this can be done with array too, so i will have ["link1", "link2", "link3"]
EDIT2: if this is done with array i would like to acces it with indexes like in JS or other languages so "$array[0]" for example... (i know its not done like this in php)

A: In this case you can use a foreach.
Let's say you have a textarea tag.
<textarea name="lyrics"></textarea>

You can access it's value:
$lyrics = $_POST['lyrics'];
$text = trim($lyrics);
$textAr = explode("\n", $text);
$textAr = array_filter($textAr, 'trim');

Use foreach
foreach ($textAr as $line)
{
    echo $line;
}


text:
Q: How to use scanner to accept only int or prevent users from inputting double? This is my current code. What I would like to do is limit the users input to only int. If a double is entered, I'd like a line printed "Please enter a whole number." I've tried to play around with scanner.hasNextint but haven't had much success. Is there a way to ignore double as an input entirely and have it round?
Thanks in advance!
public class BMI extends DecimalFormat{

    public static void main(String[] args) {
        int weight;
        int height;
        double bodyMassIndex;

        DecimalFormat dfWithTwoDecimalPlaces;
        Scanner scanner;
        scanner = new Scanner(System.in);
        System.out.print("What is your weight in kilograms (kg): ");
        weight = scanner.nextInt();
        System.out.print("What is your height in centimeters(cm): " );
        height = scanner.nextInt();
        bodyMassIndex = (weight / Math.pow(height/100.0, 2.0) );

        dfWithTwoDecimalPlaces = new DecimalFormat ("0.00");
        System.out.print("Your Body Mass Index is: " + dfWithTwoDecimalPlaces.format(bodyMassIndex));

    }

}

A: Create a user defined method getNextInt() as bellow:
/**get next integer*/
public static int getNextInt(Scanner scanner) {
    while (!scanner.hasNextInt()) {
        scanner.next();
    }
    return  scanner.nextInt();
}

public static void main(String[] args) {
    int weight;
    int height;
    double bodyMassIndex;

    DecimalFormat dfWithTwoDecimalPlaces;
    Scanner scanner;
    scanner = new Scanner(System.in);
    System.out.print("What is your weight in kilograms (kg): ");
    weight = getNextInt(scanner);//call user-defined method
    System.out.print("What is your height in centimeters(cm): " );
    height = getNextInt(scanner);//call user-defined method
    bodyMassIndex = (weight / Math.pow(height/100.0, 2.0) );

    dfWithTwoDecimalPlaces = new DecimalFormat ("0.00");
    System.out.print("Your Body Mass Index is: " + dfWithTwoDecimalPlaces.format(bodyMassIndex));

}

You can add a message inside while loop like this:
while (!scanner.hasNextInt()) {
    scanner.next();
    System.out.println("Please enter a whole number");//message
}

A: 1.use try {} catch{} block (reference java exception handling)
public class MySource extends DecimalFormat{
public static void main(String[] args) {
     int weight;
        int height;
        double bodyMassIndex;

        DecimalFormat dfWithTwoDecimalPlaces;
        Scanner scanner;
        scanner = new Scanner(System.in);

        while(true) {
            try {
                System.out.print("What is your weight in kilograms (kg): ");
                weight = scanner.nextInt();
                System.out.print("What is your height in centimeters(cm): " );
                height = scanner.nextInt();
                break;
            }catch(InputMismatchException e) {
                System.out.println("Please enter a whole number.");
                scanner.nextLine();
            }
        }

        bodyMassIndex = (weight / Math.pow(height/100.0, 2.0) );

        dfWithTwoDecimalPlaces = new DecimalFormat ("0.00");
        System.out.print("Your Body Mass Index is: " + dfWithTwoDecimalPlaces.format(bodyMassIndex));
}

}


text:
Q: Why doesn't zero padding with integers work in Matlab formatSpec? I am trying to pad a number with zeros as follows.
Desired:
7 -> '07'
8 -> '08'

(In case it matters, the input is intended as a character vector to be converted by num2str. But for the examples below, direct numeric input does not seem to be any different.)
>> num2str(7,'%02.u')
ans =
    '7'    % does not pad the zeros
>> num2str(7,'%02.f')
ans =
    '07'   % works as intended

Why doesn't '%02.u' work?


text:
Q: Indexing JTree nodes I would like to create an index (1, 1.2, 1.3, 2.1 etc.) for each node of a JTree at the time of adding the new node,
i.e.
root
|
 ---1 node
|
 ---2 node
    |
     ---2.1 node

Does anybody have an idea how I can do it? Thank you in advance for any answers.

A: As you add a node, find the current number of nodes in that level and your index of your new node is the count plus 1.

A: With complexe UI components, it is better to distinguish the data model and the rendering.
As a consequence, I suggest you implement a TreeModel which returns for example Nodes objects which may contain the integer for its level and you also implement a TreeCellRenderer which makes the rendering of the node.
The index may be either computed at each rendering using parents node which can be asked to the model of the information could be cached into the node.
You can have a look here on how to implement a custom TreeModel : http://download.oracle.com/javase/tutorial/uiswing/components/tree.html#data
If you need to do things when parent nodes are clicked, you can use Tree-Will-Expand listeners (also referenced in the tutorial)

A: Since you didn't tell us, if you have implemented your own TableModel, I assume, that you work with a standard JTree and the default model. A method that retrieves the index of a Node as a String would look like this:
public String getNodeIndex(JTree tree, TreeNode node) {
    TreeNode root = (TreeNode) tree.getModel().getRoot();
    if (node == root) {
        return "";
    }
    TreeNode parent = node.getParent();
    if (parent == null) {
        return null;
    }
    String parentIndex= getNodeIndex(tree, parent);
    if (parentIndex == null) {
        return null;
    }
    return parentIndex+"."+parent.getIndex(node);
}

This code should work as long as you don't build cycles into your tree, as if works recursively up to the root.


text:
Q: UIFont render result is different from what we see on Sketch/Figma I'm working with a designer that is sharing assets coming from Figma and Sketch.
If I use the same exact font size available on Figma/Sketch for my UILabel, I see the rendered fonts are smaller than the same fonts rendered on Figma/Sketch.
I'm using something like this to initialise my font for the labels:
self.font = UIFont(name: "MyFont-Bold", size: 14)
Both Figma and Sketch work in points the same is true for UIFont...
Is there anything we can do to align our results?

A: For me, this option works well.
UIFont(name: "Font-Name", size: UIScreen.main.bounds.height*(fontSize)/800)


text:
Q: Can we take derivative of $x$ over $f(x)$ ? I have, probably the most dumb question ever:
if we have $f = f(x)$
can we take derivative:
$$\frac{dx}{df} = \frac{dx}{df(x)} ?$$
I was thinking of that it may be possible, if we find some inverse, or smth like substitution. So if $f= cx^2$, then:
$$\frac{dx}{df} = \frac{dx}{dcx^2} $$
is actually:
$\sqrt{c}x = \sqrt{y}$, and $x = \sqrt{\frac{y}{c}}$ then:
$$\frac{dx}{df} = \frac{dx}{dcx^2} =  \frac{d \sqrt{\frac{y}{c}} }{d y}  =\sqrt{\frac{1}{c}} \frac{d \sqrt{y} }{d y} = ...$$
 Is it a correct approach?

A: Suppose that $f$ is a function $D\to\Bbb R$. To make sense of what you write, we need that $f$ has an inverse function, that is, that there exists $g$ such that for all $x\in D$, $g(f(x)) = x$. Then using the chain rule, we have that $\frac{d(g\circ f)}{dx}(x) = \frac{dg}{df}(f(x))\times \frac{df}{dx}(x)$ for all $x\in D$. Note that since $g\circ f$ is the identity function, we have that the left-hand side of the equality is equal to 1 at every $x\in D$. Therefore, we have $\frac{dg}{df}(f(x)) = \frac1{\frac{df}{dx}(x)}$. Replacing $f(x)$ by $y$, this gives the formula
$$\frac{dg}{df}(y) = \frac1{\frac{df}{dx}(g(y))}$$
and by abuse of notation, this quantity could also be written as $\frac{dx}{df}$.
Taking your example, if $f(x)=cx^2$ over $[0,+\infty]$, then $g(x) = \sqrt{\frac{x}{c}}$. We then have $\frac{dg}{df}(y) = \frac1{2\sqrt{cx}}$.


text:
Q: What is actually returned? I am recently learning express.js. The code below is copied from the router lib of express.js.
var proto = module.exports = function(options) {
  options = options || {};

  function router(req, res, next) {
    router.handle(req, res, next);
  }

  // mixin Router class functions
  router.__proto__ = proto;

  router.params = {};
  router._params = [];
  router.caseSensitive = options.caseSensitive;
  router.strict = options.strict;
  router.stack = [];

  return router;
  };

My question is what is returned if I call
var Router = require('./router');
var _router = new Router(...);

What is _router? Is it the function router(req, res, next)? If yes, can I call _router(req, res, next);?
If I am wrong, could someone please explain what does the code do?
If yes, why don't they just do it like:
var proto = module.exports = function(options) {
options = options || {};

var router = {};

// mixin Router class functions
router.__proto__ = proto;

router.params = {};
router._params = [];
router.caseSensitive = options.caseSensitive;
router.strict = options.strict;
router.stack = [];

return router;
};

A: For your first question:
var Router = require('./router');
var _router = new Router(...);

var Router is a object of created by the function router(req, res, next), and your var router is a new object of Router. In javascript almost everything is an object. You can read more here.
If they use your aproach they won't have a constructor. And they use the constructor to do router.handle(req, res, next); I don't know why they need the handle, you can study more the code or ask the developers. But you probably can use the var router new Router(req,res,next); if you know what the params do.


text:
Q: Translating column values in a view control I have an application that uses a classic frontend for the Notes users and now has a XPages frontend for web users.
I've used the Localization feature for making the application multilangual. But this doesn't help me on translating column values in a view.
I've come up with a solution via text files which works well in non-categorized views.
I've created a text file for each supported language and linked them as a bundle ressource to the XPages. In the view column I used this code :
var cat = @ReplaceSubstring(rowData.getColumnValue("Category")," ","");
var catStr = String(cat);
return categories[catStr];

If I use the same method in a categorized column, I get an error :

Error while executing JavaScript computed expression
  Script interpreter error, row=1, column=5: unknown element '' in Java-class 'java.util.PropertyResourceBundle'

Does anyone know what this means ? Or are there better solutions for getting a view columns value localized ?

A: Interesting approach. Since you categorize in a single language this will determine your sort order. How do users react when they see:
blue, yellow, green, red, black

instead of
black, blue, green, red, yellow

since your categories in the view would be
blau, gelb, gruen, rot, schwarz

Content internationalization is a tricky topic.

A: You could do the translation in an xe:objectData control and return the objects for a datatable as a sorted list


text:
Q: Understanding notation for holomorphic quadratic differentials I've found the notation in books to be a bit confusing (perhaps my background is inadequate).
For example, in Farb and Margalit's book A Primer on Mapping Class Groups, they give the following definition:
Definition
"Let $\{ z_\alpha: U_\alpha \to \mathbb{C} \}$ be an atlas for $X$ [Here $X$ is a Riemann surface]. A holomorphic quadratic differential $q$ on $X$ is specified by a collection of expressions $\{ \phi_\alpha (z_\alpha) dz_\alpha^2 \}$ with the following properties:
1. Each $\phi_\alpha : z_\alpha(U_\alpha) \to \mathbb{C}$ is a holomorphic function with a finite number of zeros.
2. For any two coordinate charts $z_\alpha$ and $z_\beta$, we have
$$ \phi_\beta(z_\beta)( \frac{dz_\beta}{dz_\alpha})^2 = \phi_\alpha(z_\alpha) $$
"
Here $\frac{dz_\beta}{dz_\alpha}$ is the derivative of the change of coordinates  $z_\beta \circ z_\alpha^{-1}$.
So, my problem comes when I try to check that this definition is independent of the coordinate system that you choose.
Say that you have $z_\alpha: U_\alpha \to \mathbb{C}, z_\beta: U_\beta \to \mathbb{C}$, $w \in U_\alpha \cap U_{\beta}$ and a vector $v \in T_wX$. Then, I would like to use property number 2 to check that $q(v)$ is well defined, i.e. that
$$ \phi_\alpha \circ z_\alpha(w)  dz_\alpha^2(v) = \phi_\beta \circ z_\beta(w)  dz_\beta^2(v) $$
I'm confused about what exactly $dz_\alpha(v)$ and $dz_\beta(v)$ are. Is it the case that $dz_\alpha = z_\alpha^*(dz)$?
I thought that could be it, but then I get $dz_\alpha(v) = dz(d_w z_\alpha(v)) $, and I don't really get anywhere. I would like to do this in a rigorous way, not just formally manipulating $dz_\alpha$ and $dz_\beta$ ("multiplying" by $dz_\alpha^2$ in property number 2 would give me what I want, but I would like to understand what I'm doing).

A: Since your confusion is on the definition of $dz_\alpha$ I will recall how we define a one-form on a Riemann surface.
Each $z_\alpha$ is a coordinate chosen for the open subset $V_\alpha = z_\alpha(U_\alpha) \subset \mathbb{C}$. Note that the map $z_\alpha\colon U_\alpha \rightarrow V_\alpha$ is a priori just a homeomorphism, it does not make sense (a priori) to talk about its derivative. We just have that the maps
$$
z_\beta\circ z_\alpha^{-1}\colon V_\alpha\cap V_\beta \rightarrow V_\alpha\cap V_\beta
$$
are biholomorphisms.
Now recall that if we have to coordinates $z,w$ on a open subset of $\mathbb{C}$ we may write a one form $\omega$ in the two coordinates and their expressions must agree
$$
f(z)dz = \omega = g(w)dw
$$
This means that if $w=T(z)$ for some biholomorphism $T$ we may have $T^\ast g(w)dw = f(z)dz$ i.e. $$g(T(z))T'(z) = f(z). \tag{1}$$
To define a one-form on a Riemann surface is to give a one form $\omega_\alpha$ on $V_\alpha$, for each $\alpha$  and impose that these forms agree on $V_\alpha \cap V_\beta \neq \emptyset$. Now if $\omega_\alpha = \phi_\alpha dz_\alpha$ we may use the previous remark to see that
$$
 \phi_\alpha dz_\alpha = (z_\beta\circ z_\alpha^{-1})^\ast \phi_\beta dz_\beta
$$
hence
$$\phi_\beta \circ (z_\beta\circ z_\alpha^{-1}) \left( \frac{d(z_\beta\circ z_\alpha^{-1})}{dz_\alpha}\right) = \phi_\alpha.$$
Moreover we can compose with $z_\alpha$ to get
$$\phi_\beta \circ z_\beta \left( \frac{d(z_\beta\circ z_\alpha^{-1})}{dz_\alpha}\right)\circ z_\alpha = \phi_\alpha\circ z_\alpha.$$
(It is just the equation $(1)$ with $z_\alpha = z$, $z_\beta = w$ and $z_\beta\circ z_\alpha^{-1} = T$).
Now you can define quadratic differentials forms in the same way.
After all we can write heuristically $dz_\alpha = z_\alpha^\ast dz$ where $z$ is a fixed coordinate on $\mathbb{C}$ and do the computations. This does not make sense a priori but may be defined after a map of Riemann surfaces is defined properly.


text:
Q: (A <-> B) -> A = B? Suppose I define this set.
Inductive Set_1 : Set :=
  | Constr_1 : Set_1
  | Constr_2 : Set_1.

Is it possible to prove this statement?
(Constr_1 = Constr_2) = False

If so, what tactics do I use? This might be useful for autorewrite.

A: (A <-> B) -> A = B is called propositional extensionality and is implied by classical logic.
But you don't need it for using equivalences with autorewrite, just Require Import Coq.Setoids.Setoid.


text:
Q: Using a foreach loop to change values in a 2D array I have encountered an interesting quark in Java.
This code segment will execute as expected (change all values inside the array to 0):
int[][] test = {{4, 2, 6}, { 7, 4, 10 }, { 3, 4, 1 } };
for (int[] current : test) {
    current[0] = 0;
    current[1] = 0;
    current[2] = 0;
}

However this will not:
int[][] test = {{4, 2, 6}, { 7, 4, 10 }, { 3, 4, 1 } };
for (int[] current : test) {
    for (int num : current) {
        num = 0;
    }
}

Any help is appreciated. Thanks in advance.
EDIT:
To clarify, I understand why the second code segment does not work. I'm wondering why the first segment works. Thanks. I am not looking for "this will work" responses, I want to know what distinguishes the first segment from the second.

A: You are making your change to a local variable only. It does not impact the array you are traversing.
for-each loop is just a synthetic sugar for loop with iterator.

A: for(Iterator<Integer> num = current.iterator(); num.hasNext(); ) {
    num = 0;
}

This is what happens when foreach is expanded. What you have to understand is that in your first snippet, the Iterator iterates over a single-dimensional array named "current", which is passed by reference. So any changes in current will reflected on  "temp". However, ints are passed by value, and that is the reason why in your second snippet, the changes made in "num" are not reflected in "current". So you are simply changing the value of some other variable not related to your original array. Try printing the following for better understanding.
    int[][] test1 = {{4, 2, 6}, { 7, 4, 10 }, { 3, 4, 1 } };
    for (int[] current : test1) {
        for (int num : current) {
            System.out.println(num);
            num = 0;
        }
    }

A: There's a library method Arrays.fill to set the same value for single-dimensional array. Use it, this way your code will be clean and fast.
int[][] test = {{4, 2, 6}, { 7, 4, 10 }, { 3, 4, 1 } };
for (int[] current : test)
    Arrays.fill(current, 0);

A: This will work:
int[][] test = {{4, 2, 6}, { 7, 4, 10 }, { 3, 4, 1 } };
for (int[] current : test)
    for (int i = 0; i < current.length; i++)
        current[i] = 0;


text:
Q: How to convert binary to decimal using BigInteger? I am trying to print decimal number from binary number using BigInteger class.
I am using BigInteger(String val, int radix) constructor of BigInteger class to convert given binary value to decimal but it is printing the exact binary value which is passed in constructor.Waht is the error?
The code is as follows:
System.out.print("Ente the decimal number:");
s=String.valueOf(sc.nextInt());

BigInteger i=new BigInteger(s,10);
System.out.println(i);

A: Actually you are not printing the decimal value of binary number
The value which is printed is the exact decimal representation of String val
According to radix that you put in this statement it will act like this :
 BigInteger i = new BigInteger("11101", 10); // 11101

11101 this output is actually decimal number not a binary number
In order to get the expected result you should change radix value to 2 after that it will print the decimal value of the binary number:
BigInteger i = new BigInteger("11101", 2);
System.out.println(i);

Output:
29

A: If you are trying to parse the input String as a binary, you should write:
BigInteger i=new BigInteger(s,2);

When you print it
System.out.println(i);

it will be displayed in decimal by default.
It doesn't make sense, however, to read the number as int and then convert to String and pass to BigInteger constructor, since that limits the range of numbers that would work.
try:
s = sc.nextLine();
BigInteger i=new BigInteger(s,2);
System.out.println(i);

A: To parse the input in binary, use Scanner.nextBigInteger() with a radix of 2:
System.out.print("Enter the decimal number:");
BigInteger i = sc.nextBigInteger(2);
System.out.println(i);

The output will be in decimal by default.


text:
Q: Factorial of a given number using sequential program I am new to this python coding.So,please can someone find what is the problem with this code.
def factorial(n):
    sum=1
    for i in range(1..n+1):
        sum=sum*i
    print(sum)
    return sum

v=int(input("enter the number:"))
factorial(v)

the error i get:
enter the number:4
Traceback (most recent call last):
File "C:/Users/Ramakrishnar/AppData/Local/Programs/Python/Python36/fact.py",line 9, in <module>
 factorial(v)
  File "C:/Users/Ramakrishnar/AppData/Local/Programs/Python/Python36/fact.py", line 3, in factorial
for i in range(1..n+1):
AttributeError: 'float' object has no attribute 'n'

A: There are two ways you can write your program. To reformat your code so that it is in good form, you might organize your program like so:
def main():
    variable = int(input('Enter the number: '))
    print(factorial(variable))

def factorial(number):
    total = 1
    for integer in range(1, number + 1):
        total *= integer
    return total

if __name__ == '__main__':
    main()

If instead you are trying to accomplish the same thing using the least amount of code, the following two lines will do the exact same thing for you:
import math
print(math.factorial(int(input('Enter the number: '))))


text:
Q: How to implement 24bit to 3bit ordered dither algorithm? I am attempting to implement a Bayer ordered dithering matrix algorithm to convert a 24bit color image to a 3bit image. I have read the Wikipedia page, and several textbook sections on the topic and am a bit confused. This is what I have so far:
for (int y = 0; x < image.Height; y++)
{
    for (int x = 0; x < image.Width; x++)
    {
        Color color = image.GetPixel(x,y);
        color.R = color.R + bayer4x4[x % 4, y % 4];
        color.G = color.G + bayer4x4[x % 4, y % 4];
        color.B = color.B + bayer4x4[x % 4, y % 4];
        image[x][y] = SetPixel(x, y, GetClosestColor(color, bitdepth);
    }
}

However, I do not have a way of implementing GetClosestColor... how can I do this?
Also, I do not have the bayer4x4 matrix defined, I believe it should look like the following:
1,  9,  3, 11
13, 5, 15, 7
4, 12,  2, 10
16, 8, 14, 6

A: Here is my implementation of Bayer 4x4.
The both input and output are in 24 bit BGR format (for visualisation purposes).
In the output each pixel plane has value 0 or 255.
const   int BAYER_PATTERN_4X4[4][4]     =   {   //  4x4 Bayer Dithering Matrix. Color levels: 17
                                                {    15, 195,  60, 240  },
                                                {   135,  75, 180, 120  },
                                                {    45, 225,  30, 210  },
                                                {   165, 105, 150,  90  }

                                            };

void    makeColorDitherBayer4x4( BYTE* pixels, int width, int height )  noexcept
{
    int col = 0;
    int row = 0;

    for( int y = 0; y < height; y++ )
    {
        row = y & 3;    //  % 4

        for( int x = 0; x < width; x++ )
        {
            col = x & 3;    //  % 4

            const pixel blue    = pixels[x * 3 + 0];
            const pixel green   = pixels[x * 3 + 1];
            const pixel red     = pixels[x * 3 + 2];

            pixels[x * 3 + 0]   = (blue  < BAYER_PATTERN_4X4[col][row] ? 0 : 255);
            pixels[x * 3 + 1]   = (green < BAYER_PATTERN_4X4[col][row] ? 0 : 255);
            pixels[x * 3 + 2]   = (red   < BAYER_PATTERN_4X4[col][row] ? 0 : 255);

        }

        pixels  += width * 3;
    }
}

If you want to get the output as "compressed" data, you should replace this part of code:
pixels[x * 3 + 0]   = (blue  < BAYER_PATTERN_4X4[col][row] ? 0 : 255);
pixels[x * 3 + 1]   = (green < BAYER_PATTERN_4X4[col][row] ? 0 : 255);
pixels[x * 3 + 2]   = (red   < BAYER_PATTERN_4X4[col][row] ? 0 : 255);

with something like this:
output.writeBit( (blue  < BAYER_PATTERN_4X4[col][row] ? 0 : 1) );
output.writeBit( (green < BAYER_PATTERN_4X4[col][row] ? 0 : 1) );
output.writeBit( (red   < BAYER_PATTERN_4X4[col][row] ? 0 : 1) );


text:
Q: Get data from 3 tables and display mysql php I have 3 tables in the same mysql db
email

id      |   emailAddresses
--------+--------------
91      |    Cras@Cumsociisnatoque.net
92      |    ante.dictum.mi@sollicitudinadipiscingligula.co.uk
93      |    Nunc.sed@pretiumet.ca
94      |    Nunc.mauris@lacusQuisque.org"
95      |    ccumsan.interdum@tellus.ca
96      |    isl@Sedpharetrafelis.com
97      |    u.accumsan.sed@Nuncsollicitudin.net
98      |    at@eleifendvitaeerat.co.uk
99      |    pede.ac.urna@pharetraQuisque.co.uk
100     |    ccumsan.laoreet.ipsum@arcueu.co.uk

groups

id      |   groupName
--------+----------
10      |    Group1
11      |    Group2
12      |    Group3
13      |    Group4

emailGroupsMatches

id      |   emailGroup_id   |   email_id
--------+-------------------|------------
400     |    10             |      91
411     |    11             |      91
412     |    12             |      93
413     |    13             |      94
414     |    10             |      95
415     |    10             |      96

I am trying to pull the group names and then check for all emails associated with that group and display them under the group heading.
Group1:
Cras@Cumsociisnatoque.net
ccumsan.interdum@tellus.ca
isl@Sedpharetrafelis.com

Group2:
Cras@Cumsociisnatoque.net

Group3:
Nunc.sed@pretiumet.ca

Group4:
Nunc.mauris@lacusQuisque.org

I think i may be overthinking this or it may be something i'm unfamiliar with.  I have tried Joining tables but i may have done it wrong.  Any help in a direction would be appreciated.
Thanks
UPDATE__________
I have tried getting two arrays and then trying to join them.  Its close but i keep having an issue.
        $emailArray1[] = '';
        $emailArray2[] = '';
         $stmt1 = $this->db->query("SELECT emailGroupsMatches.emailGroup_id, emailGroupsMatches.email_id, emailGroups.groupName FROM emailGroups,emailGroupsMatches WHERE emailGroupsMatches.emailGroup_id = emailGroups.id");
        while ($row1 = $stmt1->fetch()) {
            $emailArray1[] = $row1;

            $emailGroup_id[] = $row1['emailGroup_id'];
            $email_id[] = $row1['email_id'];
            $groupName[] = $row1['groupName'];

            $data1[] = array(
            "emailGroup_id" => $emailGroup_id,
            "email_id" => $email_id,
            "groupName" => $groupName
            );
            echo '<pre>';
            print_r($data1);

        }
        $stmt2 = $this->db->query("SELECT * FROM email,emailGroupsMatches WHERE emailGroupsMatches.email_id = email.id");
        while ($row2 = $stmt2->fetch()) {
            $emailArray2[] = $row2;

            $emailGroup_id2[] = $row2['emailGroup_id'];
            $emailAddresses[] = $row2['emailAddresses'];

            $data2[] = array(
            "emailGroup_id" => $emailGroup_id2,
            "emailAddresses" => $emailAddresses
            );

            //echo '<pre>';
            //print_r($data2);

        }

        //$c = array_combine($emailArray1, $emailArray2);

        //print_r($c);

        $result = array();

            foreach ($data1 as $value) {
                // do not handle elements without pageclass
                if (!array_key_exists('emailGroup_id', $value) || !$value['emailGroup_id']) {
                    continue;
                }
                $result[$value['emailGroup_id']] = $value;
            }
            foreach ($data2 as $value) {
                if (
                    // do not handle elements without pageclass
                    !array_key_exists('emailGroup_id', $value) || !$value['emailGroup_id'] ||
                    // do not handle elements that do not exist in array 1
                    !array_key_exists($value['emailGroup_id'], $result)
                    ) {
                    continue;
                }
                // merge values of this pageclass
                $result[$value['emailGroup_id']] = array_merge($result[$value['emailGroup_id']], $value);
            }
            echo '<pre>';
            print_r($result);

returns
Array

(
    [0] => Array
        (
            [emailGroup_id] => Array
                (
                    [0] => 11
                )
        [emailAddresses] => Array
            (
                [0] => xdbxxvfshddghd@llsfg.com
            )

    )

[1] => Array
    (
        [emailGroup_id] => Array
            (
                [0] => 11
                [1] => 11
            )

        [emailAddresses] => Array
            (
                [0] => xdbxxvfshddghd@llsfg.com
                [1] => cyeyeyddbd@gmadbdbxbil.com
            )

    )

[2] => Array
    (
        [emailGroup_id] => Array
            (
                [0] => 11
                [1] => 11
                [2] => 12
            )

        [emailAddresses] => Array
            (
                [0] => xdbxxvfshddghd@llsfg.com
                [1] => cyeyeyddbd@gmadbdbxbil.com
                [2] => luctus.et.ultrices@Vivamus.net
            )

    )

[3] => Array
    (
        [emailGroup_id] => Array
            (
                [0] => 11
                [1] => 11
                [2] => 12
                [3] => 12
            )

        [emailAddresses] => Array
            (
                [0] => xdbxxvfshddghd@llsfg.com
                [1] => cyeyeyddbd@gmadbdbxbil.com
                [2] => luctus.et.ultrices@Vivamus.net
                [3] => quis@fringillaporttitor.co.uk
            )

    )

[4] => Array
    (
        [emailGroup_id] => Array
            (
                [0] => 11
                [1] => 11
                [2] => 12
                [3] => 12
                [4] => 10
            )

        [emailAddresses] => Array
            (
                [0] => xdbxxvfshddghd@llsfg.com
                [1] => cyeyeyddbd@gmadbdbxbil.com
                [2] => luctus.et.ultrices@Vivamus.net
                [3] => quis@fringillaporttitor.co.uk
                [4] => arcu.Sed.eu@accumsan.org
            )

    )

[5] => Array
    (
        [emailGroup_id] => Array
            (
                [0] => 11
                [1] => 11
                [2] => 12
                [3] => 12
                [4] => 10
                [5] => 10
            )

        [emailAddresses] => Array
            (
                [0] => xdbxxvfshddghd@llsfg.com
                [1] => cyeyeyddbd@gmadbdbxbil.com
                [2] => luctus.et.ultrices@Vivamus.net
                [3] => quis@fringillaporttitor.co.uk
                [4] => arcu.Sed.eu@accumsan.org
                [5] => Ut@luctuslobortisClass.com
            )

    )

[6] => Array
    (
        [emailGroup_id] => Array
            (
                [0] => 11
                [1] => 11
                [2] => 12
                [3] => 12
                [4] => 10
                [5] => 10
                [6] => 13
            )

        [emailAddresses] => Array
            (
                [0] => xdbxxvfshddghd@llsfg.com
                [1] => cyeyeyddbd@gmadbdbxbil.com
                [2] => luctus.et.ultrices@Vivamus.net
                [3] => quis@fringillaporttitor.co.uk
                [4] => arcu.Sed.eu@accumsan.org
                [5] => Ut@luctuslobortisClass.com
                [6] => aliquet@ProindolorNulla.co.uk
            )

    )

[7] => Array
    (
        [emailGroup_id] => Array
            (
                [0] => 11
                [1] => 11
                [2] => 12
                [3] => 12
                [4] => 10
                [5] => 10
                [6] => 13
                [7] => 13
            )

        [emailAddresses] => Array
            (
                [0] => xdbxxvfshddghd@llsfg.com
                [1] => cyeyeyddbd@gmadbdbxbil.com
                [2] => luctus.et.ultrices@Vivamus.net
                [3] => quis@fringillaporttitor.co.uk
                [4] => arcu.Sed.eu@accumsan.org
                [5] => Ut@luctuslobortisClass.com
                [6] => aliquet@ProindolorNulla.co.uk
                [7] => hendrerit.a.arcu@sedlibero.com
            )

    )

)

A: Below query will return you the groupName and comma separated list of associated emailAddresses. So you can display group name and to display associated email just loop the emailAddresses list. Hope this will help you!
SELECT groups.groupName as groupName, GROUP_CONCAT(email.emailAddresses) as emails
FROM email
INNER JOIN emailGroupsMatchesON emailGroupsMatches.email_id = email.id
INNER JOIN groups ON emailGroupsMatches.emailGroup_id = groups.id
GROUP BY groups.id


text:
Q: catfish indexer results via pipe or STDOUT? Is it possible to use catfish indexer via command line to make use of its results in conjunction with other programs or in a script?
e.g.
catfish --filename='john' --contents=='yoga' | grep -v bak

?

A: Not really, no. catfish is just a graphical front end to other programs:
DESCRIPTION
   catfish  is gtk2 python application that provides a graphical front-end
   to the  many  different  search  back-ends  such  as  locate,  slocate,
   tracker, beagle, strigi, pinoti, and find.

All it does is run other search tools and present their results in a graphical format. There's no point in having an option to print results to standard output in graphical frontend.
The best you can do is use one of the commands that catfish depends on and parse that. For example, with locate:
locate -b0 john |
 xargs -0I{} bash -c 'grep yoga >/dev/null 2>&1 "{}" && echo "{}"'


text:
Q: Spring Boot Port Issues I have created a single web page application using Spring boot and i have configured the port number in application.properties file.
server.port=9991
When I right click my project and click as Spring Boot App it runs fine and when i run it for the second time its throwing that port is already in use.
I am using Spring Tool Suite.
Please let me know why I am getting error.
Error Message:
Description:
The Tomcat connector configured to listen on port 9991 failed to start. The port may already be in use or the connector may be misconfigured.
Action:
Verify the connector's configuration, identify and stop any process that's listening on port 9991, or configure this application to listen on another port.

A: The first application you started was  probably still running when you started oh the second time. Kill the process manually. Look for java processes and kill them.

A: If I am not mistaken, you can just configure port 0 for your application to let the OS pick a port for you. So you could have multiple instances running on the same box at the same time. Porbably you will encounter more conflicting ports for management etcetera.

A: I think you are using eclipse IDE. when you run first time your program it will take your current port number. I think you are running your application without stop your old process. simply way in eclipse, there is your application running log. there is cross btn or red square btn  click that btn and re run that.


text:
Q: Deploy Angular SSR project to cpanel (GoDaddy server) I've done an Angular 8 project on my localhost following this link:
Server Side rendering with Angular universal 8
This command builds and generates files in both browser and server, and the project runs on http://localhost:4200
npm run build:ssr && npm run serve:ssr
Is it possible to run deploy this project on cpanel (with SSR enabled)?
I've deployed normal Angular projects on cpanel in the past by copy pasting the content of dist folder.
Just wanna know if it's possible to do the same for SSR, with no Node.js installed on my godaddy server.
Any help would be appreciated.
Thanks.

A: Based on the information provided by angular itself here, you can not run SSR (server-side rendering) without nodejs being enabled in your cPanel account or any web server that can interact with renderModule() which nodejs seemed to be perfect on. However, you can easily install nodejs on your cPanel by following this guide provided by cPanel: https://docs.cpanel.net/knowledge-base/web-services/how-to-install-a-node.js-application/ though, you will need SSH access to your server. You can contact your hosting provider if you don't know your SSH details.


text:
Q: Small Swap Size in SSD Notebook I have read a lot of questions and answers about swap size but I am still quite confused. I have also read this article, which suggests swap size of half to two times of RAM, depending on low/high RAM and low/high disk space.
https://help.ubuntu.com/community/SwapFaq
My question is: I am going to buy an SSD notebook with 4GB RAM, what will be the consequences if I set the swap size to be 1GB or even 512MB only? (And can I have no swap at all...?)
I do not use hibernation and I do not use software that consumes a lot of RAM. The usual activities are: listening to music, surf Internet, BT, browsing photos (not edit), converting video etc.
Thank you.

A: If you do not use RAM intensive software (Video/Photo Editing) you should be fine with 4GB of RAM and no swap. I have 3GB and my swap rarely uses over a 20~30kb. If you're just looking for quickly browsing the internet you should be fine with nothing.
However, i personally would recommend having at least 1GB of swap, just in case, and, as you said, you might end up with no option to hibernate.
One thing, video converting, how large? What programme? Some will expect a considerable amount stored in the RAM.

A: No consequences, you will be fine. It's only a problem if your system needs more memory than RAM + swap size.

A: My laptop has 3GB of RAM, but 1 is cached for graphics only, so actually system may only use 2GB, and common usage has never reached over 1.5GB. If you don't need hibernation, common user is more than well with 3GB RAM.


text:
Q: Add keywords at the bottom of a document I want to use \documentclass[12pt,a4paper]{article} in the place of \documentclass[12pt,reqno]{amsart}. However I want to add the following in the bottom of the first page

This is my codes
\documentclass[12pt,a4paper]{report}

 \usepackage{geometry}
 \geometry{left=3cm,right=2cm,top=2.5cm,bottom=2cm}
 \usepackage{setspace}
 \onehalfspacing

\begin{document}

\footnte{2010 Mathematics Subject Classification. Primary ..; Secondary ...}
\end{document}

A: Without using a package:
\documentclass[12pt,a4paper]{report}

 \usepackage{geometry}
 \geometry{left=3cm,right=2cm,top=2.5cm,bottom=2cm}
 \usepackage{setspace}
 \onehalfspacing

% -------------
\makeatletter
\def\keywords{\xdef\@thefnmark{}\@footnotetext}
\makeatother

\begin{document}
    Hello world.%
    \keywords{2010 \emph{Mathematics Subject Classification.} Primary ..; Secondary \dots}%
    \keywords{\emph{Key words and phrases.} Positive Operator \dots}%
    \footnote{Normal footnote}
    Some text here.
\end{document}

A: With the titlefoot package:
\documentclass[12pt,a4paper]{report}

 \usepackage{geometry}
 \geometry{left=3cm,right=2cm,top=2.5cm,bottom=2cm}
 \usepackage{setspace}
 \onehalfspacing

 \usepackage{titlefoot}

\begin{document}

\unmarkedfntext{2010 Mathematics Subject Classification. Primary ..; Secondary ...\newline\hspace*{2em}Keywords:}
\end{document}


text:
Q: Replacing multiple characters in a string I have a csv file that looks like this:
Mon-000101,100.27242,9.608597,11.082,10.034,0.39,I,0.39,I,31.1,31.1,,double with 1355,,,,,,,,
Mon-000171,100.2923,9.52286,14.834,14.385,0.45,I,0.45,I,33.7,33.7,,,,,,,,,,
Mon-000174,100.27621,9.563802,11.605,10.134,0.95,I,1.29,I,30.8,30.8,,,,,,,,,,

...it's a few hundred lines long.
I just want to grab the Mon-000101 (not just that specific one, but all the Mon-######) items. I have this really really ugly little script I threw together:
file_list1 = open(raw_input("Enter your list file: "))
file_lines = []
for line in file_list1:
    line.replace(' ','\n')
    for item in line.split('\n'):
        file_lines.append(item)
stringit = ''
for item in file_lines:
    stringit += item

IDs = re.findall('Mon-\d\d\d\d\d\d',stringit)
stringIDs = str(IDs)
new = stringIDs.replace(',','\n')

newer = new.replace('\'','')
newer2 = newer.replace('[\]','')
newer3 = newer2.replace(']','')
newer4 = newer3.replace('[','')
newer5 = newer4.replace(' ','')
file_write = open("Testit.txt","w+")
file_write.write(newer4)
print newer4
file_write.close()

I know it's ugly. Clearly I don't know what I'm doing with the regex stuff, but aside from that I want to know a more efficient way of replacing all the characters that I'm replacing. I know this isn't how it's done. I've tried something along the lines of
newer2 = newer.replace('([\',\[\] ])','')

which I sorta pieced together from various posts. That didn't work though, in fact it didn't do anything.
I want to see what a more efficient way of doing this looks like.
Thanks.
I'm also aware that my variable naming is not sufficient/not up to the style guide. This is just something I quickly threw together.

A: Assuming the IDs are always the first part of the line, this is a simple way to do it:
import csv
with open('some_list_file.txt', 'rb') as list_file:
    reader = csv.reader(some_list_file)
    with open('Testit.txt', 'W+') as output_file:
        output_file.writelines(line[0] + '\n' for line in reader)

If the position varies, it gets just a little more complicated:
import csv
with open('some_list_file.txt', 'rb') as list_file:
    reader = csv.reader(some_list_file)
    with open('Testit.txt', 'W+') as output_file:
        for line in reader:
            IDs = [part for part in line if part.startswith('Mon-')]
            if IDs:
                output_file.write(IDs[0] + '\n') # or accept multiple ID values if that's a possibilty

You can shorten that a little if you're sure there's a Mon- entry in every line:
    with open('Testit.txt', 'W+') as output_file:
        output_file.writelines([part for part in line if part.startswith('Mon-')][0] + '\n' for line in reader])

A: Use regex pattern ^Mon\-\d{6} with m modifier.


text:
Q: Which signal is related to leaving a widget? I code PyQt, I have the following code:
QtCore.QObject.connect(self.checkBox, \
QtCore.SIGNAL(_fromUtf8("clicked(bool)")), lambda: \
self.interfaceCodesConstructor.setFilterList(self,"name",self.lineEdit.text()))

Abobe code causes When i click on checkbox, my function : setFilterList
will be run.
i need to run above function:
setFilterList(self,"name",self.lineEdit.text()) When i leave a
LineEdit widge, But i don't know its signal.
My question is : What's its signal when you leave a widget such as
LineEdit?
Yours,
Mohsen

A: According to the documentation QlineEdit will emit
void QLineEdit::editingFinished () [signal] when the line edit widget loses focus.


text:
Q: How to create a VM that mirrors the RoR production version I am working on an open source project and there is an issue where an upload error only seems to occur on the production side that is running apache and unicorn.
Due to privacy issues and risks, I am unable to mess around in the actual production side (such as creating a temp id for myself with various privileges.
Is there anyway that I can quickly create a VM with such setup in my own computer that would mirror the live site?
The site is running in RoR 4, latest unicorn, and latest stable version of apache.

A: There are a couple of ways you can be able to accomplish this. You can use vagrant and also with the rising popularity of Docker containers, you can easily model production environment on your computer. Since you indicated a faster way to get the VM up and running, I would recommend using railsbox.io. Its amazing and it saves you a lot of time. According to their webiste -

Fast and easy Ruby on Rails virtual machines. Streamline your
  development workflow in no time by creating production-like virtual
  machine with your development environment. Try this extremely simple
  to use VM configuration tool to create new Ruby on Rails server using
  vagrant and ansible.

The app helps you setup a VM with ease.


text:
Q: How to create an uint256 in PostgreSQL How can I create an uint256 data type in Postgres? It looks like they only support up to 8 bytes for integers natively..
They offer decimal and numeric types with user-specified precision. For my app, the values are money, so I would assume I would use numeric over decimal, or does that not matter?
NUMERIC(precision, scale)
So would I use NUMERIC(78, 0)? (2^256 is 78 digits) Or do I need to do NUMERIC(155, 0) and force it to always be >= 0 (2^512, 155 digits, with the extra bit representing the sign)? OR should I be using decimal?

A: You can create a domain.
CREATE DOMAIN uint_256 AS NUMERIC NOT NULL
CHECK (VALUE >= 0 AND VALUE < 2^256)
CHECK (SCALE(VALUE) = 0)

This creates a reusable uint_256 datatype which is constrained to be within the 2^256 limit and also prevents rounding errors by only allowing the scale of the number to be 0 (i.e. throws an error with decimal values). There is nothing like NULL in Solidity so the datatype should not be nullable.
Try it: dbfiddle

A: numeric(78,0) has a max value of 9.999... * 10^77 > 2^256 so that is sufficient.


text:
Q: SQL, Trying to get opposite result So, I was trying to select data but all I can get is opposite of results that I need.
SELECT DISTINCT
  LAND_USE_EVW.OBJECTID
FROM LAND_USE_EVW,
     MUNICIPALITIES_EVW
WHERE LAND_USE_EVW.Shape.STBoundary().STWithin(MUNICIPALITIES_EVW.Shape) = 1

When I change 1 to 0 it's not working (selecting all rows)
What could I possibly do to get opposite result?


text:
Q: R: How can I code repetitive output into an Rmarkdown file? I am doing complex exploratory analysis on a data set. I have created a function that will take the desired variables, run and evaluate several models then return a list with various results and plots. I can easily run this on the different combinations of predictor and outcome variables. I would also like to create a "function" or repeatable script that will display the results in the rmarkdown output, so I don't have to edit every chunk when I want to make a change to the output. (For instance, I just added a sensitivity analysis to the function, but now I have to edit about 45 chunks to get the results to display.)
Simplified Example:
#Packages used: dplyr, knitr, kableExtra, pander

data("airquality")
lm.1 <- lm(Solar.R ~ Wind, data = airquality, na.action = na.omit)
lm.2 <- lm(Solar.R ~ Wind + Temp, data = airquality, na.action = na.omit)

#The real output list is bigger/more complex:
myList <- list(model.1 = lm.1,  model.2 = lm.2, bic = BIC(lm.1,lm.2))

#Create a character vector containing each line of display code I wish to run:

myDisplay <- c("kable('Model Comparisons', col.names = NULL) %>%
                  kable_styling(bootstrap_options = 'striped', font_size = 20)",
               "pander(myList$bic)",
               "kable('Full Model Summary', col.names = NULL) %>%
                  kable_styling(bootstrap_options = 'striped', font_size = 20)",
               "pander(myList$model.2)")

For each analysis output list I create, I want to run what is in myDisplay. So in the following chunks, I tried:
{r, eval = T, results = 'asis'} #I tried with and without "asis"
for(i in myDisplay){
  eval(parse(text = i))
}

When I run that for loop in the console, I get the expected outputs, but when I knit my rmarkdown file, I literally get nothing from it. No warnings, messages, errors, or anything at all.
Is there a way to do this? Does it have to do with eval(parse(text = .))? Is there something else to try?
Post Script:
@Aaron Montgomery's suggestion to add cat(eval(parse(text=i))) worked. There was one small problem with my real code. One of the list items was a plot returned by ggplot(). cat() could not handle that request. That's okay as it is easy to workaround.
My code chunks for each analysis now look something like this:
{r, results = 'asis'}
myList <- myFunction(X,Y,Z)
myList$plot
for(i in myDisplay){
  cat(eval(parse(text = i)))
}

Now I only have to edit myFunction and myDisplay to change the entire document.

A: Try wrapping your eval in cat() (concatenate and print) to coax R to write something down:
{r, eval = T, results = 'asis'} #I tried with and without "asis"
for(i in myDisplay){
  cat(eval(parse(text = i)))
}


text:
Q: Implementing countries to spinner in activity I am trying to implement: https://github.com/hbb20/CountryCodePickerProject to my project to show a list of all countries in a spinner.
I added code to my build.gradle (app):
implementation 'com.hbb20:ccp:2.3.4'

After that I added it to XML file (layout) as it state on https://github.com/hbb20/CountryCodePickerProject/wiki/Use-as-a-Country-Selector:
<com.hbb20.CountryCodePicker
        android:id="@+id/country"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="28dp"
        app:ccp_showFullName="true"
        app:ccp_showNameCode="false"
        app:ccp_showPhoneCode="false"
        app:layout_constraintTop_toTopOf="parent"
        tools:layout_editor_absoluteX="0dp" />

When I run my application it looks like:

But when I click on the spinner to select country application crash and in Logcat I get an error:
2019-12-27 14:47:00.619 13536-13536/? E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.cryptowallet, PID: 13536
    android.view.InflateException: Binary XML file line #78: Binary XML file line #78: Error inflating class com.futuremind.recyclerviewfastscroll.FastScroller
    Caused by: android.view.InflateException: Binary XML file line #78: Error inflating class com.futuremind.recyclerviewfastscroll.FastScroller
    Caused by: java.lang.reflect.InvocationTargetException

A: Add below 2 lines in gradle.properties file.
android.useAndroidX=true
android.enableJetifier=true


text: Q: jQuery incrementally count selected checkbox and deselected checkbox I have an ASP.NET web form that has 6 checkbox. 1 checkbox is to call a Function to select all checkbox and show the message "You have selected" 6 "items" (in this case, 6 checkbox). If a user doesn't select the Select All checkbox, they can select or deselect other checkbox individually and the message will be "You have selected" # "items" I'm trying to do this in jQuery, but it's not working yet. Here's the script:


text:
Q: Check if all items of a list are string of integers I have a dataframe with questions and answers:
,Unnamed: 0,Unnamed: 0.1,Unnamed: 0.1.1,URL,QID,Questions,Answers,QType
0,0,0,1,When do you think your next vacation can start?,"['In next 3 months', 'In next 6 months', 'In next 1 year', 'Only once COVID-19 is under control', 'Only once COVID-19 vaccine is developed']",
1,1,1,2,What are your preferences regarding medical treatment policy (with additional cost)?,"[""Doctor's availability in hotel"", 'Ventilator availability in hotel', 'Tie-ups with nearby hospitals', 'Availability of medical rooms with primary first aid care']",
2,2,2,3,Preferences of complementary breakfast?,"['Buffet breakfast with social distancing', 'Buffet breakfast replaced with Ala-carte with limited options', 'Breakfast to be delivered in room with limited options (chargeable)', 'Packaged breakfast only']",
3,3,3,4,What is your preference for packaged food?,"['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']",
4,4,4,5,Consumer Personality,[],

I'd like to get the types of answers in the 'QType' column. That is to say: "taste scale" or "multiple choice". Taste scale are lists of string of integers, multiple choice are all the others:
,Unnamed: 0,Unnamed: 0.1,Unnamed: 0.1.1,URL,QID,Questions,Answers,QType
0,0,0,1,When do you think your next vacation can start?,"['In next 3 months', 'In next 6 months', 'In next 1 year', 'Only once COVID-19 is under control', 'Only once COVID-19 vaccine is developed']",Multiple Choice
1,1,1,2,What are your preferences regarding medical treatment policy (with additional cost)?,"[""Doctor's availability in hotel"", 'Ventilator availability in hotel', 'Tie-ups with nearby hospitals', 'Availability of medical rooms with primary first aid care']",Multiple Choice
2,2,2,3,Preferences of complementary breakfast?,"['Buffet breakfast with social distancing', 'Buffet breakfast replaced with Ala-carte with limited options', 'Breakfast to be delivered in room with limited options (chargeable)', 'Packaged breakfast only']",Multiple Choice
3,3,3,4,What is your preference for packaged food?,"['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']",scale

For the moment, I tried the following:
>>>def classifier(l):
...     try:
...         l = ast.literal_eval(l)
...         if all(type(int(item))==int for item in l):
...             l = list(map(int, l))
...     except ValueError:
...         return None
...     j = 0
...     if not l:
...         return None
...     try:
...         if all(isinstance(x, int) for x in l):
...             print("Likert Scale")
...             return "Likert Scale"
...         else:
...             print("Mult")
...             return "Multiple Choice"
...     except:
...         print("Exception")
...         return None
... df.QType = df.apply(lambda x: classifier(df.Questions), axis = 1)

That is to say that every time there are only numbers I say that the question is a scale of numbers, otherwise, it's a multiple-choice.
But it returns None because of a ValueError for every bit.
df.QType
0       None
1       None
2       None
3       None
4       None
        ...
2953    None
2954    None
2955    None
2956    None
2957    None

A: Google Forms API
If you work with Google you can use Google Forms API for this instead of BeautifulSoup: https://developers.google.com/apps-script/reference/forms/
This service allows scripts to create, access, and modify Google Forms.
Google Sheets API
You can also export all responses in a spreadsheet and work with it with Python API. I recommend you this way, because there are more resources about this topic.
Here you find how to export responses:
https://support.google.com/docs/answer/139706?hl=en&ref_topic=6063592
and here you find Google Sheets Python API:
https://developers.google.com/sheets/api/quickstart/python
and
https://github.com/burnash/gspread


text:
Q: CSS adjacent Siblings Overwriting each other I've noticed when using ~ to select the siblings, the order that the rules occur in the stylesheet is causing them to overwrite one another.
What I would like is every .test after .ColorBlue to be blue and every .test after .ColorRed to be red.
The data is going to be pulled dynamically so the order of the colors will be constantly changing.
Additionally new data can be inserted dynamically so using jquery's "nextUntil" would be pretty impractical.
What am I doing wrong?

.ColorBlue, .ColorBlue ~ tbody.test {
    background: blue;
}
.ColorRed, .ColorRed ~ tbody.test {
    background: red;
}

            red

            test

            blue

            ≡

A: You can use the + Adjacent sibling selector to achieve this.
The ~ General sibling combinator will select all elements matching the selector, not just the first. It won't be overwritten by the subsequent rule as it is not more specific than the first rule.

.ColorBlue, .ColorBlue + tbody.test {
    background: blue;
}
.ColorRed, .ColorRed + tbody.test {
    background: red;
}

            red

            test

            blue

            ≡


text:
Q: How to switch from one control to another using the tabulator key in controlP5 from processing? I am doing a GUI on processing and using controlP5. I would like to use my keyboard to switch between controls but I failed miserably.
Another thing I would like to do is remove the cursor from the TextAreas since always is a character behind instead of beeing at the end.
Have someone a clue of how to achive that? I would be really happy if someone with bigger knowledge knows how to, I am really getting monkey!
Thanks

A: Well, I did figure it out in my own. These ControlP5 are not really intuitive controls. There is not documentation at all, and the most common features in controls like this one (usability) are not covered in the examples. A pity. Anyways, here it is:
import java.awt.event.KeyEvent;
import controlP5.*;

ControlP5 cp5;

boolean isTabPressed = false;

void keyPressed()
{
      if(keyCode== TAB){
          isTabPressed = !isTabPressed;

         if(isTabPressed){
           Textfield tf = (Textfield) cp5.getController("textValue");
           tf.setFocus(true);
           Textfield tf1 = (Textfield) cp5.getController("textValue1");
           tf1.setFocus(false);
          }else{
           Textfield tf = (Textfield) cp5.getController("textValue");
           tf.setFocus(false);
           Textfield tf1 = (Textfield) cp5.getController("textValue1");
           tf1.setFocus(true);
         }
     }

}

void setup()
{
    size(400,180);

    cp5 = new ControlP5(this);

    cp5.addTextfield("textValue")
     .setPosition(100, 30)
     .setSize(200, 20)
     .setAutoClear(false)
     ;

    cp5.addTextfield("textValue1")
     .setPosition(100, 90)
     .setSize(200, 20)
     .setAutoClear(false)
     ;

}

void draw()
{

}


text:
Q: unexpected 'static' (T_STATIC), expecting identifier (T_STRING) I try to parent a function but I get this error:
unexpected 'static' (T_STATIC), expecting identifier (T_STRING)

I have PHP v5.4.7
Here is code
public function static tableExist($table, $db)
    {
        $tables = mysql_exists($db);
            while(list($temp) = mysql_fetch_array($name, $pass))
            {
                if($temp = $table)
                {
                    return TRUE;
                }
                else
                {
                    return FALSE;
                }
            }

    }

and the usage
if(register::tableExist(users, webshop));
                {
                    echo "succes";
                }

A: try public static function tableExist
EDIT: do you have a specific line reference?


text:
Q: Laravel: PDO Class not found error During deploy laravel project on Centos, I have gotten this error.
PHP Fatal error:  Class 'PDO' not found in /var/www/html/<laravel_project_name>/config/database.php on line 16

I have enabled pdo extension with editing php.ini file.
extension=pdo.so
extension=pdo_sqlite.so
extension=pdo_mysql.so
extension=sqlite.so

And when I try to php -v, I got following error.
PHP Startup: Unable to load dynamic library '/usr/lib64/php/modules/pdo_mysql.so' - /usr/lib64/php/modules/pdo_mysql.so: undefined symbol: mysqlnd_allocator in Unknown on line 0

I have restarted httpd server after edit php.ini file.
Please help me to fix this error.
Regards.

A: The error you are getting means there is an extension=... or zend_extension=... line in your php configuration files (usually php.ini) that is trying to load that extension but it cannot load the files for it, either because it does not exist or it does not have permissions to access it.
In this case you have set all of the below in your php.ini file:
extension=pdo.so
extension=pdo_sqlite.so
extension=sqlite.so
extension=pdo_mysql.so

But have they actually been installed?
Given you are using CentOS, try run the following to install PDO:
yum install php-pdo php-mysqli
If it is already installed then please check the permissions to /usr/lib64/php/modules/pdo_mysql.so have been set appropriately.

A: Line 16 of database.php is this
'fetch' => PDO::FETCH_CLASS

This means PDO class does not exist.
You can install pdo and restart if required this way
 yum install php-pdo

 service httpd restart

That said check this link http://php.net/manual/en/pdo.installation.php
Installing PDO on Unix systems
PDO and the PDO_SQLITE driver is enabled by default as of PHP 5.1.0. You may need to enable the PDO driver for your database of choice; consult the documentation for database-specific PDO drivers to find out more about that.

To create an instance of pdo in laravel you can do this way
$pdo = DB::connection()->getPdo();


text:
Q: Symfony 2: how to read excel file content usin PHPExcel I am using PHPExcel with Symfony 2 and showing the content of an excel file like this:
    $users = array();
    foreach($excel as $i=>$row) {
    if($i !== 1) {
        array_push($users,array(
            'row'=>$i,
            'name'=>$row['A'],
            'lastname'=>$row['B']
//...and so on

        ));
    }

}

Question:
How can I show the content using the row name instead of $row['A']..ect?
As $row['name']... I mean the name of the excel row.
Example:
A = name B = email...and so on...
I would like to show the content like this:
    $users = array();
    foreach($excel as $i=>$row) {
    if($i !== 1) {
        array_push($users,array(
            'row'=>$i,
            'name'=>$row['name'],
            'lastname'=>$row['surname']
//...and so on

        ));
    }

}

A: I'm pretty sure that I answered this question barely a week ago.... assuming that row #1 contains your headers:
if($i == 1) {
    $headers = $row;
} else {
    $row = array_combine($headers, $row);
    array_push($users,array(
        'row'=>$i,
        'name'=>$row['name'],
        'lastname'=>$row['surname']
        //...and so on

    ));
}


text:
Q: Python generic buffer datatype access In Python, is there any existing library-based method to polymorphically treat a buffer as being an array of any datatype -- including bits, bytes, WORDs, DWORDs, etc. -- without copying the buffer?  I have an application where I want to be able to set arbitrary ranges of bits in a stream to any unsigned value.
For example, if the buffer in bytes is [0x01, 0x02, 0x03, 0x04, 0x05, 0x06 ...] and I want to set absolute little-endian bits 27:11 to the unsigned little-endian value 54321, then the buffer in bytes becomes [0x01, 0x8A, 0xA1, 0x06, 0x05, 0x06 ...].  The low-level details of read-modify-writing the bytes should be abstracted out.  I may then want to have a WORD (uint16) view of the data as [0x8A01, 0x06A1, 0x0605, ...] and change some of the elements that way.
Do any good public Python libraries provide this capability?

A: oh, you mean the type to be mutable?
well lists are mutable, so why not use those?
But if you really want to work with bits, here's an example
http://wiki.python.org/moin/BitArrays
It uses BitArrays - you should be able to figure out everything from the example.
[EDIT]:
for inserting bits wherever you want:
import array
a=array.array('I')
a.append(5) #adds 1 element

a.extend([2,3,3,4,5,5,4]) #adds another 7 elements

a[3:6] = [6,6,6] #replaces 3 elements with the 3 6s

is this all u need?


text:
Q: U-Substitution Inconsistencies with multiple methods
Use the substitution $u = e^x$ to evaluate the following integral.
$$\int \frac{e^x}{1-e^x} dx$$

Here's what I did:
$$u = e^x$$
$$\therefore \frac{du}{dx} = e^x$$
$$\therefore dx = \frac{1}{e^x}du = \frac{1}{u}du$$
$$\therefore \int \frac{e^x}{1-e^x} dx = \int \frac{u}{1-u} \frac{1}{u}du$$
$$= \int (1-u)^{-1} du$$
$$=\ln(|1-u|)$$
$$=\ln(|1-e^x|) + c$$
However, evaluating the original integral online gave me $$\int \frac{e^x}{1-e^x} dx = -e^x-\ln \left(\left|e^x-1\right|\right)$$
Plotting both my result and the result directly above, the two curves were not vertical translations of one another - is there an incorrect step in my working out?

A: The integral should be: $-ln(\vert1-e^x\vert)$.
Remember the chain rule: the derivative of $ln(1-u)$ is not $\frac{1}{1-u}$, but rather $\frac{-1}{1-u}$. But our integral is $\int \frac{1}{1-u} du$, so we need to divide $ln(|1-u|)$ by the derivative of $1-u$, $-1$, to correct for the chain rule in order to have the correct integral.

A: The easiest way to confirm would be to differentiate both of them-however, let us assume that you did not have the result.
Your steps are absolutely correct, except in the last bit.
Note that in the last line, if $1-u=t$, then $du=-dt$.
Thus, we get $$\int (1-u)^{-1} du =-\int t^{-1} dt = -\ln (|t|)+C =-\ln (|1-u|)+C=-\ln(|1-e^x|)+C$$
Where $C$ is a constant.
The answer they gave you online was wrong.
Indeed, Wolframalpha shows your steps were right.
However, it would be correct if the question was

Use the substitution $u = e^x$ to evaluate the following integral.
$$\int \frac{e^{2x}}{1-e^x} dx$$

Indeed, note $$\int \frac{e^{2x}}{1-e^x}dx=\int -e^x+\frac{e^x}{1-e^x}dx=-\int e^x dx+\int \frac{e^x}{1-e^x} dx=-e^x-\ln(|1-e^x|)+C$$

A: To know which is correct, simply differentiate:  $$\frac{d}{dx} \left[ \log (1-e^x) \right] = \frac{1}{1-e^x} \cdot \frac{d}{dx}[1-e^x] = \frac{-e^x}{1-e^x}.$$  So, in fact, there should have been a negative sign.  However, $$\frac{d}{dx}\left[-e^x - \log (1-e^x)\right] = \frac{d}{dx} [-e^x] + \frac{e^x}{1-e^x} = -e^x + \frac{e^x}{1-e^x} = \frac{e^{2x}}{1-e^x}$$ is clearly not the original integrand.


text:
Q: How to sort the "do" output? So I have function (FindCoefficients) that iterates through some values to find the maximum value for a function. It is much quicker to hold the non-linear values constant and do a find maximum for the linear coeffiecients then to do a non linear optimization for a complicated function.
This is the main line that I'm struggling with:
Do[Print[a , b, FindCoefficients[a, b]], {a, 1, 10, 1}, {b, 1, 10, 1}]

This gives me the output of
11{value of maximum, other info}
12{value of maximum, other info}
13{value of maximum, other info}
...
21{value of maximum, other info}
...
1010{value of maximum, other info}
Is there any way to sort my output from greatest to smallest, so I can easily pick out the maximum?

A: SortBy[ Table[{a , b, FindCoefficients[a, b]} , {a, 1, 10, 1}, {b, 1, 10, 1}],{3}]

sorts your Table according to the third column.


text:
Q: Не работает переход по ссылке Во флеше есть код такого рода navigateToURL(request, "_self"); Если страница сайта, на котором находится флеш, начинается на www - то ссылка не работает. Если стрница без www - то работает. С параметром "_top" работает и в том и в другом случае. С параметром "_parent" - та же проблема. Нужно, чтобы переход по ссылке происходил в текущем окне.
A: Вариант в лоб: убирать из ссылки "www".
Кстати, чего она начинается с "www", где "http:\\"?


text:
Q: Why is CommonJS only said to be suitable for non-browser apps? Why not use it as a general component pattern for Javascript, including browser-executed Javascript?
At a glance, it seems to be a good way to modularize the project I'm currently working on, which consists of a large Javascript code-base, with lots of components, some of which interact with eachother.

A: CommonJS is definitely suitable for the browser, with some caveats. The CommonJS module pattern is quite nice (in my biased opinion), and is also a good stepping stone to the module system proposed for ECMAScript Harmony (the planned next release of the JavaScript language). Specifically, Harmony modules won't have access to the global ("window") object.
The reason that some people claim CommonJS modules are not suitable for the browser is that they can't be loaded via a <script> tag without some server-side assistance. For example, imagine you have a markdown library that exports a "convertToHTML" function. You could then make a module that looks like this:
var convertToHTML = require("markdown").convertToHTML;
exports.mangleSomeText = function() {
    // do something then call convertToHTML
}

This doesn't work via a script tag for a few reasons (the scope isn't wrapped, so convertToHTML would get attached to window, require wouldn't typically be defined and exports needs to be created separately for each module).
A client side library with a tiny bit of server side help could allow this to load via script tags easily. Or, a client side library that loads the script via XMLHttpRequest and does an eval() would also work, though the debugging experience is often not as good.
A fairly reasonable solution right now, though one that is also the subject of contentious debate among CommonJS members, is RequireJS. Using RequireJS, you can write your module like this:
define(function(require, exports, module) {

var convertToHTML = require("markdown").convertToHTML;
exports.mangleSomeText = function() {
    // do something then call convertToHTML
}

});

All we did was add that define() bit around the module. (You could likely make a server do that pretty easily as well, so that you don't even need to manually type the define part).
I've personally used RequireJS on a couple of projects now and find it an easy way to make use of CommonJS modules without a server-side bit. There are many other solutions and if you aren't reliant on running static JS files, standard CommonJS modules are a great way to go.
(ObDisclaimer: I started the CommonJS project, so I am clearly biased.)


text:
Q: "lightning__RecordPage is not a flow related target" while saving a LWC that is used in a flow? I'm trying to embed a LWC into a screen flow, but when I save the following meta-xml file, I get the "lightning__RecordPage is not a flow related target" error:
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="wizardAtendimento">
    <apiVersion>47.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__FlowScreen</target>
        <target>lightning__RecordPage</target>
    </targets>
    <targetConfigs>
        <targetConfig targets="lightning__RecordPage">
            <property name="iconName" type="String" label="Icon name"/>
            <property name="title" type="String" label="Title"/>
        </targetConfig>
        <targetConfig targets="lightning__FlowScreen">
            <property name="iconName" type="String" label="Icon name" role="inputOnly"/>
            <property name="title" type="String" label="Title" role="inputOnly"/>
            <property name="selectedProduct" type="String" label="Produto selecionado" role="outputOnly"/>
            <property name="selectedType" type="String" label="Tipo de produto selecionado" role="outputOnly"/>
            <property name="selectedReason" type="String" label="Motivo de abertura selecionado" role="outputOnly"/>
        </targetConfig>
    </targetConfigs>
</LightningComponentBundle>

Is there something wrong with this setup? What is the correct way of exposing the properties on the flow?

A: It somehow does not work when we have multiple targets of different type (especially with Flow target) with multiple targetConfig. I even tested by adding masterLabel, decription as well as with the latest Api version (49.0), but still no luck.
I wanted a component in Managed Package which supports Lightning Page Builder, Flow Screens & Lightning Communities with support for multiple form-factors, since Flow does not support SupportedFormFactors tag, I created separate targetConfig for Flow. But I'm receiving same error as above.
Issue can be resolved by:

*

*Removing multiple targets (lightning__FlowScreen).

*Combining all properties to single targetConfig (comma-separated), but then won't be able to use SupportedFormFactors tag.

*Create a component wrapper for Flow target.

A: It seems changing targetConfig is in some cases not allowed once you deploy and place the component to the dev org.
I had to remove all components placed in the dev org with lightning builder, and delete the component source code from project and org using sfdx via VSCode.
I copied the source code before delete, so bring it back to the project, then deploy again. Yes, it somehow worked.

A: Adding the masterLabel and description attributes, and reducing the target list to a single target (the flow), and removing unnecessary attributes form the properties seem to have solved the issue for me. The only attributes that remained on the properties were name, type and role.


text:
Q: SQL Server full-text search for Latex content I have a web app that allows users to save Latex content to a SQL Server 2012 database. I am running a full-text query as below to search for Latex expression.
SELECT MessageID, Message FROM Messages m  WHERE CONTAINS (m.Message, N'2x-4=0');

The problem I am facing with above query is that some of the messages being returned by above query do not contain the latex expression 2x-4=0. For example, a message whose saved value is as below is also being returned by above query. You can clearly see that there is no 2x-4=0 contained in this message.

Another example of inline Latex is \$x=34\$.

What are the roots of following equation: \$x^2 - 2x + 1 = 0\$?

Question
Why is this happening and is there a way to get correct records returned when doing a full text search to look for  the latex expression 2x-4 = 0? I have tried to repopulate the full text search data for the table being used, but it had no effect.
UPDATE 1
Strange, but the following Latex expression filter always returns exact matching results. I am now looking for $2x-4=0$ rather than 2x-4=0.
SELECT MessageID, Message FROM Messages m  WHERE CONTAINS (m.Message, N'$2x-4=0$');

I have two types of delimiters for latex expression in my app: $$ for paragraph display and \$ for inline display of Latex expression, and therefore there will always be a $ symbol surrounding the latex expression stored in database, though the trailing delimiter could be \$ but full-text search seems to ignore the backslash character.
Why this modified query returns exact matches is not clear to me.
UPDATE 2
Another approach that works accurately is as mentioned in the answer. The full query for this is mentioned below. So, the LIKE operator ends up scanning only those rows that are selected by full-text search query.
WITH x AS
  (SELECT MessageID,
          Message
   FROM Messages m
   WHERE CONTAINS (m.Message,
                   N'2x-4=0') )
SELECT MessageID,
       Message
FROM x
WHERE x.Message LIKE "%2x-4=0%"

A: To understand why it happens you can run the following query (1033 is the English language id):
select * from sys.dm_fts_parser('2x-4=0', 1033, 0,1)

In my instance it would return the following results:

Note, all other parts of the search criteria are considered to be noise words except for 2x. Therefore, I suspect your full text index simply does not have the full 2x-4=0 string and instead you get results with occurrences of 2x.
I tried adding 2x-4=0 to my own FTS index and CONTAINS was able to find it as the top result for both CONTAINS(col, '2x-4=0') and CONTAINS(col, '"2x-4=0"'). However, partial matches were included too right after the exact match.
Note, that when extra white space is added around = in the search term the FTS parser won't accept it and complain about syntax error.

A: CONTAINS is more like an end-user search operation, with support for keywords like NEAR, AND and OR. Try adding quotes within the quotes, to force the exact search term:
SELECT MessageID, Message FROM Messages m WHERE CONTAINS (m.Message, N'"2x-4=0"');

This is called <simple-term> in the documentation.
You can also try the LIKE operator:
SELECT MessageID, Message FROM Messages m WHERE m.Message LIKE '%2x-4=0%';

But note that this is probably slower than CONTAINS because it doesn't use a full text search index. If it's too slow, maybe you can even combine both of them in one query, so the CONTAINS is used to filter the result set down to the non-noise words using the index, and then LIKE applies the final matching.


text:
Q: Should I Treat Entity Framework as an Unmanaged Resource? I am working with a class that uses a reference to EF in its constructor.
I have implemented IDisposable, but I'm not sure if I need a destructor because I'm not certain I can classify EF as an unmanaged resource.
If EF is a managed resource, then I don't need a destructor, so I think this is a proper example:
public ExampleClass : IDisposable
{
    public ExampleClass(string connectionStringName, ILogger log)
    {
        //...
        Db = new Entities(connectionStringName);
    }

    private bool _isDisposed;

    public void Dispose()
    {
        if (_isDisposed) return;

        Db.Dispose();

        _isDisposed= true;
    }
}

If EF is unmanaged, then I'll go with this:
public ExampleClass : IDisposable
{
    public ExampleClass(string connectionStringName, ILogger log)
    {
        //...
        Db = new Entities(connectionStringName);
    }

    public void Dispose()
    {
        Dispose(true);
    }

    ~ExampleClass()
    {
        Dispose(false);
    }

    private bool _isDisposed;

    protected virtual void Dispose(bool disposing)
    {
        if (_isDisposed) return;

        // Dispose of managed resources
        if (disposing)
        {
            // Dispose of managed resources; assumption here that EF is unmanaged.
        }
        // Dispose of unmanaged resources
        Db.Dispose();

        _isDisposed = true;
        //freed, so no destructor necessary.
        GC.SuppressFinalize(this);

    }
}

Which one is it?

A: You would never want to use a finalizer (destructor) in this case.
Whether DbContext contains unmanaged resources or not, and even whether it responsibly frees those unmanaged resources or not, is not relevant to whether you can try to invoke DbContext.Dispose() from a finalizer.
The fact is that, any time you have a managed object (which an instance of DbContext is), it is never safe to attempt to invoke any method on that instance.  The reason is that, by the time the finalizer is invoked, the DbContext object may have already been GC-collected and no longer exist.  If that were to happen, you would get a NullReferenceException when attempting to call Db.Dispose(). Or, if you're lucky, and Db is still "alive", the exception can also be thrown from within the DbContext.Dispose() method if it has dependencies on other objects that have since been finalized and collected.
As this "Dispose Pattern" MSDN article says:

X DO NOT access any finalizable objects in the finalizer code path, because there is significant risk that they will have already been finalized.
For example, a finalizable object A that has a reference to another finalizable object B cannot reliably use B in A's finalizer, or vice versa. Finalizers are called in a random order (short of a weak ordering guarantee for critical finalization).

Also, note the following from Eric Lippert's When everything you know is wrong, part two:

Myth: Finalizers run in a predictable order
Suppose we have a tree of objects, all finalizable, and all on the finalizer queue. There is no requirement whatsoever that the tree be finalized from the root to the leaves, from the leaves to the root, or any other order.
Myth: An object being finalized can safely access another object.
This myth follows directly from the previous. If you have a tree of objects and you are finalizing the root, then the children are still alive — because the root is alive, because it is on the finalization queue, and so the children have a living reference — but the children may have already been finalized, and are in no particularly good state to have their methods or data accessed.

Something else to consider: what are you trying to dispose?  Is your concern making sure that database connections are closed in a timely fashion?  If so, then you'll be interested in what the EF documentation has to say about this:

By default, the context manages connections to the database. The context opens and closes connections as needed. For example, the context opens a connection to execute a query, and then closes the connection when all the result sets have been processed.

What this means is that, by default, connections don't need DbContext.Dispose() to be called to be closed in a timely fashion.  They are opened and closed (from a connection pool) as queries are executed.  So, though it's still a very good idea to make sure you always call DbContext.Dispose() explicitly, it's useful to know that, if you don't do it or forget for some reason, by default, this is not causing some kind of connection leak.

And finally, one last thing you may want to keep in mind, is that with the code you posted that doesn't have the finalizer, because you instantiate the DbContext inside the constructor of another class, it is actually possible that the DbContext.Dispose() method won't always get called.  It's good to be aware of this special case so you are not caught with your pants down.
For instance, suppose I adjust your code ever so slightly to allow for an exception to be thrown after the line in the constructor that instantiates the DbContext:
public ExampleClass : IDisposable
{
    public ExampleClass(string connectionStringName, ILogger log)
    {
        //...
        Db = new Entities(connectionStringName);

        // let's pretend I have some code that can throw an exception here.
        throw new Exception("something went wrong AFTER constructing Db");
    }

    private bool _isDisposed;

    public void Dispose()
    {
        if (_isDisposed) return;

        Db.Dispose();

        _isDisposed= true;
    }
}

And let's say your class is used like this:
using (var example = new ExampleClass("connString", log))
{
    // ...
}

Even though this appears to be a perfectly safe and clean design, because an exception is thrown inside the constructor of ExampleClass after a new instance of DbContext has already been created, ExampleClass.Dispose() is never invoked, and by extension, DbContext.Dispose() is never invoked either on the newly created instance.
You can read more about this unfortunate situation here.
To ensure that the DbContext's Dispose() method is always invoked, no matter what happens inside the ExampleClass constructor, you would have to modify the ExampleClass class to something like this:
public ExampleClass : IDisposable
{
    public ExampleClass(string connectionStringName, ILogger log)
    {
        bool ok = false;
        try
        {
            //...
            Db = new Entities(connectionStringName);

            // let's pretend I have some code that can throw an exception here.
            throw new Exception("something went wrong AFTER constructing Db");

            ok = true;
        }
        finally
        {
            if (!ok)
            {
                if (Db != null)
                {
                    Db.Dispose();
                }
            }
        }
    }

    private bool _isDisposed;

    public void Dispose()
    {
        if (_isDisposed) return;

        Db.Dispose();

        _isDisposed= true;
    }
}

But the above is really only a concern if the constructor is doing more than just creating an instance of a DbContext.

A: C# provides garbage collection and thus does not need an explicit destructor. If you do control an unmanaged resource, however, you will need to explicitly free that resource when you are done with it. Implicit control over this resource is provided with a Finalize( ) method (called a finalizer), which will be called by the garbage collector when your object is destroyed.
https://www.oreilly.com/library/view/programming-c/0596001177/ch04s04.html


text:
Q: Si tengo una referencia de memoria almacenada en un String puedo convertirla en su objeto original partiendo desde ese String? esto es lo que esto intentando. Tengo el objeto persona y lo serializo obteniendo así su referencia de memoria, la cual almaceno en un String.
¿es posible a partir de ese String obtener el objeto Persona inicialmente?
import java.io.Serializable;

public class Persona implements Serializable {

    private String nombre;
    private String apellidos;

    public Persona(String nombre, String apellidos) {
        super();
        this.nombre = nombre;
        this.apellidos = apellidos;
    }

    public static void main(String args[]) {

        Persona benito = new Persona("benYto", "camelas");

        // serializar objeto a mano
        String serializadoManual = benito.getClass() + "@" + benito.hashCode();

        if (serializadoManual.equals(benito.toString())) {
            System.out.print("Serializado manual efectuado con exito");
        }

        // aplicamos ingenieria inversa. DEsserializar.
        //serializadoManual convertir una referencia de memoria almacenada en un string en su objeto orignal.
        Object object = serializadoManual;
        Persona benitoDeserializado = (Persona) object;
        // ERROR

    }

}

A: No podrias serializarlo asi, porque estarias combirtiendo el objeto de tipo string a objeto, lo que si podrias hacer es convertir el objeto de tipo persona a un objeto de tipo object y luego volver a convertirlo a persona:
public static void main(String args[]) {
    Persona benito = new Persona("benYto", "camelas");
    Object object = benito;
    Persona benitoDeserializado = (Persona) object;
    System.out.println(benitoDeserializado.getNombre());
}


text:
Q: Extending home network using multiple access point originating from another access point I have a home network with the current setup (RJ45 running from main router to access point) :
     +-------------+               +--------------+
     | 192.168.2.1 |               |192.168.2.2   |
     |  router     +--------------->access point 1|
     +-----^-------+               +--------------+
           |
           |
     +-----+--------+
     | 192.168.1.1  |
     |   modem      |
     +-----^--------+
           |
           |
           |
           |
        +--+--+
        | ISP |
        +-----+

However I would like to extend the network to two more floors in the house via the existing Access Point (router is too far and not reachable using a network cable, hence I need to extend using current access point). Please see diagram below :
     +-------------+               +--------------+          +----------------+
     | 192.168.2.1 |               |192.168.2.2   |          |   192.168.2.3  |
     |  router     +--------------->access point 1+----------> access point 2 |
     +-----^-------+               +--------+-----+          +----------------+
           |                                |
           |                                |
     +-----+--------+                       |
     | 192.168.1.1  |                       |
     |   modem      |                       |
     +-----^--------+                       |                +----------------+
           |                                +---------------->   192.168.2.4  |
           |                                                 | access point 3 |
           |                                                 +----------------+
           |
        +--+--+
        | ISP |
        +-----+

*

*Q1 : is this setup possible?

*Q2 : if possible, will I have to do
anything different from what I did to setup access point 1?

edit 1 : I am trying to study the dd-wrt documentation to see which would be the correct mode of operation for me Linking Routers but Im confused because I dont see any info on how to use an existing Access point to extend the signal of the SSID. If anyone could point me to the correct wiki for how I should setup AP2 and AP3 based on AP1, it would be very helpful.
For AP1, I did the following

*

*Use static IP and setup same SSID as primary wireless router

*use same security as primary wireless router

*make AP1 point to 192.168.2.1 (primary router) for DHCP

Thanks in advance.

A: Surely it's possible.
You need to configure your additional access points as wireless repeaters. You didn't specify brand and model of your APs, but most of them have this feature onboard.

A: If you have cables running from your new access points to your existing access points, then you can use a network switch to connect the router uplink and all three access points.
This will be much faster than using a wireless repeater.
Just make sure you get a switch, not a hub, and you should be good.

A: The path you are on is fret with problems.... unless you enjoy troubleshooting your home network.  For ease of use I would recommend a product like this:
TrendNet Powerline APs
You plug it into any AC outlet in your home, and voila!  your wired AND wireless network is available at any other AC outlet in the home.  No cables, no drilling.  Typically the remote unit has one or two Ethernet ports plus wireless antennas.
Other companies offer similar solutions.
Ive gone both routes for clients.  This solution has the fewest problems.
Good luck.


text:
Q: Center radio button vertically next to label I'm trying to center all my radio buttons vertically with its label, but vertical-align doesn't help:

input[type="radio"]{
    vertical-align: center;
}

 Option:

<input type="radio" name="group1"> Label1

<input type="radio" name="group1"> Label2

<input type="radio" name="group1"> Label3

A: Correct is: vertical-align: middle;

A: You can use these CSS settings:

input[type="radio"] {
  display: block;
  margin: 0 auto 5px auto;

}
label {
  text-align: center;
  display: inline-block;
  width: 80px;
}

 Option:

<input type="radio" name="group1"> Label1

<input type="radio" name="group1"> Label2

<input type="radio" name="group1"> Label3

And applied to your jsfiddle: https://jsfiddle.net/p5ts1rco/1/

A: [Solved]
I edit this example for checkboxes https://stackoverflow.com/a/494922/7767664 (changed to radio buttons):

.checkboxes label {
  display: block;
  float: left;
  padding-right: 3px;
  white-space: nowrap;
}
.checkboxes input {
  vertical-align: middle;
}
.checkboxes label span {
  vertical-align: middle;
  font-size:29px;
}

     Option:
    <input type="radio" name="group1" id="x" /> Label text x
    <input type="radio" name="group1" id="y" /> Label text y
    <input type="radio" name="group1" id="z" /> Label text z