Q: Optimize the rearranging of bits I have a core C# function that I am trying to speed up. Suggestions involving safe or unsafe code are equally welcome. Here is the method:
public byte[] Interleave(uint[] vector)
{
    var byteVector = new byte[BytesNeeded + 1]; // Extra byte needed when creating a BigInteger, for sign bit.
    foreach (var idx in PrecomputedIndices)
    {
        var bit = (byte)(((vector[idx.iFromUintVector] >> idx.iFromUintBit) & 1U) << idx.iToByteBit);
        byteVector[idx.iToByteVector] |= bit;
    }
    return byteVector;
}

PrecomputedIndices is an array of the following class:
class Indices
{
    public readonly int iFromUintVector;
    public readonly int iFromUintBit;
    public readonly int iToByteVector;
    public readonly int iToByteBit;

    public Indices(int fromUintVector, int fromUintBit, int toByteVector, int toByteBit)
    {
        iFromUintVector = fromUintVector;
        iFromUintBit = fromUintBit;
        iToByteVector = toByteVector;
        iToByteBit = toByteBit;
    }
}

The purpose of the Interleave method is to copy bits from an array of uints to an array of bytes. I have pre-computed the source and target array index and the source and target bit number and stored them in the Indices objects. No two adjacent bits in the source will be adjacent in the target, so that rules out certain optimizations.
To give you an idea of scale, the problem I am working on has about 4,200 dimensions, so "vector" has 4,200 elements. The values in vector range from zero to twelve, so I only need to use four bits to store their values in the byte array, thus I need 4,200 x 4 = 16,800 bits of data, or 2,100 bytes of output per vector. This method will be called millions of times. It consumes approximately a third of the time in the larger procedure I need to optimize.
UPDATE 1: Changing "Indices" to a struct and shrinking a few of the datatypes so that the object was just eight bytes (an int, a short, and two bytes) reduced the percentage of execution time from 35% to 30%.

A: These are the crucial parts of my revised implementation, with ideas drawn from the commenters:

*

*Convert object to struct, shrink data types to smaller ints, and rearrange so that the object should fit into a 64-bit value, which is better for a 64-bit machine:
struct Indices
{
    /// <summary>
    /// Index into source vector of source uint to read.
    /// </summary>
    public readonly int iFromUintVector;
    /// <summary>
    /// Index into target vector of target byte to write.
    /// </summary>
    public readonly short iToByteVector;
    /// <summary>
    /// Index into source uint of source bit to read.
    /// </summary>
    public readonly byte iFromUintBit;
    /// <summary>
    /// Index into target byte of target bit to write.
    /// </summary>
    public readonly byte iToByteBit;
    public Indices(int fromUintVector, byte fromUintBit, short toByteVector, byte toByteBit)
    {
        iFromUintVector = fromUintVector;
        iFromUintBit = fromUintBit;
        iToByteVector = toByteVector;
        iToByteBit = toByteBit;
    }
}

*Sort the PrecomputedIndices so that I write each target byte and bit in ascending order, which improves memory cache access:
Comparison<Indices> sortByTargetByteAndBit = (a, b) =>
{
    if (a.iToByteVector < b.iToByteVector) return -1;
    if (a.iToByteVector > b.iToByteVector) return 1;
    if (a.iToByteBit < b.iToByteBit) return -1;
    if (a.iToByteBit > b.iToByteBit) return 1;
    return 0;
};
Array.Sort(PrecomputedIndices, sortByTargetByteAndBit);

*Unroll the loop so that a whole target byte is assembled at once, reducing the number of times I access the target array:
public byte[] Interleave(uint[] vector)
{
    var byteVector = new byte[BytesNeeded + 1]; // An extra byte is needed to hold the extra bits and a sign bit for the BigInteger.
    var extraBits = Bits - BytesNeeded << 3;
    int iIndex = 0;
    var iByte = 0;
    for (; iByte < BytesNeeded; iByte++)
    {
        // Unroll the loop so we compute the bits for a whole byte at a time.
        uint bits = 0;
        var idx0 = PrecomputedIndices[iIndex];
        var idx1 = PrecomputedIndices[iIndex + 1];
        var idx2 = PrecomputedIndices[iIndex + 2];
        var idx3 = PrecomputedIndices[iIndex + 3];
        var idx4 = PrecomputedIndices[iIndex + 4];
        var idx5 = PrecomputedIndices[iIndex + 5];
        var idx6 = PrecomputedIndices[iIndex + 6];
        var idx7 = PrecomputedIndices[iIndex + 7];
        bits = (((vector[idx0.iFromUintVector] >> idx0.iFromUintBit) & 1U))
             | (((vector[idx1.iFromUintVector] >> idx1.iFromUintBit) & 1U) << 1)
             | (((vector[idx2.iFromUintVector] >> idx2.iFromUintBit) & 1U) << 2)
             | (((vector[idx3.iFromUintVector] >> idx3.iFromUintBit) & 1U) << 3)
             | (((vector[idx4.iFromUintVector] >> idx4.iFromUintBit) & 1U) << 4)
             | (((vector[idx5.iFromUintVector] >> idx5.iFromUintBit) & 1U) << 5)
             | (((vector[idx6.iFromUintVector] >> idx6.iFromUintBit) & 1U) << 6)
             | (((vector[idx7.iFromUintVector] >> idx7.iFromUintBit) & 1U) << 7);
        byteVector[iByte] = (Byte)bits;
        iIndex += 8;
    }
    for (; iIndex < PrecomputedIndices.Length; iIndex++)
    {
        var idx = PrecomputedIndices[iIndex];
        var bit = (byte)(((vector[idx.iFromUintVector] >> idx.iFromUintBit) & 1U) << idx.iToByteBit);
        byteVector[idx.iToByteVector] |= bit;
    }
    return byteVector;
}

*

*#1 cuts the function from taking up 35% of the execution time to 30% of the execution time (14% savings).

*#2 did not speed the function up, but made #3 possible.

*#3 cuts the function from 30% of exec time to 19.6%, another 33% in savings.

Total savings: 44%!!!


Q: how to have a double border for a cell I want to display a double bordered like following image...

The border has a dark color (magenta) and a light color (white) (not the actual colors).
I have created a custom .xib file and a custom class extending UITableViewCell for my table view cells.
self.tableView.separatorColor = [UIColor whiteColor];

Then in the custom table view class, I did this...
- (void)awakeFromNib
{
    [super awakeFromNib];
    UIView *cellBottom = [[UIView alloc] initWithFrame:CGRectMake(0, self.bounds.size.height, self.bounds.size.width, 1.0f)];
    cellBottom.backgroundColor = [UIColor magentaColor]; //
    [self addSubview:cellBottomView];

    // ... other code
}

I got the following result... there seems to be some gap between backgroundColor and separatorColor.

Why is this happening? The height of UIView has been set to 1 and is positioned at the bottom of UIView as well.
If there is some better solution to this could somebody throw some light on that?

A: Michal Zygar is partially correct.
Make sure your -(NSInteger)tableView:(UITableView*) heightForRowAtIndexPath:(NSIndexPath*) is correctly set to the height of the view. It doesn't automatically do that for you.
The other tip I would suggest as I do it myself, is to NOT use separators. Set your separator to none, and then add in two 1px-heigh views at the top and bottom of the cell in the XIB file.
Make sure to set the autosizing for the bottom two to stick only to the bottom edge, just in case you want to change the cell's height!


Q: How to get the selected items on Source Control History window when creating a Visual Studio Extension? I develop a Visual Studio extension. I attached a button to the Source Control History Window's Context Menu (the menu with 'changeset details', 'compare', etc.. on it)
I need to get the selected History items from the window, but couldn't figure it out how to do it.
Update:
I'm using team foundation server as source control. Here's the screenshot of the window i want to access to. Screenshot
I have found a way to retrieve the window object's data, but i still have some issues:
package.FindToolWindow(typeof(/*I don't know the type of the window*/), 0, false);

(package is instance of Microsoft.VisualStudio.Shell.Package class)
What is the type of the Source Control History window (the one on the screenshot)? This is the missing part of the puzzle i think.
Please help :)
Thanks.

A: Maybe this will be helpful for your needs:
Tool Window
I dont know your other code parts, but I guess you initiate a window application, where you want to render the history list.
This window application needs:
private FirstToolWindow window;
private void ShowToolWindow(object sender, EventArgs e)
{
     window = (FirstToolWindow) this.package.FindToolWindow(typeof(FirstToolWindow), 0, true);
...


Q: Select Data from 3 tables whereas multiple values should be comma separated I have following 3 tables:
.......
.......

…………………………           ………………………………                       …………………………
I run the following query
SELECT Employee.EmployeeId,
  EmployeeName,
  ProjectName
FROM Employee
JOIN ProjEmp
ON Employee.EmployeeId=ProjEmp.EmployeeId
JOIN Project
ON Project.ProjectId=ProjEmp.ProjectId

And it gives following result:

But I need result like this:

Suggest me the best query for my desired result.

A: You can do the following to get what you are looking for :
WITH CTE AS(SELECT Employee.EmployeeId,
  EmployeeName,
  ProjectName
FROM Employee
JOIN ProjEmp
ON Employee.EmployeeId=ProjEmp.EmployeeId
JOIN Project
ON Project.ProjectId=ProjEmp.ProjectId)

SELECT EmployeeId,EmployeeName,
      ProjectName = STUFF((
          SELECT ',' + convert(varchar(10),T2.ProjectName)
          FROM CTE T2
          WHERE T1.EmployeeName = T2.EmployeeName
          FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
FROM CTE T1
GROUP BY EmployeeId,EmployeeName
ORDER BY EmployeeId

Result:
EMPLOYEEID   EMPLOYEENAME   PROJECTNAME
1            Emp1           ProjA,ProjB
3            Emp3           ProjC
4            Emp4           ProjC,ProjD
5            Emp5           ProjE
7            Emp7           ProjE
8            Emp8           ProjE

See result in SQL Fiddle.


Q: Count requests from access log for the last 7 days I would like to parse an access log file and have returned the amount of requests for the last 7 days. I have this command
cut -d'"' -f3 /var/log/apache/access.log | cut -d' ' -f2 | sort | uniq -c | sort -rg
Unfortunately, this command returns the amount of requests since the creation of the file and sorts it into HTTP-code categories. I would like just a number, no categories, and only for the last 7 days.

A: It's a Microsoft utility so probably not what you're after but there's a utility called LogParser (link) that will analyse Apache log files and let you use SQL-style syntax to filter, aggregate etc.
You'll want to specify the input format parameter as NCSA.

A: I'd set up log rotation daily (how to do this would be dependent on your OS), then use the same command above on the 7 most recent logs.  As for your existing log, either use a tool like grep to extract just the days you want, or split that log into logs for each day.
If you want something more elegant than that, I'd just look for one of the myriad log parsing tools already out there.
Here's an example to split up your existing log:
Split access.log file by dates using command line tools

A: It should be possible, but I'm getting mired in Bash command nesting that doesn't work, and I don't understand why.
Conceptually, do this:

*

*Find the date 7 days ago, in the format that's in your Apache log

*

*date -d "-7 days" +%d\/%b\/%Y -> 10/Oct/2013

*Delete from the first line, up to the first mention of that date

*

*sed '1,/~pattern~/d' access_log

*Feed the result into wc to get a count.

*

*| wc -l
So there should be a way to combine the above into one command:
$ sed '1,/10\Oct\/2013/d' access_log | wc -l
29
$ sed '1,/$(date -d "-7 days" +%d\/%b\/%Y)/d' access_log | wc -l
$

Somewhere in the nesting, my date command and sed aren't playing nicely. And everything I try with various combinations of quotes and escapes doesn't make any difference.
What am I missing?

A: How about looking at tools like Splunk or Loggly? Loggly has a free-trial, Splunk Storm (http://splunkstorm.com) is free to sign up, and unless your log files exceed their limits, it should be trivial to get your logs indexed and run various stats on requests in the past 7 days (or various other time frames).


Q: Equation to find if a set of vertices form a concave shape? i'm trying to get around the rule of only being able to form concave shapes in the SFML c++ library by forming the non-concave shape out of many concave shapes.
What I don't know is the equation for testing a shapes concaveness:
What is it and how does it work?

A: A polygon is concave if and only if at least one of its interior angles has a measure greater than $\pi$ radians. To calculate this, take three consecutive vertices going clockwise (we will do this for every such list) - $(x_1, y_1)$, $(x_2, y_2)$, and $(x_3, y_3)$. The magnitude in the $z$ direction of the cross product of the angle's two vectors will be $ab\sin(\theta)$, where $a$ and $b$ are the magnitudes and $\theta$ is the angle in between. This will be positive if and only if $\theta > \pi$ radians. So we calculate $(x_2 - x_1)(y_3 - y_2) - (x_3 - x_2)(y_2 - y_1)$, which is the magnitude of the cross product. If, for any set of 3 consecutive vertices (going clockwise, of course), this value is positive, the polygon is concave. Note that in Mathematica (which you tagged this post with), you can split a list of vertices into such groups of 3 with the command Partition[vertices, 3, 1]. If you need the shape to be convex instead, test whether all such cross products are negative.
I only know the solution for polygons, not other shapes.


Q: Как обновить несколько записей одного поля? Имеется
1. Таблица - table
2. Поля:
- id;
- pole_1;
- pole_2;
- pole_3;
3. Таблица содержит 9-ть записей.
Можно ли обновить записи "pole_2" для "id" > 3 одним запросом?
Или нужно для каждой записи делать отдельный запрос?
Для id = 4
update table
set
 `pole_2` = 'zapis_4_izm_1'
 where id = 4

Для id = 5
update table
set
 `pole_2` = 'zapis_5_izm_2'
 where id = 5

и т.д.
Значение записи "zapis_4_izm_1", "zapis_5_izm_2" приведены в условном виде.
По факту все записи pole_2 будут разные и не будут иметь прослеживаемой тенденции.
Вопрос.
Как обновить записи "pole_2" для "id" > 3 одним запросом ?
Т.е. имеем набор разных не повторяющихся записей для поля "pole_2".
Данные поступают из парсера.
Соответствие между значениями и id обновляемых записей устанавливается по порядку от указанного id в запросе..
Указываем в запросе, что нужно обновить все записи поля "pole_2" у которых "id" > 3.
Вставляем в запрос набор данных.
Выполняем запрос.

A: update `table`
set pole_2 = CONCAT('zapis_',id,'_izm_',id-3)
where id IN (4,5)


Q: Propositional Logic (converting sentence to formula) How do I put this into a formula? If Jones drove the car, Smith is innocent. If Brown fired the gun, then Smith is not innocent. Jones did not drive the car. I put $(J\Rightarrow S)\vee  (B\Rightarrow \neg S)$ Can anyone let me know if this is right or wrong? And if wrong, what the right one would be?

A: Let's name some statements.
$ \mathcal{J}$ : Jones drove the car.
$ \mathcal{S}$ : Smith is innocent.
$ \mathcal{B}$ : Brown fired the gun.
Then, if you convert those sentences, you would get
$$(\mathcal{J}\Rightarrow \mathcal{S}) \wedge (\mathcal{B}\Rightarrow \neg \mathcal{S}) \wedge (\neg \mathcal{J})$$


Q: Porque queda Valor null después de ser eliminado un usuario de una collections? mongodb CRUD API REST Estoy haciendo un delete de un usuario y funciona colocando su id en req.params.id Sin embargo al volver a hacer el delete al mismo id envía un null, quiero saber si es posible hacer una manejo de errores que me devuelva usuario no existe y no simplemente null Al hacer get del usuario eliminado también indica null y quiero enviar un error de usuario no encontrado cómo puedo hacer para retornar un error y no simplemente null.
Aqui el ejemplo que tengo:

// eliminar Usuario
router.delete("/usuario/:id", async (req, res) => {
    const { id } = req.params;
    UsuarioSchema
    .findByIdAndRemove({ _id: id })
    .then((data) => await = res.status(200).send("usuario eliminado con exito" + data))
    .catch((error) => res.status(404).send("usuario no encontrado" + error));
    });

Este codigo me funciona, elimina un usuario de mi base de datos, pero cuando lo vuelvo a ejecutar no me da un error, me envia un status 200 pero con usuario null. Por eso quiero agregarle un manejo de errores que si el usuario es null tambien me diga que no existe.

A: No encontrar un dato no significa que hubo un error(de manera nativa). Debes especificar que mande un error.
router.delete("/usuario/:id", async (req, res) => {
    const { id } = req.params;
    UsuarioSchema
    .findByIdAndRemove({ _id: id })
    .then((data) => {
        if (!data) throw "No existe el usuario o lo que sea"
        res.status(200).send("usuario eliminado con exito" + data))
      }
    .catch((error) => res.status(404).send("usuario no encontrado" + error));
    });

``


Q: How to retreive password stored in Firefox? I would like to retrieve an important password which I forgot, but which Firefox has remembered and uses to log in. Where is this password stored and is it (or can it be made) readable?

A: Go to Edit --> Preferences --> Security Tab and select Saved Passwords

Then select Show Passwords


Q: Existence of arithmetic function satisfying a certain property I was interested in an arithmetic function satisfying a certain property, I am not sure at the moment if such thing even exists or not. But I was wondering maybe I could get some hint or idea or input from someone.
Fix $k \in \mathbb{N}$ and some $\epsilon > 0$. I would like a function $f$ defined for all $\mathbb{Z}$ such that
$$| \ f(n_1) ... f(n_k) \ | \ll | \ n_1+ n_2 + .. + n_k \ |^{-\epsilon} $$
and
$$| \ f(n_1) ... f(n_k) \ | \gg 1 ~~~\text{if}~~\ n_1+ n_2 + .. + n_k = 0$$
I would greatly appreciate any assistance on this matter! Thank you very much!

A: Suppose that $f$ satisfies your conditions: $|f(n_1)\dotsb f(n_k)|\le
A|n_1+\dotsb+n_k|^{-\epsilon}$ if $n_1+\dotsb+n_k\ne 0$, and
$|f(n_1)\dotsb f(n_k)|\ge B$ if $n_1+\dotsb+n_k=0$, with positive $A$ and
$B$ depending only on $k$ and $\epsilon$. The second condition implies
that $\max\{|f(n)|,|f(-n)|\}\ge \sqrt B/|f(0)|^{k/2-1}$, for every
positive integer $n$ (take $n_1=n,n_2=-n$, and $n_3=\dotsb=n_k=0$). Using
now the first condition with the $n_i\in\{-n,n\}$ chosen to satisfy
$|f(n_i)|\ge \sqrt B/|f(0)|^{k/2-1}$ (and all equal each other), we get
$B^{k/2}/|f(0)|^{k(k/2-1)}\le A(kn)^{-\epsilon}$. This cannot be true for
$n$ large enough. Consequently, no such function exists.


Q: Conditional proof demonstration I know how to use conditional proof assumption to demonstrate that $A \rightarrow  C$. For example, having the premises:

*

*A → B       ("If A, then B")

*B → C   ("If B, then C")

We can prove that that $A \rightarrow  C$ in the following manner:

*A   (conditional proof assumption, "Suppose A is true")

*B   (follows from lines 1 and 3, modus ponens; "If A then B; A, therefore B")

*C   (follows from lines 2 and 4, modus ponens; "If B then C; B, therefore C")

*A → C   (follows from lines 3–5, conditional proof; "If A, then C")

However, I do not understand exactly why this works. What is the formal proof for this method?
I know that $A \rightarrow  C$ will be true for all cases except when A is TRUE and C is FALSE. Therefore, if A is TRUE, then C must be necessarily TRUE in order for $A \rightarrow  C$ to be true. But I don't know wether A is TRUE or FALSE, so why does making the assumption "A is true" always lead us to a correct result?

A:
I know that $A→C$ will be true for all cases except when A is TRUE and C is FALSE.

That is exactly the reason.   The semantics is that $A\to C$ is valued as false only by valuing $A$ as true and $C$ as false.
Therefore there is no need to consider what happens when $A$ is valued as false; since that shall vacuously value $A\to C$ as true.
Thus the syntactic proof only needs to ensure that the truth of $C$ shall be a valid derivation under an assumption of the truth of $A$.

A: Here is the proof written in
natural deduction:
$\def\fitch#1#2{\quad\begin{array}{|l}#1\\\hline#2\end{array}}$
$$\fitch{1.~~A\to B\\2.~~B\to C}{\fitch{3.~~A}{4.~~B\hspace{5ex}\to\text{Elim}1,3\\5.~~C\hspace{5ex}\to\text{Elim}2,4}\\6.~~A\to C\hspace{3.2ex}\to\text{Intro3-5}}$$
The rule used in $4,5$ also konwn as Modus ponens, rule for line $6$ also known as Conditional Introduction.
Even we don't know wether A is TRUE or FALSE, but we only need to prove it hold when $A$ is true, since if the condition is false, the statement $A\to C$ is vacuously true.

A: Consider that a conditional statement of the form $p \to q$ is false if and only if the antecedent, $p$, is true and the consequent, $q$, is false.
If you assume $p$ is true on its own line and are subsequently able to deduce $q$ using the rules of inference, then $q$ must be true if $p$ is true (because $q$ was validly deduced from $p$ using the rules of inference).
Thus, if $p$ is true, then $q$ is true and the conditional statement $p \to q$ must be true. If $p$ is false, then the conditional statement $p \to q$ is still true. Hence, the conditional method is a valid means of producing conditional statements.

A: What steps 1 through 5 are showing is that the two givens $A \to B$, $B \to C$, together with assumption $A$, logically imply the statement $C$.
Using the $\vDash$ symbol for loigical notation, we can write this as: $$\{ A \to B, B \to C, A \} \vDash C \tag{1}$$
Now, on line 6, you conclude that this means that $A \to C$ follows from the two givens $A \to B$ and $B \to C$ alone, i.e. that $$\{ A \to B, B \to C\} \vDash A \to C \tag{2}$$
Your question is: why would this be correct? Why would the fact that (1) imply that (2)?
Well, for $(2)$ to be the case, it must be the case that for any truth-assignment to the variables $A$, $B$, and $C$, it is impossible for $A \to B$ and $B \to C$ to br true, and $A \to C$ to be false.  But, the only way for  $A \to C$ to be false, is when $A$ is true and $C$ is false. Hence, $(2)$ would be the case if for any truth-assignment to the variables $A$, $B$, and $C$, it is impossible for $A \to B$ and $B \to C$ and $A$ to be true, and for $C$ to be false. But, that is exactly what $(1)$ is telling us. So, $(1)$ implies $(2)$
... and that is what the rule of Conditional Introduction does in general. Where $\Gamma$ is any set of statements, where $\varphi$ is some assumption, and where $\psi$ is some statement you are able to derive from the asumption, together with the given statementds $\Gamma$,  you go from the finding that:
$$\Gamma \cup \varphi \vDash \psi$$
to:
$$\Gamma \vDash \varphi \to \psi$$
and the validity of that follows the same reasoning as above.

A: For those who are unfamiliar with set notation in logic, here I provide a translation of Bram28's awesome demostration, but using simple conjunctions instead of sets.
Let's say that $\delta$ contains all the logical variables of our problem (i.e the variables that can only take the value true or false):
$$\delta = \{A,B,C,D, \ldots\}$$
We also have a collection of givens $P_1(\delta), P_2(\delta), \ldots, P_N(\delta)$ that depend on the aforementioned variables. Now, let's say we want to prove that $A \rightarrow C$ is true based on those givens. That is, we want to prove that the following expression is true for any truth-assignment to the variables contained in $\delta$ (i.e. tautology):
$$(P_1(\delta) \wedge P_2(\delta) \wedge \ldots \wedge P_N(\delta)) \rightarrow (A \rightarrow C) \tag{1}$$
At first glance, this may be hard to prove, therefore we will need to use the conditional proof assumption approach to make the process easier.
The conditional proof assumption states that:
If we are able to prove (using the well-known inference rules) that the following expression evaluates to true for any truth-assignment to the variables contained in $\delta$ (i.e. tautology):
$$[(P_1(\delta) \wedge P_2(\delta) \wedge \ldots \wedge P_N(\delta)) \wedge A] \rightarrow C \tag{2}$$
then, we can be sure that the following expression (the one we mentioned initially) will also evaluate to true for any truth-assignment to the variables contained in $\delta$ (i.e. tautology):
$$(P_1(\delta) \wedge P_2(\delta) \wedge \ldots \wedge P_N(\delta)) \rightarrow (A \rightarrow C) \tag{1}$$
This is because (2) implies (1). Or expressed mathematically:
$$[(P_1(\delta) \wedge P_2(\delta) \wedge \ldots \wedge P_N(\delta)) \wedge A] \rightarrow C \Rightarrow (P_1(\delta) \wedge P_2(\delta) \wedge \ldots \wedge P_N(\delta)) \rightarrow (A \rightarrow C)$$
But why does (2) imply (1)? Because when (2) is true, (1) is necessarily true. The only way that (1) can be false is when the antecedent $(P_1(\delta) \wedge P_2(\delta) \wedge \ldots \wedge P_N(\delta))$ is true and the consequent $(A \rightarrow C)$ is false. Likewise, the only way that $A \rightarrow C$ can be false is when the antecedent $A$ is true and the consequent $C$ is false. So, in other words, the only way that (1) can be false is when $(P_1(\delta) \wedge P_2(\delta) \wedge \ldots \wedge P_N(\delta))$ and $A$ are true, and $C$ is false. But if (2) is true and $(P_1(\delta) \wedge P_2(\delta) \wedge \ldots \wedge P_N(\delta))$ and $A$ are true, then $C$ will also be true. So (2) implies (1).
Therefore, this demonstrates that the conditional proof assumption (CPA) method works.


Q: extracting the generic type of other props in interface How can I achieve something like this?
interface Props {
   result: <type of function with a lot of generic>
   data: <type of one of the generics in the function above>
}

I've found a question that sounds similar here, but I'm such a newbie and not sure if this applies to my case.
The background:
I'm using react-query, and want to make a wrapper component that takes a react-query result object and a component, then shows spinner or the given component based on the query state (isLoading, isSuccess etc), whatever the query response data type is.
import React from 'react'
import {useQuery} from 'react-query'

interface WrapperProps {
   result: <type of react query result>;
   render: (data: <type of query data>) => React.ReactNode;
}

const Wrapper: React.FC<WrapperProps> = ({result, render}) => {
  if (result.isLoading) {
     return
spinner

  }

  if (result.isSuccess) {
    return render(result.data)
  }

  return
otherwise

}

const App: React.FC = () => {
  const responseString = useQuery(
    ['string']
    async () => Promise.resolve("string")
  )

  const responseNumber = useQuery(
    ['number']
    async () => Promise.resolve(3)
  )

  return (

    <Wrapper
      result={responseString}
      render={(data) => (
successfully loaded string {data}
)} // <= want the data to be type string
    />
    <Wrapper
      result={responseInt}
      render={(data) => (
successfully loaded int {data}
)} // <= want the data to be type number
    />

  )
}

*1 the type of useQuery is something like this

A: You were close. You need to update Wrapper component a bit.
First of all, you need to get rid FC. Instead you need to add extra generic type to infer query result.
Consider this example:
import React from 'react'

import { useQuery, UseQueryResult } from 'react-query'

interface WrapperProps<T> {
  result: UseQueryResult<T, unknown>
  render: (data: T) => JSX.Element;
}

const Wrapper = <T,>({ result, render }: WrapperProps<T>) => {
  if (result.isLoading) {
    return
spinner

  }

  if (result.isSuccess) {
    return render(result.data)
  }

  return
otherwise

}

const App: React.FC = () => {
  const responseString = useQuery(
    ['string'],
    async () => Promise.resolve("string")
  )

  const responseNumber = useQuery(
    ['number'],
    async () => Promise.resolve(3)
  )

  return (

      <Wrapper
        result={responseString}
        render={(data /** string */) => (
successfully loaded string {data}
)}
      />
      <Wrapper
        result={responseNumber}
        render={(data /** number */) => (
successfully loaded int {data}
)}
      />

  )
}

Playground
Please keep in mind that it is impossible to infer component props with extra generic and FC explicit type.
Please be aware that TS since 2.9 supports explicit generics for react  components


Q: Porque existe FloatToStr se o Delphi não possui o tipo de dado Float? Lendo sobre os tipos de dados do Delphi/Pascal percebi que não existe o tipo Float, porém, existe a função FloatToStr(), assim como StrToFloat().
Neste caso, poderia utilizar variável de ponto flutuante de qualquer tipo e a função se encarrega de realizar a conversão corretamente?

A: Tem programador que tem dificuldade de nomear coisas. Na verdade é meio normal entre as pessoas em geral, tem até uma citação que as duas coisas mais difíceis da computação é invalidar cache e nomear coisas.
Não posso falar qual o motivo de terem feito isso, mas pra mim é só uma forma de tentar dar um nome só pra várias coisas e tornar a função mais descobrível tendo algumas sobrecargas.
De fato o que ela faz é trabalhar com vários tipos que possuem parte decimal, com ponto flutuante, ou não, o que é bem engraçado :)
Documentação do Free Pascal.
Outra coisa curiosa é que a função que cria um tipo de ponto flutuante é única, o que mostra que quem fez não estava pensando muito bem no problema. Documentação.


Q: MySQL Syntax Error With Stored Procedures I must be missing something simple because I can't figure out what is causing my script to fail.
Below is the stored procedure I've written:
CREATE PROCEDURE `Search_contacts`(IN `in_owner_id` INT,
    IN `in_first_name` VARCHAR(255))
 IF in_first_name IS NOT NULL THEN
     SELECT * FROM `contacts`
     WHERE `owner_id` = in_owner_id AND `first_name` LIKE in_first_name;
END IF;

When I try and execute this on my MySQL server I get the following error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 5

I'd like to know what is causing this error and why so I can avoid it again.
Any help is appreciated!

A: Try adding "BEGIN", "END" and "DELIIMITER", like this:
DELIMITER $$
CREATE PROCEDURE `Search_contacts`(IN `in_owner_id` INT,
    IN `in_first_name` VARCHAR(255))
BEGIN
    IF in_first_name IS NOT NULL THEN
        SELECT * FROM `contacts`
        WHERE `owner_id` = in_owner_id AND `first_name` LIKE in_first_name;
    END IF;
END $$
DELIMITER ;


Q: Mapping a many-to-two relationship in fluent-nhibernate I'm working with a node/link structure, but I'm having problems mapping it using fluent nhibernate.
This is a simplification of the classes I'm using.

class Node
{
  public virtual IList Links { get; set; }
}

class Link
{
  public virtual Node StartNode { get; set; }
  public virtual Node EndNode { get; set; }
}

A node can have many links connected to it.
A link has to be connected to two nodes.
And I need to know which node is the start node and end node, so they have to be specific. Which is why I can not use a list and limit it to two nodes.
Has anyone come across this problem and found a solution to it?
Edit: Clearifying question
I'm not using Automapping, I'm using the explisit mapping methods: References, HasMany and HasManyToMany. Essentially following the methods found in the introductory tutorial: http://wiki.fluentnhibernate.org/Getting_started#Your_first_project
I don't have a database either, I'll create the database schema from the mappings using nhibernate.
What I'm asking is, how do I create a many-to-two relation?

A: Well there's not a special many to two relationship but what you'd probably do is something like this:
public class NodeMap : ClassMap<Node>
{
    public NodeMap()
    {
        //Id and any other fields mapped in node

        HasMany(x => x.Links);
    }
}

public class LinkMap : ClassMap<Link>
{
    public LinkMap()
    {
        //Id and any other fields mapped in node

        References(x => x.StartNode);
        References(x => x.EndNode);
    }
}

Again this is just a brief overview above.  You will probably need additional mapping attributes if you want to for example cascade any create/update/delete actions.


Q: How to feed in and retrieve state of LSTM in tensorflow C/ C++ I'd like to build and train a multi-layer LSTM model (stateIsTuple=True) in python, and then load and use it in C++. But I'm having a hard time figuring out how to feed and fetch states in C++, mainly because I don't have string names which I can reference.
E.g. I put the initial state in a named scope such as
    with tf.name_scope('rnn_input_state'):
        self.initial_state = cell.zero_state(args.batch_size, tf.float32)

and this appears in the graph as below, but how can I feed to these in C++?

Also, how can I fetch the current state in C++? I tried the graph construction code below in python but I'm not sure if it's the right thing to do, because last_state should be a tuple of tensors, not a single tensor (though I can see that the last_state node in tensorboard is 2x2x50x128, which sounds like it just concatenated the states as I have 2 layers, 128 rnn size, 50 mini batch size, and lstm cell - with 2 state vectors).
    with tf.name_scope('outputs'):
        outputs, last_state = legacy_seq2seq.rnn_decoder(inputs, self.initial_state, cell, loop_function=loop if infer else None)
        output = tf.reshape(tf.concat(outputs, 1), [-1, args.rnn_size], name='output')

and this is what it looks like in tensorboard

Should I concat and split the state tensors so there is only ever one state tensor going in and out? Or is there a better way?
P.S. Ideally the solution won't involve hard-coding the number of layers (or rnn size). So I can just have four strings input_node_name, output_node_name, input_state_name, output_state_name, and the rest is derived from there.

A: I managed to do this by manually concatenating the state into a single tensor. I'm not sure if this is wise, since this is how tensorflow used to handle states, but is now deprecating that and switching to tuple states. Instead of setting state_is_tuple=False and risking my code being obsolete soon, I've added extra ops to manually stack and unstack the states to and from a single tensor. Saying that, it works fine both in python and C++.
The key code is:
# setting up
zero_state = cell.zero_state(batch_size, tf.float32)
state_in = tf.identity(zero_state, name='state_in')

# based on https://medium.com/@erikhallstrm/using-the-tensorflow-multilayered-lstm-api-f6e7da7bbe40#.zhg4zwteg
state_per_layer_list = tf.unstack(state_in, axis=0)
state_in_tuple = tuple(
    # TODO make this not hard-coded to LSTM
    [tf.contrib.rnn.LSTMStateTuple(state_per_layer_list[idx][0], state_per_layer_list[idx][1])
    for idx in range(num_layers)]
)

outputs, state_out_tuple = legacy_seq2seq.rnn_decoder(inputs, state_in_tuple, cell, loop_function=loop if infer else None)
state_out = tf.identity(state_out_tuple, name='state_out')

# running (training or inference)
state = sess.run('state_in:0') # zero state

loop:
    feed = {'data_in:0': x, 'state_in:0': state}
    [y, state] = sess.run(['data_out:0', 'state_out:0'], feed)

Here is the full code if anyone needs it
https://github.com/memo/char-rnn-tensorflow


Q: Where exactly are variables or identifiers stored in C++? According to my current knowledge variables(identifiers) point to object of a particular type(int,bool,etc..) that are objects in memory. Where and how are the the variables themselves store? Are they stored with the objects they point to or are they stored in some other place?
For example;
int main()
{
    int a_number = 2;
    return 0;
}

So the variable a_number point to an int object in memory, but where is a_number itself??
If say the 2 is in a 4 byte memory, is a_number consuming a portion of it?? Or is a_number consuming some other allocated memory somewhere??
By the way I currently studying C++(am a beginner in programming) and I was considering this and couldn't really visualize it.
Thank you.

A: In this particular case, a_number names an int object that consumes sizeof(int) bytes and has automatic storage duration. Memory for storage with automatic duration is typically allocated in the stack frame of the function to which the declaration belongs (main() in this case).
a_number effectively becomes a name for the int object stored in these bytes. The name does not exist at runtime, because it is no longer needed at that time. The only purpose of the name is to allow you to refer to the object in code.

A: Variables can stored in memory areas or in processor registers, depending on the compiler and optimization settings.
Let's assume that your compiler is using a stack for function local variables and parameters.  Your a_number variable would be placed on the stack since it's lifetime is temporary (will disappear after execution leaves the function).
The compiler is allowed to place the a_number into a processor register.  In this case, the variable doesn't exist in memory because processor registers are not in memory (they don't have addresses).
Since your program doesn't use the a_number variable after declaration, the compiler can eliminate the variable and not use memory.  There is no difference in behavior of your program with or without the variable; thus the compiler can eliminate the variable.
The location of your variable depends on your compiler.  You compiler can store variables "on the stack", in a processor register or eliminate the variable.  The location also depends on the "optimization setting" on your compiler.  Some compilers may not optimize on the lowest settings and remove the variable on the higher settings.

A:
but where is a_number itself?

Just where you see it, in the source code file.  The compiler sees it there and keeps track of it, generating what code it needs to.  If you have debugging turned on, then the symbol is stored along with the code in a special look up table so you can see it in the debugger as well.


Q: Google App Flexible Java Logging Not Working I have a simple servlet as below. And I'm unable to see any of System.out or log.info in the gcloud logs. I used gcloud app logs tail -s my-app-name. I only see logs for GET and favicon. Please help to enable logs in my google cloud app.
@SuppressWarnings("serial")
@WebServlet(name = "Home", description = "Write low order IP address to response", urlPatterns = "/")
public class HomeServlet extends HttpServlet {
    Logger logger = Logger.getLogger(HomeServlet.class.getName());
    Connection conn;

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        if(logger.isLoggable(Level.FINE)) {
            log("FINE is loggable.");
            System.out.println("This is System Out. FINE is loggable");
            logger.fine("Received GET request");
        } else {
            log("FINE is not loggable");
            System.out.println("This is System Out. FINE is not loggable");
            logger.severe("Received GET request");
        }
        String path = req.getRequestURI();
        if (path.startsWith("/favicon.ico")) {
            return; // ignore the request for favicon.ico
        }

        PrintWriter out = resp.getWriter();
        resp.setContentType("text/plain");

        String userIp = req.getRemoteAddr();
        out.print("Your IP is: " + userIp);
        log("responded GET request from: " + userIp);
    }

}

A: You can use the command this way:
gcloud app logs tail --service=my-service --version=my-app-version

in order to specify the service and version, then see If you're not really getting all the logs. See a list of all options here. Also you can see all your logs by going to Stackdriver -> Logging -> Logs:

Once there, you can filter the logs by app version:

Also be aware that depending on the request you make, sometimes you'll only see certain kind of logs. I pasted your code in the quickstart for app engine flexible and I got this:
    ...........

    2017-12-18 09:40:07 my-service[my-app-version]  "GET /favicon.ico" 200
    2017-12-18 09:40:07 my-service[my-app-version]  "GET /" 200
    2017-12-18 09:40:07 my-service[my-app-version]  "GET /favicon.ico" 200
    2017-12-18 09:40:08 my-service[my-app-version]  "GET /" 200
    2017-12-18 09:40:13 my-service[my-app-version]  org.eclipse.jetty.server.handler.ContextHandler.root: com.example.appengine.gettingstartedjava.helloworld.HomeServlet: FINE is not loggable
    2017-12-18 09:40:13 my-service[my-app-version]  com.example.appengine.gettingstartedjava.helloworld.HomeServlet: Received GET request
    2017-12-18 09:40:13 my-service[my-app-version]  org.eclipse.jetty.server.handler.ContextHandler.root: com.example.appengine.gettingstartedjava.helloworld.HomeServlet: responded GET request from: 35.187.117.231
    2017-12-18 09:40:13 my-service[my-app-version]  This is System Out. FINE is not loggable
    2017-12-18 09:40:15 my-service[my-app-version]  This is System Out. FINE is not loggable

..........

In addition to this, you can use the Stackdriver Logging Client Libraries. First add this to your POM dependencies:
<dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-logging</artifactId>
    <version>1.14.0</version>
</dependency>

then use the quickstart and paste this code in the HelloServlet.java. Your code would look like this:
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    PrintWriter out = resp.getWriter();
    out.println("Hello, world - Flex Servlet");

    Logging logging = LoggingOptions.getDefaultInstance().getService();

    String logName = "My-log";

    String text = "Hello World";

    LogEntry entry = LogEntry.newBuilder(StringPayload.of(text)).setSeverity(Severity.ERROR).setLogName(logName)
            .setResource(MonitoredResource.newBuilder("global").build()).build();

    logging.write(Collections.singleton(entry));

    System.out.printf("Logged: %s%n", text);

}

You can see this result in Stackdriver:


Q: Not getting expected return value from function So, I am getting a csv file from a url. I am then turning each row into an array of objects.
const translation = {
    '緯度': 'latitude',
    '経度': 'longitude',
    '測定局コード': 'Measuring station code',
    '測定局名称': 'Bureau name',
    '所在地': 'location',
    '測定局種別': 'Measuring station type',
    '問い合わせ先': 'Contact information',
    '都道府県コード': 'Prefecture code'
}
const csv_url = 'https://soramame.env.go.jp/data/map/kyokuNoudo/2022/10/06/01.csv';

// request the csv file from csv_url and create an array of stations objects

var stations = [];
request(csv_url, (err, res, body) => {
    if (err || res.statusCode !== 200) {
        console.log(err);
    }
    else {
        const rows = body.split('\n');
        const headers = rows[0].split(',');
        for (let i = 1; i < rows.length; i++) { // start at 1 to skip headers
            let station = {}; // create a new station object for each row
            const row = rows[i].split(','); // split the row into columns
            for (let j = 0; j < row.length; j++) { // loop through each column
                station[translation[headers[j]]] = row[j]; // add the value to the station object by using the header as the key
            }
            var data = stations.push(station)
            console.log(stations)
            return data;
        }
    }
}
);

That all works fine... when I console.log(stations) inside of the function I get the expected output.
{
  latitude: '43.123333',
  longitude: '141.245000',
  'Measuring station code': '01107030',
  'Bureau name': '手稲',
  location: '札幌市手稲区前田２－１２',
  'Measuring station type': '一般局',
  'Contact information': '札幌市',
  'Prefecture code': '01'
}
{
  latitude: '43.123333',
  longitude: '141.245000',
  'Measuring station code': '01107030',
  'Bureau name': '手稲',
  location: '札幌市手稲区前田２－１２',
  'Measuring station type': '一般局',
  'Contact information': '札幌市',
  'Prefecture code': '01'
}
{
  latitude: '43.123333',
  longitude: '141.245000',
  'Measuring station code': '01107030',
  'Bureau name': '手稲',
  location: '札幌市手稲区前田２－１２',
  'Measuring station type': '一般局',
  'Contact information': '札幌市',
  'Prefecture code': '01'
}

however when I console.log(stations) outside of the function I get an empty list. I am declaring 'stations' outside of the function, and the function is appending the objects to the array. Why isn't it working and what can I do to solve this? also, when I return 'data' that doesn't return the array from. 'stations' either.

A: The call to request is asynchronous.
Therefore, calling console.log(stations) in the line immediately after your call to request will print the empty list while your request continues to run in the background.
It prints too quickly - before the stations list has been populated.
Whatever you need to do with stations, you either need to do it in a success callback passed to request, or you need to await the request.
As Dai says above, push is actually mutating the stations array.
I am not sure what implementation of request you are using but it may return a value so you may be able to do something like const response = await request(...) (this could work in conjunction with fixing the error Dai pointed out - one way would be to move the declaration of stations inside the else clause, and then return stations at the end of the else clause).
If you can't await it, you will need to pass a callback that performs the pushes to stations defined as is.


Q: How to get the desired output by modifying string after removing / from string I have a string like this:
30/04/2018 o/p=300418
01/03/2017 o/p=010317
10/11/2018 o/p=101118
12/11/2123 o/p=121123
1/1/2018 o/p =010118
code tried but can't  get the last one 1/1/2018
string a = "31/04/2018";
string b = a.Replace("/","");
   b = b.Remove(4, 2);

A: You should parse to a DateTime and then use the ToString to go back to a string. The following works with your given input.
var dateStrings = new []{"30/04/2018", "01/03/2017","10/11/2018","12/11/2123","1/1/2018"};
foreach(var ds in dateStrings)
{
    Console.WriteLine(DateTime.ParseExact(ds, "d/M/yyyy", System.Globalization.CultureInfo.InvariantCulture).ToString("ddMMyy"));
}

The only change I made is to the first date as that is not a valid date within that month (April has 30 days, not 31). If that is going to be a problem then you should change it to TryParse instead, currently I assumed your example was faulty and not your actual data.

A: Your structure varies, all of the examples above use two digit month and day, while the bottom only uses a single digit month and day.  Your current code basically will replace the slash with an empty string, but when you remove index four to two your output would deviate.
The simplest approach would be:
var date = DateTime.Parse("...");
var filter = $"o/p = {date:MMddyyyy}";

Obviously you may have to validate and ensure accuracy of your date conversion, but I don't know how your applications works.

A: If you can reasonably expect that the passed in dates are actual dates (hint: there are only 30 days in April) you should make a function that parses the string into DateTimes, then uses string formats to get the output how you want:
public static string ToDateTimeFormat(string input)
{
    DateTime output;
    if(DateTime.TryParse(input, out output))
    {
        return output.ToString("MMddyy");
    }
    return input; //parse fails, return original input
}

My example will still take "bad" dates, but it will not throw an exception like some of the other answers given here (TryParse() vs Parse()).
There is obviously a small bit of overhead with parsing but its negligible compared to all the logic you would need to get the proper string manipulation.
Fiddle here

A: Parse the string as DateTime. Then run ToString with the format you desire.
var a = "1/1/2018";
var date = DateTime.Parse(a);
var result = date.ToString("ddMMyyyy");

A: You can use ParseExact to parse the input, then use ToString to format the output.
For example:
private static void Main()
{
    var testData = new List<string>
    {
        "31/04/2018",
        "01/03/2017",
        "10/11/2018",
        "12/11/2123",
        "1/1/2018",
    };

    foreach (var data in testData)
    {
        Console.WriteLine(DateTime.ParseExact(data, "d/m/yyyy", null).ToString("ddmmyy"));
    }

    GetKeyFromUser("\nDone! Press any key to exit...");
}

Output

A: You didn't specify whether these are DateTime values or just strings that look like date time values.  I'll assume these are DateTime values.
Convert the string to a DateTime.  Then use a string formatter.  It's important to specify the culture.  In this case dd/mm/yyyy is common in the UK.
    var culture = new CultureInfo("en-GB");//UK uses the datetime format dd/MM/yyyy

    var dates = new List<string>{"30/04/2018", "01/03/2017","10/11/2018","12/11/2123","1/1/2018"};

    foreach (var date in dates)
    {
        //TODO:  Do something with these values
        DateTime.Parse(date, culture).ToString("ddMMyyyy");
    }

Otherwise, running DateTime.Parse on a machine with a different culture could result in a FormatException.  Parsing dates and times in .NET.


Q: How to stop youtube player when resize screen under 768px? I would like to stop the youtube video only in mobile. I need to show it on desktop device, and hide it on mobile.
Is possibile with javascript? I'm sorry but I don't know Javascript, I need a complete code.
The Html code is:

Can I integrate the windows resize function with youtube?
function stopVideo() {
  player.stopVideo();

Please Help me! If I use only a "display: none" the video disappears but you can still hear the sound.


Q: Injective Morphism of Commutative $C^*$-algebras Let $X$ and $Y$ be compact Hausdorff spaces, and let $\varphi : C(X) \to C(Y)$ an injective morphism of $C^*$-algebras. The book I'm reading through claims that there exists a continuous surjection $\alpha : Y \to X$ such that $$\varphi (f) = f \circ \alpha$$ for every $f \in C(X)$. But I am having trouble verifying this.

A: Here's how $\alpha$ is defined.  If $y\in Y$, then
$$\operatorname{ev}_y\circ\ \varphi:C(X)\to\mathbb C$$
is a non-zero $*$-homomorphism, hence there is some $\alpha(y)$ such that $\operatorname{ev}_{\alpha(y)}=\operatorname{ev}_y\circ\ \varphi$.  Continuity of $\alpha$ is readily verified.
Now, suppose that $\alpha$ is not surjective.  Then $\alpha(Y)$ is a proper closed subspace of $X$, hence there is a non-zero function $f\in C(X)$ which vanishes on $\alpha(Y)$ (by Urysohn's lemma).  But then
$$\|\varphi(f)\|_\infty=\sup_{y\in Y}|(\operatorname{ev}_y\circ\ \varphi)(f)|=\sup_{y\in Y}|\operatorname{ev}_{\alpha(y)}(f)|=0,$$
and thus $\varphi$ is not injective.


Q: How can I speed up my old computer? I run Ubuntu on an old Dell Dimension 2400 (with only 2d accel.) and it runs really slow when opening up certain programs, like the Ubuntu Software Center.  So I was just wondering if there is any software that can speed it up.  Any response at all is appreciated.

A: You can use some less powerful DE's such as
Xubuntu/XFCE
Xubuntu is lightweight and contains a basic set of applications, Looks similar to gnome-panel .To install it
sudo apt-get install xubuntu-desktop
Lubuntu/LXDE
Lubuntu is very lightweight and is very basic. Resembles gnome-panel . To install it
sudo apt-get install lubuntu-desktop

A: I would use the Xubuntu distro as it has been designed to have a small footprint as far as performance goes.


Q: Frequency Distribution Histogram with Bins with Two Variables on the Y-axis in R I was given this dataframe, which is at the same time a frequency distribution, and was given a task of plotting a histogram  of the age distribution of the whole population adding to the plot the male and female profile. What I need to achieve is a histogram like this one for example: Two-variable frequency bar plot with the male and female profile overlapping, but with the AgeClasses on the x axis. This is my code:
AgeClasses <- c('0-9','10-19','20-29','30-39','40-49', '50-59', '60-69','70-79','80-89', '90-99')
Frequencies <- c(1000,900,800,700,600,500,400,300,200,100)
SexRatioFM <- c(0.4,0.42,0.44,0.48,0.52,0.54,0.55,0.58,0.6,0.65)
df$Females <- c(SexRatioFM*Frequencies)
df$Males <- c(Frequencies-Females)

library(ggplot2)

ggplot(df) +
    geom_bar(mapping = aes(x = AgeClasses, y = Females), stat = "identity")

I would really appreciate your help in solving this task.

A: This type of plot is a stacked bar plot. To produce it most easily with ggplot2, you need to transform your data into long format, so that one column has all the counts for both male and female, and another column contains a factor variable with the labels "Male" and "Female". You can do this using tidyr::pivot_longer:
library(ggplot2)
library(tidyr)

pivot_longer(df, cols = c(Females, Males)) %>%
  ggplot() +
  geom_col(mapping = aes(x = AgeClasses, y = value, fill = name)) +
  labs(x = "Age", y = "Count", fill = "Gender")

A: Try the following code:
AgeClasses <- c('0-9','10-19','20-29','30-39','40-49', '50-59', '60-69','70-79','80-89', '90-99')
Frequencies <- c(1000,900,800,700,600,500,400,300,200,100)
SexRatioFM <- c(0.4,0.42,0.44,0.48,0.52,0.54,0.55,0.58,0.6,0.65)
Females <- SexRatioFM*Frequencies
Males <- Frequencies-Females
df <- data.frame(AgeClasses=AgeClasses, Females=Females, Males=Males)
df <- reshape2::melt(df, id.vars = 'AgeClasses')
library(ggplot2)

ggplot(df) +
  geom_bar(mapping = aes(x = AgeClasses, y = value, fill=variable), stat = "identity")

A: Allan is right, but to make the one in the plot, you need the bars superposed rather than stacked.  I did it like this:

library(ggplot2)
library(dplyr)
AgeClasses <- c('0-9','10-19','20-29','30-39','40-49', '50-59', '60-69','70-79','80-89', '90-99')
Frequencies <- c(1000,900,800,700,600,500,400,300,200,100)
SexRatioFM <- c(0.4,0.42,0.44,0.48,0.52,0.54,0.55,0.58,0.6,0.65)
df <- tibble(
Females = c(SexRatioFM*Frequencies),
Males = c(Frequencies-Females),
AgeClasses = AgeClasses,
Frequencies=Frequencies,
SexRatioFM = SexRatioFM)

df %>% select(AgeClasses, Males, Females) %>%
  tidyr::pivot_longer(cols=c(Males, Females), names_to = "gender", values_to="val") %>%
ggplot() +
  geom_bar(mapping = aes(x = AgeClasses, y=val, fill=gender, alpha=gender), stat="identity", position="identity") +
  scale_alpha_manual(values=c(.5, .4))

A: You'll need to revamp how you create your sample dataframe. Here's one way to do it:
df <- data.frame(
  AgeClasses = c('0-9','10-19','20-29','30-39','40-49', '50-59', '60-69','70-79','80-89', '90-99'),
  Frequencies = c(1000,900,800,700,600,500,400,300,200,100),
  SexRatioFM = c(0.4,0.42,0.44,0.48,0.52,0.54,0.55,0.58,0.6,0.65))

df$Females = df$SexRatioFM*df$Frequencies
df$Males = df$Frequencies-df$Females

library(ggplot2)

ggplot(df) +
  geom_bar(mapping = aes(x = AgeClasses, y = Females), fill="purple", stat = "identity", alpha=.8) +
  geom_bar(mapping = aes(x = AgeClasses, y = Males), fill="navy blue", stat = "identity", alpha=.4)

And you should get something like this:


Q: How can you use Python to fill out HTML forms that also have Javascript? I am making a python program that automatically enters information into a form on a website. I looked at a module called mechanize at first but then I realized that it didn't support javascript. Is there any way to take a piece of information and insert it into a "form" on a website that uses javascript?
The website I am using is www.locationary.com.
If you login and then go to a place/business page like this,
http://www.locationary.com/place/en/US/California/Los_Angeles/Z_Pizza-p1001157911.jsp
then you will see a bunch of spots that need to be filled in. I looked at the page source and this "form" uses javascript. I just need a way to fill in those blanks now. Like I said, I tried mechanize and it didn't work but I also googled it and got nothing.
The "form" uses "onclick"
If you could offer any advice, I would really appreciate it.
Thanks.

A: I think probably the best way to do this is to use a framework that can operate through a browser.  There are several options, but the most pythonic is windmill http://www.getwindmill.com/
I've found it useful on a number of projects.


Q: Flex 4 Combo - using IME I am trying to use ime (for hiragana input) in a flex 4 spark combo.
On creation complete I am setting the following.
cbx_text.textInput.imeMode = IMEConversionMode.JAPANESE_HIRAGANA;

And to check, tracing the following:
trace(cbx_text.textInput.enableIME); returns true;
trace(cbx_text.textInput.imeMode); returns JAPANESE_HIRAGANA;

However, when I select the text input and start to type some text I am unable to switch to hiragana.
I can set it to work on a textinput component with no problems.
<s:TextInput imeMode="JAPANESE_HIRAGANA"></s:TextInput>

Has anyone had any experience with this?
Any insights much appreciated.

A: Although I haven't had any experience with IME, I took a quick look at the documentation : http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/system/IME.html
Can it be that it's not enabled application wise? That, maybe what returns true is only valid for the component you are tracing from?

A: Obvious questions first:
Are you certain the TextInput is a member of cbx_text? I know this seems silly, but it's best to eliminate the obvious first.
Do you have an IME enabled on your computer? For example, do you regularly type in hiragana on your computer and have the appropriate language pack enabled?
Are you sending the IME the string appropriately? IME.setCompositionString() for windows computers?
Does your OS support the use of IMEs? Linux only supports the following methods:

*

*Capabilities.hasIME

*IME.enabled <= Can set or return value.

Try tracing hasIME and see if it's installed. Again, we're shotgunning here – trying to track down any possibility of a problem.
When all else fails, go to the source:

*

*http://livedocs.adobe.com/flex/3/html/help.html?content=18_Client_System_Environment_6.html


Q: Add Custom label in JSQViewMessageViewController iOS I want to add a custom label (with a time stamp) in each cell as well as an image (for warning message) in JSQMessageViewController. I am already using bottomlabel as well as toplabel. But I am unable to get the result I want.
The image is a reference of what I would like it to look like

A: UIImage *bubbleImage = [UIImage imageNamed:@"Commentbox_right.png"];
        UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(textFrame.origin.x-2, textFrame.origin.y-2, textFrame.size.width+4 , textFrame.size.height+7)];
        imgView.image= [bubbleImage stretchableImageWithLeftCapWidth:bubbleImage.size.width/2-5 topCapHeight:bubbleImage.size.height/2];
        [cell addSubview:imgView];
        [cell bringSubviewToFront:txtViewMessage];

        UILabel *lblTimeStamp = [[UILabel alloc]initWithFrame:CGRectMake(textFrame.origin.x+2, imgView.frame.size.height+imgView.frame.origin.y, 90, 10)];
        [lblTimeStamp setText:message.dateTime];//set time here
        [lblTimeStamp setFont:FONT_300_LIGHT(7)];
        [lblTimeStamp setTextColor:GET_COLOR_WITH_RGB(129,129,129, 1)];
        [lblTimeStamp setTextAlignment:NSTextAlignmentLeft];
        [lblTimeStamp setBackgroundColor:[UIColor  clearColor]];
        [cell addSubview:lblTimeStamp];

A: Sorry i didn't get much time to look in to it .. but again you can add that image in same message bubble xib and add constraints according to your need. Try this xib

A: How I add custom Label in JSQMessageviewcontroller is... I declare Label text before ViewDidLoad.
 // Add Text Label
let myLabel: UILabel = {
    let lb = UILabel()
    lb.translatesAutoresizingMaskIntoConstraints = false
    lb.textAlignment = .center
    lb.numberOfLines = 1
    lb.textColor = UIColor.white
    lb.font=UIFont.systemFont(ofSize: 22)
    lb.backgroundColor = UIColor(red: 0.0/255.0, green:70.0/255.0, blue:110.0/255.0, alpha:1)
    lb.text = NSLocalizedString("No Notification", comment: "")

    return lb
}()

And add this code in viewDidiLoad or call anywhere you like.
 self.view.addSubview(myLabel)
 setUpMyLabel()

This is how I add custom label in my app. Hope this will help you. :)


Q: Can not connect to MySQL in a thread in python (fine on main thread) Problem in short: MySQLdb.connect() works on main thread, doesn't work in other threads.
I have a class called Bot with some methods.
something like this:
class Bot():
    def task1():
        read_from_db()
        # some other work
    def task2():
        read_from_db()
        # some other work

and i have a thread class which accepts a Bot object and a task_name and starts the task on the bot object.
class taskThread (threading.Thread):
def __init__(self, bot, task):
    threading.Thread.__init__(self)
    self.bot = bot
    self.task = task
def run(self):
    print "Starting " + self.task + " for " + self.bot.username

    if self.task == "task1":
        self.bot.task1()

    elif self.task == "task2":
        self.bot.task2()
    print "Exiting " + self.task + " for " + self.bot.username

I tried every thing in read_from_db() but it does not work in a thread.
it works fine if i call bot.task1() in main thread but if i create a myThread object and tell it to run task1 it stops exactly on MySQLdb.connect() line with no error. it just stops.
def read_from_db():
        db = MySQLdb.connect(host="localhost",
                        user="root",
                        passwd="",
                        db="db_name",
                        unix_socket="/opt/lampp/var/mysql/mysql.sock")
    db.set_character_set('utf8')

I have searched a lot but i couldn't find anything.
edit: weirdly when the code is stopped right before creating a connection to db, if i press ctrl+c in terminal (where i ran the code) the code resumes and works just as expected.
do anyone know such a behavior ?

A: You have a problem with your def run(self):. You're referencing a task variable that isn't defined. You mean self.task:
# Consider renaming: it's more standard to have `TaskThread`
class taskThread (threading.Thread):
    # Init is fine
    def run(self):
        print "Starting " + self.task + " for " + self.bot.username

        # It used to be just 'task'. Make it self.task
        if self.task == "task1":
            self.bot.task1()

        elif self.task == "task2":
            self.bot.task2()
        print "Exiting " + self.task + " for " + self.bot.username

You also might want to consider:
    def run(self):
        print "Starting " + self.task + " for " + self.bot.username

        action = getattr(self.bot, self.task)
        action()
        print "Exiting " + self.task + " for " + self.bot.username


Q: UML-Designer: Hide labels on associations My first post on stackoverflow, 'hope I do it the right way :-)
I want to create a new entity-relationship-model of our new project.
After a little bit of search I found UMLDesigner. Installation was easy and create this first classes also.
But when I "paint" associations, I got "hundreds" of labels around them.
Have a look into the documentation, I found a way to hide labels, but ...
But
a) I could not select association lables in bulk. The filter works only of the caption of a object and not of the typ (e.g. association vs. class).
Is there a way to only select "associations"?
b) If I hide "a" label of the association, all labels are hidden. What I wanted was to hide only the "end"/role"-labels, but not the name of the association itself
c) Is there a global way to hide/show labels or have I always select a new created object and then hide things?
Question over question, maybe someone can answer them :-)
Ingo

A: Thanks great to see you managed to install it.
Sorry, no it exists no bulk actions on hide you should select one by one the element or decide to hide all.


Q: Method retake in Java I'm developing a project in which i  have a method to know if a JTextField is empty or not, but i was wondering if a way to implement that method just once and send several JTextFields components to check if they are empty or not exists, if so, could you please tell me how?, here's my sample code.
public static void Vacio(JTextField txt){
    if(txt.getText().trim().equals(null)==true){/*Message*/}
}

Also i would like to know if i could improve the method using some Lambda Expressions, beforehand.

A: Use :
 if(txt.getText().trim().length()==0)
    //Do something

Your code will not work because a blank string("") is not a null String. I simply check if the trimmed length() of TextField is 0.
A sample function:
public boolean isEmpty(JTextField jtf)
{
  try{
     jtf.getText();
  }catch(NullPointerException e){return true;}
  if(jtf.getText().trim().length() == 0)
     return true;
  return false;
}

A: Check explicitly for null and then compare with "".
public static void Vacio(JTextField txt){
     String str = null;
    try {
        str = txt.getText();
     }
     catch (NullPointerException npe) {
        System.out.println("The document is null!");
        return;
     }
    if(str.trim().equals("")==true){/*Message*/}
}

A: I cannot imagine how adding Lambda expressions can improve what you're trying to do (?).
Anyway, to check for an empty String I'd probably use:
field.getText().trim().isEmpty()

You don't need to check for null but you do need to catch NullPointerException in the event that the underlying document in the JTextField is null.
For the other part of your quesiton, if you really want to check multiple JTextFields in one method you could pass them as a variable length argument list:
public static void vacio(JTextField... fields) {
    for(JTextField field : fields) {
        try {
            if( field.getText().trim().isEmpty() ) {
                 // do something
            }
        }
        catch(NullPointerException ex) {
            // handle exception (maybe log it?)
        }
    }
}

and call it like:
vacio(field1, field2, field3);

But, generally speaking, keeping functions brief and only doing one thing is usually better than trying to make a function do too much.
One final aside, your method is named Vacio but java naming conventions suggest you should compose method names using mixed case letters, beginning with a lower case letter and starting each subsequent word with an upper case letter.


Q: Open Fragments through App Bar/Toolbar using Navigation component I implemented a bottom navigation view which also handles multiple backstacks using Google's own workaround as given in the architecture components sample ,using the file
private fun setupBottomNavigationBar() {
        val navGraphIds = listOf(
            R.navigation.blog,
            R.navigation.events,
            R.navigation.practice,
            R.navigation.login
        )

        val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottom_nav)
        val controller = bottomNavigationView.setupWithNavController(
            navGraphIds = navGraphIds,
            fragmentManager = supportFragmentManager,
            containerId = R.id.fragment,
            intent = intent
        )

        //use this to setup Action bar

        controller.observe(this) { navController ->
            setupActionBarWithNavController(navController)
        }
        currentNavController = controller
    }

This is how I setup the bottom navigation view. I have an app bar which should open the settings fragment , but so far I have been unable to do so. Any solutions? This is how selecting the options should look like
override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.settings -> TODO()//->should open settings fragment
        }
        return true
    }

I cannot directly navigate to settings as the current architecture has multiple nav graphs and as such it says,
java.lang.IllegalArgumentException: Navigation action/destination com.istemanipal.lumos:id/themeFragment cannot be found from the current destination Destination(com.istemanipal.lumos:id/blogFragment

A: if the id of the menu item is set to the fragment id, you could probably use navigation controller to switch the destination.
override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.settings -> currentNavController.navigate(R.id.navigation_destination_id)
        }
        return true
    }


Q: How do you change the timeout on a flash.net.netconnection? Timeout appears to be about 10 seconds.  Can this be modified?

A: I don't see a built-in way to do it.
However, it's definitely possible to implement on your own.
Just create a transaction class representing each call you make to a NetConnection instance.
This transaction class, for example "NetTransaction", should keep a private static list of all active transactions, and should store the result handler function in a private instance variable that is to be called when a transaction completes (on result, on status, or on timeout).  Note that this handler is unified, so it handles all kinds of results (success/error/timeout/canceled).
In your transaction class's constructor, add "this" new instance to the active transactions list, start a timeout timer if a non-zero timeout is specified (adding an event listener pointing to the cancelTransaction function described below), and then perform the network call last.
When you complete a transaction (success/error/timeout/canceled), remove it from the active transactions list, cancel the timeout timer if one was set, and finally forward a meaningful result to the result handler function.
The trick to making this all work is that you must create result and status handler functions in the transaction class, and pass THOSE to your call to NetConnection.  Those two functions will be responsible for INTERCEPTING the network result (result or status), completing the transaction (as described above), and forwarding a unified result to the REAL result handler function that was passed to the constructor.
Here's the stripped down insides of the base NetTransaction class with the basic necessities.  My implementation has more stuff, including generating transaction ids (just a simple static counter, a method for looking up an active transaction by id number.  It also has overridable get/set methods for the transaction's data object, so I can have automatic header wrapping/unwrapping for custom data protocols in classes deriving from NetTransaction (e.g. WidgetNetTransaction).
static private var active_transactions:Array = new Array(); //active network requests pending a result
static private var transaction_count:int = 0; //incremented each time a NetTransaction instance is created so each one can have a unique transaction id number assigned to it

private var transaction_id:int; //Transaction identifier, which may assist a widget in managing its own concurrent transactions.  It comes from a static field, auto-incremented in the NetTransaction constructor, so it is always unique for each NetTransaction within the current session... unless more than 2147483648 transactions occur in a single session and the value wraps around, but by then, old transactions wil be forgotten and there shouldn't be any problems as a result.
private var description:String; //an optional description string to describe the transaction or what it is supposed to do (especially for error-reporting purposes).
private var request_data:Object; //this stores the data that will be forwarded to your web server
private var result_handler:Function; //this is the method to be called after intercepting a result or status event.  it's left public, because it's acceptable to modifiy it mid-transaction, although I can't think of a good reason to ever do so
private var internal_responder:Responder; //internal responder attached to the transaction
private var timeout:int;
private var timeout_timer:Timer;

//Constructor
public function NetTransaction( network_service:NetworkService, request_data:Object, result_handler:Function = null, description:String = null, timeout:int = 0 )
{
    //Throw something a little more friendly than a null-reference error.
    if (network_service == null)
        throw new ArgumentError( "A NetworkService object must be specified for all NetTransaction objects." );
    if (timeout < 0)
        throw new ArgumentError( "Timeout must be 0 (infinite) or greater to specify the number of milliseconds after which the transaction should be cancelled.\rBe sure to give the transaction enough time to complete normally." );

    //Save information related to the transaction
    this.result_handler = result_handler;
    this.request_data = request_data;
    this.internal_responder = new Responder( net_result, net_status ); //should use override versions of these methods
    this.description = description;
    this.timeout = timeout;
    this.timeout_timer = null;

    //Grab a new transaction id, add the transaction to the list of active transactions, set up a timeout timer, and finally call the service method.
    this.transaction_id = transaction_count++;
    active_transactions.push( this ); //transaction is now registered; this is done BEFORE setting the timeout, and before actually sending it out on the network
    if (timeout > 0) //zero, represents an infinite timeout, so we'll only create and start a timer if there is a non-zero timeout specified
    {
        timeout_timer = new Timer( timeout, 1 );
        timeout_timer.addEventListener( TimerEvent.TIMER, this.cancelTransaction, false, 0, true );
        timeout_timer.start();
    }
    network_service.call( internal_responder, request_data );
}

//Finalizes a transaction by removing it from the active transactions list, and returns true.
//Returns false to indicate that the transaction was already complete, and was not found in the active transactions list.
private function completeTransaction():Boolean
{
    var index:int = active_transactions.indexOf( this );
    if (index > -1)
    {
        active_transactions.splice( index, 1 );
        if (timeout_timer != null)
        {
            timeout_timer.stop();
            timeout_timer.removeEventListener( TimerEvent.TIMER, this.cancelTransaction, false );
        }
        return true;
    }
    else
    {
        //Transaction being removed was already completed or was cancelled
        return false;
    }
}

//An instance version of the static NetTransaction.cancelTransaction function, which automatically passes the transaction instance.
public function cancelTransaction( details_status_object:Object = null )
{
    NetTransaction.cancelTransaction( this, details_status_object );
}

//Cancels all active transactions immediately, forcing all pending transactions to complete immediately with a "NetTransaction.Call.Cancelled" status code.
static public function cancelAllActiveTransactions( details_status_object:Object )
{
    for each (var transaction:NetTransaction in active_transactions)
        transaction.cancelTransaction( details_status_object );
}

//Cancels the transaction by spoofing an error result object to the net_status callback.
static public function cancelTransaction( transaction:NetTransaction, details_status_object:Object )
{
    //Build cancel event status object, containing somewhat standard properties [code,level,description,details,type].
    var status:NetTransactionResultStatus = new NetTransactionResultStatus(
        "NetTransaction.Call.Cancelled",
        "error", //cancelling a transaction makes it incomplete, so the status level should be "error"
        "A network transaction was cancelled.  The description given for the transaction was: " + transaction.description,
        details_status_object, //include, in the details, the status object passed to this method
        "" //no type specified
    );
    //Call the net_status handler directly, passing a dynamic Object-typed version of the NetTransactionResultStatus to the net_status handler.
    transaction.net_status( status.ToObject() );
}

//Result responder.  Override, then call when you're ready to respond to pre-process the object returned to the result_handler.
protected function net_result( result_object:Object ):void
{
    if (completeTransaction())
        if (result_handler != null)
            result_handler.call( null, new NetTransactionResult( this, result_object, null ) );
}

//Status responder.  Override, then call when you're ready to respond to pre-process the object returned to the result_handler.
protected function net_status( status_object:Object ):void
{
    if (completeTransaction())
        if (result_handler != null)
            result_handler.call( null, new NetTransactionResult( this, null, NetTransactionResultStatus.FromObject( status_object ) ) );
}

The NetTransactionResult and NetTransactionResultStatus classes are just simple data classes I've set up for type-safe results to be sent to a unified result handler function.  It interprets results as an error if the NetTransactionResult has a non-null status property, otherwise, it interprets the result as a success and uses the included data.  The NetworkService class you see is just a wrapper around the NetConnection class that handles specifying the call path, and also handles all the low-level NetConnection error events, packages status messages compatible with the NetTransaction class, and finally calls cancelAllTransactions.
The beauty of this setup is that now no matter what kind of error happens, including timeouts, your result handler for a transaction will ALWAYS be called, with all the information you need to handle the result (success/error/timeout/canceled).  This makes using the NetConnection object almost as simple and reliable as calling a local function!

A: Not really. Unless you write your own functionality for aborting after a specified amount of time, using a Timer object (or better, a GCSafeTimer object, if you don't know that one, google it).


Q: Avoid to get "system.indexes" as a collection name in casbah I'm using casbah to find collection names in a mongodb-database
    val mongoClient = MongoClient()
    val db = mongoClient("db_name")
    val coll = db.collectionNames()

It also gives 'system.indexes' because each mongo database has that one. Is there any way to get rid from this ?

A: You have to filter it by yourself.
val coll = db.collectionNames().filterNot(_.startsWith("system."))


Q: Emacs With GUI on mac os. Different keyboard layout key bindings I am using two version of emacs. One in terminal, and other from emacsformacosx.com. In terminal I can use non-English keyboard layout and everything fine. But emacs version with gui don't understands these commands. Why it happening? Why I can't just run terminal version with GUI?
update:
For example when I pressed M-x with non-English keyboard layout in minibuffer appear text - M-ч is undefined. ч is a symbol equal to x. Pressing same shortcut in terminal version of Emacs works fine. Emacs running on other OS haven't this problem. I think to solve it needs to run terminal version with gui and use it. It is impossible. But why?


Q: Finding the posterior distribution of a Bayesian analysis prior I have a prior distribution $f(x)=\pi cos(\pi x) $ where $x$ is the probability of getting tails in a coin toss.
Should a coin toss result in tails, how would this be reflected in the posterior distribution?
Would the posterior distribution simply be $f(x)=\pi cos(\pi/2) $, as $P(x)=1/2$?
Thank you!

A: If your prior is made valid, e.g. as in your comment, $f(x)=\pi/2\sin(\pi x)$, you can find the posterior via Bayes Rule ($D$ denotes your experiment):
$$f(x|D)=\frac{p(D|x)f(x)}{p(D)}\propto p(D|x)f(x)=x\pi/2\sin(\pi x)$$
$p(D|x)=x$ because we have only one toss and it is tails. Finally, we need to normalize this expression by calculating the following integral and dividing the expression by it:
$$Z=\pi/2\int_0^1 x\sin(\pi x)dx\rightarrow f(x|D)=\frac{1}{Z}x\pi/2\sin(\pi x)$$

A: If $f(x)\propto x\,\sin \pi x\Bbb 1_{(0,1)}(x)$, then
$$\int_0^1 x\,\sin \pi x\,\text{d}x=\pi^{-2}\int_0^\pi x\,\sin x\,\text{d}x=\pi^{-2}\underbrace{\left[-x\cos x\right]_0^\pi}_{=\pi-0}+\pi^{-2}\underbrace{\int_0^\pi \cos x\,\text{d}x}_{=0}=\pi^{-1}$$
therefore
$$f(x)=\pi x \sin \pi x$$


Q: How to get the finding links from the post content I need some help in finding links in html code.
  function get_content_link( $content = false, $echo = false ){

  if ( $content === false )
        $content = get_the_content();

   $content = preg_match_all('#[\'"]https?://([^/]+\.)*example.com/[^\'"]*[\'"]#siU', $content, $links );

    $content = $links[1][0];

    if ( empty($content) ) {
        $content = false;
    }

    return $content;
   }

This doesn't work as it should I'm afraid. I don't know what is wrong because have no experience with preg_match.
Any help would be appreciated.
Thanks.

A: This is the answer
To help for all
function get_Example( $content = false, $echo = false ){
    if ( $content === false )
    $content = get_the_content();
    $regexp = '/href=\"https:\/\/example\.com\/([^\"]*)"/i';
    if(preg_match_all($regexp, $content, $link)) {
        $content = $link[1][0];
}
    if ( empty($content) ) {
        $content = false;
    }
    return $content;
}


Q: Trying to reset counter results to zero by clicking button in Python I made a game with python 3.9.5, kivy 2.0.0rc4 and kivymd 0.104.2. I've made counter. It's adding one after "check" button is pressed. Game works smoothly but I want to reset this counter results to zero by clicking "back" button. Because, when I get back to it, I want to start the game from the top. Technically restart the game. Here's my python code:
class Begin(MDFloatLayout):

    def back_on(self):
        self.ids.to_back.source = 'icons/back_pressed.png'
        click = SoundLoader.load('sounds/clickb_effect.wav')
        if click:
            click.play()

    def back_off(self):
        self.ids.to_back.source = 'icons/back.png'
        myapp.screen_manager.transition = SlideTransition(direction='right', duration=.25)
        myapp.screen_manager.current = 'Second'

    def update_score(self, score_one):
        self.ids.score_one.text = score_one

class Begin1After(MDFloatLayout):
    count = -1
    my_text = StringProperty("0")

    def check_on(self):
        self.ids.to_check.source = 'icons/check_pressed.png'
        correct = SoundLoader.load('sounds/correct.wav')
        if correct:
            correct.play()

    def check_off(self, *args):
        self.ids.to_check.source = 'icons/check.png'
        self.count += 1
        self.my_text = str(self.count)
        begin = self.my_text = str(self.count)
        myapp.begin.update_score(begin)

And here's my kivy/kivymd code:
<Begin>:

    Label:
        id: score_one
        text: "0"
        color: 0, 1, 0, 1
        pos_hint: {'x': -.22, 'y': .33}
        font_size: 80
        font_name: 'CursedTimerUlil-Aznm'

    Button:
        size_hint: .1, .11
        pos_hint: {'x': .01, 'y': .9}
        background_color: 0, 0, 0, 0
        on_press: root.back_on()
        on_release: root.back_off()

        Image:
            id: to_back
            source: "icons/back.png"
            allow_stretch: True
            allow_ratio: True
            keep_ratio: True
            size: 160, 160
            center_x: self.parent.center_x
            center_y: self.parent.center_y

<Begin1After>:

    Label:
        text: root.my_text
        pos_hint: {'x': .0, 'y': .35}
        font_size: 100
        bold: True
        color: 0, 20, 0, 1

    Button:
        size_hint: .19, .11
        pos_hint: {'x': .76, 'y': .14}
        background_color: 0, 0, 0, 0
        on_press: root.check_on()
        on_release: root.check_off()

        Image:
            id: to_check
            source: "icons/check.png"
            allow_stretch: True
            allow_ratio: True
            keep_ratio: True
            size: 170, 170
            center_x: self.parent.center_x
            center_y: self.parent.center_y

A: Good day.
1. Reset Function
Create a 'reset' method to contain all the code to revert your game as you might have other attributes to change as well.
2. Callback Method
Create a callback function for your 'back' button. This callback might check for a condition before it calls the 'reset' method. i,e
if game_won: reset()


Q: Ranking users with weekly date period and listing all first ranked users I have a table called coupons with schema below:
CREATE TABLE "public"."coupons" (
   "id" int4 NOT NULL,
    "suprise" bool NOT NULL DEFAULT false,
    "user_id" int4 NOT NULL,
    "start" timestamp NOT NULL,
    "win_price" numeric(8,2) NOT NULL DEFAULT 0::numeric,
    "fold" int4 NOT NULL DEFAULT 3,
    "pay" numeric(8,2) NOT NULL DEFAULT 0::numeric,
    "rate" numeric(8,2) NOT NULL DEFAULT 0::numeric,
    "win" varchar(255) NOT NULL DEFAULT 'H'::character varying COLLATE "default",
    "end" timestamp NOT NULL,
    "win_count" int4 NOT NULL DEFAULT 0,
    "match_count" int4 NOT NULL DEFAULT 0,
    "played" bool NOT NULL DEFAULT false,
    "created_at" timestamp NOT NULL,
    "updated_at" timestamp NOT NULL
)
WITH (OIDS=FALSE);

To rank users over win_price weekly I wrote the query below to get top 5 between 27-07-2015 and 03-08-2015:
SELECT ROW_NUMBER() OVER(ORDER BY sum(win_price) DESC) AS rnk,
       sum(win_price) AS win_price, user_id,
       min(created_at) min_create
FROM coupons
WHERE played = true AND win = 'Y'
AND created_at BETWEEN '27-07-2015' AND '03-08-2015'
GROUP BY user_id
ORDER BY rnk ASC
LIMIT 5;

I'm looking to a new query that lists first ranked users basis on weekly but in given date period.
I.e : for the period between 01-09-2015 and 30-09-2015:

rnk - win_price - user_id - min_create
 1  - 1.52      - 1       - ...........  (first week)
 1  - 10.92     - 2       - ...........  (send week)
 1  - 11.23     - 1       - ...........  (third week and so on)

A: SELECT *
FROM  (
   SELECT date_trunc('week', created_at) AS week
        , rank() OVER (PARTITION BY date_trunc('week', created_at)
                       ORDER BY sum(win_price) DESC NULLS LAST) AS rnk
        , sum(win_price) AS win_price
        , user_id
        , min(created_at) min_create
   FROM   coupons
   WHERE  played = true
   AND    win = 'Y' AND created_at BETWEEN '27-07-2015' AND '03-08-2015'
   GROUP  BY 1, 4  -- reference to 1st & 4th column
   ) sub
WHERE  rnk = 1
ORDER  BY week;

This returns the winning users per week - the ones with the greatest sum(win_price).
I use rank() instead of row_number(), since you did not define a tiebreaker for multiple winners per week.
The added clause NULLS LAST prevents NULL values from sorting on top in descending order (DESC) - if you should have NULL. See:

*

*Sort by column ASC, but NULL values first?
The week is represented by the starting timestamp, you can format that any way you like with to_char().
The key feature of this query: you can use window functions over aggregate functions. See:

*

*Postgres window function and group by exception
Consider the sequence of events in a SELECT query:

*

*Best way to get result count before LIMIT was applied


Q: OData [JsonConverter] attribute serialization I am trying to use the default .Net serialization methods when serving OData via EntitySetController.
When using:
[DataContract]
public class TestClassA
{
    public int Id { get; set; }
    public string Stam { get; set; }
    [DataMember]
    public TestClassB TestClassB { get; set; }
}

public class TestClassB
{
    public int Ids { get; set; }
    public string Name { get; set; }
}

The result of calling GET
{
 "odata.metadata":"http://**MyHost**/odata/$metadata#TestClassA","value":[
     {
    "TestClassB":{
      "Ids":110,"Name":"Bla"
    }
   }
  ]
 }

Which works great with the DataContract Attributes.
However, when trying to use the [JsonConverter] attribute:
public class TestClassA
{
    public int Id { get; set; }
    public string Stam { get; set; }
    [JsonConverter(typeof(MyFormatter))]
    [DataMember(EmitDefaultValue = false)]
    public TestClassB TestClassB { get; set; }
}

public class TestClassB
{
    public int Ids { get; set; }
    public string Name { get; set; }
}

public class MyFormatter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override bool CanConvert(Type objectType)
    {
        throw new NotImplementedException();
    }
}

The JsonConverter is completely ignored. (the MyFormatter class is never created).
Any idea how to make it work?


Q: How to pass properties to a method in another namespace I have defined some settings and plan on defining many more in my VS 2008 C# WPF project.  I am aware that settings can be specified in the project through the settings designer at design time.  I am also aware that the settings can be retrieved and set during run time.  What I would like to do though is be able to access the settings from other assemblies and projects.
I don't understand how this can be done without writing a new class.  Since the settings class is defined in my root namespace, I can't access the settings directly from other assemblies without creating a circular reference (which is what happens if you try to add a reference to a project that is already referencing that project).  Is there a way to pass the properties without having to create a duplicate class with the exact same property definitions?

A: I understand you're trying to read properties from an assembly that you did not reference in your project. In that case, reflection is the answer.
Read the info from that assembly, wherever the dll is. Load the Settings class, get the Default settings, and access the parameter you want.
As an example, I have a dll called se2.dll, with a parameter that I'd normally access as:
string parameterValue = se2.Settings2.Default.MyParameter;

Now, from a different project, I have to use reflection like this:
// load assembly
 System.Reflection.Assembly ass = System.Reflection.Assembly.LoadFrom(@"M:\Programming\se2\se2\bin\Debug\se2.exe");
// load Settings2 class and default object
Type settingsType = ass.GetType("se2.Settings2");
System.Reflection.PropertyInfo defaultProperty = settingsType.GetProperty("Default");
object defaultObject = defaultProperty.GetValue(settingsType, null);
// invoke the MyParameter property from the default settings
System.Reflection.PropertyInfo parameterProperty = settingsType.GetProperty("MyParameter");
string parameterValue = (string)parameterProperty.GetValue(defaultObject, null);


Q: Is there a way of Creating lnk file using javascript mslink.sh As per this link
Is there a way of Creating lnk file using javascript
I am trying to create a .lnk file.
I would like to know how to set the property Start In, which is a folder location of the .lnk file
and also the .lnk file that I am trying to create has additional parameters in the Target property.
Ex : Expected .lnk file properties
Target : "C:\Windows\System32\Calc.exe" /mode:QWE /role:Admin
Start In : C:\Windows\System32\
Is there a way of Creating lnk file using javascript

A: You can use the WScript.Shell function CreateShortcut
var objShell = new ActiveXObject("WScript.Shell")
var lnk = objShell.CreateShortcut("C:\\my_shortcut.lnk")

lnk.TargetPath = "C:\\Windows\\System32\\Calc.exe";
lnk.Arguments = "/mode:QWE /role:Admin";
lnk.Description = "Your description here...";
lnk.IconLocation = "C:\\Windows\\System32\\Calc.exe, 0";
lnk.WorkingDirectory = "C:\\Windows\\System32";
lnk.Save();


Q: Brower cache issue for animated GIF loader image I am displaying animated GIF image as loader in the web page using below code. It's working fine. Loader image has animation which plays for 3 seconds and then stops and stays non-animated.
<style>
    .content {display:none;}
    .loader {
        position: fixed;
        left: 0px;
        top: 0px;
        width: 100%;
        height: 100%;
        z-index: 9999;
        background: url('../images/loader.gif?random=323527528432525.24234') 50% 50% no-repeat rgb(0,0,0, 0.90); }
</style>
<script>
    setTimeout(function(){
        $('.loader').css('display', 'none');
    }, 5000);
</script>

Now, when page is loaded first time or reloaded using CTRL+F5, animated GIF is displaying from start to end. For rest of the time, whenever page is refreshed, it just shows non-animated part of the loader image due to browser's caching.
To resolve caching issue, I have tried following things but no one is working.
#1 - I have attached random number as a query string after image name shown as below.
background: url('../images/loader.gif?random=1234.5678')

#2 - HTML headers to not to cache pages are mentioned as below:
<meta http-equiv="Cache-control" content="no-cache">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="-1">

Am I missing something more or else? Or is it not caching issue? Please advise.


Q: Web API Serialize/Deserialize Derived types I have a Web API that returns a list of objects, when the client passes Accept application/json I want my globally registered json formatter to include TypeNameHandling for the derived types during serialization. However this doesn't work and I can't see why this shouldn't work ?
My objects
public class BaseClass
{
    public int Id { get; set; }
}

public class SubClass : BaseClass
{
    public string SubClassProp { get; set; }
}

public class SubClassA : SubClass
{
    public string SubClassAProp { get; set; }
}

public class SubClassB : SubClass
{
   public string SubClassBProp { get; set; }
}

WebApiConfig
public static void Register(HttpConfiguration config)
{
   var formatters = GlobalConfiguration.Configuration.Formatters;
   var jsonFormatter = formatters.JsonFormatter;
   var settings = jsonFormatter.SerializerSettings;
   settings.Formatting = Formatting.Indented;
   settings.NullValueHandling = NullValueHandling.Ignore;
   settings.TypeNameHandling = TypeNameHandling.Auto;
}

Web API Controller
public class MyController : ApiController
{
    [HttpGet]
    public async Task<IList<BaseClass>> GetClasses()
    {
       return new List<BaseClass>
              {
                 new SubClassA
                 {
                    Id = 1,
                    SubClassProp = "SubClass",
                    SubClassAProp = "SubClassAProp"
                 },
                 new SubClassB
                 {
                    Id = 2,
                    SubClassProp = "SubClass",
                    SubClassBProp = "SubClassBProp"
                 }
              };
    }
}

Call from API Client in same solution
var client = new HttpClient() { BaseAddress = new Uri("uri goes here...")}
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

var resp = await client.GetAsync("uri goes here..."));
var jsonContent = await resp.Content.ReadAsStringAsync();

var ListOfClasses = JsonConvert.DeserializeObject<IList<BaseClass>>(jsonContent, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto });

I'am expecting to get one element which is SubClassA and one that is SubClassB, but both is BaseClass ?
I also want it to be possible to Deserialize json to object in Post method.
And this should be possible for both json and xml


Q: Flutter add round app icon for android in VSCode I added app-icons to my app for both iOS and Android. I watched this Tutorial and it is working so far. But the problem I have is that my Android Icon looks like this at the moment:

But the icon should fill the circle. In the tutorial it is shown how you can do it in Android Studio, but I am using VSCode.
I tried searching for it but couldn't find anything..
How can I get this done?
By the way, I am not using flutter_launcher_icons .

A: It seems that you can't do it from vs code, it has to be done in android studio...
I have searched for an answer as well as I was stuck with this and ended up doing it in android studio.
If someone has a solution please share.

A: Flutter has its own default icon for every app in its Android and Ios folder so there are few steps that I would like to show to change the app icon.
Head over to https://appicon.co/ and generate your own icon using icon image (the zip file contains two main folders android and Assets.xcassets)
For android: Go inside android\app\src\main\res in your flutter app and there paste the android folder content.
For IOS: Go inside ios\Runner in your flutter app and there paste the Assets.xcassets content
Restart your emulator or rebuild your application


Q: how to convert string object to json object in javascript I have changed data in string format where it was like [object object] but I want to change the string object into json object I tried json.parse but it not changing into json object
can you please suggest me where I am doing wrong and how to fix this
try {
  var timekeep = await Orders.findAndCountAll({
    where: {
      cid: orders_info.cid,
    },
    order: [
      ['id', 'DESC']
    ],
    limit: 1,
    raw: true,
  });
  var cont1 = JSON.stringify(timekeep.rows[0]);
  var obj = JSON.parse(cont1);
} catch (err) {
  console.log(err)
}

console.log('org data' + timekeep)
console.log('data as string' + cont1);

// now when I am trying to print
console.log('data as json' + obj);

the output of the console.logs
org data [object Object]

data as sttring{"id":4006,"mid":1,"cid":41,"wid":7138,"oid":null,"status":null,"options":null,"starttime":"2018-08-15T06:08:55.000Z","duration":null,"ordertotal":50,"counter":null,"closetime":null}

data as json [object object]

A: From what I can see you are already converting it to a JSON with var obj = JSON.parse(cont1);
So you already have a JSON, it's just that how you're printing it is wrong. To it with a comma instead of +.
console.log('data as json', obj)

The + is doing a string concatenation, and it's attempting to concatenate a string with an object

A: After String concat it prints data as json [object object]. if you put , instead of + will print that object correctly. In the snippet, you can see the difference.

var jsonstr = '{"id":4006,"mid":1,"cid":41,"wid":7138,"oid":null,"status":null,"options":null,"starttime":"2018-08-15T06:08:55.000Z","duration":null,"ordertotal":50,"counter":null,"closetime":null}';

console.log(JSON.parse(jsonstr));

console.log('data as json' , JSON.parse(jsonstr));

console.log('data as json' + JSON.parse(jsonstr));

A: console.log just the object;
if you want log object and a string use , instead of +

jsonString = '{"key1":"value1","key2":"value2"}'

jsonObject = JSON.parse(jsonString)

console.log(jsonObject) // logging just the object

console.log('jsonObjectName' , jsonObject) // logging object with string

console.log('jsonObject.key1 : ' +  jsonObject.key1 )

// this may come handy with certain IE versions
function parseJSON(resp){
    if (typeof resp === 'string')
        resp = JSON.parse(resp);
    else
        resp = eval(resp);
    return resp;
}