text:
Q: Understanding quotient groups Admittedly this will be probably be a naive question, but here it goes:
Is it possible to flesh out in simple terms, for someone with little background in group theory, what it means to take the quotient group of $\mathbb{R}$ or $\mathbb{C}$ by a lattice $\Lambda$ or by $\mathbb Z$? How to evaluate this quotient? As in what comes out?
More precise examples:

*

*If $\Lambda$ is a lattice spanned by linearly independent primitive vectors $\mathbf{a}_1$ and $\mathbf{a}_2,$ then how to interpret the quotient: $\mathbb C /\Lambda?$

*Another example: the circle $S^1$ can be identified with the quotient $\mathbb R/2\pi\mathbb Z,$ but I fail to make this identification myself. Any help is much appreciated here.

A: You can think of a quotient as glueing things together. If you quotient out by $\Lambda$ then you consider every point that differs by an element of $\Lambda$ to be the same, i.e. glued together.
A simple example is modular arithmetic: $[0]_5=\{0, \pm 5, \pm 10, \pm 15\,\ldots\}$ are all the same, modulo five. They form the same residue class $[0]_5$. In terms of a quotient, this residue class is $\mathbb Z / 5\mathbb Z$.
In the case of $\mathbb C/\Lambda$ consider all points in $\mathbb C$, that differ only by an element of $\Lambda$, to be the same/glued. I assume your lattice is given by integer multiples of the complex numbers $u$ and $v$.
That means $\Lambda = \{\lambda u + \mu v : \lambda,\mu \in \mathbb Z \}$.
Let the elements of $\mathbb C$ that differ from $z \in \mathbb C$ by addition of an element of $\Lambda$ by $[z]$. We have
$$[z] = \{ z+ \lambda u + \mu v : \lambda,\mu \in \mathbb Z \}$$
In modular notation, $w \in [z]$ if, and only if, $w \equiv z \bmod \Lambda$.
The set $[z]$ forms a single element of the quotient $\mathbb C/\Lambda$. You'll After a while, you can convince yourself that $\mathbb C/\Lambda = \{ [\lambda u + \mu v] : 0 \le \lambda , \mu < 1 \}$.

A: The quotient $\mathbb{C}/\Lambda$ is a complex torus (see the picture for it on page $4$ here); and the group is isomorphic to the group $E(\mathbb{C})$ of an elliptic curve $E$. The isomorphism is given by $(x,y)\mapsto (\wp(z),\wp'(z))$, for the Weierstrass $\wp$-function, with the elliptic curve equation
$$
\wp'(z)^2=4\wp(z)^3-g_2\wp(z)-g_3.
$$
Hence quotients $\mathbb{C}/\Lambda$  are tori, and tori are elliptic curves over $\mathbb{C}$.

A: It may help you to consider some examples of quotient groups that you are already comfortable in working with:

$\mathbb Z/n\mathbb Z$

The set of integers $\mathbb Z$ forms a group under addition. It contains a subgroup $n\mathbb Z=\{nk:k\in\mathbb Z\}$ consisting of the elements of $\mathbb Z$ that are divisible by $n$.
The quotient group is the set of cosets
$$\{n\mathbb Z, 1+n\mathbb Z, 2+n\mathbb Z,\ldots,(n-1)+n\mathbb Z\}$$
where $m+n\mathbb Z =\{m+nk:k\in\mathbb Z\}$, which is a group under the operation inherited from $\mathbb Z$:
$$(a+n\mathbb Z)+(b+n\mathbb Z) = (a+b)+n\mathbb Z$$
where you should notice that if $a+b\in n\mathbb Z$, then $(a+b)+n\mathbb Z = n\mathbb Z$.
This group is exactly the group of integers modulo $n$: write
$$a\equiv b\pmod n$$
if and only if $n\mid(b-a)$. Then the map sending $a+n\mathbb Z$ to $a\pmod n$ is an isomorphism.

$\mathbb R/\mathbb Z$

Let $[\cdot]:\mathbb R\to [0,1)$ be the map which sends a real number $x$ to its decimal part (e.g. $231.35642\mapsto 0.34642$).
If $x,y\in \mathbb R$, then it is easy to check that $$[x]+[y]=[x+y]$$
so that in particular, $[\cdot]$ defines a group structure on $[0,1)$.
You should check that with this group structure, $[0,1)\cong \mathbb R/\mathbb Z$. $\mathbb R/\mathbb Z$ is therefore the group of real numbers where we consider two numbers as the same if they differ by an integer.
An important observation is that there is an isomorphism between $[0,1)$ and the unit circle in $S^1\subset\mathbb C^\times$ (both are groups under multiplication) given by
$$[0,1)\to S^1 \\ x\mapsto e^{2\pi ix}$$
So $\mathbb R/\mathbb Z\cong S^1$, and can be viewed as a unit line in $\mathbb R$, where the two ends are glued together.
The quotient $\mathbb C/(\mathbb Z+\mathbb Zi)$ is a two-dimensional analgoue of this: it is a unit square in $\mathbb R^2$ with opposite sides glued together - or a torus $S^1\times S^1$

and $\mathbb C/\mathbb Z$ can be defined similarly for a general lattice.


text:
Q: Ошибка ValueError при int(input()), хотя ввожу цифры! Ошибка ValueError при int(input()), хотя ввожу цифры!!!
КОД:
'''
a = int(input())
b = int(input())
c = int(input())

'''
ВЫДАЁТ:
'''
1
2
Traceback (most recent call last):
  File "C:/Users/User/PycharmProjects/pythonProject1/venv/Изучаем Python /2,3.py", line 2, in <module>
    b = int(input())
ValueError: invalid literal for int() with base 10: ''

Process finished with exit code 1

'''

redpajama_set_name: RedPajamaStackExchange


text:
Q: Evaluate $\int_{0}^\infty \sin\left(\frac{1}{x}\right)\sin\left(x^2\right)\,dx$ I don't really have much a reason for giving this question other than curiosity. I am looking to evaluate
$$\int_{0}^\infty \sin\left(\frac{1}{x}\right)\sin\left(x^2\right)\,dx$$
Using the complex definition of $\sin(x)$ doesn't seem to work, nor can I give a reasonable differentiating under the integral sign. Also, it doesn't seem Wolfram Alpha has a closed answer, but I would be curious to see if there is one.

A: This is too long for a comment.
Just out of curiosity, I used a CAS to see what could be the result of
$$I_{p,q}=\int_{0}^\infty \sin(\frac{1}{x^p})\sin(x^q)dx$$ and observed (for limited ranges of $p$ and $q$) that, if $p\neq q$, the result is either a Meijer G-function (as Phoenix already commented) or a nasty linear combination of hypergoemetric functions.
To my surprise, the very first cases where $p=q$ leads to quite simple results
$$I_{1,1}=\frac{\pi  }{2}J_1(2)$$
$$I_{2,2}=\frac{1}{4} \sqrt{\frac{\pi }{2}} \left(\frac{1}{e^2}+\sin (2)-\cos (2)\right)$$
$$I_{3,3}=\frac{1}{6} \left(\pi  \left(J_{\frac{1}{3}}(2)-J_{-\frac{1}{3}}(2)\right)+\sqrt{3}
   K_{\frac{1}{3}}(2)\right)$$
$$I_{4,4}=-\frac{\sqrt{2+\sqrt{2}}}{16}  \left(\sqrt{2} \pi
   \left(J_{-\frac{1}{4}}(2)-J_{\frac{1}{4}}(2)\right)-2 K_{\frac{1}{4}}(2)\right)$$ where appear Bessel functions.

A: $\int_0^\infty\sin\dfrac{1}{x}\sin x^2~dx$
$=\int_0^\infty\sum\limits_{n=0}^\infty\dfrac{(-1)^n\sin x^2}{(2n+1)!x^{2n+1}}~dx$
$=\int_0^\infty\sum\limits_{n=0}^\infty\dfrac{(-1)^n\sin x}{(2n+1)!(\sqrt x)^{2n+1}}~d(\sqrt x)$
$=\int_0^\infty\sum\limits_{n=0}^\infty\dfrac{(-1)^n\sin x}{2(2n+1)!x^{n+1}}~dx$
$=\sum\limits_{n=0}^\infty\dfrac{(-1)^{n+1}(n+1)!\sin\dfrac{n\pi}{2}}{2(2n+1)!}$ (according to http://eqworld.ipmnet.ru/en/auxiliary/inttrans/FourSin2.pdf)
$=\sum\limits_{n=0}^\infty\dfrac{(-1)^{n+1}(n+1)\sin\dfrac{n\pi}{2}}{2^{2n+1}\left(\dfrac{3}{2}\right)_n}$ (according to http://mathworld.wolfram.com/PochhammerSymbol.html)
$=\sum\limits_{n=0}^\infty\dfrac{(-1)^{n+1}(2n+2)}{2^{4n+3}\left(\dfrac{3}{2}\right)_{2n+1}}$


text:
Q: How to avoid dropping schemas when publishing DB in VS 2019 Database project When publishing a database from Visual Studio, there are several options to "do not drop" an object if it is not in the Source. However, it seems that there is no option to avoid dropping schemas. Do anyone know if this is possible to achieve, or do I have to manually edit the publish script?

A: It would probably be simplest just to add the schema to the project. The script would be simple enough, we use:

CREATE SCHEMA [api]
AUTHORIZATION [dbo];

(Also, I wish I'd seen this question much earlier, hopefully this isn't too late to help someone.)


text:
Q: NSURLSessionDownloadTask cancelByProducingResumeData return null I use NSURLSessionDownloadTask to download a file from server, it is run in a background session. I want to save resume data to resume the download when the app is terminated. However, the call of cancelByProducingResumeData always returns null. I cannot figure out the issue, cause I used to do a sample of resumable download task successful before. Does anybody get the same issue?

A: Do you know if the request satisfies the criteria outlined in the documentation for the cancelByProducingResumeData method?

A download can be resumed only if the following conditions are met:

*

*The resource has not changed since you first requested it

*The task is an HTTP or HTTPS GET request

*The server provides either the ETag or Last-Modified header (or both) in its response

*The server supports byte-range requests

*The temporary file hasn't been deleted by the system in response to disk space pressure


text:
Q: Link from Thumbnail to Post not working i am trying to link my posts thumbnail to the post that it is pulling, however its not coming through as a link :S
<?php
    $carouselPosts = new WP_Query();
    $carouselPosts->query('showposts=3');
    ?>
    <?php while ($carouselPosts->have_posts()) : $carouselPosts->the_post(); ?>
    <a href="<?php the_permalink(); ?>">
<?php the_post_thumbnail(array(70,70)); ?>

<?php the_excerpt(); ?>

    <?php endwhile; ?>

I put the wrap round the actual div, is this the correct way to do this?
thanks

A: You probably have more than one query in your page, let's make sure we are working with this query:
<?php
    $carouselPosts = new WP_Query();
    $carouselPosts->query('showposts=3');
    // checking if there are posts to show
    if($carouselPosts->posts){
       foreach ($carouselPosts->posts as $carouselPost) {
        echo 'ID). '">';
        echo '
';
          echo get_the_post_thumbnail($carouselPost->ID,array(70,70));
        echo '
';
        echo '';
        $excerpt = get_the_excerpt();
        if($excerpt)
             echo '
'. $excerpt .'
';
        echo '

';
      }
    }


text:
Q: How to parse JSON strings with single quotes (') in Ruby? I am trying to parse a JSON String like this:
JSON.parse("{'foo' : 42 }")

However, this yields a JSON::ParseError:
JSON::ParserError: 757: unexpected token at '{'foo' : 42 }'
    from /Users/nils/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/json/common.rb:155:in `parse'
    from /Users/nils/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/json/common.rb:155:in `parse'
    from (irb):2
    from /Users/nils/.rvm/rubies/ruby-2.1.2/bin/irb:11:in `<main>'

I think it expects the ' character to be a " character. Since I have multiple gigabytes of such files I would like to make the parser work with this. Since some of the values may also include ' characters I can't simply run search and replace over them because that may destroy the original content.
Any suggestions on how to make the JSON parser parse this?

A:
I am trying to parse a JSON String like this:
JSON.parse("{'foo' : 42 }")

That's not a JSON string.

However, this yields a JSON::ParseError:

Which is correct, since the string is not JSON.

Any suggestions on how to make the JSON parser parse this?

You cannot parse this with a JSON parser because it's not JSON.
You need to figure out what language it is, and then use a parser for that language.
The snippet you posted looks like YAML, but of course that could just be accidental.
require 'yaml'

YAML.load("{'foo' : 42 }")
# => { "foo" => 42 }

But note that trying to guess the language from one single, short example is highly error-prone. You should confer with the producer of that serialization and ask them what language it is.


text:
Q: how can i get this script to run without user input I'm trying to make this batch script automatic. The drive letter changes and i cant find a way in window to force it to use the same one each time. im not using the %date% environment variable because i need the date format to be like this: "YYYY_MM_DD"
Is there any way I can i get this script to run without user input?
    @echo off
    set /p "Drive_Letter=Enter Drive letter.>"
    set /p "BKDate=Enter date.>"
    cd\
    %Drive_Letter%:
    cd %Drive_Letter%:\Backup\
    md BK_%BKDate%
    cd\
    Robocopy /E c:\users\%username%\Dropbox\ %Drive_Letter%:\Backup\BK_%BKDate% *
    cd %Drive_Letter%:\Backup
    dir /s %Drive_Letter%:\Backup\BK_%BKDate%% >> LOG_%BKDate%.txt

A: This should do want you want.
@echo off
Z:
cd Z:\Backup\
Rem Get Day,Mth & Year from %Date%
set Day=%Date:~0,2%
set Mth=%Date:~3,2%
set Yr=%Date:~6,4%
md BK_%Yr%_%Mth%_%Day%

Robocopy /E %userprofile%\Dropbox\ Z:\Backup\BK_%Day%_%Mth%_%Yr% *

dir /s Z:\Backup\BK_%Yr%_%Mth%_%Day%% >> LOG_%Yr%_%Mth%_%Day%.txt

This Link will show you how to force the USB to use the same drive letter each time it is connected

A: This uses:
robocopy inside a subroutine to get the current date (an error is forced to get the time stamp of the error in yyyy/mm/dd format)
mountvol to enumerate the defined drives
vol to test drive accesibility
It will search for a "flag" folder (the backup folder) in the drives to determine which to use
Once all the information is retrived, the adecuated robocopy command is used.
@echo off
    setlocal enableextensions disabledelayedexpansion

    call :getDriveLetter "\Backup\bk*" drive
    if errorlevel 1 (
        echo Drive not found
        goto :eof
    )

    call :getTodayDate   today
    if errorlevel 1 (
        echo Date retrieval error
        goto :eof
    )

    set "BKDate=%today:/=_%"
    set "source=c:\users\%username%\Dropbox"
    set "target=%drive%:\Backup\BK_%BKDate%"

    robocopy "%source%" "%target%" /e
    dir /s "%target%" > "%drive%:\Backup\LOG_%BKDate%.txt"

    endlocal
    exit /b

:getTodayDate returnVar
    set "%~1=" & for /f %%a in (
        'robocopy "|" "." "%~nx0" /njh /r:0 /nocopy /l'
    ) do set "%~1=%%a" & exit /b 0
    exit /b 1

:getDriveLetter folderToTest returnVar
    set "%~2=" & for /f "tokens=1 delims=: " %%a in (
        'mountvol ^| find ":\"'
    ) do vol %%a: >nul 2>&1 && (if exist "%%a:%~1" set "%~2=%%a" & exit /b 0)
    exit /b 1


text:
Q: openFileOutput FileNotFoundException This is my noob question for the week. I'm looking more for general speculation than specific code and maybe hoping the Android folks are watching and could correct this:
the SDK documentation for Context.openFileOutput says:

Open a private file associated with this Context's application package for writing. Creates the file if it doesn't already exist.

Ok, that sounds good. I can create a file. Except this method also throws a FileNotFoundException, so apparently something is amiss. Why would a function that is supposed to create a file if it's not found throw an exception if the file is not found???
Kinda defeats that whole "Creates the file..." thing, doesn't it?

A: I have to apologize for leaping before I looked on this one. I kinda panicked while reading the documentation. After some testing, I found that openFileOutput() does, in fact, work as advertised and will create a file if it's not found, not just throw an FnF exception as I feared. Apparently, the FnF throw was added in case the Activity's application directory does not exist.
Again, my apologies but hopefully, this might help others who are confused by the documentation.

A: FileNotFoundException is an exception thrown in case that you are trying to write to a file that does not exist, or cannot be currently accessed. When else would this occur?

*

*Perhaps you forgot to close the file, and tried to open the same file.

*Perhaps you tried to create multiple FileOutputStream objects pointing to the same file.

These will result in a FileNotFoundException.
Anyway, you can insert a throws FileNotFoundException at the end of your function declaration where you call openFileOutput (and to other functions that call this function).

A: Possibly also thrown if you use MODE_APPEND, which appends to an existing file and the file doesn't exist.

A: Have you inserted the right Permission?
see http://developer.android.com/reference/android/Manifest.permission.html
for reference.
i think
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

could be the one You are fine with


text:
Q: UICollection View reloadData() not working I have a problem of reloadData() not working for my collection view. I have three collection views and I have used this code to attempt to reload the data everytime the view is opened.
override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    self.newArrivalsCollectionView.reloadData()
    self.recommendedTitleCollectionView.reloadData()
    self.popularTitlesCollectionVIew.reloadData()
}

The problem is that at first, the collection views display the correct number of cells and the image (it has a UIImage inside the cell). However, when I press the button to go back to the view with these collection views. It apparently reuses the cells and creates more of the same cell. I have attempted to reload the data in the collection view function that creates these cell however it creates an error.
EDIT:
I have set the view controller as the Data Source & Delegate for all 3 view controllers under the viewDidLoad() method. Also, the cells are interactive, when touched they should do something (ie. go to another view), so it shouldn't just hide the unwanted reused cells but remove them completely.
I also realised every-time I reopen the view, it would add the same number of cells to the current number of cells. For example, if originally, the collection view has 2 different cells, it would recreate those 2 cells, and now there would be 4 cells of the same 2 types of cells. If I do this again, there would be 6 cells of the same 2 types of cells. I reckon that it was with my array of books, so I tried setting it empty in viewDidAppear() method, however, it still doesn't work.
Other Following Codes:
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    if collectionView == newArrivalsCollectionView {
        return bookNewArrivalDataBase.count
    }
    else if collectionView == popularTitlesCollectionVIew
    {
        return bookPopularDatabase.count
    }
    else {
        return bookRecommendedDatabase.count
    }
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    //if it is a new arrival

    if collectionView == newArrivalsCollectionView{

    let newArrivalsCell = collectionView.dequeueReusableCell(withReuseIdentifier: "newArrivalsCell", for: indexPath) as! bookNewArrivalsCollectionViewCell

    //sets the book that is being displayed
    let bookCell = bookNewArrivalDataBase[indexPath.row]

    // set the photo of the book that the new arrival cell is at
    newArrivalsCell.setBookImage(bookCell)

    return newArrivalsCell
    }

else if collectionView == popularTitlesCollectionVIew {

    let popularTitlesCell = collectionView.dequeueReusableCell(withReuseIdentifier: "popularTitlesCell", for: indexPath) as! bookPopularTitlesCollectionViewCell

    //sets the book that is being displayed
    let bookCell = bookPopularDatabase[indexPath.row]

    // set the photo of the book that the new arrival cell is at
    popularTitlesCell.setBookImage(bookCell)
    return popularTitlesCell

    }
    else {

        //create recommended title cell
        let recommendedTitlesCell = collectionView.dequeueReusableCell(withReuseIdentifier: "recommendedTitlesCell", for: indexPath) as! bookRecommendedTitlesCollectionViewCell

        let bookCell = bookRecommendedDatabase[indexPath.row]

        // set the photo of the book
        recommendedTitlesCell.setBookImage(bookCell)

        return recommendedTitlesCell
    }

} // end of cellforitemat

So, how can I reload the collection view everytime the view appears again so that it would not reuse the cells originally loaded at the first time the view appears?

A: I resolved my own problem as it lies in the array database itself and not the collection view being unable to reload the data. Apparently, I just had to reset the database every time.
The key learning point is

Similar collection view cells does not necessarily mean that it is duplicating previous ones.

A: The problem seems with your delegate methods of collection view :
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return number
}

func register(AnyClass?, forCellWithReuseIdentifier: String)

func cellForItem(at: IndexPath)

Fixing the methods will solve the issue else try using prepareForReuse() method in your cell class and set values to nil of the imageview image .ex :
override func prepareForReuse() {
    super.prepareForReuse()
    imageview.image = nil

}

A: You have to all reload data put into
DispatchQueue.main.async{
      // your function to reloadData
}


text:
Q: How to create multiple code behind file for .aspx page I have a situation where I need to create multiple code behind files for a single .aspx page in c# asp.net. Actually I have a web form on that huge coding is done and I need multiple developer's working on it simultaneously. How can I achieve the same?
Here is the code snippet I tried
Class 1 MyPartialClass.cs
namespace WebApplication1
{
    public partial class Default : System.Web.UI.Page
    {
        protected void PrintText(string pt)
        {
            Response.Write(pt);
            //lblTest.Text = pt;    //Can not access this label in partial class.
        }
    }
}

Class 2 which is Default.aspx.cs
namespace WebApplication1
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            PrintText("Hello World");
        }
    }
}

and my HTML source
<%@ Page Language="C#" AutoEventWireup="false" CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="lblTest" runat="server"></asp:Label>
    </div>
    </form>
</body>
</html>

A: ASP.NET will always generate your code behind files as partial classes
namespace WebApplication1
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
    }
}

You can therefor separate the code behind in different files, if you pertain the definition as partial and keep the class under the same namespace.
Edit : The Web Project
//Default.aspx
<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master"     AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:Label ID="lblTest" runat="server" Text="Label"></asp:Label>
</asp:Content>

//Default.aspx.cs
namespace WebApplication1
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            PrintText("Hello World");
        }
    }
}

//MyPartialClass.cs
namespace WebApplication1
{
    public partial class Default
    {
        protected void PrintText(string pt)
        {
            Response.Write(pt);
            lblTest.Text = pt;    //lblTest is accessible here
        }
    }
}

I haven't modified any other generated files. One thing I like to mention is that the Default.aspx.cs file that has been generated was generated with the class name "_Default". I have changed it to Default and Visual Studio refactored the change across all files that contain a definition for that class, except the Default.aspx file, where I had to manually modifiy from Inherits="WebApplication1._Default" to Inherits="WebApplication1.Default".
Edit 2:
I kept searching the internet, and according to http://codeverge.com/asp.net.web-forms/partial-classes-for-code-behind/371053, what you are trying to do is impossible. Same idea is detailed at http://codeverge.com/asp.net.web-forms/using-partial-classes-to-have-multiple-code/377575
If possible, consider converting from Web Site to Web Application, which supports what you are trying to achieve. Here is a walkthrough on how to perform this conversion: http://msdn.microsoft.com/en-us/library/vstudio/aa983476(v=vs.100).aspx

A: You need to set up a source safe server in order to that, like Team Foundation Server.

A: You can easily just add partial classes to your code.
http://www.codeproject.com/Articles/709273/Partial-Classes-in-Csharp-With-Real-Example


text:
Q: R ggplot: Change Grouped Boxplot Median line I have plotted grouped boxplots and now I would like to replace the standard black median line with a white line while keeping the borders in an other color. I'm following the instructions on the site Minimalist Boxplots because I really like their style.
They use the command stat_summary(geom = "crossbar", width=0.65, fatten=0, color="white", fun.data = function(x){ return(c(y=median(x), ymin=median(x), ymax=median(x))) }).
That command worked well with simple boxplots:

But now that I'm trying to use it on my grouped boxplots its not working anymore (white median line is missing):

Here is my the code for reproducing my data:
Data <- data.frame(
  W = sample(1:100),
  M = sample(1:100),
  A = sample(1:100),
  O = sample(1:100),
  Type = sample(c("1", "2", "3", "4", "5")))

And my script:
Data_Boxplot <- melt(Data,id.vars='Type', measure.vars=c('W','M','A', 'O'))
Boxplots <- ggplot(Data_Boxplot, aes(Type, value, group=variable)) +
  geom_boxplot(outlier.colour = NULL, aes(color=variable, fill=variable)) +
  stat_summary(geom = "crossbar", width=0.65, fatten=0, color="white",
               fun.data = function(x){c(y=median(x), ymin=median(x), ymax=median(x))})
Boxplots

What do I have to change? Thank you very much for your help.

A: You only mapped x and y for the geom_boxplot. Variables that are shared among geoms should be mapped for all. In this case, you also need to group by variable.
ggplot(Data.m, aes(Type, value, group=variable) +
  geom_boxplot(outlier.colour = NULL, aes(color=variable, fill=variable)) +
  stat_summary(geom = "crossbar", width=0.65, fatten=0, color="white",
               fun.data = function(x){c(y=median(x), ymin=median(x), ymax=median(x))})

I did not test, as you did not provide data.
Edit:
Ok, now that we have a good example with data we can see what's going on.
There is actually a two issues I had missed. Both are because geom_boxplot will automatically solve some problems for you because of the fill, that stat_summary doesn't. So we'll have to do them manually.
Firstly, we want to be grouping on both variable as well as Type, we can do this by using the interaction function.
Secondly, the boxplots are automatically dodged (i.e. moved apart within groups), while the horizontal lines aren't. We'll define our positioning using position_dodge, and apply it to both geoms. Applying it to both is the easiest way to make them exactly line up. We end up with:
p <- position_dodge(0.8)
ggplot(Data_Boxplot, aes(Type, value, group = interaction(variable, Type))) +
  geom_boxplot(aes(color = variable, fill = variable), outlier.colour = NULL, position = p) +
  stat_summary(geom = "crossbar", width = 0.6, fatten=0, color="white", position = p,
               fun.data = function(x){c(y=median(x), ymin=median(x), ymax=median(x))}) +
  theme_minimal()


text:
Q: What does this java .execute() method call mean? I was doing some reading through the sun java tutorials, and I came across this page here:
How to Make an Applet
Under the heading, "Threads in Applets" I found this piece of code:
   //Background task for loading images.
    SwingWorker worker = (new SwingWorker<ImageIcon[], Object>() {
            public ImageIcon[] doInBackground() {
                final ImageIcon[] innerImgs = new ImageIcon[nimgs];
            ...//Load all the images...
            return imgs;
        }
        public void done() {
            //Remove the "Loading images" label.
            animator.removeAll();
            loopslot = -1;
            try {
                imgs = get();
            } ...//Handle possible exceptions
        }

    }).execute();
}

First up I'm newish, so I'm sorry if this is a stupid question. However I've never heard of that ".excecute()". I don't understand it, and I'm unable to find anything about it from google. I see this here is... an anonymous inner class? (Please correct me) and it is starting a thread to load in images. I thought that the run() method is invoked with a call to start()? Please help me clear this confusion.

A: execute is a method of SwingWorker. What you're seeing there is an anonymous class being instantiated and having its execute method called immediately.
I have to admit I'm a bit surprised that code compiles, though, because it seems to be assigning the result of execute to the worker variable, and the documentation tells us that execute is a void function.
If we deconstruct that code a bit, it can be clearer. First, we create an anonymous class extending SwingWorker and create an instance of it, all at the same time (this is the big bit in parentheses):
SwingWorker tmp = new SwingWorker<ImageIcon[], Object>() {
    public ImageIcon[] doInBackground() {
            final ImageIcon[] innerImgs = new ImageIcon[nimgs];
        ...//Load all the images...
        return imgs;
    }
    public void done() {
        //Remove the "Loading images" label.
        animator.removeAll();
        loopslot = -1;
        try {
            imgs = get();
        } ...//Handle possible exceptions
    }

};

Then we call execute and assign the result to worker (which is the bit that, it seems to me, shouldn't compile):
SwingWorker worker = tmp.execute();

Update: And indeed, I tried it and it doesn't compile. So not great example code. This would compile:
SwingWorker worker = new SwingWorker<ImageIcon[], Object>() {
    public ImageIcon[] doInBackground() {
            final ImageIcon[] innerImgs = new ImageIcon[nimgs];
        ...//Load all the images...
        return imgs;
    }
    public void done() {
        //Remove the "Loading images" label.
        animator.removeAll();
        loopslot = -1;
        try {
            imgs = get();
        } ...//Handle possible exceptions
    }

};
worker.execute();

A: The .execute() is calling the execute method on an instance of an anonymous class; i.e. the object created by new SwingWorker<ImageIcon[], Object>(){...}.  (It is a class that extends the SwingWorker class.)
According to the javadoc, the execute method schedules the task represented by the instance to be executed on an existing worker thread.  The lifecycle of the worker thread (e.g. creation, starting, etcetera) is taken care of by Swing infrastructure.


text:
Q: Start Python asyncio courutines execution immediately I am trying to understand Python asyncio module. It seems to be much more complicated than similar functionalities in other languages.
Here is an excerpt from documentation:

Calling a coroutine does not start its code running – it is just a generator, and the coroutine object returned by the call is really a generator object, which doesn't do anything until you iterate over it. In the case of a coroutine object, there are two basic ways to start it running: call yield from coroutine from another coroutine (assuming the other coroutine is already running!), or schedule its execution using the async() function or the BaseEventLoop.create_task() method.
Coroutines (and tasks) can only run when the event loop is running.

Does it mean that it is impossible to achieve similar execution flow like here with Hack?
function main() : void
{
    $info = Vector {};
    for ($i = 0; $i < 5; $i++) {
        $info[] = genInfo($i);
    }

    echo '[main] Calling Async Function'."\n";
    $asyncCall = GenVectorWaitHandle::create($info);

    echo '[main] Doing whatever...'."\n";

    echo '[main] Time To Request Async Return Information'."\n";
    $output = $asyncCall->join();

    // Output Vector Data
    foreach ($output as $key => $value)
    {
        echo '['.$key.'] => '.$value."\n";
    }
}

async function genInfo(int $id): Awaitable<String> {
    echo '[genInfo] Generating '.$id."\n";

    $tmp = [];
    $tmp['id'] = $id;
    $tmp['start'] = date('H:i:s');

    //do some heavy working.
    await SleepWaitHandle::create(mt_rand(1000000,15*1000000));

    $tmp['end'] = date('H:i:s');

    echo "[genInfo] Completed $id\n";

    return json_encode($tmp);
}

main();

/*
 * This is a modified example from http://kernelcurry.com/blog/asynchronous-hack/
 */

//Output
[genInfo] Generating 0
[genInfo] Generating 1
[genInfo] Generating 2
[genInfo] Generating 3
[genInfo] Generating 4
[main] Calling Async Function
[main] Doing whatever...
[main] Time To Request Async Return Information
[genInfo] Completed 0
[genInfo] Completed 3
[genInfo] Completed 2
[genInfo] Completed 1
[genInfo] Completed 4
[0] => {"id":0,"start":"19:46:00","end":"19:46:03"}
[1] => {"id":1,"start":"19:46:00","end":"19:46:08"}
[2] => {"id":2,"start":"19:46:00","end":"19:46:05"}
[3] => {"id":3,"start":"19:46:00","end":"19:46:04"}
[4] => {"id":4,"start":"19:46:00","end":"19:46:08"}

As you can see, genInfo() execution starts immediately after call and yields on the await statement. I think that such execution flow is much more natural then this one with Python.
Is there any way to achieve the same in Python?
I tried to iterate coroutines generators one time (in order to allow them to execute and approach first yield) before passing them to loop.run_until_complete(), but without success.


text:
Q: Reactjs, re-render same components, but different return data A little hard to explain, but please bear with me.
I have this function Component. The function Component code is almost the same, but how can i simplify my function MyComponent with the return value are different to each pages?
Below is my code and to better understand here is the complete sandbox code https://codesandbox.io/.
import { React, useState, useEffect } from "react";

function MyComponent() {
  const [error, setError] = useState(null);
  const [isLoaded, setIsLoaded] = useState(false);
  const [items, setItems] = useState([]);
  useEffect(() => {
    fetch(
      "https://api.unsplash.com/search/photos?query=nature?orientation=landscape&client_id=ddIh7_ebg4KwNHzNLf3ePCZb6yIPREJ5jxG3dYgoj6U"
    )
      .then((res) => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
          setItems(result.results);
        },
        (error) => {
          setIsLoaded(true);
          setError(error);
        }
      );
  }, []);

  if (error) {
    return
Error: {error.message}
;
  } else if (!isLoaded) {
    return
Loading...
;
  } else {
    return (

        This return has to be dynamic. See the function Home and About below.

    );
  }
}

export default MyComponent;

Here is my Home and About pages.
function Home() {
  const [items, setItems] = useState([]);
  return (

Home

        {items.map((item) => (

{item.user.last_name}

        ))}

  );
}

function About() {
  const [items, setItems] = useState([]);
  return (

About

        {items.map((item) => (

{item.user.first_name}

        ))}

  );
}

MyComponent doesn't appear to be rendered in my codesandbox, thats why im asking how can achieve my questions.

A: The issue is that you've no centralized source of truth. Each of MyComponent, Home, and About each have their own items state. The question you are asking is how to get the items that MyComponent fetched passed to the other two.
The solution is to Lift State Up. Move all the fetching and rendering logic from MyComponent into App. Pass the items state down to both Home and About.
App
export default function App() {
  const [error, setError] = useState(null);
  const [isLoaded, setIsLoaded] = useState(false);
  const [items, setItems] = useState([]);

  useEffect(() => {
    fetch(
      "https://api.unsplash.com/search/photos?query=nature?orientation=landscape&client_id=ddIh7_ebg4KwNHzNLf3ePCZb6yIPREJ5jxG3dYgoj6U"
    )
      .then((res) => res.json())
      .then((result) => {
        setItems(result.results);
      })
      .catch((error) => {
        setError(error);
      })
      .finally(() => {
        setIsLoaded(true);
      });
  }, []);

  return (
    <BrowserRouter>
      {<Layout />}

        {error ? (

Error: {error.message}

        ) : !isLoaded ? (

Loading...

        ) : (
          <React.Suspense fallback={
Loading...
}>
            <Routes>
              <Route path="/" element={<Home items={items} />} />
              <Route path="/about" element={<About items={items} />} />
            </Routes>
          </React.Suspense>
        )}

    </BrowserRouter>
  );
}

Home
function Home({ items }) {
  return (

Home

        {items.map((item) => (

{item.user.last_name}

        ))}

  );
}

About
function About({ items }) {
  return (

About

        {items.map((item) => (

{item.user.first_name}

        ))}

  );
}


text:
Q: How to implement scroll on page in angular2? aboutData['intro'] contains the following html

Om statistikk.siu.no

Vilkår for bruk

  Om statistikk.siu.no Lorem ipsum Lorem ipsum Lorem ipsum

  Vilkar Lorem ipsum Lorem ipsum Lorem ipsum

On clicking href, the page scrolls to corresponding id element but it gives the error :
Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'Vilkar'.

I cannot define these href routes in the routing config as this html came from database and appended to div element as innerhtml.

The problem is that I want the page to scroll but without hitting routes. Can someone help me with this out?

A: Try like this below : my example code
important { path: '**', redirectTo: '', pathMatch: 'full' } in your route file like below added
home.route.ts
import { Routes } from "@angular/router";

import { HomeComponent } from './';

export const HomeRoute: Routes = [
    {
        path: '',
        component: HomeComponent
    },
    { path: '**', redirectTo: '', pathMatch: 'full' }
];

home.module.ts
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { RouterModule } from '@angular/router';

const HOME_STATES = [
    ...HomeRoute
];

@NgModule({
    imports: [
        RouterModule.forRoot(HOME_STATES, { useHash: true })
    ]
})

home.component.html

Om statistikk.siu.no

Vilkår for bruk

  Om statistikk.siu.no Lorem ipsum Lorem ipsum Lorem ipsum

  Vilkar Lorem ipsum Lorem ipsum Lorem ipsum


text:
Q: How to auto-accept Wi-Fi Direct connection requests in Android I have 2 Android devices using WiFi Direct. On one device I can get information about the other device using the WifiP2pManager class, and request a connection to the other device. However when I request a connection, the other device pops up a little window and asks the user if they want to accept the connection request.
Is it possible to auto-accept these connection requests? I.E to be able to connect to the other device without user confirmation?

A: It can be easily done with the help of Xposed framework. You just need to replace the single method inside one of android java classes (see the link from snihalani's answer). But of course to use Xposed your device must be rooted. The main idea can be expressed in the following code (using Xposed)
@Override
public void handleLoadPackage(LoadPackageParam lpparam) {
    try {
        Class<?> wifiP2pService = Class.forName("android.net.wifi.p2p.WifiP2pService", false, lpparam.classLoader);
        for (Class<?> c : wifiP2pService.getDeclaredClasses()) {
            //XposedBridge.log("inner class " + c.getSimpleName());
            if ("P2pStateMachine".equals(c.getSimpleName())) {
                XposedBridge.log("Class " + c.getName() + " found");
                Method notifyInvitationReceived = c.getDeclaredMethod("notifyInvitationReceived");
                final Method sendMessage = c.getMethod("sendMessage", int.class);

                XposedBridge.hookMethod(notifyInvitationReceived, new XC_MethodReplacement() {
                    @Override
                    protected Object replaceHookedMethod(MethodHookParam param) throws Throwable {
                        final int PEER_CONNECTION_USER_ACCEPT = 0x00023000 + 2;
                        sendMessage.invoke(param.thisObject, PEER_CONNECTION_USER_ACCEPT);
                        return null;
                    }
                });

                break;
            }
        }
    } catch (Throwable t) {
        XposedBridge.log(t);
    }
}

I tested it on SGS4 stock 4.2.2 ROM and it worked.
I guess the same could be done with the help of Substrate for android.

A: From my current understanding of the API, You cannot really accept connections automatically without user's intervention. You can initiate a connection, that doesn't require user intervention. If both of your devices are mobile devices, you will have to accept connection request on one end.
I have put this as a feature request in android project hosting.
You can monitor their response here: https://code.google.com/p/android/issues/detail?id=30880

A: Based on the comments, do you really need to connect to the devices if you just want to track and log the vehicles around you ?
I don't know the scope of the project, but you could simply use the WifiP2pDeviceList that you get when you request the peers in the WifiP2pManager. You could get the list of the devices (~= vehicles) around you and could log this.
Connection is useful if you want to send more detailed information I guess.

A: If you can modify the framework, you can ignore the accept window and direct send the "PEER_CONNECTION_USER_ACCEPT".
Base on Android 5.0, "frameworks/opt/net/wifi/service/java/com/android/server/wifi/p2p/WifiP2pServiceImpl.java".
You must find the "notifyInvitationReceived", and modify to ...
private void notifyInvitationReceived() {
    /*Direct sends the accept message.*/
    sendMessage(PEER_CONNECTION_USER_ACCEPT);
/*
... old code
*/
}


text:
Q: Filling array with random numbers using Intel TBB I have two different functions to fill a global array with random numbers: A serial version and a parallel version using lamba expression and TBB.
void get_data(void)
{
    int j = 0;
    srand((unsigned) time(NULL));
    cout << "Generating random numbers ...\n";

for (j = 0; j < DATASIZE; j++)
    data[j] = (rand() % range) + range_min ;

}

void parallel_get_data(void)
{
    int j = 0;
    srand((unsigned) time(NULL));
    parallel_for(0, DATASIZE, 1, [=](int i)
      { data[i] = (rand() % range) + range_min ; });

}

The program is running an Intel Xeon cluster but unfortunatly the parallel version is much slower. If instead of filling the array with random numbers I simply do a data[i] *= 2 a speed up of up to 50 % can be measured. Has this something to do with the random function? Is there a way to avoid that?

A: Yes you're calling a function vs. executing a multiply instruction. Each time the function is called it has to set up the call frame, jump to the function, calculate the random number and return from the function. Add the stack manipulation, stack checking, etc. and it's going to be slower. About the only way to avoid it is to provide your own implementation of random and hope it can be inlined by the compiler.


text:
Q: About strlen function in C programming currently compiling a C programming for a PIC mcu in MPLAB IDE.
I just want to count the length of a string and I'm using the strlen function. But it keep return the value 0. Below is my coding:
In Main loop I got this function:
BYTE RXDATA[128];

CountData(RXDATA);

And the CountData function is as below:
BYTE CountData(BYTE* pData)
{
    BYTE nLen;
    nLen = strlen((char*)pData);
    return nLen;
}

The actual length of the RXDATA usually is more than 50 but my nLen always give me 0. Do you guys know what's wrong?
Or is there any other way to count the length?

A: For a start, your call to CountData() needs to store the value somewhere, such as with:
int x = countData(RXDATA);

But think about this for a while. Untold millions of people use strlen every day without it failing. The number of people who have tested your code would probably be in the low single digits. Where do you think the problem would lie?
:-)
If your strlen is returning zero, it's almost certainly because the first byte of your input buffer is a \0, meaning the string has a length of zero.
Temporarily change:
BYTE RXDATA[128];
CountData(RXDATA);

into something like:
BYTE RXDATA[128];
strcpy (RXDATA, "Pax");
int x = CountData(RXDATA); // then check x.

and see what happens. I suspect you'll see three as the return value.

A: perhaps you actually want
int x  = sizeof(RXDATA);

Here is a gcc program (that I named `dd.c') that demonstrates this
#include <stdio.h>

unsigned char RXDATA[80];

int main () {
    printf(" sizeof RXDATA = %d\n", (int) sizeof(RXDATA));
}

Compiling it
$ gcc dd.c -o ddd

Running it
$ ./ddd
 sizeof RXDATA = 80
$

See also related thread sizeof- function or macro?


text:
Q: Pull version label from TFS in TeamCity I need to pull from a specific label in TFS and then build it in TeamCity.  Is there any way to do this?  I've done it before in SVN with custom steps, I was trying to avoid this. I assume a custom step like the below would work, but wanted to avoid it if possible.
Any ideas?  Maybe a way through the fetch URL or appended to the collection URL that I don't know about.
tf get * /r /version:Lyourlabelname

A: See https://youtrack.jetbrains.com/issue/TW-7370

You can run a build on a specified change[set] manually using Run
  Custom Build dialog.

Edit:
Another way is to run tf.exe using the Get command.
See https://msdn.microsoft.com/en-us/library/fx7sdeyf.aspx

Synchronize a workspace to match a labeled version of the team's codebase
  c:\code\SiteApp\Main>tf get /v:LLastKnownGood
  Synchronizes the workspace to match the items in the codebase that are labeled LastKnownGood

Edit 2
Also see https://teamcity-support.jetbrains.com/hc/en-us/community/posts/207091635-Checkout-TFS-Label

TeamCity does not support getting labeled sources at this time. The feature request is addressed by TW-5061, please vote for it.


text:
Q: ¿Cómo predominar un campo de fecha en el GROU BY de MYSQL, para evitar el NULL? Mi problema es que quiero traer el listado de mesas(tables) con su respectiva reserva(bookings). El siguiente código sirve a medias, ya que lo que hace es que trae todas las mesas y sus reservas en un rango de tiempo. Pero -a la hora de agrupar por tipo y número de mesa- lo que hace es que agrupa sin tomar en cuenta la fecha que está en la tabla(bookings) y por lo tanto lo deja en nulo.
EJ:
(Esto me lo trae con el GROUP BY)

(Esto me lo trae SIN el GROUP BY)

Consulta MYSQL:
 SELECT
 t.id,
 t.type,
 t.number,
 t.chairs,
 t.status,
 b.booking_id,
 b.dateTime
 FROM tables AS t
 LEFT JOIN bookings_tables AS bt ON bt.table_id = t.id
 LEFT JOIN (
   SELECT
   b1.id AS booking_id,
   b1.date_time AS dateTime
   FROM bookings AS b1
   WHERE b1.date_time BETWEEN "2020-01-02 21:01:27" AND "2020-01-03 01:01:27"
 ) AS b ON bt.booking_id = b.booking_id
 GROUP BY t.number, t.type
 ORDER BY t.type, t.number;

La pregunta es:
¿Que debo de hacer para que la tupla que tenga la fecha predomine y no quede en null?

A: La respuesta depende un poco del corte de la información que quieres ver, y no me queda del todo claro. Pero planteando que:
1.- Propósito de cada entidad en el modelo de datos:

*

*La tabla tables (preferiría que se llamara mesas ) representa las mesas del restaurant y sus características: ID, tipo, cantidad de asientos, etc.

*La tabla bookings representa las reservas y su única característica relevante fuera del ID es la fecha/hora solicitada.

*La tabla bookings_tables no representa una entidad tangible sino que es sólo una tabla de paso que permite una relación many to many entre tablas y reservas

¿Qué sentido tiene la tabla de paso, cuando bastaría que la tabla de reservas contuviera el ID de la mesa? Conceptualmente, se justifica su existencia dado que una misma reserva podría aludir a dos mesas (una cena con 30 invitados, por ejemplo).
2.- Supuestos
El ID y número de la mesa parecen representar lo mismo. Para este ejemplo vamos a decir que sólo tiene ID.
En ese listado una mesa no puede estar reservada y libre al mismo tiempo. La mesa está reservada si existe un registro en booking_table asociando la mesa con una reserva de esta noche. (O de la fecha que quieras revisar)
Aunque se podría, vamos a dejar fuera el caso en que una misma mesa tenga dos reservas para hoy, porque no puedes expulsar al comensal de las 21:00 que se quedó haciendo sobremesa para darle su mesa al comensal de las 23:00.
A consecuencia de lo anterior, cada mesa puede aparecer solamente una vez ya sea libre o reservada. Por lo tanto no tiene sentido agrupar.
Finalmente, una misma reserva podría aludir a dos o más mesas dado que el número de comensales justifique juntarlas.
3.- Poblamiento
Vamos a decir que  el restaurant tiene 4 mesas:
| id |  sillas | tipo
---------------------
| 1  |    4    | Mesa
| 2  |    4    | Mesa
| 3  |    6    | Mesón
| 4  |    6    | Mesón

Que has tenido 4 reservas. Una antes de ayer, otra ayer y dos para hoy.
| id     |  horafecha
-------------------------------
| 154554 |  2020-01-01 21:00:00
| 154555 |  2020-01-02 21:00:00
| 154556 |  2020-01-03 21:15:00
| 154557 |  2020-01-03 22:00:00

Y que la relación entre reservas y mesas es:
| id_mesa | id_booking
----------------------
|   1     | 154554
|   1     | 154555
|   1     | 154556
|   3     | 154557
|   4     | 154557

(la reserva 154557 es para 12 personas, así que ocupará las mesas 3 y 4).

Solución Propuesta
Bajo el supuesto que quieres ver una especie de "agenda de hoy para la cena del  restaurant", el producto final debiera entregarte información del tipo
| id_mesa | sillas | status    | id_booking | horafecha
----------------------------------------------------------
|  1      |  4     | Reservada |  154556    | 2020-01-03 21:15:00
|  2      |  4     | Libre     |     -      |  -
|  3      |  6     | Reservada |  154557    | 2020-01-03 22:00:00
|  4      |  6     | Reservada |  154557    | 2020-01-03 22:00:00

Con esto el administrador del restaurant se programa en base a que esta noche

*

*La mesa 1 está reservada a las 21:15

*La mesa 2 no está reservada

*Las mesas 3 y 4 están reservadas a las 22:30 por una persona que trae 12 invitados, así que hay que juntarlas. (misma reserva, 2 mesas)

Si estamos de acuerdo en todo lo anterior, yo señalaría que en la cláusula FROM donde pones:
FROM tables AS t
LEFT JOIN bookings_tables AS bt ON bt.table_id = t.id

Hay un problema. Ese producto cruz contiene todas las combinaciones de reservas  de toda la historia sobre todas las mesas. La mesa 1 ha sido reservada 3 veces esta semana, pero no tiene sentido mostrarla tres veces en la consulta. Creo que por eso exploraste la idea de agrupar, que en este caso no aporta nada. Fíjate que:
SELECT
  t.id as id_mesa,
  bt.id_booking as id_reserva
FROM mesas t
LEFT JOIN  bookings_tables bt ON bt.id_mesa=t.id;

Se trae las reservas de días anteriores:
| id_mesa | id_reserva
----------------------
|   1     | 154554
|   1     | 154555
|   1     | 154556
|   3     | 154557
|   4     | 154557
|   2     | NULL

Segundo, la subconsulta contra el segmento de fechas relevantes:
LEFT JOIN (
   SELECT
   b1.id AS booking_id,
   b1.date_time AS dateTime
   FROM bookings AS b1
   WHERE b1.date_time BETWEEN "2020-01-02 21:01:27" AND "2020-01-03 01:01:27"
 ) AS b ON bt.booking_id = b.booking_id

Cumple con quitar las fechas ajenas a la cena de hoy, pero debido al LEFT JOIN, no constituye un filtro. (Sólo provoca que el campo de fechahora se liste como nulo)
Creo que la manera correcta sería que la subconsulta generase un listado con las reservas de hoy y sus respectivas mesas, sin usar un LEFT JOIN.
SELECT id_mesa, id_booking, horafecha
  FROM bookings b
  JOIN bookings_tables bt ON bt.id_booking=b.id
  WHERE b.horafecha BETWEEN "2020-01-03 21:00:00" AND "2020-01-04 01:01:00"
  ORDER BY id_mesa;

Que tiene la forma
| id_mesa | id_booking | horafecha
-------------------------------------------
|   1     | 154556     | 2020-01-03 21:15:00
|   3     | 154557     | 2020-01-03 22:00:00
|   4     | 154557     | 2020-01-03 22:00:00

En la cual cada mesa aparece solamente una vez (porque dijimos que no se puede reservar la misma mesa dos veces el mismo día)
Contra esa subconsulta sí tiene sentido hacer el left join:
SELECT
 t.id as id_mesa,
 t.sillas,
 IF(bookings_hoy.id_booking IS NULL,'Libre','Reservada') as status,
 bookings_hoy.id_booking,
 bookings_hoy.horafecha
FROM mesas t
LEFT JOIN (
  SELECT id_mesa, id_booking, horafecha
  FROM bookings b
  JOIN bookings_tables bt ON bt.id_booking=b.id
  WHERE b.horafecha BETWEEN "2020-01-03 21:00:00" AND "2020-01-04 01:01:00"
) bookings_hoy ON bookings_hoy.id_mesa = t.id ;

Como cada mesa aparece una vez en la tabla de mesas y en la subconsulta, esta vez el LEFT JOIN no genera filas duplicadas, y sólo tiene horafecha nula cuando la mesa está libre. Es lo que señalamos previamente como el formato deseado:
| id_mesa | sillas | status    | id_booking | horafecha
----------------------------------------------------------
|  1      |  4     | Reservada |  154556    | 2020-01-03 21:15:00
|  2      |  4     | Libre     |    NULL    | NULL
|  3      |  6     | Reservada |  154557    | 2020-01-03 22:00:00
|  4      |  6     | Reservada |  154557    | 2020-01-03 22:00:00

Te dejo un Fiddle con el ejemplo.


text:
Q: Why are all the values in my appended list the same? When I plot y as a function of t, the values for a do not change. When I print the appended list I see they are all 0.0. Please help! I'm confused because y as a function of x plots fine. I can't include the actual code, but here is a minimum working example.
import numpy as np
from math import *
from astropy.table import Table
import matplotlib.pyplot as plt
from random import random

x = 0
y = 0
t = 0
h = 0.0100
tf = 40
N=ceil(tf/h)
tnew = t
x_list = [x]
y_list = [y]
t_list = [t]

for i in range(N):
    #while y >= 0:
        tnew = t + h*i
        t = tnew
        print(t)

        #First and second derivatives
        # stuff happens (can't share the code)
        x_new = random()
        y_new = random()

        x = x_new
        y = y_new

        """ appends selected data for ability to plot"""
        x_list.append(x)
        y_list.append(y)
        t_list.append(t)
    #break

""" Plot1"""
plt.plot(t_list,y_list)
plt.show()

""" Plot2"""
plt.plot(x_list,y_list)
plt.show()

First plot I just get a vertical line
Second plot is the way it should be
First plot:
Second plot


text:
Q: Emoji might be overwhelming the app When trying to view iOS SE: What happens when I use Emoji's? via the iOS app, I get this:

It's consistent, retrying does not help and the request always fail.
All other questions load just fine, so I highly suspect the cause is the Emoji icons used in there, especially in the comments that contain lots of them.
Beta channel, version 1.0.1.85
Update: still happening in 1.0.1.88 and I also found that the "preview" seen for example in tag search shows the Emoji just fine:

A: This was an API issue that was fixed sometime ago by Kevin Montrose.


text:
Q: Nested object from an array using lodash in typescript My Data structure reads this
{property: ["a","b"] , value : "somevalue" , comparision : "somecomparison"}
I want to create a object out of it like
{
 "properties": {
    "a": {
      "properties": {
         "b": {
            "somecomparision": "somevalue"
            }
          }
        }
      }
    }

What is best way to implement the nested part of it .
  {
      properties: {
        [property[0]: {
          [comparison]: value,
        },
      },
    }

A: Use Array.flatMap() to add the 'properties' key to the property array, concat the comparison, and then use Array.reduceRight() to create the object (TS playground):

const fn = ({ property, value, comparision }) =>
  property
    .flatMap(p => ['properties', p])
    .concat(comparision)
    .reduceRight((acc, p) => ({ [p]: acc }), value)

const obj = {property: ["a","b"] , value : "somevalue" , comparision : "somecomparison"}

const result = fn(obj)

console.log(result)

With lodash you can use the _.set() function:

const fn = ({ property, value, comparision }) =>
  _.set(
    {},
    _.flatMap(property, p => ['properties', p]).concat(comparision),
    value
  )

const obj = {property: ["a","b"] , value : "somevalue" , comparision : "somecomparison"}

const result = fn(obj)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>


text:
Q: Get-AzureStorageBlob without -blob parameter returns images twice It seems like the Get-AzureStorageBlob cmdlet returns two items with the same name (but different ContentType) when I omit the -blob  parameter (to retrieve all images):
Now when I use the Where-Object cmdlet to retrieve a specific blob by name I get two blobs back:

If I instead specify the blob name in the Get-AzureStorageBlob cmdlet, I only get one file back:

Is this behavior desired? Also in the Azure Storage Explorer I only see one item.
This is how the Request without the -blob parameter looks like:
GET https://XXX.blob.core.windows.net/XXX?restype=container&comp=list&prefix=&maxresults=5000&include=snapshots%2Cmetadata%2Ccopy HTTP/1.1
x-ms-version: 2017-04-17
x-ms-client-request-id: Azure-Storage-PowerShell-XXX
User-Agent: Azure-Storage/8.5.0 (.NET CLR 4.0.30319.42000; Win32NT 10.0.15063.0) AzurePowershell/v5.0.0
x-ms-date: Fri, 16 Mar 2018 08:32:56 GMT
Authorization: SharedKey XXX
Host: XXX.blob.core.windows.net

A: Verify case. -Blob items are case-sensitive. PowerShell where -eq ... is not case sensitive.
Perhaps the two JPG of the first example differ only in some characters case.


text:
Q: Using ES6 import to import and use express router in single line What's the one line equivalent of below statement using ES6 Import
My existing code (using require)
app.use('/c', require('./route/routesc')); // routes which are common
app.use('/d', require('./route/routesd')); // routes for Data Agent
app.use('/a', require('./route/routesa')); // routes for Admin

Same code using ES6 Import
import routesc from "./route/routesc.js"
import routesd from "./route/routesd.js"
import routesa from "./route/routesa.js"

app.use('/c', routesc); // routes which are common
app.use('/d', routesd); // routes for Data Agent
app.use('/a', routesa); // routes for Admin

I am wondering is there any ONE liner for import?
FYI, I spent 40 mins searching for this answer and finally posted here on SO.

A: The ONE-liner equivalent would be
import routesc from "./route/routesc.js"; app.use('/c', routesc); // routes which are common
import routesd from "./route/routesd.js"; app.use('/d', routesd); // routes for Data Agent
import routesa from "./route/routesa.js"; app.use('/a', routesa); // routes for Admin

There is no way to combine them into a single statement, an import declaration always needs to stand on its own.

A: Create an index.js file with export { routesc } from './routesc.js' in your /route folder.
Then do import * as routers from './route'.
Now you can use it like app.use('/c', routers.routesc);


text:
Q: RecyclerView vs. ListView From android developer (Creating Lists and Cards):

The RecyclerView widget is a more advanced and flexible version of
  ListView.

Okay, it sounds cool, but when I saw this example picture, I got really confused about the difference between these two.

The picture above can be easily created by ListView using custom adapter.
So, in what situation should one use RecyclerView?

A: I think the main and biggest difference they have is that ListView looks for the position of the item while creating or putting it, on the other hand RecyclerView looks for the type of the item. if there is another item created with the same type RecyclerView does not create it again. It asks first adapter and then asks to recycledpool, if recycled pool says "yeah I've created a type similar to it", then RecyclerView doesn't try to create same type. ListView doesn't have a this kind of pooling mechanism.

A: RecyclerView info
The RecyclerView was introduced with Android 5.0 (Lollipop). it is included in the Support Library. Thus, it is compatible with Android API Level 7.
Similarly to the ListView, RecyclerView's main idea is to provide listing functionality in a performance friendly manner. The 'Recycler' part of this view's name is not there by coincidence. The RecyclerView can actually recycle the items with which it's currently working. The recycling process is done thanks to a pattern called View Holder.
Pros & Cons of RecyclerView
Pros:

*

*integrated animations for adding, updating and removing items

*enforces the recycling of views by using the ViewHolder pattern

*supports both grids and lists

*supports vertical and horizontal scrolling

*can be used together with DiffUtil

Cons:

*

*adds complexity

*no OnItemClickListener

ListView info
The ListView has been around since the very beginning of Android. It was available even in API Level 1 and it has the same purpose as the RecyclerView.
The usage of the ListView is actually really simple. In this aspect, it's not like its successor. The learning curve is smoother than the one for the RecyclerView. Thus, it is easier to grasp. We don't have to deal with things like the LayoutManager, ItemAnimator or DiffUtil.
Pros & Cons of ListView
Pros:

*

*simple usage

*default adapters

*available OnItemClickListener

*it's the foundation of the ExpandableListView
Cons:

*

*doesn't embrace the usage of the ViewHolder pattern

A: In addition to above differences following are few more:

*

*RV separates view creation and binding of data to view.
In LV, you need to check if convertView is null or not for creating view, before binding data to it.
So, in case of RV, view will be created only when it is needed but in case of LV, one can miss the check for convertview and will create view everytime.

*Switching between Grid and List is more easy now with LayoutManager.

*No need to notify and update all items, even if only single item is changed.

*One had to implement view caching in case of LV.
It is provided in RV by default. (There is difference between view caching n recycling.)

*Very easy item animations in case of RV.

A: For list views to have good performance you'll need to implement the holder pattern, and that's easy to mess up especially when you want to populate the list with several different kinds of views.
The RecyclerView bakes this pattern in, making it more difficult to mess up.  It's also more flexible, making it easier to handle different layouts, that aren't straight linear, like a grid.

A: ListView is the ancestor to RecyclerView. There were many things that ListView either didn't do, or didn't do well.  If you were to gather the shortcomings of the ListView and solved the problem by abstracting the problems into different domains you'd end up with something like the recycler view. Here are the main problem points with ListViews:

*

*Didn't enforce View Reuse for same item types (look at one of the adapters that are used in a ListView, if you study the getView method you will see that nothing prevents a programmer from creating a new view for every row even if one is passed in via the convertView variable)

*Didn't prevent costly findViewById uses(Even if you were recycling views as noted above it was possible for devs to be calling findViewById to update the displayed contents of child views. The main purpose of the ViewHolder pattern in ListViews was to cache the findViewById calls.  However this was only available if you knew about it as it wasn't part of the platform at all)

*Only supported Vertical Scrolling with Row displayed Views (Recycler view doesn't care about where views are placed and how they are moved, it's abstracted into a LayoutManager. A Recycler can therefore support the traditional ListView as shown above, as well as things like the GridView, but it isn't limited to that, it can do more, but you have to do the programming foot work to make it happen).

*Animations to added/removed was not a use case that was considered.  It was completely up to you to figure out how go about this (compare the RecyclerView. Adapter classes notify* method offerings v. ListViews to get an idea).
In short RecyclerView is a more flexible take on the ListView, albeit more coding may need to be done on your part.

A: RecyclerView was created as a ListView improvement, so yes, you can create an attached list with ListView control, but using RecyclerView is easier as it:

*

*Reuses cells while scrolling up/down  - this is possible with implementing View Holder in the ListView adapter, but it was an optional thing, while in the RecycleView it's the default way of writing adapter.

*Decouples list from its container - so you can put list items easily at run time in the different containers (linearLayout, gridLayout) with setting LayoutManager.
Example:
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
//or
mRecyclerView.setLayoutManager(new GridLayoutManager(this, 2));

*Animates common list actions - Animations are decoupled and delegated to ItemAnimator.

There is more about RecyclerView, but I think these points are the main ones.
So, to conclude, RecyclerView is a more flexible control for handling "list data" that follows patterns of delegation of concerns and leaves for itself only one task - recycling items.

A: In my opinion RecyclerView was made to address the problem with the recycle pattern used in listviews because it was making developer's life more difficult.
All the other you could handle more or less.
For instance I use the same adapter for ListView and GridView it doesn't matter in both views the getView, getItemCount, getTypeCount is used so it's the same.
RecyclerView isn't needed if ListView with ListAdapter or GridView with grid adapters is already working for you.
If you have implemented correctly the ViewHolder pattern in your listviews then you won't see any big improvement over RecycleView.

A: I worked a little with RecyclerView and still prefer ListView.

*

*Sure, both of them use ViewHolders, so this is not an advantage.

*A RecyclerView is more difficult in coding.

*A RecyclerView doesn't contain a header and footer, so it's a minus.

*A ListView doesn't require to make a ViewHolder. In cases where you want to have a list with sections or subheaders it would be a good idea to make independent items (without a ViewHolder), it's easier and doesn't require separate classes.

A:
The RecyclerView is a new ViewGroup that is prepared to render any
  adapter-based view in a similar way. It is supossed to be the
  successor of ListView and GridView, and it can be found in the
  latest support-v7 version. The RecyclerView has been developed
  with extensibility in mind, so it is possible to create any kind of
  layout you can think of, but not without a little pain-in-the-ass
  dose.

Answer taken from Antonio leiva
 compile 'com.android.support:recyclerview-v7:27.0.0'

RecyclerView is indeed a powerful view than ListView .
For more details you can visit This page.

A: *

*You can use an interface to provide a click listener. I use this
technique with ListViews, too.

*No divider: Simply add in your row a View with a width of
match_parent and a height of 1dp and give it a background color.

*Simply use a StateList selector for the row background.

*addHeaderView can be avoided in ListViews, too: simply put the
Header outside the View.

So, if efficiency is your concern, then yes, it's a good idea to replace a ListView with a RecyclerView.

A: Simple answer: You should use RecyclerView in a situation where you want to show a lot of items, and the number of them is dynamic. ListView should only be used when the number of items is always the same and is limited to the screen size.
You find it harder because you are thinking just with the Android library in mind.
Today there exists a lot of options that help you build your own adapters, making it easy to build lists and grids of dynamic items that you can pick, reorder, use animation, dividers, add footers, headers, etc, etc.
Don't get scared and give a try to RecyclerView, you can starting to love it making a list of 100 items downloaded from the web (like facebook news) in a ListView and a RecyclerView, you will see the difference in the UX (user experience) when you try to scroll, probably the test app will stop before you can even do it.
I recommend you to check this two libraries for making easy adapters:
FastAdapter by mikepenz
FlexibleAdapter by davideas

A: There are many differences between ListView and RecyclerView, but you should be aware of the following in particular:

*

*The ViewHolder pattern is entirely optional in ListView, but it's baked into RecyclerView.

*ListView only supports vertical scrolling, but RecyclerView isn't limited to vertically scrolling lists.

A: I want just emphasize that RecyclerView is a part of the compatibility package. It means that instead of using the feature and code from OS, every application carries own RecyclerView implementation. Potentially, a feature similar to RecyclerView can be a part of a future OS and using it from there can be beneficial. For example Harmony OS will be out soon.The compatibility package license can be changed in the future and it can be an implication. Summery of disadvantages:

*

*licensing

*a bigger foot print especially as a part of many apps

*losing in efficiency if some feature coming from OS can be there

But on a good note, an implementation of some functionality, as swiping items, is coming from RecyclerView.
All said above has to be taken in a consideration.

A: Following are few key points/differences between RecyclerView & ListView. Take your call wisely.

If ListView works for you, there is no reason to migrate. If you are
  writing a new UI, you might be better off with RecyclerView.
RecylerView has inbuilt ViewHolder, doesn't need to implement our own
  like in listView. It support notify at particular index as well
Things like animating the addition or removal of items are already
  implemented in the RecyclerView without you having to do anything
We can associate a layout manager with a RecyclerView, this can be
  used for getting random views in recycleview while this was limitation
  in ListView In a ListView, the only type of view available is the
  vertical ListView. There is no official way to even implement a
  horizontal ListView. Now using a RecyclerView, we can have a
i) LinearLayoutManager - which supports both vertical and horizontal
  lists, ii) StaggeredLayoutManager - which supports Pinterest like
  staggered lists, iii) GridLayoutManager - which supports displaying
  grids as seen in Gallery apps.
And the best thing is that we can do all these dynamically as we want.

A: Major advantage :
ViewHolder is not available by default in ListView. We will be creating explicitly inside the getView().
RecyclerView has inbuilt Viewholder.

A: Advantages of RecyclerView over listview :

*

*Contains ViewHolder by default.

*Easy animations.

*Supports horizontal , grid and staggered layouts
Advantages of listView over recyclerView :

*

*Easy to add divider.

*Can use inbuilt arrayAdapter for simple plain lists

*Supports Header and footer .

*Supports OnItemClickListner .


text:
Q: ruote and workflow, which is better? We will develop an OA(Office Automation) system in Ruby on Rails, and we need a "Workflow Engine".
I have found two open source projects route and workflow on GitHub.
Which is better?

A: "ruote" is a workflow engine, "workflow" is a state machine library.


text:
Q: Inheritance in asp.net I'm new to asp.net C#, but I want to create a website that has one page with a grid view and a few buttons, that the all other pages will inherit, how can I do this?
I tried using site.master and nested master pages but i think there is another way

A: I would try creating the grid view and buttons within a Custom Control, and then re-using the custom control across any pages that need it. You can define properties set in the pages containing the custom control if you need to customize anything, like the data source provided to the grid view.
See: http://msdn.microsoft.com/en-us/library/y6wb1a0e(v=vs.100).aspx


text:
Q: Let $X$ be a compact metric space. If $f:X \to X$ is surjective and $1$-Lipschitz, then $f$ is an isometry I'm trying to prove a result mentioned in this thread, i.e.,

Let $(X, d)$ be a compact metric space. Let $f:X \to X$ be surjective and $1$-Lipschitz. Then $f$ is an isometry.

My approach is different from those given in the other thread. Could you confirm if my below attempt is fine?

Proof For $x \in X$ and $n \in \mathbb N$, we define
$$
f^{n} (x) := \underbrace{f \circ \cdots \circ f}_{n \, \text{times}} (x).
$$
Then $f^n$ is $1$-Lipschitz for all $n \in \mathbb N$ and thus
$$
d(f^n (x), f^n (y)) \le d(f^m (x), f^m (y)) \quad \forall x,y \in X, \forall n \ge m.
$$
Let $x, y\in X$. We need to prove $d(x, y) \le d (f(x), f(y))$. Because $f$ is surjective, there are sequences $(x_n)$ and $(y_n)$ such that
$$
x_0 = x , f(x_{n+1}) = x_n
\quad \text{and} \quad
y_0 = y , f(y_{n+1}) = y_n.
$$
Then $f^n (x_n) = x$ for all $n \in \mathbb N^*$. Because $X$ is compact, there is a sub-sequence $\varphi$ of $\mathbb N$ and $a, b\in X$ such that $x_{\varphi (n)} \to a$ and $y_{\varphi (n)} \to b$.  Because $f$ is $1$-Lipschitz,
$$
d(x, f^{\varphi (n)} (a)) \le d(x_{\varphi (n)}, a)
\quad \text{and} \quad
d(y, f^{\varphi (n)} (b)) \le d(y_{\varphi (n)}, b).
$$
Hence
$$
f^{\varphi (n)} (a) \to x
\quad \text{and} \quad
f^{\varphi (n)} (b) \to y.
$$
So
$$
d (f^{\varphi (n)} (a), f^{\varphi (n)} (b)) \to d(x, y).
$$
Because $f$ is continuous,
$$
f^{\varphi (n)+1} (a) \to f(x)
\quad \text{and} \quad
f^{\varphi (n)+1} (b) \to f(y).
$$
So
$$
d (f^{\varphi (n)+1} (a), f^{\varphi (n)+1} (b)) \to d(f(x), f(y)).
$$
Convergence of a sequence implies convergence of any sub-sequence, so
$$
d (f^{\varphi (n-1)+1} (a), f^{\varphi (n-1)+1} (b)) \to d(f(x), f(y)).
$$
WLOG, we assume $\varphi (n-1)+1 \le \varphi (n)$. Because $f$ is $1$-Lipschitz,
$$
d (f^{\varphi (n)} (a), f^{\varphi (n)} (b)) \le d (f^{\varphi (n-1)+1} (a), f^{\varphi (n-1)+1} (b)).
$$
The result then follows by taking the limit $n \to \infty$ in the above inequality.


text:
Q: How do I keep my $_SESSION until I submit my form Firstly thank you for reading this,
I have a form it has 3 pages with data needed to be store from page 1 and page 2 and finally on page 3, then it gets sent to the database.
I use this on page 2 to store info from page 1
(assuming on page 1 of my form has session_start();)
$_SESSION['firstName']= $_POST['firstName'];
$_SESSION['telephone']= $_POST['telephone'];
$_SESSION['surname']= $_POST['surname'];
$_SESSION['mobile']= $_POST['mobile'];

Then page 3 gets information from page 2 using this to keep the info.
 $_SESSION['address1']= $_POST['address1'];
 $_SESSION['address2']= $_POST['address2'];
 $_SESSION['address3']= $_POST['address3'];
 $_SESSION['email']= $_POST['email'];
 $_SESSION['customerType']= $_POST['customerType'];

It works to a point if I echo $_SESSION['email'] on page 3 it shows up BUT IF I echo any $_SESSION from page 2 on my final page it doesn't show up anything.
I've spent ages looking at storing sessions, but I can't seem to work it out.
To summerise:-

*

*PAGE 1 Starts the session (session_start()) and user enters their Name, Number Surname and Mobile.

*PAGE 2 Stores the information inputted by the user on Page 1 and users enter their address, email and select membership type.

*PAGE 3 Stores the    information inputted by the user on Page 2 and user selects payment method(no payment is taken as I just want to know how a member would like to pay ,so cheque or paypal)

*PAGE 3 also has one piece of info which isn't stored as the page
Submits all the information to the database.

Problem on PAGE 3 no data from PAGE 1 is displayed if I try to ECHO any info from PAGE 1 I get  this error :- Notice: Undefined index:
Thank you once again for reading this, and sorry as I am new so this is prbablya stupid question to many of you, but I want to learn and this site is great.
Sorry forgot the add this, I have a main page called Default.php which includes this code:-
 if ($_REQUEST['p']) { include('includes/'.$_REQUEST['p'].'.php');

all my pages then are called from this page which is in the following format
  default.php?p=addmember
  default.php?p=addmember-page2
  default.php?p=addmember-page3

default.php has the session_start(); so every page has this called

A: You need to initialise the session using session_start() in each page.

A: Maybe this will help.
<?php
session_start();
?>
<?php
#session_destroy();
function form($type)
{
    return "<form action=\"\" method=\"POST\" >
            <input type=\"text\" name=\"next\" />
            <input type=\"submit\" name=\"$type\" />
            </form> ";
}

function module()
{
    echo form('one');
    if (isset($_POST['one'])) {
        if (isset($_POST['next']) && !empty($_POST['next'])) {
            $_SESSION['title'] = $_POST['next'];
        } else {
            echo "post is empty";
        }
    } else {
        echo "Please fill the field";
    }
}

function module2()
{
    echo form('two');
    if (isset($_POST['two'])) {
        if (isset($_POST['next']) && !empty($_POST['next'])) {
            $_SESSION['content'] = $_POST['next'];
        } else {
            echo "post is empty";
        }
    } else {
        echo "Please fill the field";
    }
}

function module3()
{
    echo form('three');
    if (isset($_POST['three'])) {
        if (isset($_POST['next']) && !empty($_POST['next'])) {
            $_SESSION['category'] = $_POST['next'];
        } else {
            echo "post is empty";
        }
    } else {
        echo "Please fill the field";
    }
}
if (!isset($_SESSION['title'])) {
    echo module();
} else if (isset($_SESSION['title']) && !isset($_SESSION['content'])) {
    echo module2();
} else if (isset($_SESSION['content']) && !isset($_SESSION['category'])) {
    echo module3();
}

// you can delete, below this line.
echo "
";
function SessionChecker($type)
{
    if (isset($_SESSION[$type]) && !empty($_SESSION[$type])) {
        echo "Session $type is set as " . $_SESSION[$type] . "
";
    } else {
        echo "Session '$type' is not set
";
    }
}

echo SessionChecker('title');
echo SessionChecker('content');
echo SessionChecker('category');
echo "
";

A: Do you have session_start() called on every page?
session_start() creates a session or resumes the current one and you would therefore need to call this at the top of every page, not just your initial page.


text:
Q: Change Apache2 ports.conf in order to localhost interface to listen to port 80 At the moment I have this config in /etc/apache2/ports.conf:
NameVirtualHost *:80
Listen 80

All works fine, but I want to change it to:
NameVirtualHost 127.0.0.1:80
Listen 127.0.0.1:80

However after restarting apache, it displays the following error message:
[warn] NameVirtualHost 127.0.0.1:80 has no VirtualHosts

So I've updated the website VirtualHost file under /etc/apache2/sites-available/foo.com:
Original:
<VirtualHost *:80>
...
</VirtualHost>

Updated:
<VirtualHost 127.0.0.1:80>
...
</VirtualHost>

But after restarting apache, it shows the default apache2 index.html that is in /var/www instead of the project under /var/www/foo
This is the only enabled VirtualHost on the server.
Also here is my /etc/hosts file:
127.0.0.1   localhost
127.0.1.1   debian
<publicIP>  <foo.com> <serverhostname>

The host OS is Debian 7.
Any suggestions?

A: Have you symlinked the /etc/apache2/sites-available/foo.com to /etc/apache2/sites-enabled/000-foo.com.
The default apache configuration only reads virtual hosts from the sites-enabled directory and not sites available.
I am guessing that if you go to /etc/apache2/sites-enabled and type ls -la you will only see a configuration for default site and not your new site. If this is the case then symlink your foo.com into the sites enabled directory as follows ln -s ../sites-available/foo.com 001-foo.com

A: I don't think Listen 80 should have been changed to Listen 127.0.0.1:80. All other changes look ok.

A: *

*Uninstall apache2 service

*Run update cmd

*Reinstall apache2

*Edit virtual host

This worked for me.


text:
Q: Is there a solution for $y\sqrt{y^2 + 1} + \sinh^{-1}(y) = x$? Is there a closed form solution for $y\sqrt{y^2 + 1} + \sinh^{-1}(y) = x$?
I would like to invert the arc length of a parabola so I can parameterize it with a constant speed.

A: Hint: inverse hyperbolic functions can be expressed in terms of logarithms:
$$y+\sqrt{y^2 + 1} + \sinh^{-1}(y) = y+\sqrt{y^2 + 1} + \log(y + \sqrt{y^2+1})= z + log(z) = x$$
where $z = y + \sqrt{y^2+1}$
The last equation can be expressed in a closed form only by using the Lambert W function
Edited: Sorry, I misread the first term (are you sure you got it right?). This turns the equation almost hopeless to find a closed form solution.


text:
Q: Sorting Results of a Multi-valued Faceted Search Using bobo-browse MultiValueFacetHandler to gather multi-valued faceted results, how do I sort these facets by the top-scoring document in each facet?
For example, if:

*

*Document d1 has facets f1 and f2 and score 3.5

*Document d2 has facets f2 and f3 and score 4.7

*Document d3 has facets f1 and f3 and score 0.9

*Document d4 has facets f2 and f3 and score 2.2

*Document d5 has facet f1 and score 3.4

*Document d6 has facet f3 and score 5.4

I would expect these results in this order:

*

*f3, f2, f1

Thank you.

A: There is no straightforward answer to this question.  Documents don't have enough information to associate different fields, so only easy solution is to generate derived fields whose value is a concatenation of other field values and use this to build facets.


text:
Q: One year Interval mysql condition Hello I am trying to write a case statement that has a 1 year interval in this case the year starts at April and ends march of the following year, however If for example march of this year is entered then it would be the end of last year due to the fact that, the year would have started from last year April
Have a look at the sqlfiddle here
and this is the code that I have so far, note the
sum(case
        when Month(py.pay_date) = 4 interval())1 year
        then amount end) yearly_amount

This is where I am having the major problem

A: You can use this for your yearly_amount calculation for the current year (starting in april and ending at the end of march in the next year):
sum(case
        when py.pay_date >= STR_TO_DATE(CONCAT(YEAR(NOW()), '-04-01'), '%Y-%m-%d') and
             py.pay_date <  STR_TO_DATE(CONCAT(YEAR(NOW()), '-04-01'), '%Y-%m-%d') + interval 1 year
             then amount
        end) yearly_amount

SQLFiddle Demo


text:
Q: How come processStartInfo doesn't work I want to open the document with wordpad.exe but it is still opening with microsoft word
I currently have:
string fullPath = helpFiles[index];
ProcessStartInfo psi = new ProcessStartInfo("wordpad.exe");
psi.FileName = Path.GetFileName(fullPath);
psi.WorkingDirectory = Path.GetDirectoryName(fullPath);
psi.Arguments = fullPath;
Process.Start(psi);

A: I asume fullPath is your document's name. You're setting the FileName property to the document which means it'll open in the default document editor (Word in this case).
The overload of ProcessStartInfo you're using sets the filename for you but you're replacing that value with Path.GetFileName(fullPath); which is why wordpad.exe is completely ignored. Set the FileName as wordpad and the arguments as your file path (i.e remove your FilePath line).
ProcessStartInfo psi = new ProcessStartInfo("wordpad");
psi.WorkingDirectory = Path.GetDirectoryName(fullPath);
psi.Arguments = fullPath;
Process.Start(psi);

A: You should just be doing this:
string fullPath = helpFiles[index];
//Check to make sure the path is valid
Process.Start(fullPath);

And let the computer determine the best program to open the file with, according to how the user has their file defaults set up.


text:
Q: How can i access entity manager if i create custom event in symfony2 I have created custom event like when user is generataed then Event dispatcher will fire that event.
I am following this tutorial. I want to know that in his class CommentListener how can I access the entity manager because I want to persist few things in the database.
The class is like this:
class CommentListener
{
    protected $mailer;

    public function __construct(Swift_Mailer $mailer)
    {
        $this->mailer = $mailer;
    }

    public function onCommentEvent(CommentEvent $event)
    {
        $post = $event->getPost();
        $comment = $event->getComment();

        foreach ($post->getSubscribers() as $subscriber) {
            $message = Swift_Message::newInstance()
                ->setSubject('New comment posted on ' . $post->getTitle())
                ->setFrom('send@example.com')
                ->setTo($subscriber->getEmail())
                ->setBody("Hey, somebody left a new comment on a post you're subscribed to! It says: " . $comment->getBody())
            ;
            $this->mailer->send($message);
        }
    }
}

So how can I access entity manager inside onCommentEvent?

A: Listeners are normal services. You can just inject it into constructor along with mailer. Something along these lines:
Service:
services:
    foo_bundle.listener.comment:
        class: FooVendorBarBundleEventListenerCommentListener
        arguments:
            mailer: "@mailer"
            entityManager: "@doctrine.orm.entity_manager"
        tags:
            - { name: kernel.event_listener, event: foo_bundle.post.comment_added, method: onCommentEvent }

Listener class:
class CommentListener
{
    protected $mailer;

    protected $entityManager;

    public function __construct(Swift_Mailer $mailer, $entityManager)
    {
        $this->mailer = $mailer;
        $this->entityManager = $entityManager;
    }

...

If you ever need to find out name of certain service run php app/console container:debug.


text:
Q: Python: search - in nested list I want to search '-' in my nested list that contains a nested dictionary. I have also tried the below solution but it didn't work.
List Output:
[[[[50.0, 23.0], [196.0, 23.0], [196.0, 46.0], [50.0, 46.0]], ('주민등록층', 0.8442377)], [[[95.0, 51.0], [154.0, 51.0], [154.0, 65.0], [95.0, 65.0]], ('재외국민', 0.857541)], [[[59.0, 75.0], [118.0, 75.0], [118.0, 95.0], [59.0, 95.0]], ('이영희', 0.92137283)], [[[59.0, 105.0], [197.0, 105.0], [197.0, 121.0], [59.0, 121.0]], ('470315-9428744', 0.96879905)], [[[46.0, 126.0], [144.0, 129.0], [143.0, 146.0], [46.0, 142.0]], ('전라묵도 흥천군', 0.71075964)], [[[48.0, 144.0], [130.0, 144.0], [130.0, 158.0], [48.0, 158.0]], ('각남대요거리는', 0.73041165)], [[[45.0, 160.0], [144.0, 160.0], [144.0, 173.0], [45.0, 173.0]], ('설현말미마를 ', 0.74398714)], [[[132.0, 180.0], [220.0, 179.0], [220.0, 194.0], [132.0, 195.0]], ('-20210908', 0.79617107)], [[[112.0, 199.0], [281.0, 200.0], [281.0, 217.0], [112.0, 216.0]], ('부산특별시 무산구청정', 0.8322405)]]

Code:
var = '-' in (y for x in result for y in x)
        print(var)

Final Output

A: As you change your question. I change the solution to provide position info.
test_list = [
    [
        [[50.0, 23.0], [196.0, 23.0], [196.0, 46.0], [50.0, 46.0]],
        ("주민등록층", 0.8442377),
    ],
    [
        [[95.0, 51.0], [154.0, 51.0], [154.0, 65.0], [95.0, 65.0]],
        ("재외국민", 0.857541),
    ],
    [
        [[59.0, 75.0], [118.0, 75.0], [118.0, 95.0], [59.0, 95.0]],
        ("이영희", 0.92137283),
    ],
    [
        [[59.0, 105.0], [197.0, 105.0], [197.0, 121.0], [59.0, 121.0]],
        ("470315-9428744", 0.96879905),
    ],
    [
        [[46.0, 126.0], [144.0, 129.0], [143.0, 146.0], [46.0, 142.0]],
        ("전라묵도 흥천군", 0.71075964),
    ],
    [
        [[48.0, 144.0], [130.0, 144.0], [130.0, 158.0], [48.0, 158.0]],
        ("각남대요거리는", 0.73041165),
    ],
    [
        [[45.0, 160.0], [144.0, 160.0], [144.0, 173.0], [45.0, 173.0]],
        ("설현말미마를 ", 0.74398714),
    ],
    [
        [[132.0, 180.0], [220.0, 179.0], [220.0, 194.0], [132.0, 195.0]],
        ("-20210908", 0.79617107),
    ],
    [
        [[112.0, 199.0], [281.0, 200.0], [281.0, 217.0], [112.0, 216.0]],
        ("부산특별시 무산구청정", 0.8322405),
    ],
]
positions = []
text_infos = []
for line in test_list:
    position = line[0]
    text_info = line[1]
    if "-" in text_info[0]:
        print(f"position: {position}")
        print(f"text_info: {text_info}")
        positions.append(position)
        text_infos.append(text_info)

print(f"positions: {positions}")
print(f"text_infos: {text_infos}")

A: This may help
llist = [[[[50.0, 23.0], [196.0, 23.0], [196.0, 46.0], [50.0, 46.0]], ('주민등록층', 0.8442377)], [[[95.0, 51.0], [154.0, 51.0], [154.0, 65.0], [95.0, 65.0]], ('재외국민', 0.857541)], [[[59.0, 75.0], [118.0, 75.0], [118.0, 95.0], [59.0, 95.0]], ('이영희', 0.92137283)], [[[59.0, 105.0], [197.0, 105.0], [197.0, 121.0], [59.0, 121.0]], ('470315-9428744', 0.96879905)], [[[46.0, 126.0], [144.0, 129.0], [143.0, 146.0], [46.0, 142.0]], ('전라묵도 흥천군', 0.71075964)], [[[48.0, 144.0], [130.0, 144.0], [130.0, 158.0], [48.0, 158.0]], ('각남대요거리는', 0.73041165)], [[[45.0, 160.0], [144.0, 160.0], [144.0, 173.0], [45.0, 173.0]], ('설현말미마를 ', 0.74398714)], [[[132.0, 180.0], [220.0, 179.0], [220.0, 194.0], [132.0, 195.0]], ('-20210908', 0.79617107)], [[[112.0, 199.0], [281.0, 200.0], [281.0, 217.0], [112.0, 216.0]], ('부산특별시 무산구청정', 0.8322405)]]

for x in llist:
    for item1 in x[0]:
        for item1_1 in item1:
            if '-' in str(item1_1):
                print(item1_1)
    for item2 in x[1]:
        if '-' in str(item2):
            print(item2)

It has more simpler logic and it is according to your dataset.


text:
Q: How to create user-accounts' separate folders to save user data in--PHP How would I save each user's 'default photo' onto a website? This same photo may be used during some of their interactions on the site(maybe in a chat session), and it may be displayed on their profile page.  Will each user have their own folder? If so, how can I create such a folder. Will this folder stay on ftp? Or MySQL? Will it take any space? As of now, whatever photos are uploaded onto the server, are simply stored in a folder that reads--'uploadportrait.php'. Where can I go from this? If someone can tell me the general principles of this, then that would be great! Thank you in advance.

A: If it is just one photo it doesn't make much sense to create a folder for each user. If you already have a working upload routine, simply store the file path of the uploaded file inside of the user database. You don't need to duplicate the image then.


text:
Q: geometry (similarity transformation about ellipses) Consider the ellipses $\frac{x^2}{a^2}+\frac{y^2}{b^2}=1$ and $\frac{x^2}{a_1^2}+\frac{y^2}{b_1^2}=1$. Find a necessary and sufficient condition for the ellipses to be similar. (The relation should relate $a$, $b$, $a_1$ and $b_1$)
Definition of similar:
let $E_1$ and $E_2$ be two ellipses, if there exists a dialation $H_v,r$ such that
$H_v,r(E_1)=E_2$, then they are similar.

A: Since the two ellipses have the same center and the same orientation, don't you think that $$\frac{a_1}{a}=\frac{b_1}{b}$$ is sufficient ?


text:
Q: Change PHP function to JavaScript I have a table that is created dynamically. Which works just fine. I would like to take the outlined PHP function which creates buttons in each cell(the buttons do not work but do show up) and use JavaScript or another like language. My ultimate goal is when the user clicks the button a box pops up where the user makes a choice and is submitted just like in the PHP function. I do not have a lot of experience with JavaScript and honestly cant find anything on how to do this.
Below is my PHP file:
 <?php
 session_start();
 $tbvbr= $_SESSION['gamecode'];

 //user can only edit the row they created

 $_GET["editmode"]=$_SESSION['playername'];

//start creating the table
 function stripslashes2( $string )
 {
 if ( get_magic_quotes_gpc() ) {
    return stripslashes( $string );
} else {
    return $string;
}
}

function display_db_query( $tablename, $header_bool , $border )
{
// find out the number of columns in result
$result = mysql_query( "SHOW FIELDS FROM $tablename" );
while ( $row = mysql_fetch_assoc( $result ) ) {
    if ( $row['Key'] == "PRI" )
        $primarykey = $row['Field'];
    else
        $field[$row['Field']] = array( $row['Type'] );
  }

    if ( isset( $_POST["update$tablename"] ) ) {
    $sql = sprintf( "update $tablename SET " );
    $sqlfields = array();

    foreach( $field AS $k => $v ) {
        if ( !empty( $_POST["edit"][$k] ) )
            $sqlfields[] = "$k='" . mysql_real_escape_string( stripslashes2(    $_POST["edit"][$k] ) ) . "'";
        else
            $sqlfields[] = "$k = NULL ";
    }
    if ( count( $sqlfields ) > 0 ) {
        $sql .= implode( " , " , $sqlfields ) . " WHERE $primarykey=" . intval( $_POST["updateid"] ) ;

    mysql_query( $sql ) OR DIE( mysql_error() );
    if ( mysql_affected_rows() > 0 )
        print "Updated succesfully
";
    }
    else
    echo "No change
";
}
// perform the database query
$result_id = mysql_query( "SELECT * from $tablename" )
or die( "display_db_query:" . mysql_error() );

  if ( $header_bool ) {
    echo "
";
    echo "
";
    foreach( $field AS $k => $v )
    print( "$k	" );

    } else
    echo "
 ";

while ( $row = mysql_fetch_assoc( $result_id ) ) {
    print( "
" );
    // can edit only edit their row
    if ( $_GET["editmode"] AND $_GET["editmode"] == $row[$primarykey] ) {
        $editmodeison = true;
        echo "<form method=\"post\" action=\"{$_SERVER["PHP_SELF"]}\">";

        // this keeps users from editing other users rows
    } else
        $editmodeison = false;

    foreach( $field AS $k => $v ) {

        if ($editmodeison)
                         print( "<input type=\"button\" name=\"edit[$k]\"  value=\"" . ( !empty( $row[$k] )?htmlspecialchars( $row[$k] ) : htmlspecialchars( '' ) ) . "\" />	\n" );

        else
            print( "" . ( !empty( $row[$k] )?htmlspecialchars( $row[$k] ) : htmlspecialchars( 'change' ) ) . "	\n" );
    }

    if ( $editmodeison )
        print( "<input type=\"hidden\" name=\"updateid\" value=\"{$row[$primarykey]}\"><input type=\"submit\" name=\"update$tablename\" value=\"update\"></form>	\n" );
    else

        print( "change	\n" );
    print( "
\n" );
}
print( "
\n" );
}

?>
<TITLE>Products Orderable table</TITLE>

<?php

 /* For the following details, ask your server vendor  */
 $dbhost = "localhost";
 $dbuser = "placeholder";
 $dbpass = "placeholder";
 $dbname = "placeholder";
 mysql_connect( $dbhost, $dbuser, $dbpass ) or die ( "Unable to connect to MySQL server" );
 mysql_select_db( "$dbname" );
 mysql_query( "SET NAMES utf8" );

 $table = $tbvbr;

 display_db_query( $table, // $global_dbh,
 true, "border='2'" );

  ?>

And this is the function I'm trying to change and use JavaScript or something else with:
 if ($editmodeison)
                         print( "<input type=\"button\" name=\"edit[$k]\"  value=\"" . ( !empty( $row[$k] )?htmlspecialchars( $row[$k] ) : htmlspecialchars( '' ) ) . "\" />	\n" );

        else
            print( "" . ( !empty( $row[$k] )?htmlspecialchars( $row[$k] ) : htmlspecialchars( 'change' ) ) . "	\n" );
    }

    if ( $editmodeison )
        print( "<input type=\"hidden\" name=\"updateid\" value=\"{$row[$primarykey]}\"><input type=\"submit\" name=\"update$tablename\" value=\"update\"></form>	\n" );
    else

        print( "change	\n" );

A: Once again i have to give credit to the above people that helped me.
The below code is the answer to my question.
My edited code
if ($editmodeison)
                         print( "<input type=\"button\"onClick=\"reply_click(this.name)\" name=\"edit[$k]\"  value=\"" . ( !empty( $row[$k] )?htmlspecialchars( $row[$k] ) : htmlspecialchars( '' ) ) . "\" />	\n" );

and of course i had to add the scripts to my code as well.

Thanks again for pointing me in the correct direction!