Q: CKEditor inside jQuery Dialog, how do I build it? So, I'm working with CKEditor and jQuery, trying to build a pop-out editor.
Below is what I have coded so far, and I can't seem to get it working the way I want it to.
Basically, click the 'Edit' link, dialog box pops up, with the content to edit loaded into the CKEditor.
Also, not required, but helpful if you can suggest how to do it. I can't seem to find out how to make the save button work in CKEditor (though I think the form will do it).
Thanks in advance for any help.
$(document).ready(function(){
    var config = new Array();
    config.height = "350px";
    config.resize_enabled = false;
    config.tabSpaces = 4;
    config.toolbarCanCollapse = false;
    config.width = "700px";
    config.toolbar_Full = [["Save","-","Cut","Copy","Paste","-","Undo","Redo","-","Bold","Italic", "-", "NumberedList","BulletedList","-","Link","Unlink","-","Image","Table"]];

    $("a.opener").click(function(){
        var editid = $(this).attr("href");
        var editwin = \'<form>
<input type="text">

<textarea id="content"></textarea>
</form>\';

        var $dialog = $("
"+editwin+"
").dialog({
            autoOpen: false,
            title: "Editor",
            height: 360,
            width: 710,
            buttons: {
                "Ok": function(){
                    var data = $(this).val();
                }
            }
        });
 //$(this).dialog("close");

        $.getJSON("ajax/" + editid, function(data){
            alert("datagrab");
            $dialog.("textarea#content").html(data.content).ckeditor(config);
            alert("winset");
            $dialog.dialog("open");
        });

        return false;
    });
});

A: After doing some more digging and research, I have hacked together a working solution to my problem. I'm posting here in case anyone else needs to do something like this:
function redirect(url, outsite){if(outsite){location.href = url;}else{location.href = 'http://siteurl.com/' + url;}}

function editdialog(editid){
    var editwin = '
<form action="formprocess/'+editid+'" method="post" class="inform">
Column Title: <input type="text" name="coltitle" id="coltitle">

<textarea id="ckeditcolcontent"></textarea>
<input type="hidden" value="edit"></form>
';
    var $dialog = $(editwin).dialog({
        autoOpen: false, title: "Editor",
        height: 520, width: 640,
        closeOnEscape: false, modal: true,
        open: function(event, ui){
            $(this).parent().children().children(".ui-dialog-titlebar-close").hide();
        },
        buttons: {
            "Save and Close": function(){
                var editor = $("#ckeditcolcontent").ckeditorGet();
                var coltitle = $("#coltitle").val();
                var colcontent = $("#ckeditcolcontent").val();
                $.post("formprocess/"+editid, {
                        coltitle: coltitle,
                        colcontent: colcontent
                    }, function(data){
                        redirect(location.href, 1);
                    }
                );
            },
            "Cancel": function(){
                redirect(location.href, 1);
            }
        }
    });

    $.getJSON("ajax/" + editid, function(data){
        $("#coltitle").attr("value", data.header);
            $("#ckeditcolcontent").val(data.content).ckeditor(config);
            $("

").addClass("ui-widget-overlay").appendTo(document.body).css({width:$(document).width(),height:$(document).height()});
        $dialog.dialog("open");
    });
}

var config = new Array();
config.height = "280px";
config.resize_enabled = false;
config.tabSpaces = 4;
config.toolbarCanCollapse = false;
config.width = "600px";
config.toolbar_Full = [["Cut","Copy","Paste","-","Undo","Redo","-","Bold","Italic","Underline", "-", "NumberedList","BulletedList","-","Link","Unlink","-","Image","Table"]];

$(document).ready(function(){
    $("a.admineditlink").click(function(){
        var editid = $(this).attr("href");
        editdialog(editid);
        return false;
    });
});


Q: .redirect() from mounted middleware with relative destination fails I want to restrict a certain subtree only to authenticated users. The basic setup is as follows (fat removed):
app.use(express.bodyParser())
 .use(express.cookieParser('MY SECRET'))
 .use(express.cookieSession())
 .use('/admin', isAuthenticatedHandler)
 .use('/admin', adminPanelHandler);

Where the handler functions is:
isAuthenticatedHandler = function(req, res, next) {
   if (!req.session.username) {
     res.redirect('login');
   } else {
     next();
   }
};

The problem is that even though I provide the redirect destination as a relative path 'login', it doesn't lead to <mount_point>/login i.e. /admin/login but to /login which of course throws a 404.
From the expressjs API reference:
 This next redirect is relative to the mount point of the application.
 For example if you have a blog application mounted at /blog, ideally
 it has no knowledge of where it was mounted, so where a redirect of
 /admin/post/new would simply give you `http://example.com/admin/post/new`,
 the following mount-relative redirect would give you
 `http://example.com/blog/admin/post/new`:

      res.redirect('admin/post/new');

Am I misreading this?

A: What are you trying to achieve? Why not just redirect to '/admin/login' ?  And the mount point they are talking about is the place where your Express app is located, not necessarily the current URL. So /blog might be setup on your server to be the root of your app while / might be a totally different app. At least that's the way I read this.

A: The issue here is that while you are using your middleware off of /admin, your app itself is not mounted at /admin.  Your app is still off of the root, and your configuration simply says to only use your isAuthenticatedHandler middleware if the request comes in off the /admin path.
I whipped together this gist.  Notice how it uses 2 Express applications, one mounted inside the other (line 23 pulls this off).  That is an example of mounting the application at a different point rather than just putting a given middleware at a given point.  As presently written, that example will give you an endless redirect, since the isAuthenticatedHandler fires for everything off of / in the child application, which equates to /admin overall.  Using 2 separate applications might introduce other issues you're not looking to deal with, and I only include the example to show what Express means when it talks about mounting entire applications.
For your present question, you'll either need to follow what Yashua is saying and redirect to /admin/login or mount your admin interface as a separate Express application.


Q: How to print asterisk triangles side-by-side in python? I am trying to print 4 star triangle side-by-side using nested for-loops in python. I included the code I am using now that prints the triangles vertically, but I do not know how to print them horizontally.
n = 0

print ("Pattern A")
for x in range (0,11):
    n = n + 1
    for a in range (0, n-1):
        print ('*', end = '')
     print()
print ('')
print ("Pattern B")
for b in range (0,11):
    n = n - 1
    for d in range (0, n+1):
        print ('*', end = '')
    print()
print ('')

enter image description here

A: maximum = 10
a, b, c, d = 1, maximum, maximum, 1

while a <= maximum:
    print('*'*a + ' '*(maximum-a) + ' '*2 + '*'*b + ' '*(maximum-b) + ' '*2 + ' '*(maximum-c) + '*'*c  + ' '*2 + '*'*d + ' '*(maximum-d))
    a += 1
    d += 1
    b -= 1
    c -= 1

A: Thanks to @AzBakuFarid the main idea is to print every line of shapes from the top to the last together. @AzBakuFarid code had a very little mistake that you can see the corrected one below :
maximum = 10
a, b, c, d = 1, maximum, maximum, 1

while a <= maximum:
    print('*'*a + ' '*(maximum-a) + ' '*2 + '*'*b + ' '*(maximum-b) + ' '*2 + ' '*(maximum-c) + '*'*c  + ' '*2 +  ' '*(maximum-d) + '*'*d)
    a += 1
    d += 1
    b -= 1
    c -= 1

As u wanted to be with for-loops I came up with this :
longest = int(input())
asterisk_a = 1
spaces_a = longest - 1
asterisk_b = longest
spaces_b = 0
asterisk_c = longest
spaces_c = 0
asterisk_d = 1
spaces_d = longest - 1
for i in range(0,longest):
    print(asterisk_a * '*' + spaces_a * ' ' + '  ' + asterisk_b * '*' + spaces_b * ' ' + '  ' + spaces_c * ' ' +  asterisk_c * '*' + '  ' + spaces_d * ' ' +  asterisk_d * '*')
    asterisk_a += 1
    spaces_a -= 1
    asterisk_b -= 1
    spaces_b += 1
    asterisk_c -= 1
    spaces_c += 1
    asterisk_d += 1
    spaces_d -= 1

In the first line you should give the number of asterisks in the longest case.
I tried to use meaningful variable names for better understanding.


Q: Chromebook to Ubuntu without crouton I only see tutorials for installing Ubuntu on a Chromebook with crouton, but I want fully working Ubuntu!
Is it possible to Install Ubuntu on a Chromebook without crouton?

A: To install a full Linux distribution on your chromebook you have multiple choices.
You can use chrx to make a dual boot.
Or you can install directly a full version of Ubuntu (best to go for LUbuntu or Xubuntu).
I would recommend to install GalliumOS as it is derived from XUbuntu and it's optimized for chromebooks.
To do this, you should follow GalliumOS installation steps:

*

*First, you have to enable developer mode on your chromebook (and remove all data on your disk).

*Second, you have to update your firmware to be able to boot on a USB key.

*Third, install your Ubuntu/Gallium, or a dual boot using chrx.

Step one and two are really well documented on GalliumOS's wiki, you will find all your answers here.


Q: setTimeout("window.close()", 100) not working in Firefox I am a learner on HTML, PHP, Javascript.
I am currently working on a barcode scanning system.  The steps are simple, scan in an order number, the system(form) will then generate another sequence number and print it out along with the scanned order number right away so that the warehouse worker can stick the print out on the scanned parcel.
Same steps keep on until the whole log of cargo done.
We have created a simplified program, and test it.  If it works then we can follow the same logic to create the actual form.
Up to this point, we have successfully scan in the bar code, the form then jump into another form by using windows.open.  Inside this pop up windows, it is a PDF document which's created by FPDF.  By enable FIREFOX silence print feature.  The pop up form can printout the label automatically.  Everything good except we cannot close the popup windows.  We have already drilled out every possibilities and search thru the net...couldn't find anything.
We did turn on the Firefox option dom.allow_scripts_to_close_windows to TRUE
first form
<?PHP
session_start();
if (isset($_POST['submit'])){
$_SESSION['CUSTNO']=$_REQUEST['CUSTNO'];
$_SESSION['ORDERNO']=$_REQUEST['ORDERNO']   ;
//header('Location:TESTwai.php');
echo "myFunction();";
}
?>

<form action="" method="post" name="form1">

<input type="text" id="CUSTNO" name="CUSTNO"  style="font-size: 24pt"/>
<input type="text" id="ORDERNO" name="ORDERNO"  style="font-size: 24pt"/>

<input name="submit" type="submit" value="SUBMIT" onclick="return myFunction()"></form>

Second pop up window form
I have put the setTimeout, close.window inside or out PHP script and still no luck.
<?php

require('pdf_js.php');

class PDF_AutoPrint extends PDF_JavaScript
{
function AutoPrint($dialog=false)
{

    //Open the print dialog or start printing immediately on the standard printer
    //$param=($dialog ? 'true' : 'false');
    //echo $param;
    //$script="print($param);";
    $script="print(false);";
    $this->IncludeJS($script);
}
}
$pdf=new PDF_AutoPrint();
$pdf->AddPage();
$pdf->SetFont('Arial','',20);
$pdf->Text(90, 50, 'Print me!');
//Open the print dialog
$pdf->AutoPrint('false');
ob_end_clean();
$pdf->Output();

?>

Please ignore those customer, orderno. They are just dummy input...
The actual testing is just
1) press the submit button
2) pop up windows
3) auto print the label out without any system prompt
4) close the pop up windows and get back to the first form  (stuck here)

A: It is not a issue with setTimeout method. This is the issue with window.close() . It is not a good practice to close the window within itself.Still if you its very necessary you can try the below code:
window.open('','_parent',''); //fool the browser that it was opened with a script
window.close();

You can put this in a function and call it use in setTimeout .Helpful link


Q: reading and deleting lines in python I am trying to read all the lines in a specific file, and it prints the number of the line as an index.
What I am trying to do is to delete the line by inputting the number of the line by the user.
As far as it is now, it prints all the lines with the number of that line, but when I enter the number of the line to be deleted, it's not deleted.
This is the code of the delete function:
def deleteorders ():

    index = 0
    fh = open ('orders.txt', 'r')
    lines = fh.readlines()

    for line in lines:
        lines = fh.readlines()
        index = index+1
        print (str(index) + ' ' + line)

    try:
        indexinp = int(input('Enter the number of the order to be deleted, or "B" to go back: '))

        if indexinp == 'B':
            return
        else:
            del line[indexinp]
            print (line)

            fh = open ('orders.txt', 'w')
            fh.writelines(line)
            fh.close()

    except:
        print ('The entered number is not in the range')
        return

A: This should work (you'll need to add the error handling back in):
lines = enumerate(open('orders.txt'))
for i, line in lines:
    print i, line
i = int(input(">"))
open('orders.txt', 'w').write(''.join((v for k, v in lines if k != i)))


Q: Make two divs share one scrollbar Here is my code:

How to make them share the same scrollbar? I tried this
But it didn't work, since in the first div I have tinymce.


Q: Solve $a^x + b^x = c$ for $x$. This is something I came across today (a specific case of this equation), only to realize I don't have the necessary tools to attack this problem.
This is not any kind of homework or research problem or anything like that. I'm genuinely interested how to approach solving this sort of problems. It may be surprisingly simple, but I just don't see it.
Any help would great appreciated.

A: Since your original question is to solve
$$6^x - 2^x = 32$$
and since there is no closed-form solution for the general equation, let's focus on the specific case. First you can easily find a solution $x=2$, but what about others?
Let $f(x) = 6^x - 2^x -32 = 2^x\cdot(3^x-1) - 32$. Now you can apply Rolle's theorem to show that the only solution is $x=2$:

*

*the function is stricly increasing (its derivative is $f'(x) = 6^x \log (6)-2^x \log (2) = 2^x\cdot(3^x \cdot \log 6 - \log 2) > 0 \quad \forall x \in \mathbb{R^+}$

*$f(0) = -32 < 0, f(3) > 0$

*since it's a composition of continuous and differentiable functions, it is continuous and differentiable. Thus the theorem tells us that the only solution is a member of the interval $[0;3]$ so $x=2$ is the only solution.

A: Just as  Yves Daoust commented, in the most general case, this equation does not show explicit solutions and numerical methods (such as Newton method) will be required.
This does not make (in principle) any problem if a reasonable estimate can be used for starting iterations.
So, let us consider $$f(x)=a^x+b^x-c$$ the zero of which being looked for. This function can be very stiff and, so, it would be better to consider $$g(x)=\log(a^x+b^x)-\log(c)$$ Let us assume $a >b>1$ and $c>0$; so, the solution would be such that $$\frac{\log (c)-\log (2)}{\log (a)}< x<\frac{\log (c)-\log (2)}{\log (b)}$$ which is already good since we bracketed the solution.
So, let us be lazy and choose the midpoint as $x_0$.
Let us try using $a=\pi$, $b=e$, $c=123456789$. If you look at the plot of function $g(x)$, you should notice that it is very close to  straight line (which is always good).
 Using the above bounds, we already know that $$15.6703<x<17.9383$$ So let us start iterating with Newton methods : it will provide as successive iterates $$x_0=16.8042746089317$$ $$x_1=16.1960353781344$$  $$x_2=16.1957749465687$$ $$x_3=16.1957749465186$$ which is the solution for fifteen significant figures.

A: Considering the equation $a^x+b^x=c$, where $a>b>0$:
(Not $6^x-2^x=32$ from the comments.)
The derivative of the LHS is
$$f'(x)=\ln(a)a^x+\ln(b)b^x,$$
which has a single root,
$$x'=\log_{a/b}\left(-\frac{\ln(b)}{\ln(a)}\right)$$ when $a>1>b$, corresponding to a minimum of $f$, and none otherwise.
If $x'$ exists, the equation has two solutions iff $f(x')<c$; if $x'$ does not exist, it has a single solution iff $c>0$.
An efficient procedure to bracket the solutions is to start from $x=x'$ and try arguments $x\pm s$ where the step increases by doubling, $s=2^{k}$. Very quickly, $f(x\pm 2^k)$ will exceed $c$.
In the monotonic case, the comparison $f(0)=2>c$ tells you the sign of the solution and the direction to step to.
From there, you can use one of the dichotomic or Regula Falsi methods which will guarantee convergence. Newton's iterations may be faster, but guarantees on convergence are much harder to establish (and in case you cross the $x'$ border, you are stuck).


Q: Formatting input value and restrictions for user (JavaScript) How I could create an <input type="text" /> with following restrictions for the User and formatting extensions, namely using JavaScript or jQuery?

*

*The User can use only numeric chars. Nothing else.

*The User can't delete the dot. Never. Is it possible? If it isn't and the user will remove the dot, how to give the dot back automatically on losing focus?

*On blur (lose focus), if the decimal places are empty, script will fill it with zeros (↓).

*I need this pattern for view: X XXX.XX
(toFixed(2) I can use for two decimal places, but I don't know way to separate string according pattern).

Certainly you've noticed, that the text field should be the price. The script should operate on multiple input fields with class "pr-dec".
<input type="text" class="pr-dec" size="8" value="0.00" />

Thanks a lot for any help, your time and suggestions.
jsfiddle can facilitate it.

A: Google Translate says he said:
"Matus know the těchhle point I stopped, I'm a beginner and do not know what I stand on it all night"
Sounds like you need to read up on some JavaScript and jQuery tutorials.  I began with something like this: jQuery for Absolute Beginners: The Complete Series
Really hope this helps.

A: You have a number of problems you need to solve.
Break them down into smaller chunks and tackle it from there.
Only numbers
You could watch the field (check out .on) for a change and then delete any character that's not part of the set [\d] or [0-9], but that could get messy.
A better idea might be to watch for a keydown event and only allow the keys that represent numbers.
The Dot
Trying to dynamically stop the user from deleting the dot is messy, so let's just focus on adding it back in when the field is blurred.
That's pretty easy, right? Just check for a . and if there isn't one, append ".00" to the end of the field.
Decimal Places
This is really the same problem as above. You can use .indexOf('.') to determine if the dot is present, and if it is, see if there are digits after it. If not, append "00" if so, make sure there's 2 digits, and append a "0" if there's only 1.
String Pattern
This could really be solved any number of ways, but you can reuse your search for the decimal place from above to split the string into "Full Dollar" and "Decimal" parts.
Then you can use simple counting on the "Full Dollar" part to add spaces.  Check out the Javascript split and splice functions to insert characters at various string indexes.
Good luck!


Q: Is it necessary to create 151 connections to the server when displaying 150 images in a RecyclerView, stored in Firebase Storage's 'Images' folder? Suppose you have 150 images stored in the images folder within your Firebase Storage. Each image should have a title, which will be inserted during the uploading process. Now, let's say you want to display all of these images in a RecyclerView. In this scenario, you would need to create 151 separate connections to the server instead of just one. This may seem counterintuitive, so allow me to explain.
The first connection is to retrieve all the images using the following line of code: FirebaseStorage.getInstance().getReference().child("Images/").listAll(). This will return a list of all the images in the folder.
For each image, you would need to make another connection to the server to retrieve the metadata for that image. This means that for every single image, you would need to make a separate call to the server, resulting in a total of 151 connections.
Here is a preview of the code for this scenario:
FirebaseStorage.getInstance().getReference().child("Images/").listAll().addOnCompleteListener(task -> {
if (task.isSuccessful()) {
    for (int i = 0; i < 150; i++) {
        task.getResult().getItems().get(0).getMetadata().addOnCompleteListener(task1 -> {
            if (task1.isSuccessful()) {
                task1.getResult().getCustomMetadata("title"); //Finally I got the image title that stored inside image, it is cumbersome process.
            } else {
                //Handle error
            }
        });
    }
} else {
    //Handle error
}
});

However, it's possible that I may be missing something. Is this really the way it works, or is there a better solution? I don't want to name the image directly as the file name because I've tried that before and found that the length is not enough.
I would greatly appreciate any suggestions or alternative solutions to this problem. Thank you in advance!
Additionally, I would like to express my gratitude to OpenAI's GPT-3 for helping me write this clear and concise question.

A: First of all, FirebaseStorage.getInstance() is a singleton, which will always create a single instance.
Furthermore, while Mauricio Gracia Gutierrez's will work, please see below a solution that uses Tasks#whenAllSuccess(Collection> tasks):
StorageReference imagesRef = FirebaseStorage.getInstance().getReference().child("Images/");
imagesRef.listAll().addOnCompleteListener(new OnCompleteListener<ListResult>() {
    @Override
    public void onComplete(@NonNull Task<ListResult> task) {
        if (task.isSuccessful()) {
            List<StorageReference> storageReferenceList = task.getResult().getItems();
            List<Task<StorageMetadata>> tasks = new ArrayList<>();
            storageReferenceList.forEach(item ->
                    tasks.add(item.getMetadata())
            );
            Tasks.whenAllSuccess(tasks).addOnSuccessListener(new OnSuccessListener<List<Object>>() {
                @Override
                public void onSuccess(List<Object> objects) {
                    for (Object object : objects) {
                        String title = ((StorageMetadata) object).getCustomMetadata("title");
                        Log.d("TAG", title);
                    }
                }
            });
        } else {
            Log.d(TAG, task.getException().getMessage()); //Never ignore potential errors!
        }
    }
});

In this way, you'll wait until you have a List full of titles.

A: You can create a backend API method that returns the list of titles for you in a single call
I know now that your code was demostration purposes only but....

*

*your code says task.getResult().getItems().get(0) meaning that only the first item is being used 150 times

*Calling task.getResult().getItems() inside the for, means that  you are calling something that only needs to be called once 150 times

*Using harcoded 150 instead of the items.length is not a good idea
When you see that your code cumbersome or hard to read, follow the "Single Responsability" to split it into simpler methods.
In the code below I'm using type "Item" because  I dont now the name of the type returned by task.getResult().getItems()

void getAllImagesMetadata() {
    FirebaseStorage.getInstance().getReference().child("Images/").listAll().addOnCompleteListener(task -> {
    if (task.isSuccessful()) {
        Item []items = task.getResult().getItems() ;

        for (int i = 0; i < items.length ; i++) {
            title[i] = getTitle(items[i] ;
        }
    } else {
        //Handle error
    }

    // Make sure the connection to get list of all items is closed here
}

string getTitle(Item item) {
    string title ;

    item.getMetadata().addOnCompleteListener(task -> {
    if (task.isSuccessful()) {
        title = task.getResult().getCustomMetadata("title");
    } else {
        //Handle error
    }

    // Make sure the connection to get the metada is closed here
    return title ;
}


Q: how to store the large amount data in windows phone 8.1? in android for storing data we are using array list,hash map...etc.
in windows how we save the large amount of data? what about collections in windows phone development. Please any one explain me how to store the data in windows phone 8.1 development.

A: Here you have the main type of collections available in C#: https://msdn.microsoft.com/en-us/library/ybcx56wz.aspx
All of them can be used in Windows Phone.


Q: Problema con Web Service tipo Soap Estoy tratando de consumir un Web Service SOAP desde un Ajax pero al invocar dicho Ajax algo falla. ¿Qué puedo hacer? El Web Service se encuentra alojado en un servidor IIS con la siguiente ruta.
http://iis:8888/WebServices.asmx?op=ActualizarPassword
cuando ejecuto esta ruta en el navegador desde mi equipo se ve así:

Pero al ejecutar la misma ruta desde el servidor IIS se ve así:

La petición Ajax que estoy ejecutando es la siguiente:

$('#btnAceptar').on('click', function () {
                if (Validar() === false) {
                    $.post("http://iis:8888/WebServices.asmx/ActualizarPassword", { claveAntigua: $("#txtClave").val(), claveNueva: $("#txtClaveNueva").val(), nit: $("#nitUsuario").val() })
                        .done(function (resultado) {
                            num = resultado
                            var respuesta = parseInt(num.documentElement.textContent)
                            if (respuesta >= 1) {
                                toastr.success('Su contraseña fue actualizada correctamente');
                                Limpiar();
                            } else {
                                toastr.error('No se ha podido actualizar la información.');
                                Limpiar();
                            }

                        }).fail(function (resultado) {
                            toastr.error('Hubo un error en el sistema, intente de nuevo más tarde.');
                            Limpiar();
                        });
                }
            });

Y tengo una ServiceReference referenciando la url del IIS así:

He intentado también poner en la ruta de la petición la url del servidor http://iis:8888/WebServices.asmx?op=ActualizarPassword pero tampoco funciona.
Al ejecutar la petición se va por el fail de la petición y sale un error 500

Cualquier aporte me ayudará mucho para conocer cuál es el problema el cual se está presentando.

A: Cuando publicas un WS en IIS no te va a mostrar los parámetros, ésto solo lo muestra localmente, no implica que no podas consumir tu servicio web.
El error 500, se muestra porque tu servicio web está caído.
El motivo por el que no te consume el servicio web puede ser porque que tu WS no tiene los parámetros de configuración en el web.config.
Pon los siguientes parámetros de configuración de protocolos en el web.config de tu WS y nos cuentas como te va.

  <system.webServer>
    <httpProtocol>
      <customHeaders>
       <add name="Access-Control-Allow-Origin" value="*" />
       <add name="Access-Control-Allow-Headers" value="Content-Type" />
       <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>


Q: Binomial expansion and combinatorics Coefficient of $x^{11}$ in the expansion of $(1+x^2)^4 (1+x^3)^7 (1+x^4)^{12}$ is
If I were to write out all the product terms straight out, I would have 23 terms to choose from. How do I actually apply such combinatorics approach to solve it? I realize that I will have to sum up different cases of choosing out terms to make up $x^{11}$ but can someone help me figure out how?

A: Remember the binomial theorem tells us that the coefficient of $a^k$ in $(1+a)^n$ is $_nC_k$.
Identify the different compositions of terms where the product gives $x^{11}$.
From $(1+x^2)^4(1+x^3)^7(1+x^4)^{12}$, we have $x^0x^3x^8,x^2x^9x^0,x^4x^3x^4,x^8x^3x^0$. If you find the coefficients for each of these, and add them up, you'll get the answer (which should be $1113$).

A: Put
 $P(u)=(1+u)⁴(1+u^2)^{12}$ and $Q(u)=(1+u)^7$. your expression is $P(x^2)Q(x^3)$. You obtain a term in $x^{11}$ by the product of a term in $P(x^2)$, say $x^{2k}$ (up to a constant), and a term in $Q(x^3)$, say $x^{3l}$, we must have $11=2k+3l$. Compute the solutions to this equation,  , $k=1$ and $l=3$ and $k=4$, $l=1$. So you have to find the coefficient of $u^3$ in $Q$, and the coefficient of $u$ in $P(u)$ (ie to compute $P^{\prime}(0)$), and to multiply them. Do the same for the second case. It is easy to finish.


Q: Cache Get_posts I have a query (see below) that gives a list of 10 news items ordered by the meta value "event_date" and filtered so that only posts earlier than today are displayed. This query is taking two seconds to process, so I am looking for a simple way to cache the results to get the load time faster. I already use WPEngine so I don't need any caching plugins. Thanks in advance for your help.
<?php $today = time();?>
<?php $args = array(
'numberposts' => 10,
'orderby'       => 'meta_value_num',
'order'         => 'DESC',
'meta_key'      => 'event_date',
'meta_query'    => array(
    array(
        'key' => 'event_date',
        'value' => $today,
        'compare' => '<=',
        'type' => 'NUMERIC'
        )
    )
 );

$postslist = get_posts( $args );

foreach ($postslist as $post) :  setup_postdata($post); ?>

A: You can use transient cache to cache your custom query. Here is a simple code to set_transient cache for your query for 12 hours. In 12 hours WordPress will not make new query but fetch posts from transient. On expiration, it will save new query in transient again for next 12 hours.
I have been using transient for many queries on my website but make sure you set expiration time carefully otherwise your new post might not appear on your website for some time.
<?php

    // Check for transient. If none, then execute Query
    if ( false === ( $postslist = get_transient( 'postslist_query' ) ) ) {

        $args = array(
            'numberposts' => 10,
            'orderby'       => 'meta_value_num',
            'order'         => 'DESC',
            'meta_key'      => 'event_date',
            'meta_query'    => array(
                array(
                    'key' => 'event_date',
                    'value' => $today,
                    'compare' => '<=',
                    'type' => 'NUMERIC'
                )
            )
        );

        $postslist = get_posts( $args );

      // Put the results in a transient. Expire after 12 hours.
      set_transient( 'postslist_query', $postslist, 12 * 60 * 60 );

    }

    foreach ( $postslist as $post ) :  setup_postdata( $post );

?>

read more on Transient API

A: I wrapped @Robert-hue's code into a helper method called get_cached_posts, which is a drop-in replacement for get_posts with Transients caching enabled:
/**
 * Gets cached posts for a query. Results are stored against a hash of the
 * parameter array. If there's nothing in the cache, a fresh query is made.
 *
 * @param Array $args The parameters to pass to get_posts().
 * @return Array List of posts matching $args.
 */
public static function get_cached_posts( $args )
{
    $post_list_name = 'get_posts_' . md5( json_encode( $args ) );

    if ( false === ( $post_list = get_transient( $post_list_name ) ) ) {
        $post_list = get_posts( $args );

        set_transient( $post_list_name, $post_list, 86400 );
    }

    return $post_list;
}

Note: 86400 is one day.


Q: Standard ml function in datatype problem I have to create a function about peano numbers defined as the following datatype:
datatype 'a peano = P of ('a -> 'a) * 'a -> 'a
val zero = P(fn (f, x) => x)

The function that I have to implement finds the succesive peano number of the peano parameter P(p). This is what I have written:
fun suc (P(p)) = case P(p) of P(fn(f,x)=>x) => P(fn(f,x)=>f(x));

The problem is that i get these errors:
stdIn:4.33-4.36 Error: syntax error: deleting FN LPAREN
stdIn:4.43 Error: syntax error found at RPAREN

I don't know what Im doing wrong. Please help!

A: There are a number of problems in this code.  The one the compiler is whining about is that you have a function definition
fn (f,x) => x

on the left-hand side of a case arm, where only patterns are permitted.
Some other problems:

*

*Redundant parentheses make the code hard to read (advice is available on removing them).

*Your case expression is redundant; in the function definition
 fun suc (P p) = ...

it should be possible just to compute with p without any more case analysis.

*Since P carries a function, you will probably have an easier time if you write
 fun suc (P f) = ...

and make sure that in the result, f is applied to a pair (as required by the datatype declarations).


Q: VS Code Node.js - Run and Debug opens automatically when encountering a break point whenever I debug Node.JS in VS Code and a breakpoint is encountered, the "Run and Debug" window open automatically (as if I pressed Ctrl+Shift+D). It is very annoying, how can I disable it?


Q: iframe won't show up unless domain has www I have a site with an iframe. The iframe shows up if the address url is www.mysite.com, but not if I use mysite.com.  The iframe location is www.mysite.com/thepage.html
The JS error I get is.

Load denied by X-Frame-Options: the site page does not permit
  cross-origin framing.

On my server (webfaction) I have the site setup to recognize both with and without the www -- a control panel item on webfaction.
How do I get mysite.com to show the iframe?

A: I'm afraid the webmaster of the domain has set XSS protection. So to load a XSS protected site with javascript is simply can't be done.
Update: XSS only allow access to data if both frames (iframe/parent frame) they are on the same protocol, have the exact domain name (mysite.com == mysite.com, but www.mysite.com != mysite.com they are considered different) and both of frames running on the same port. But though, you can ive it a try by placing document.domain on all pages so it allows communication even on different subdomains.


Q: How to store value of pointer in a recursive function? Let say now I would like to write a function that search a certain node in a linked list recursively. When I successfully reached the targeted node, this function will return the ID and another information of it by reference, where its ID will be stored by struct:
struct P{
     int ID;
     int some_info;
     P* next_node;
}

The function will be something like
void search(int targeted_ID, P*& current_node){
     P* c = current_node;
     if(c->ID == targeted_ID){
           current_node = c;
     }
     if(c->next_node == nullptr){
           return;
     }
     else{
          search(ID, current_node->next_node);
     }
}

And the output statement will be something like
cout << "The targeted node have ID= " << current_node->ID << "with" << current_node->some_info << endl;

However, this function will recursively called by itself until all node has been reached and checked, and the value of pointer current_node will constantly changed throughout the process.
The main question is how can I remain the value of it unchanged when doing recursion.
p.s. There are constraints that:

*

*Cannot add any global variable

*Cannot use any static variable

*Cannot add any parameters in the void function

*Cannot use array

*Cannot changed the struct's content

*The output statement cannot be changed

*Cannot use goto

A: I just coded a bit, as @Ted Lyngmo pointed out, you have to return a value, so you can't use a void-function.
Here is the code:
#include <iostream>

struct P {
    int ID;
    int some_info;
    P* next_node;
};

P* newNode(int ID, int some_info) {
    P* temp = new (std::nothrow) P;

    if (temp == nullptr){
        return nullptr;
    }
    else {
        temp->ID = ID;
        temp->some_info = some_info;
        temp->next_node = nullptr;
        return temp;
    }
}

P* search(int targeted_ID, P* current_node) {
    // check if current node is valid
    if (current_node == nullptr) {
        return nullptr;
    }
    // check for ID of current node
    else if (current_node->ID == targeted_ID) {
        return current_node;
    }
    // this node isn't the desired one --> go to nex node
    else {
        return search(targeted_ID, current_node->next_node);
    }
}

void freeMem(P* list) {
    P* tmp = nullptr;

    while (list != nullptr) {
        tmp = list->next_node;
        delete list;
        list = tmp;
    }
}

int main()
{
    P* list = nullptr;
    P* tmp = nullptr;
    P* lastNode = nullptr;

    // populate list
    for (int i = 0; i < 10; ++i) {
        tmp = newNode(i, i * 10);

        if (tmp == nullptr) {
            // error occured
            // free memory
            freeMem(list);
            list = nullptr;
            return -1;
        }

        if (list == nullptr) {
            // first node
            list = tmp;
            lastNode = list;
        }
        else {
            lastNode->next_node = tmp;
            lastNode = tmp;
        }
    }

    tmp = nullptr;
    lastNode = nullptr;

    int ID_to_find = 1;
    P* node = search(ID_to_find, list);

    if (node == nullptr) {
        // node not found ...
        std::cout << "node not found" << std::endl;
    }
    else {
        // node found
        std::cout << "node found at: " << node << std::endl;
    }

    freeMem(list);
    list = nullptr;

    return 0;
}

This code works, but it is not really C++, it is more like C. If you want to write C++-Code use STL-Containers and don't write your own list, because it will be much more readable and the chance to have a bug is much smaller. Also consider to use exceptions instead of (std::nothrow).

A: Recursive:
void search(int targeted_ID, P*& current_node) {
    if(current_node && current_node->ID != targeted_ID) {
         current_node = current_node->next_node;
         search(targeted_ID, current_node);
    }
}

But I suggest a non-recursive version to not get stack overflow when searching a long linked list:
void search(int targeted_ID, P*& current_node) {
    while(current_node && current_node->ID != targeted_ID)
        current_node = current_node->next_node;
}

Demo


Q: Powershell: Unquoting arguments when invoking an external command Consider the following cmd.exe batch script:
testpar.cmd
@echo [%1] [%2]

If we call it it in Powershell, these results are rather obvious:
PS> .\testpar.cmd arg1 arg2
[arg1] [arg2]
PS> .\testpar.cmd "arg1 arg2"
["arg1 arg2"] []

But, when passing a variable:
PS> $alist= "arg1 arg2"
PS> .\testpar.cmd $alist
["arg1 arg2"] []

It seems that $alist is passed with quotes.
One solution:
PS> $alist= "`"arg1`" `"arg2`""
PS> .\testpar.cmd $alist
["arg1"] ["arg2"]

which identifies arguments, but without stripping quotes.
Another possibility:
PS> Invoke-Expression  (".\testpar.cmd " + $alist)
[arg1] [arg2]

This works, but is very convoluted.  Any better way?
In particular is there a way to unquote  a string variable?

A: I found a similar question here
What you can do is use a comma: $alist = "a,b"

The comma will be seen as a paramater seperator:
PS D:\temp> $arglist = "a,b"
PS D:\temp> .\testpar.cmd $arglist
[a] [b]

You can also use an array to pass the arguments:
PS D:\temp> $arglist = @("a", "c")
PS D:\temp> .\testpar.cmd $arglist
[a] [c]

A: The most convenient way to  me to pass $alist is:
PS> .\testpar.cmd $alist.Split()
[arg1] [arg2]

In this way I don't need to change the way I build $alist.
Besides Split() works well also for quoted long arguments:
PS> $alist= @"
>> "long arg1" "long arg2"
>> "@

This is:
PS> echo $alist
"long arg1" "long arg2"

and gives:
PS> .\testpar.cmd $alist.Split()
["long arg1"] ["long arg2"]

A: In general, I would recommend using an array to build up a list of arguments, instead of mashing them all together into a single string:
$alist = @('long arg1', 'long arg2')
.\testpar.cmd $alist

If you need to pass more complicated arguments, you may find this answer useful.


Q: split(regexp_replace ) Like Function In Presto : 331 Is there any way to split values based on consecutive 0's in presto.Minimum 6 digits should be there in first split, if digit count is less than 6 than need to consider some 0's as digit then split if digit count is  >= 6 then just need to split in 2 groups.
below query is working as expected in Hive.But I am not able to do the same using presto.
 select low as orginal_Value,
 split(regexp_replace(low,'(\\d{6,}?)(0+)$','$1|$2'),'\\|')  Output_Value  from test;

Presto Query:
presto> SELECT regexp_split('1234567890000', '(\d{6,}?)(0+)$') as output;

output
[1234567890000]
(1 row)

A: It worked Now.
select split(regexp_replace('1234567890000','(\d{6,}?)(0+)$','$1|$2'), '|') as output;
enter code here

output
-------------------
[123456789, 0000]


Q: About graph of a Lebesgue measurable function I have been dealing with the following question, but could not find the answer. How can I solve ?
Question: Let $f\colon\mathbb{R} \to \mathbb{R}$ be a Lebesgue measurable function and $E:=\{(x,f(x)) \in \mathbb{R}^2 \mid x \in \mathbb{R} \} \subset \mathbb{R}^2$ be graph of the function. If $\operatorname{esssup}\{|f(x)| : x \in [-n,n] \} < \infty$ for all $n \in \mathbb{N}$, then for each $\epsilon > 0$
there exists a Lebesgue measurable set $K \subset \mathbb{R}^2$ such that $E \subset K$ and $\operatorname{Area}(K) < \epsilon$.
EDIT: My idea is that
Let $\{(a_i,b_i)\}$ be a sequence covering $\mathbb{R}$ with $b_i−a_i=1, \forall i \in \mathbb{N}$.
Define $$K_i:=\{(x,f(x)−\frac{\epsilon}{2^{i+2}})\times(x,f(x)+\frac{\epsilon}{2^{i+2}}) \mid x \in (a_i,b_i)\}$$
Then $K = \bigcup_i K_i$ covers $E$ and
$$\lambda(K) \leq \sum_i(b_i−a_i)\frac{2\epsilon}{2^{i+2}}= \frac{\epsilon}{2} < \epsilon.$$
If it is true, can you tell me in which step I used essentially boundedness of $f$ ?
Since $f(x)$ is essentially bounded, $\lambda((f(x)+\epsilon) - (f(x)-\epsilon))=2\epsilon$ ?


Q: Why global variable inside jQuery each() function is breaking up my rollover effect? I'm trying to accomplish a rollover effect through jQuery in which when I hover over a black & white image, it gets replaced by the colored one & when I move out of the image, the original B&W image appears again. The code I'm using is :
var origImgSrc;
$('#gallery img').each(function() {
    origImgSrc = $(this).attr('src');
    var imgExt = /(\.\w{3,4}$)/;
    var newImg = origImgSrc.replace(imgExt, '_h$1');
    $(this).hover(function() {
      $(this).attr('src', newImg);
     }, function() {
      $(this).attr('src', origImgSrc);
     }); // end hover
}); // end each

I have two copies of each image(one B&W, one colored). For example, green.jpg (B&W), green_h.jpg (colored). A regular expression replaces the name of image & whole code is written directly inside $(document).ready() method.
The code somewhat works, when I hover over any of the image, it gets replaced by its corresponding colored one but on mouseout, irrespective of the image, the original image now gets replaced by the last image in the markup, the actual corresponding B&W image doesn't come back.
I came down to a working solution i.e. instead of declaring var origImgSrc; variable outside the each function, I should define it inside the each function. The rollover effect now works perfectly but I want to find what exactly goes wrong here & the possible reason I came across for this behaviour is Asynchronous flow of JS or the Asynchronicity. Completely read about it & understood it but still I can't relate this problem to it.
Can anybody please explain in any way what's going wrong here? Whether by taking the help of JS runtime's Call Stack, WebAPIs, Callback Queue, etc. I understand these concepts but in context of quite easy examples, just can't relate in this case.

A: Because when hover callback runs it use global variable origImgSrc.
Variable origImgSrc rewrites every iteration and equals last image src after all.
Just put origImgSrc into your each.


Q: sqlite3 autoincrement - am I missing something? I want to create unique order numbers for each day. So ideally, in PostgreSQL for instance, I could create a sequence and read it back for these unique numbers, because the readback both gets me the new number and is atomic. Then at close of day, I'd reset the sequence.
In sqlite3, however, I only see an autoincrement for the integer field type. So say I set up a table with an autoincrement field, and insert a record to get the new number (seems like an awfully inefficient way to do it, but anyway...) When I go to read the max back, who is to say that another task hasn't gone in there and inserted ANOTHER record, thereby causing me to read back a miss, with my number one too far advanced (and a duplicate of what the other task reads back.)
Conceptually, I require:

*

*fast lock with wait for other tasks

*increment number

*retrieve number

*unlock

...I just don't see how to do that with sqlite3. Can anyone enlighten me?

A: In SQLite, autoincrementing fields are intended to be used as actual primary keys for their records.
You should just it as the ID for your orders table.
If you really want to have an atomic counter independent of corresponding table records, use a table with a single record.
ACID is ensured with transactions:
BEGIN;
SELECT number FROM MyTable;
UPDATE MyTable SET number = ? + 1;
COMMIT;

A: ok, looks like sqlite either doesn't have what I need, or I am missing it. Here's what I came up with:

*

*declare zorder as integer primary key autoincrement, zuid integer in orders table
this means every new row gets an ascending number, starting with 1

*generate a random number:
rnd = int(random.random() * 1000000) # unseeded python uses system time

*create new order (just the SQL for simplicity):
'INSERT INTO orders (zuid) VALUES ('+str(rnd)+')'

*find that exact order number using the random number:
'SELECT zorder FROM orders WHERE zuid = '+str(rnd)

*pack away that number as the new order number (newordernum)

*clobber the random number to reduce collision risks
'UPDATE orders SET zuid = 0 WHERE zorder = '+str(newordernum)
...and now I have a unique new order, I know what the correct order number is, the risk of a read collision is reduced to negligible, and I can prepare that order without concern that I'm trampling on another newly created order.
Just goes to show you why DB authors implement sequences, lol.


Q: What would be a globally accepted regular expression to match e-mail addresses I have seen many examples, with many 'no, you missed something' comments.  What is the right way to match an e-mail address?
For Sanity sake, only fully-qualified domain names, no @localhost allowed. (or, both ways)
Subdomains must be allowed (issac@deptartment.company.museum)

A: It is impossible to do so in a pure regex. Regexen cannot match nested parentheses, which the full RFC spec requires. (The latest RFC on this matter is RFC5322, only released a few months ago.)
Full validation of email addresses requires something along the lines of a CFG, and there are a few more things to be wary of; for example, email addresses can contain '\0', the null character... so you can't use any of C's normal string functions on them.
I actually feel a bit weird answering a question with a link to something I've written, but as it so happens, I have one I prepared earlier: a short and (as far as I can tell) fully-compliant validator, in Haskell; you can see the source code here. I imagine the code could be easily ported to any similar parsing library (perhaps C++’s Boost.Spirit), or just as easily hooked into from another language (Haskell has a very simple way for C to use Haskell code, and everything can use C bindings...)
There are also extensive test cases in the source code (I didn't export them from the module), which are due to Dominic Sayers, who has his own version of an RFC-compliant parser in PHP. (Several of the tests fail, but they are more strict than RFC5322 specifies, so I'm fine with that at the moment.)

A: That was asked here a couple of weeks ago. What it comes down to is, there are many legal addresses that an easy regex won't match. It takes a truly insane regex to match the majority of legal addresses. And even then, a syntactically legal address doesn't guarantee the existence of an account behind it - take foo@example.invalid, for example.

A: Not to mention that Chinese/Arabic domain names are to be allowed in the near future. Everyone has to change the email regex used, because those characters are surely not to be covered by [a-z]/i nor \w. They will all fail.
After all, best way to validate the email address is still to actually send an email to the address in question to validate the address. If the email address is part of user authentication (register/login/etc), then you can perfectly combine it with the user activation system. I.e. send an email with a link with an unique activation key to the specified email address and only allow login when the user has activated the newly created account using the link in the email.
If the purpose of the regex is just to quickly inform the user in the UI that the specified email address doesn't look like in the right format, best is still to check if it matches basically the following regex:
([^.@]+)(\\.[^.@]+)*@([^.@]+\\.)+([^.@]+)

Simple as that. Why on earth would you care about the characters used in the name and domain?

A: Unfortunately, it's not a regex, but...  The right way to validate an email address is to send it a message and see if the user replies.
If you really, really want to verify that an address is syntactically-valid/RFC-compliant, then a regex is still unlikely to be the right tool for the job.  You could most likely create a parser in fewer characters than the length of a regex with a similar level of RFC compliance and the parser would probably run faster to boot.
Even with a perfect test of RFC compliance, anon@ymo.us is perfectly-formed and refers to an existing domain, so you're not going to know whether the address you're given is actually valid or not unless you send it a message.

A: General advice is don't
It's probably worth a simple check that they entered "something@somethign.something" just to check they put the email in the right box.
Beyond that most of the official regex allow for so many obscure cases that they have a huge false positive rate (they will allow technically legal but extremely unlikely
entries)

A: From http://www.ex-parrot.com/~pdw/Mail-RFC822-Address.html :
The grammar described in RFC 822 is suprisingly complex. Implementing validation with regular expressions somewhat pushes the limits of what it is sensible to do with regular expressions, although Perl copes well:
(?:(?:\r\n)?[ \t])*(?:(?:(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t]
)+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:
\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(
?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[
\t]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\0
31]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\
](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+
(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:
(?:\r\n)?[ \t])*))*|(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z
|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)
?[ \t])*)*\<(?:(?:\r\n)?[ \t])*(?:@(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\
r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[
 \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)
?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t]
)*))*(?:,@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[
 \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*
)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t]
)+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*)
*:(?:(?:\r\n)?[ \t])*)?(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+
|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r
\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:
\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t
]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031
]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](
?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?
:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?
:\r\n)?[ \t])*))*\>(?:(?:\r\n)?[ \t])*)|(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?
:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?
[ \t]))*"(?:(?:\r\n)?[ \t])*)*:(?:(?:\r\n)?[ \t])*(?:(?:(?:[^()<>@,;:\\".\[\]
\000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|
\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>
@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"
(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t]
)*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\
".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?
:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[
\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*|(?:[^()<>@,;:\\".\[\] \000-
\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(
?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)*\<(?:(?:\r\n)?[ \t])*(?:@(?:[^()<>@,;
:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([
^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\"
.\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\
]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*(?:,@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\
[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\
r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\]
\000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]
|\\.)*\](?:(?:\r\n)?[ \t])*))*)*:(?:(?:\r\n)?[ \t])*)?(?:[^()<>@,;:\\".\[\] \0
00-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\
.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,
;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?
:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*
(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".
\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[
^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]
]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*\>(?:(?:\r\n)?[ \t])*)(?:,\s*(
?:(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\
".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(
?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[
\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t
])*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t
])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?
:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|
\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*|(?:
[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\
]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)*\<(?:(?:\r\n)
?[ \t])*(?:@(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["
()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)
?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>
@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*(?:,@(?:(?:\r\n)?[
 \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,
;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t]
)*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\
".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*)*:(?:(?:\r\n)?[ \t])*)?
(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".
\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:
\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[
"()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])
*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])
+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\
.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z
|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*\>(?:(
?:\r\n)?[ \t])*))*)?;\s*)

A: This regular expression complies with the grammar described in RFC 2822, it's very long, but the grammar described in the RFC is complex...

A: If you're using Perl, I believe the Regex::Common module would be the one you want to use, and in particular, Regex::Common::Email::Address.

A: I had to recently build some RSS feeds, and part of that included going over the Xml schema, including the items for Webmaster and ManagingEditor, both of which are defined as an e-mail address matching this pattern:
([a-zA-Z0-9_\-])([a-zA-Z0-9_\-\.]*)@(\[((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}|((([a-zA-Z0-9\-]+)\.)+))([a-zA-Z]{2,}|(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\])


Q: CSS-only masonry layout I need to implement a masonry layout. However, for a number of reasons I don't want to use JavaScript to do it.

Parameters:

*

*All elements have the same width

*Elements have a height that cannot be calculated server side (an image plus various amounts of text)

*I can live with a fixed number of columns if I have to

there is a trivial solution to this that works in modern browsers, the column-count property.
The problem with that solution is that elements are ordered in columns:

While I need the elements to be ordered in rows, at least approximately:

Approaches I've tried that don't work:

*

*Making items display: inline-block: wastes vertical space.

*Making items float: left: lol, no.
Now I could change the server side rendering and reorder the items dividing the number of items by the number of columns, but that's complicated, error-prone (based on how browsers decide to split the item list into columns), so I'd like to avoid it if possible.
Is there some flexbox magic that makes this possible?

A: I find This solution, It is most probably compatible with all browsers.
Note: if anyone finds any error or browser support issues. please update this answer Or comments
CSS Profpery Support reference:
column-count, gap, fill break-inside, page-break-inside
Note: page-break-inside This property has been replaced by the break-inside property.

.container {
  -moz-column-count: 1;
       column-count: 1;
  -moz-column-gap: 20px;
       column-gap: 20px;
  -moz-column-fill: balance;
       column-fill: balance;
  margin: 20px auto 0;
  padding: 2rem;
}
.container .item {
  display: inline-block;
  margin: 0 0 20px;
  page-break-inside: avoid;
  -moz-column-break-inside: avoid;
       break-inside: avoid;
  width: 100%;
}
.container .item img {
  width: 100%;
  height: auto;
}
@media (min-width: 600px) {
  .container {
    -moz-column-count: 2;
         column-count: 2;
  }
}
@media (min-width: 900px) {
  .container {
    -moz-column-count: 3;
         column-count: 3;
  }
}
@media (min-width: 1200px) {
  .container {
    -moz-column-count: 4;
         column-count: 4;
  }
}

 CSS-Only Masonry Layout

A: Finally a CSS-only solution to easily create masonry layout but we need to be patient since there is no support for it for now.
This feature was introduced in the CSS Grid Layout Module Level 3

This module introduces masonry layout as an additional layout mode for CSS Grid containers.

Then

Masonry layout is supported for grid containers by specifying the value masonry for one of its axes. This axis is called the masonry axis, and the other axis is called the grid axis.

A basic example would be:

.container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  grid-template-rows: masonry; /* this will do the magic */
  grid-gap: 10px;
}

img {
  width: 100%;
}

This will produce the following result on Firefox if you enable the feature like explained here: https://caniuse.com/?search=masonry

*

*open Firefox and write about:config in the url bar

*do a search using masonry

*you will get one flag, make it true

If we reduce the screen screen, the reponsive part is perfect!

A: 2021 Update
CSS Grid Layout Level 3 includes a masonry feature.
Code will look like this:
grid-template-rows: masonry
grid-template-columns: masonry

As of March 2021, it's only available in Firefox (after activating the flag).

*

*https://drafts.csswg.org/css-grid-3/#masonry-layout

*https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout/Masonry_Layout
end update; original answer below

Flexbox
A dynamic masonry layout is not possible with flexbox, at least not in a clean and efficient way.
Flexbox is a one-dimensional layout system. This means it can align items along horizontal OR vertical lines. A flex item is confined to its row or column.
A true grid system is two-dimensional, meaning it can align items along horizontal AND vertical lines. Content items can span across rows and columns simultaneously, which flex items cannot do.
This is why flexbox has a limited capacity for building grids. It's also a reason why the W3C has developed another CSS3 technology, Grid Layout.

row wrap
In a flex container with flex-flow: row wrap, flex items must wrap to new rows.
This means that a flex item cannot wrap under another item in the same row.

Notice above how div #3 wraps below div #1, creating a new row. It cannot wrap beneath div #2.
As a result, when items aren't the tallest in the row, white space remains, creating unsightly gaps.

column wrap
If you switch to flex-flow: column wrap, a grid-like layout is more attainable. However, a column-direction container has four potential problems right off the bat:

*

*Flex items flow vertically, not horizontally (like you need in this case).

*The container expands horizontally, not vertically (like the Pinterest layout).

*It requires the container to have a fixed height, so the items know where to wrap.

*As of this writing, it has a deficiency in all major browsers where the container doesn't expand to accommodate additional columns.

As a result, a column-direction container is not an option in this case, and in many other cases.

CSS Grid with item dimensions undefined
Grid Layout would be a perfect solution to your problem if the various heights of the content items could be pre-determined. All other requirements are well within Grid's capacity.
The width and height of grid items must be known in order to close gaps with surrounding items.
So Grid, which is the best CSS has to offer for building a horizontally-flowing masonry layout, falls short in this case.
In fact, until a CSS technology arrives with the ability to automatically close the gaps, CSS in general has no solution. Something like this would probably require reflowing the document, so I'm not sure how useful or efficient it would be.
You'll need a script.
JavaScript solutions tend to use absolute positioning, which removes content items from the document flow in order to re-arrange them with no gaps. Here are two examples:

*

*Desandro Masonry

Masonry is a JavaScript grid layout library. It
works by placing elements in optimal position based on available
vertical space, sort of like a mason fitting stones in a wall.
source: http://masonry.desandro.com/

*

*How to Build a Site that Works Like Pinterest

[Pinterest] really is a cool site, but what I find interesting is how these pinboards are laid out... So the purpose of this tutorial is to re-create this responsive block effect ourselves...
source: https://benholland.me/javascript/2012/02/20/how-to-build-a-site-that-works-like-pinterest.html

CSS Grid with item dimensions defined
For layouts where the width and height of content items are known, here's a horizontally-flowing masonry layout in pure CSS:

grid-container {
  display: grid;                                                /* 1 */
  grid-auto-rows: 50px;                                         /* 2 */
  grid-gap: 10px;                                               /* 3 */
  grid-template-columns: repeat(auto-fill, minmax(30%, 1fr));   /* 4 */
}

[short] {
  grid-row: span 1;                                             /* 5 */
  background-color: green;
}

[tall] {
  grid-row: span 2;
  background-color: crimson;
}

[taller] {
  grid-row: span 3;
  background-color: blue;
}

[tallest] {
  grid-row: span 4;
  background-color: gray;
}

grid-item {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.3em;
  font-weight: bold;
  color: white;
}
<grid-container>
  <grid-item short>01</grid-item>
  <grid-item short>02</grid-item>
  <grid-item tall>03</grid-item>
  <grid-item tall>04</grid-item>
  <grid-item short>05</grid-item>
  <grid-item taller>06</grid-item>
  <grid-item short>07</grid-item>
  <grid-item tallest>08</grid-item>
  <grid-item tall>09</grid-item>
  <grid-item short>10</grid-item>
  <grid-item tallest>etc.</grid-item>
  <grid-item tall></grid-item>
  <grid-item taller></grid-item>
  <grid-item short></grid-item>
  <grid-item short></grid-item>
  <grid-item short></grid-item>
  <grid-item short></grid-item>
  <grid-item tall></grid-item>
  <grid-item short></grid-item>
  <grid-item taller></grid-item>
  <grid-item short></grid-item>
  <grid-item tall></grid-item>
  <grid-item short></grid-item>
  <grid-item tall></grid-item>
  <grid-item short></grid-item>
  <grid-item short></grid-item>
  <grid-item tallest></grid-item>
  <grid-item taller></grid-item>
  <grid-item short></grid-item>
  <grid-item tallest></grid-item>
  <grid-item tall></grid-item>
  <grid-item short></grid-item>
</grid-container>

jsFiddle demo

How it works

*

*Establish a block-level grid container. (inline-grid would be the other option)

*The grid-auto-rows property sets the height of automatically generated rows. In this grid each row is 50px tall.

*The grid-gap property is a shorthand for grid-column-gap and grid-row-gap. This rule sets a 10px gap between grid items. (It doesn't apply to the area between items and the container.)

*The grid-template-columns property sets the width of explicitly defined columns.

The repeat notation defines a pattern of repeating columns (or rows).
The auto-fill function tells the grid to line up as many columns (or rows) as possible without overflowing the container. (This can create a similar behavior to flex layout's flex-wrap: wrap.)
The minmax() function sets a minimum and maximum size range for each column (or row). In the code above, the width of each column will be a minimum of 30% of the container and maximum of whatever free space is available.
The fr unit represents a fraction of the free space in the grid container. It's comparable to flexbox's flex-grow property.

*With grid-row and span we're telling grid items how many rows they should span across.

Browser Support for CSS Grid

*

*Chrome - full support as of March 8, 2017 (version 57)

*Firefox - full support as of March 6, 2017 (version 52)

*Safari - full support as of March 26, 2017 (version 10.1)

*Edge - full support as of October 16, 2017 (version 16)

*IE11 - no support for current spec; supports obsolete version

Here's the complete picture: http://caniuse.com/#search=grid

Cool grid overlay feature in Firefox
In Firefox dev tools, when you inspect the grid container, there is a tiny grid icon in the CSS declaration. On click it displays an outline of your grid on the page.

More details here: https://developer.mozilla.org/en-US/docs/Tools/Page_Inspector/How_to/Examine_grid_layouts

A: This is recently discovered technique involving flexbox: https://tobiasahlin.com/blog/masonry-with-css/.
The article makes sense to me, but I haven't tried to use it, so I don't know if there are any caveats, other than mentioned in Michael's answer.
Here's a sample from the article, making use of the order property, combined with :nth-child.
Stack snippet

.container {
  display: flex;
  flex-flow: column wrap;
  align-content: space-between;
  /* Your container needs a fixed height, and it
   * needs to be taller than your tallest column. */
  height: 960px;

  /* Optional */
  background-color: #f7f7f7;
  border-radius: 3px;
  padding: 20px;
  width: 60%;
  margin: 40px auto;
  counter-reset: items;
}

.item {
  width: 24%;
  /* Optional */
  position: relative;
  margin-bottom: 2%;
  border-radius: 3px;
  background-color: #a1cbfa;
  border: 1px solid #4290e2;
  box-shadow: 0 2px 2px rgba(0,90,250,0.05),
    0 4px 4px rgba(0,90,250,0.05),
    0 8px 8px rgba(0,90,250,0.05),
    0 16px 16px rgba(0,90,250,0.05);
  color: #fff;
  padding: 15px;
  box-sizing: border-box;
}

 /* Just to print out numbers */
div.item::before {
  counter-increment: items;
  content: counter(items);
}

/* Re-order items into 3 rows */
.item:nth-of-type(4n+1) { order: 1; }
.item:nth-of-type(4n+2) { order: 2; }
.item:nth-of-type(4n+3) { order: 3; }
.item:nth-of-type(4n)   { order: 4; }

/* Force new columns */
.break {
  flex-basis: 100%;
  width: 0;
  border: 1px solid #ddd;
  margin: 0;
  content: "";
  padding: 0;
}

body { font-family: sans-serif; }
h3 { text-align: center; }


Q: How can I get translateZ to work in svg groups? I have created a svg image animation. I am trying to make some nice effects with mouseover. I want to move the svg depending on mouse position. The rotate part works fine so far. But I also want to move the <g> inside the svg in z-axis (popout) so they comes out in "different layers". Should be possible with translateZ(). But I can not get it to work.

const container = document.querySelector('.container');
const image = document.querySelector('.image');

const sun = document.querySelector('.sun');
const cloudBehind = document.querySelector('.cloud-center');
const cloudLeft = document.querySelector('.cloud-left');
const cloudRight = document.querySelector('.cloud-right');

const devideAxis = 10;

container.addEventListener('mousemove', e => {
  let xAxis = ~(window.innerWidth / 2 - e.pageX) / devideAxis;
  let yAxis = (window.innerHeight / 2 - e.pageY) / devideAxis;

    image.style.transform = `rotateY(${xAxis}deg) rotateX(${yAxis}deg)`;
});

container.addEventListener('mouseenter', e => {
    image.style.transition = 'none';
  //popout
  cloudLeft.style.transform = 'translateZ(400px)'
})

container.addEventListener('mouseleave', e => {
    image.style.transition = 'all 0.5s ease';
    image.style.transform = `rotateY(0deg) rotateX(0deg)`

  cloudLeft.style.transform = 'translateZ(0)'
})
body,html {
  height: 100%;
  width: 100%;
  padding: 0;
  margin: 0;
  perspective: 300px;
}

.container {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.image {
  width: 50%;
  transform-style: preserve-3d;
}

.cloud-left {
  transition: all .5s ease-out
}

.cloud-left,
.cloud-right,
.cloud-center {
  transition: transform .5s;
}

.cloud-center{
  fill:url(#CLOUD-CENTER);
}
.cloud-right{
  fill:url(#CLOUD-FRONT);
}
.cloud-left{
  fill:url(#CLOUD-FRONT);
}
.sun{
  fill:url(#SUN);
}
.shine{
  fill:url(#SHINE);
}

    <?xml version="1.0" encoding="utf-8"?>
    <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
       viewBox="0 0 500 250" >

    <g id="wheather">
      <radialGradient id="SHINE" cx="100" cy="100" r="100" gradientUnits="userSpaceOnUse">
        <stop  offset="0.7568" style="stop-color:#FFFFFF"/>
        <stop  offset="1" style="stop-color:#FFF3AB"/>
      </radialGradient>
      <linearGradient id="SUN" gradientUnits="userSpaceOnUse" x1="27.6083" y1="98.0519" x2="169.5758" y2="98.0519">
        <stop  offset="0" style="stop-color:#FFF3AB"/>
        <stop  offset="1" style="stop-color:#FFF2C0"/>
      </linearGradient>
      <linearGradient id="CLOUD-CENTER" gradientUnits="userSpaceOnUse" x1="0" y1="66.2549" x2="288.0558" y2="66.2549">
        <stop  offset="0" style="stop-color:#8EABBF"/>
        <stop  offset="1" style="stop-color:#ECF1F7"/>
      </linearGradient>
      <linearGradient id="CLOUD-FRONT" gradientUnits="userSpaceOnUse" x1="0" y1="62.1091" x2="294.4617" y2="62.1091">
        <stop  offset="5.759445e-07" style="stop-color:#FFFFFF"/>
        <stop  offset="1" style="stop-color:#C5D6E5"/>
      </linearGradient>

      <g transform="translate(250 0)" class="sun">
        <path class="shine" d="M162.4,147.8l22,0.9l-9.8-15.5c-0.2-0.5-0.5-1-0.8-1.5v0c-3.1-4.9-1.6-11.1,3-14.2l20.3-8.1l-14.9-9.9
          c-0.5-0.5-1-0.9-1.5-1.3h0c-4.9-3.3-6-9.8-2.8-14.5l15-15.3l-17.3-2.9c-0.7-0.3-1.4-0.5-2.2-0.6h0c-6-1-9.7-6.9-8.4-12.6l7.3-19.6
          l-16.9,4.3c-0.7,0-1.5,0.1-2.2,0.3h0c-6.3,1.6-12.5-2.9-12.9-9.4v0c0-0.2,0-0.3,0-0.4l-1.2-19.1l-13.8,10.9
          c-0.6,0.3-1.1,0.7-1.7,1.1c-5.1,4-12.6,2.4-15.6-3.3l0,0c-0.2-0.5-0.5-0.9-0.8-1.3L98.6,0l-8.4,16c-0.3,0.4-0.6,0.9-0.8,1.3v0
          c-3,5.8-10.5,7.4-15.6,3.3h0c-0.5-0.4-1.1-0.8-1.7-1.1L58.3,8.6l-1.2,19.1c0,0.1,0,0.3,0,0.4v0c-0.4,6.5-6.6,11-12.9,9.4h0
          c-0.8-0.2-1.5-0.3-2.2-0.3l-16.9-4.3l7.3,19.6c1.3,5.7-2.4,11.6-8.4,12.6h0c-0.8,0.1-1.5,0.3-2.2,0.6L4.3,68.5l15,15.3
          c3.2,4.7,2.1,11.2-2.8,14.5c-0.6,0.4-1.1,0.8-1.5,1.3L0,109.5l20.3,8.1c4.6,3,6.1,9.3,3,14.2l0,0c-0.3,0.5-0.6,1-0.8,1.5l-9.8,15.5
          l22-0.9c5.4,0.9,9.3,6,8.4,11.7v0c0,0.3-0.1,0.6-0.1,0.9l-2.8,19l19.7-9.8c5-1.3,10.3,1.3,12.2,6.1l5.7,20.4l13.8-16.7
          c3.9-3.4,9.7-3.4,13.5,0l13.8,16.7l5.7-20.4c2-4.9,7.3-7.4,12.2-6.1l19.7,9.8l-2.8-19c0-0.3,0-0.6-0.1-0.9v0
          C153.2,153.8,157,148.7,162.4,147.8z">
          <animateTransform
            attributeName="transform"
            attributeType="XML"
            type="rotate"
            from="0 100 100"
            to="360 100 100"
            dur="80s"
            repeatCount="indefinite"
          />

        </path>
        <circle class="sun-inside" cx="98.6" cy="98.1" r="71"/>
      </g>

      <g transform="translate(70 70)">
        <path class="cloud-center" style="transform: " d="M261.5,79.4c-3.4,0-6.6,0.6-9.6,1.8c-1.9-5.5-6-10-11.3-12.5c0-0.2,0-0.3,0-0.5c0-27.1-21.9-49-49-49
          c-0.6,0-1.2,0-1.8,0c-9-11.7-23.1-19.2-39-19.2c-18,0-33.8,9.7-42.3,24.1c-3.8-3.1-8.6-5-13.8-5c-11.1,0-20.3,8.4-21.6,19.2
          c-3.7-1.1-7.7-1.7-11.7-1.7C39,36.6,21,54.6,21,76.9c0,2.8,0.3,5.6,0.9,8.3C9.6,86.1,0,96.3,0,108.8c0,13.1,10.6,23.7,23.7,23.7
          h237.8c14.7,0,26.6-11.9,26.6-26.6S276.2,79.4,261.5,79.4z">
          <animateMotion
            path="M50,0 -50,0 50,0 z"
            dur="80s"
            repeatCount="indefinite"
          />
        </path>
      </g>

      <g transform="translate(10 126)">
        <path class="cloud-left" d="M270.4,76.2C270.4,76.2,270.4,76.2,270.4,76.2c-1.1-22-19.3-39.6-41.6-39.6c-5.1,0-9.9,0.9-14.4,2.6
          C206.9,16.4,185.5,0,160.2,0c-20.6,0-38.6,10.9-48.6,27.3c-4.6-1.5-9.4-2.3-14.5-2.3c-23.4,0-42.8,16.9-46.7,39.1
          c-5.1-3.3-11.2-5.2-17.7-5.2C14.6,58.9,0,73.5,0,91.6c0,18,14.6,32.7,32.7,32.7h237.8c13.3,0,24-10.8,24-24
          C294.5,86.9,283.7,76.2,270.4,76.2z M194.9,102.4h-0.2c0.1,0,0.1-0.1,0.2-0.1C194.9,102.4,194.9,102.4,194.9,102.4z">
          <animateMotion
            path="M30,0 0,0 00,0 30,0 z"
            dur="15s"
            repeatCount="indefinite"
          />
        </path>
      </g>

      <g transform="translate(260 140)">
        <path class="cloud-right" d="M228.8,73.7c0-19.9-16.1-36-36-36c-3.5,0-6.8,0.5-10,1.4c-4.4-18.7-21.2-32.7-41.3-32.7c-10.7,0-20.5,4-28,10.6
          C104.6,6.6,91.4,0,76.7,0C49.9,0,28.3,21.7,28.3,48.4c0,1.6,0.1,3.2,0.2,4.8c-0.1,0-0.2,0-0.2,0C12.7,53.2,0,65.9,0,81.5
          s12.7,28.3,28.3,28.3H198v-0.4C215.4,106.8,228.8,91.8,228.8,73.7z">
          <animateMotion
            path="M-40,0 0,0 -100,0 -40,0 z"
            dur="60s"
            repeatCount="indefinite"
          />
        </path>
      </g>

    </g>
    </svg>

Main code things:
So I have body, which has perspective: 300px;. Then I have .image which has transform-style: preserve-3d; and inside that element I have the <g>'s with classes.
As an example I have a .cloud-left.
So the structure is basically:

      <svg>
        <g id="wheather">
          <g class="cloud-left">...</g>

          ...

       </g>
      </svg>

In javascript I have this (Shortned, to see all code, please see the fiddle above):
const cloudLeft = document.querySelector('.cloud-left'); // get the element

container.addEventListener('mouseenter', e => {
  //popout
  cloudLeft.style.transform = 'translateZ(400px)'
})

container.addEventListener('mouseleave', e => {
  //popback
  cloudLeft.style.transform = 'translateZ(0)'
})

But this does not work as I want.
I have also tried to set transform-style: preserve-3d; on <g id="weather"> which is the direct parent to the other <g>'s, but no difference.
I am not getting the <g> to move/popout in z-axis. Am I missing something in the svg or does this not work in svg groups?
I have another example where this works, but it is not an svg: https://jsfiddle.net/saturday99/94o5j8ts/

A: Ok, so as I suspected. It worked with svg's instead of groups/paths. Paths/groups are 2D only, as figured out. But svg's are possible to make 3D and use translateZ on. Down here is the answer for the future ones looking for answer. Ps. The code could be cleaned up a bit, but it works.
So the basic structure is now split into many svg's instead of one svg containing many groups:

      <svg class="sun">
        <g>

          ...

       </g>
      </svg>
      <svg class="cloud-left">
        <g>

          ...

       </g>
      </svg>

      ...

And here is the "finale" code and solution: https://jsfiddle.net/saturday99/fkrh6bzm/. Feel free to fork the code.


Q: Classification of finite dimensional representations of split complex reductive groups Finite dimensional, irreducible representations of simply connected, complex semisimple algebraic groups can be classified by their highest weight.  I was wondering if there is an analogous classification of representations of reductive groups.
This can be made precise as follows: let $\mathfrak g = \operatorname{Lie}(G)$ with $G$ a complex simply connected algebraic group.  Let $\mathfrak t$ be a Cartan subalgebra of $\mathfrak g$ with set of simple roots $\Delta$ and simple coroots $\Delta^{\vee} \subset \mathfrak t^{\ast}$. We define a partial order on $\mathfrak t^{\ast}$ by saying that $\lambda \geq \mu$ if $\lambda - \mu$ is a nonnegative linear combination of simple coroots.
We say that $\mu \in \mathfrak t^{\ast}$ is dominant if $\langle \mu,\alpha \rangle \geq 0$ for all $\alpha \in \Delta$, and we say that $\mu$ is integral if $\langle \mu, \alpha \rangle$ is an integer for all $\alpha \in \Delta$.
Then there is a bijection between isomorphism classes of irreducible representations of $G$, ones of $\mathfrak g$, and dominant integral weights.  The explicit correspondence is we begin with a representation $(\pi, V)$ of $G$, and let $(d\pi, V)$ be the associated tangent space map on $\mathfrak g$.  Now $V$ has an associated weight space decomposition $V = \bigoplus\limits_{\mu \in \mathfrak t^{\ast}} V_{\mu}$, where $$V_{\mu} = \{ v \in V : d\pi(X)v = \mu(X)v \textrm{ for all } X \in \mathfrak t\}$$ There is a unique maximal dominant, integral element $\mu \in \mathfrak t^{\ast}$ for which $V_{\mu}$ is nonzero, and this $\mu$ determines $\pi$ and $d\pi$ up to isomorphism.
If we assume that $G$ is connected and semisimple, but not necessarily simply connected, then the classification is the same, but $\pi \mapsto d \pi$ is no longer a bijection.

Question: Is there a classification along similar lines to irreducible, finite dimensional representations of connected, complex reductive groups?

When $G$ is reductive, but not semisimple, the notion of highest weight still makes sense, since we can write the Cartan subalgebra as the direct sum of that of the derived group of $G$ and the Lie algebra of the center.


Q: Entity Framework Core, one-to-many relationship, collection always empty I'm trying to do a simple one to many relationship in a InMemory database that is built up in runtime by http requests. I'm new to Entity Framework Core, so I'm unsure if the is a proper way of working with it.
ValuesController.cs
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    private readonly DataListContext _Context;
    public ValuesController(DataListContext context)
    {
        _Context = context;
    }

    [HttpGet]
    public ActionResult<IEnumerable<DataList>> Get()
    {
        // Datas keeps is value
        Console.WriteLine("Root Count: " + _Context.RootDatas.Count());
        if (_Context.RootDataLists.Count() > 0)
        {
            // InsideDatas is always
            Console.WriteLine("Inside Count: " + _Context.RootDataLists.First().InsideDatas.Count);empty next request
        }

        return _Context.RootDataLists.ToList();
    }

    [HttpPost]
    public void Post([FromBody] string value)
    {
        var data = new Data() { Id = Guid.NewGuid() };
        _Context.RootDatas.Add(data);

        var dataList = new DataList();
        dataList.Name = value;
        dataList.InsideDatas.Add(data);

        _Context.RootDataLists.Add(dataList);
        _Context.SaveChanges();

        // InsideDatas has an element
        Console.WriteLine("Inside Count: " + _Context.RootDataLists.First().InsideDatas.Count);
    }
}

public class DataListContext : DbContext
{
    public DbSet<DataList> RootDataLists { get; set; }
    public DbSet<Data> RootDatas { get; set; }
    public DataListContext(DbContextOptions<DataListContext> options) : base(options) { }
}

public class Data
{
    [Key] public Guid Id { get; set; }
}

public class DataList
{
    public DataList()
    {
        InsideDatas = new List<Data>();
    }

    [Key]
    public string Name { get; set; }
    public ICollection<Data> InsideDatas { get; set; }
}

Startup.cs
public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<DataListContext>(options => options.UseInMemoryDatabase(databaseName: "DataList"));
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseMvc();
    }
}

My problem if that the InsideDatas list is always empty in the next call, but not RootDatas. The DbSet RootDatas in DataListContext is not really anything I would need in my application, but I though it would make the database keep the InsideDatas element. But no.
So I'm I using this all wrong? My use case is a server listing, built up in runtime by hosts posting it's presence to the listing service. My plan is to swap the InMemoryDatabase for redis to be able to scale this properly if needed. (This code is just a slimmed version of the actual one with he same problem)

A: You need to tell EF Core to load related entities. One way is through eager loading:
// notice the Include statement
_Context.RootDataLists.Include(x => x.InsideDatas).First().InsideDatas


Q: Dynamically generated hash keys are not displaying correctly when using render json in controller render json: is not displaying my hash key correctly and I am not sure exactly why.  I will post the controller code and the view output below.
    merger = {}

    stops = OpsHeader.joins(
        ops_stop_rec: :driver_header
      )
    .select(
        :pb_net_rev,
        :pbbname,
        :ops_driver1,
        :pb_id,
        :ops_stop_id,
        :dh_first_name,
        :dh_last_name
      )
      .where(
        :ops_stop_rec => {
            ops_arrive_time: params[:startDate] .. params[:endDate]
        })

    OpsStopRec.joins(
        :ops_line_items
      ).select(
        :opl_amount,
        :ops_type,
        :ops_stop_id,
        :ops_order_id,
        :ops_driver1
      )
      .where(
        :ops_stop_rec => {
            ops_arrive_time: params[:startDate] .. params[:endDate]
        }
      ).each do |lines|
        stops.each do |stop|
          if (lines.ops_stop_id == stop.ops_stop_id && lines.ops_driver1 == stop.ops_driver1)
              merger[stop] = (merger[stop] ||= []) << lines
          end
          if (!merger.key?(stop))
              merger[stop] = merger[stop]
          end
        end
      end

render json: merger

Here is the actual output of my render json::
#<OpsHeader:0x0a61cdd8>: [
{
ops_stop_id: 260772,
ops_order_id: "129215.0",
ops_type: "P",
ops_driver1: 97,
opl_amount: "625.0"
},
{
ops_stop_id: 260772,
ops_order_id: "129215.0",
ops_type: "P",
ops_driver1: 97,
opl_amount: "112.5"
}
],

If I am looping over the record collection and using the looped elements as keys in my merger hash, how come it is still not displaying correctly in the view?
What is odd is the values that you see are also from a looped collection but they seem to display correctly.  It will display correctly in binding.pry() but not in the view.
Any ideas?
Let me give you a better example of what I am referring to.  This is close to what I want but it's still not rendered to json.  In this case, I am using the attributes method to display the key:
{"pb_id"=>0.133204e6, "pbbname"=>"AMARR INC", "pb_net_rev"=>0.24259e4, "ops_driver1"=>61, "ops_stop_id"=>268970, "dh_first_name"=>"MARK", "dh_last_name"=>"STAYTON"}: null,
{"pb_id"=>0.133203e6, "pbbname"=>"AMARR INC", "pb_net_rev"=>0.251647e4, "ops_driver1"=>89, "ops_stop_id"=>268966, "dh_first_name"=>"RICHARD", "dh_last_name"=>"STROEMER"}: null,
{"pb_id"=>0.133203e6, "pbbname"=>"AMARR INC", "pb_net_rev"=>0.251647e4, "ops_driver1"=>89, "ops_stop_id"=>268967, "dh_first_name"=>"RICHARD", "dh_last_name"=>"STROEMER"}: null,
{"pb_id"=>0.133203e6, "pbbname"=>"AMARR INC", "pb_net_rev"=>0.251647e4, "ops_driver1"=>89, "ops_stop_id"=>268968, "dh_first_name"=>"RICHARD", "dh_last_name"=>"STROEMER"}: null,
{"pb_id"=>0.133204e6, "pbbname"=>"AMARR INC", "pb_net_rev"=>0.24259e4, "ops_driver1"=>61, "ops_stop_id"=>268971, "dh_first_name"=>"MARK", "dh_last_name"=>"STAYTON"}: null,
{"pb_id"=>0.133204e6, "pbbname"=>"AMARR INC", "pb_net_rev"=>0.24259e4, "ops_driver1"=>61, "ops_stop_id"=>268972, "dh_first_name"=>"MARK", "dh_last_name"=>"STAYTON"}: null,
{"pb_id"=>0.133204e6, "pbbname"=>"AMARR INC", "pb_net_rev"=>0.24259e4, "ops_driver1"=>61, "ops_stop_id"=>268973, "dh_first_name"=>"MARK", "dh_last_name"=>"STAYTON"}: [
{
ops_stop_id: 268973,
ops_order_id: "133204.0",
ops_type: "P",
ops_driver1: 61,
opl_amount: "2375.9"
},
{
ops_stop_id: 268973,
ops_order_id: "133204.0",
ops_type: "P",
ops_driver1: 61,
opl_amount: "50.0"
},
{
ops_stop_id: 268973,
ops_order_id: "133204.0",
ops_type: "P",
ops_driver1: 61,
opl_amount: "0.0"
}

As you can see, some are nested and others have null values, which is fine.

A: So in JSON format, a key has to be a string. Just that ruby allows you to have pretty much anything as a key of the hash, doesn't mean it will be compatible with the JSON standard. I will suggest you to change the format of your data so you can produce something like this:
# It is JSON, not ruby
{
  "ops_headers": [ # each of your OpsHeader instances
    {
      "pb_id": 133204,
      "pbbname": "AMARR INC",
      "pb_net_rev": 2425.9,
      "ops_driver1": 61,
      "ops_stop_id": 268970,
      "dh_first_name": "MARK",
      "dh_last_name": "STAYTON",
      "ops_stop_recs": [ # contains array of their OpsStopRec instances
        {
          "ops_stop_id": 268973,
          "ops_order_id": "133204.0",
          "ops_type": "P",
          "ops_driver1": 61,
          "opl_amount": "2375.9"
        },
        {
          "ops_stop_id": 268973,
          "ops_order_id": "133204.0",
          "ops_type": "P",
          "ops_driver1": 61,
          "opl_amount": "2375.9"
        }
      ]
    }
  ]
}


Q: Breaking the loop after checking the result from observable in angular I would like to break the loop after checking the condition from the return of observable. When the status is False, I want to exit the loop. I have the below code:
var response = Observable<responseService>;
var i;
for (i =0; i < lin.length; i++){
 response = this.http.post<responseService>(this.Url, {}, options).pipe(
    map(data => {
      return data;
    }),
    catchError((err) => {
      return of(null);
      }
    ));

  var res = response.map(x => x.status);
  console.log(res);
  if (res === "False" || res === null) {
    response{
     status: "FALSE",
     message: "ERROR"
    }
   return of(response);
  }
}
return response;

But I am getting error for the if condition as below
"The condition will always return false since the types 'Observable <>' and 'string' has no overlap".
I would greatly appreciate if anyone knows what I am doing wrong or have solution. Thank you!

A: *

*You aren't subscribing the observable and trying to compare an observable to a string. When you compare if (res === "False" || res === null), res variable is still an observable.

*Having nested subscriptions isn't a good practice. And it won't help you here if you wish to make each request sequentially until one request emits False or if null.
You could try create an array of requests and subscribe to it sequentially using RxJS from function and concatMap operator. Then break the sequence using the takeUntil operator if the condition is satisfied. Try the following
import { Subject, from, of } from 'rxjs';
import { takeUntil, concatMap } from 'rxjs/operators';

private getData() {
  let closeRequest$ = new Subject<any>();
  let response = Observable<responseService>;
  let requests = Observable<responseService>[];
  for (let i =0; i < lin.length; i++) {
    requests.push(this.http.post<responseService>(this.Url, {}, options))   // <-- don't map response here
  }

  from(requests).pipe(
    concatMap(request => of(request)),
    takeUntil(closeRequest$)
  ).subscribe(
    response => {
      if (!response['status'] && response['status'] === "False") {    // <-- check for `response.status` truthiness
        // response is false
        this.someVar = { status: "FALSE", message: "ERROR" };
        this.closeRequest$.next();
        this.closeRequest$.complete();
      } else {
        this.someVar = status;
      }
    },
    error => { }
  );
}


Q: Setup PhpStorm's to reformat code based on phpcs (codesniffer-rules from Squizlabs) I've taken over a code base, where most of the code is following the codesniffer settings from squizlabs/PHP_CodeSniffer.
How do I setup PhpStorm to automatically reformat the code upon saving files; so I always follow those standards. Ideally I would only reformat files that I save (and not unchanged files).
I'm imagining that I'm looking for a 'Import code style from phpcs.xml.dist' or something like that. But I'm not sure.
I'm trying to avoid having going to through all the code styles line for line, figuring out if it should be if ( $blah ) { or if($blah){, and adjusting the values in Settings one setting at the time.
And bonus points, if one can point out how to do this is VSCode, while I'm at it (to help my colleagues).

Attempt 1: Read online ressources

*

*Reformat and rearrange code

*Configuring code style

*EditorConfig for PhpStorm

*Copy code style settings
Attempt 2: Read around 'Settings'
I went to 'Settings' >> 'Editor' >> 'Code Style' (and also >> 'PHP'). I found the 'Set from'-button, so I could set it to follow Symfony2's code style. But I'm not sure if that follows squidlabs conventions.
I also read around, to see if I could find a 'Generate code styles from code'.
Attempt 3: Generate code style from code
I know that it's a tall order, but I would have been cool, if I could have pointed PhpStorm to a couple of correctly formatted files - and then get PhpStorm to automatically generate the code style from those files. I couldn't find this.
I tried this by trying to copy some of the well-formatted code from the project into the editor in the settings-box, to see if a 'Adjust values based on example code'. But I couldn't find this.

A: I found the answer by carefully reading this post here: PHP_CodeSniffer.
There are several steps to it - and it's highly customizable:

*

*Only 'flag' editted lines

*Only 'flag' editted files

*Which standards to use

*Should it show it as a warning or an error.

Etc...
That combined with: The 'reformat on save' I found in 'Settings' >> 'Actions on save'.


Q: How to create Multi-pages in PDF file created with JSPDF from a html page I have a html page containing many text in tables. I'm using jspdf version 1.5 and higher and html2canvas libraries for creating a pdf when clicking on a button "generate the pdf".
The pdf is correctly generated.
Here is my code:
<!DOCTYPE html>

            <meta charset="utf-8">
            <title>Template 01</title>
            <link id="BootstrapCSS" rel="stylesheet" type="text/css" href="bootstrap.min.css">

<button type="button" class="btn btn-primary btn-lg" onclick="download()">Generate PDF</button>

                                ...

                                ...

                            ...

And the jsfiddle code: http://jsfiddle.net/amadese57/17npbu4y
My problem is the tables are sometimes broken at the bottom of the page (and at the top of the next page).
I would like to create automatically a break when the tables cannot be entirely on the page.
I don't know how to do that and if I can do that in the function pdf.html() that I used.
Could you help me please with that ?
Thanks in advance for your help

A: you have added the width of the PDF file, try to add the height of the PDF file. And add some more information to the meta data


Q: Check of two list have colliding element? Is there a way to check if one list collides with another? ex:
    bool hit=false;
    foreach(var s in list2)
    {
        if (list1.Contains(s))
        {
            hit = true;
            break;
        }
    }
    if (!hit)
    {

A: .NET has a number of set operations that work on enumerables, so you could take the set intersection to find members in both lists. Use Any() to find out if the resulting sequence has any entries.
E.g.
if(list1.Intersect(list2).Any())

A: You can always use linq
if (list1.Intersect(list2).Count() > 0) ...

A: If you're able to use Linq then if(list1.Intersect(list2).Count > 0) {...collision...}.