Q: Unexpected response code 403 for https://www.googleapis.com/games/v1/players/xxxxx LibGDX Android I'm making a Android game with LibGDX and I want to use the Google Play Game Services API but I can't get it working.
Here's what happens when I try to login:
06-12 20:08:47.745: E/Volley(4046): [253] tk.a: Unexpected response code 403 for https://www.googleapis.com/games/v1/players/115171141636978128288
06-12 20:08:47.846: E/SignInIntentService(4046): Access Not Configured. Please use Google Developers Console to activate the API for your project.
06-12 20:08:47.846: E/SignInIntentService(4046): ebw
06-12 20:08:47.846: E/SignInIntentService(4046):    at dwp.a(SourceFile:146)
06-12 20:08:47.846: E/SignInIntentService(4046):    at dfx.a(SourceFile:390)
06-12 20:08:47.846: E/SignInIntentService(4046):    at dfx.a(SourceFile:371)
06-12 20:08:47.846: E/SignInIntentService(4046):    at dex.a(SourceFile:719)
06-12 20:08:47.846: E/SignInIntentService(4046):    at ecp.a(SourceFile:250)
06-12 20:08:47.846: E/SignInIntentService(4046):    at com.google.android.gms.games.service.GamesSignInIntentService.onHandleIntent(SourceFile:389)
06-12 20:08:47.846: E/SignInIntentService(4046):    at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
06-12 20:08:47.846: E/SignInIntentService(4046):    at android.os.Handler.dispatchMessage(Handler.java:102)
06-12 20:08:47.846: E/SignInIntentService(4046):    at android.os.Looper.loop(Looper.java:136)
06-12 20:08:47.846: E/SignInIntentService(4046):    at android.os.HandlerThread.run(HandlerThread.java:61)
06-12 20:08:47.846: E/LoadSelfFragment(9533): Unable to sign in - application does not have a registered client ID
06-12 20:08:47.846: W/SignInActivity(9533): onSignInFailed()...
06-12 20:08:47.846: W/SignInActivity(9533): ==> Returning non-OK result: 10004

I checked if the app is linked and if the SHA1 key is the same between my keystore and in the Google Developers Console and I checked if I was been a tester of the app who was allowed to use the API.
Now I don't know where to look for to get this working.
Thank you for your help.


Q: How to get value of checked radio? HTML:

        <input type="radio" name="pet_chipped" class="chipped" value="Yes" id="chipyes" checked> Yes

        <input type="radio" name="pet_chipped" class="chipped" value="No" id="chipno"> No

jQuery:
$("input[name='pet_chipped']:checked").val();

when I am alerting 'pet_chipped' it displaying undefined.

A:

//onload event
$(document).ready(function(){
  /*show alert on load time*/
  alert($('[name="pet_chipped"]:checked').val());
})
// on change radio button value fire event
$(document).on('change', '[name="pet_chipped"]', function(){
  //show value of radio after changed
   alert($('[name="pet_chipped"]:checked').val());
})

 <input type="radio" name="pet_chipped" class="chipped" value="Yes" id="chipyes" checked> Yes
<input type="radio" name="pet_chipped" class="chipped" value="No" id="chipno"> No

A: Try this
HTML :
<input type="radio" name="pet_chipped" class="chipped" value="Yes">    Yes

<input type="radio" name="pet_chipped" class="chipped" value="No" checked> No
<input type="submit" onclick="getChecked()" />

Jquery :


Q: IIFE Syntax best practice This is from MDN web docs
(function () {
    //statements
})();

But i've seen this usage down below too
(function() {
    //statements
}());

It seems both works. But which is best practice and why is there such difference? First one seems more appropriate imo


Q: Running Bat file from Excel VBA I have the following VBA code which works:
Sub TfrSec()
Dim argh As Double
argh = Shell("C:\Users\Avishen\Desktop\Transfer Rates File.bat", vbNormalFocus)
End Sub

I want to change Avishen so that it picks up automatically the current user which is login on windows.
Thanks for helping

A: Use the Environ function to retrieve the environment variables that are set in Windows.
Sub TfrSec()
    Dim argh As Double
    argh = Shell(Environ("USERPROFILE") & "\Desktop\Transfer Rates File.bat", vbNormalFocus)
End Sub

See here for a list of available variables in Windows 10.


Q: MySQL: What is the most performant way of storing a whole year (365 elements) in MySQL? Within a project, I have to store the daily availability of different meeting rooms. So let's suppose around 1.000.000 meeting rooms, where each meeting room is in a city, and a city could have hundreds of meeting rooms.
I would also like to be able to make SELECT Queries entering the city and the availability that I need, so I would like to get a list of the available meeting rooms for a day, or set of continues days, in a concrete city.
I have one table called "MeetingRoom", when I store the city and the name of the meeting room, but my design question is how to design the availability part:

*

*Is it better in terms of performance to have a binary array that stores the 365 days of the year with a '1' or '0' according to the availability of the meeting room?

*Is it better in terms of performance to have another table called "Availability" that stores a DATE and a BIT with the availability, and then JOIN both tables for each meeting room that exists in a city?

*Could it better another option I don't have in mind?
I wonder what querying time would be optimal having around 1.000.000 meeting rooms, and searching for the meeting rooms in a city and available for concrete days. Is it crazy about thinking in database responses below 100 ms?
Some colleagues told me that I should also consider to migrate to MongoDB or NoSQL approach. I don't know if a change of DB could fit better with my issues, or if it don't. Any comment about this?
Thank you very much for the help!!

A: I don't know if this will help, but if it doesn't, please write me to delete the answer.
Instead of these options you may want to consider that in the "Availability" table to store only the id(surrogate) of the room and the date on which it is reserved. So when you select the data and join both tables you will get only the reserved rooms. I personally think that there is no point of storing all of the room-date relations with status.
Moreover, to improve the performance you can create non-clustered index on the City column for instance.

A: Please don't fill your database with lots of rows which are default values.
so you don't store availability of a meeting room, you store booking of a meeting room.
primary key of booking table is date and room id , other fields are who booked this room, when booking was asked, a booking id...
If it is possible to book meeting room for part of the day then primary key should be start_date and room id, end date is stored in another field of the table.


Q: Python Hyperlinks function I'm trying to create a function in python which reads an html and then takes out only the hyperlink and the theme of the hyperlink..The html page is specific and the function is only for this page..So as i'm a really amateur in python learning i thought something like this..
def fun("string","start of hyper","end of hyper")

.And when i call this function,i'll read the html file,and pop up only the parts which have tha classic html words for start and finish hyperlinks <a, .Also i must not use any modules like beautiful soup for this function!!Thanks for any response

A: This might be the complete solution as you are looking for.

This code is from the udacity computer science course (CS101)

It uses simulated webpages using method get_page(url):

Run in your computer once and read the code

It also try to remove duplicate urls
def get_page(url):
    # This is a simulated get_page procedure so that you can test your
    # code on two pages "http://xkcd.com/353" and "http://xkcd.com/554".
    # A procedure which actually grabs a page from the web will be
    # introduced in unit 4.
    try:
        if url == "http://xkcd.com/353":
            return  '<?xml version="1.0" encoding="utf-8" ?><?xml-stylesheet href="http://imgs.xkcd.com/s/c40a9f8.css" type="text/css" media="screen" ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">  <title>xkcd: Python</title> <link rel="stylesheet" type="text/css" href="http://imgs.xkcd.com/s/c40a9f8.css" media="screen" title="Default" />  <link rel="alternate" type="application/atom+xml" title="Atom 1.0" href="/atom.xml" /> <link rel="alternate" type="application/rss+xml" title="RSS 2.0" href="/rss.xml" /> <link rel="icon" href="http://imgs.xkcd.com/s/919f273.ico" type="image/x-icon" /> <link rel="shortcut icon" href="http://imgs.xkcd.com/s/919f273.ico" type="image/x-icon" />

\t

Archive

\t
News/Blag

Store

About

Forums

A webcomic of romance,
 sarcasm, math, and language.

XKCD updates every Monday, Wednesday, and Friday.

Python

|<

< Prev

Random

Next >

>|

|<

< Prev

Random

Next >

>|

Permanent link to this comic: http://xkcd.com/353/

Image URL (for hotlinking/embedding): http://imgs.xkcd.com/comics/python.png

[[ Guy 1 is talking to Guy 2, who is floating in the sky ]]Guy 1: You39;re flying! How?Guy 2: Python!Guy 2: I learned it last night! Everything is so simple!Guy 2: Hello world is just 39;print "Hello, World!" 39;Guy 1: I dunno... Dynamic typing? Whitespace?Guy 2: Come join us! Programming is fun again! It39;s a whole new world up here!Guy 1: But how are you flying?Guy 2: I just typed 39;import antigravity39;Guy 1: That39;s it?Guy 2: ...I also sampled everything in the medicine cabinet for comparison.Guy 2: But i think this is the python.{{ I wrote 20 short programs in Python yesterday. It was wonderful. Perl, I39;m leaving you. }}

  <map name="comicmap"> <area shape="rect" coords="0,0,100,100" href="/150/" alt="Grownups" /> <area shape="rect" coords="104,0,204,100" href="/730/" alt="Circuit Diagram" /> <area shape="rect" coords="208,0,308,100" href="/162/" alt="Angular Momentum" /> <area shape="rect" coords="312,0,412,100" href="/688/" alt="Self-Description" /> <area shape="rect" coords="416,0,520,100" href="/556/" alt="Alternative Energy Revolution" /> </map>

Search comic titles and transcripts:
<form action="//www.google.com/cse" id="cse-search-box">
 <input type="hidden" name="cx" value="012652707207066138651:zudjtuwe28q" /> <input type="hidden" name="ie" value="UTF-8" /> <input type="text" name="q" id="q" autocomplete="off" size="31" /> <input type="submit" name="sa" value="Search" />
</form>RSS Feed - Atom Feed

 Comics I enjoy:
 Dinosaur Comics, A Softer World, Perry Bible Fellowship, Copper, Questionable Content, Achewood, Wondermark, Indexed, Buttercup Festival

 Warning: this comic occasionally contains strong language (which may be unsuitable for children), unusual humor (which may be unsuitable for adults), and advanced mathematics (which may be unsuitable for liberal-arts majors).

We did not invent the algorithm. The algorithm consistently finds Jesus. The algorithm killed Jeeves.
The algorithm is banned in China. The algorithm is from Jersey. The algorithm constantly finds Jesus.
This is not the algorithm. This is close.

  This work is licensed under a Creative Commons Attribution-NonCommercial 2.5 License.
 This means you\"re free to copy and share these comics (but not to sell them). More details.

  '
        elif url == "http://xkcd.com/554":
            return  '<?xml version="1.0" encoding="utf-8" ?> <?xml-stylesheet href="http://imgs.xkcd.com/s/c40a9f8.css" type="text/css" media="screen" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">   <title>xkcd: Not Enough Work</title> <link rel="stylesheet" type="text/css" href="http://imgs.xkcd.com/s/c40a9f8.css" media="screen" title="Default" />  <link rel="alternate" type="application/atom+xml" title="Atom 1.0" href="/atom.xml" /> <link rel="alternate" type="application/rss+xml" title="RSS 2.0" href="/rss.xml" /> <link rel="icon" href="http://imgs.xkcd.com/s/919f273.ico" type="image/x-icon" /> <link rel="shortcut icon" href="http://imgs.xkcd.com/s/919f273.ico" type="image/x-icon" />

Archive

News/Blag

Store

About

Forums

A webcomic of romance,
 sarcasm, math, and language.

 XKCD updates every Monday, Wednesday, and Friday.
 Blag: Remember geohashing? Something pretty cool happened Sunday.

Not Enough Work

|<

< Prev

Random

Next >

>|

|<

< Prev

Random

Next >

>|

Permanent link to this comic: http://xkcd.com/554/

Image URL (for hotlinking/embedding): http://imgs.xkcd.com/comics/not_enough_work.png

Narration: Signs your coders don39;t have enough work to do: [[A man sitting at his workstation; a female co-worker behind him]] Man: I39;m almost up to my old typing speed in dvorak [[Two men standing by a server rack]] Man  1: Our servers now support gopher. Man  1: Just in case. [[A woman standing near her workstation speaking to a male co-worker]] Woman: Our pages are now HTML, XHTML-STRICT, and haiku-compliant Man: Haiku? Woman: <div class="main"> Woman: <span id="marquee"> Woman: Blog!< span>< div> [[A woman sitting at her workstation]] Woman: Hey! Have you guys seen this webcomic? {{title text: It39;s even harder if you39;re an asshole who pronounces <> brackets.}}

  <map name="comicmap"> <area shape="rect" coords="0,0,100,100" href="/150/" alt="Grownups" /> <area shape="rect" coords="104,0,204,100" href="/730/" alt="Circuit Diagram" /> <area shape="rect" coords="208,0,308,100" href="/162/" alt="Angular Momentum" /> <area shape="rect" coords="312,0,412,100" href="/688/" alt="Self-Description" /> <area shape="rect" coords="416,0,520,100" href="/556/" alt="Alternative Energy Revolution" /> </map>

 Search comic titles and transcripts:
   <form action="//www.google.com/cse" id="cse-search-box">
 <input type="hidden" name="cx" value="012652707207066138651:zudjtuwe28q" /> <input type="hidden" name="ie" value="UTF-8" /> <input type="text" name="q" id="q" autocomplete="off" size="31" /> <input type="submit" name="sa" value="Search" />
 </form>  RSS Feed - Atom Feed

 Comics I enjoy:
 Three Word Phrase, Oglaf (nsfw), SMBC, Dinosaur Comics, A Softer World, Buttersafe, Perry Bible Fellowship, Questionable Content, Buttercup Festival

 Warning: this comic occasionally contains strong language (which may be unsuitable for children), unusual humor (which may be unsuitable for adults), and advanced mathematics (which may be unsuitable for liberal-arts majors).

We did not invent the algorithm. The algorithm consistently finds Jesus. The algorithm killed Jeeves.
The algorithm is banned in China. The algorithm is from Jersey. The algorithm constantly finds Jesus.
This is not the algorithm. This is close.

  This work is licensed under a Creative Commons Attribution-NonCommercial 2.5 License.
 This means you"re free to copy and share these comics (but not to sell them). More details.

   '
    except:
        return ""
    return ""

def get_next_target(page):
    start_link = page.find('<a href=')
    if start_link == -1:
        return None, 0
    start_quote = page.find('"', start_link)
    end_quote = page.find('"', start_quote + 1)
    url = page[start_quote + 1:end_quote]
    return url, end_quote

def union(p,q):
    for e in q:
        if e not in p:
            p.append(e)

def get_all_links(page):
    links = []
    while True:
        url,endpos = get_next_target(page)
        if url:
            links.append(url)
            page = page[endpos:]
        else:
            break
    return links

def crawl_web(seed):
    tocrawl = [seed]
    crawled = []
    while tocrawl:
        page = tocrawl.pop()
        if page not in crawled:
            union(tocrawl, get_all_links(get_page(page)))
        crawled.append(page)
    return crawled

print crawl_web('http://xkcd.com/353')

A: Do you want to extract urls from a html file? Then this is what you need:
http://youtu.be/MagGZY7wHfU?t=1m54s
Its a great course by the way. Maybe you are interested.

A: To parse html file you should use XML parsing library. See: https://docs.python.org/2/library/xml.html


Q: IOException error when creating a socket in java I am working on a chat client and I have created a registration Jframe where a user gets to register.
when registering, it is supposed to connect to server so that server can check if the userid already exists or not.
when I am creating a new socket it keeps giving me an error.
the code for the socket creation is:
try
    {
        String serverIP;
        int Port = 5000;
        Socket socks;
        serverIP = String.valueOf(InetAddress.getLocalHost());
        socks = new Socket(serverIP, Port);
        InputStreamReader streamreader = new InputStreamReader(socks.getInputStream());
        reader = new BufferedReader(streamreader);
        writer = new PrintWriter(socks.getOutputStream());
        writer.println(inputUsername + ":"+inputPassword+":"+inputConfirmPassword+":Register");
        writer.flush(); // flushes the buffer

    }
    catch(IOException io)
    {
        System.err.println(io.getMessage()+"---connection error 1");
    }
    catch(SecurityException se)
    {
        System.err.println(se.getMessage()+"---connection error 2");
    }
    catch(IllegalArgumentException ae)
    {
        System.err.println(ae.getMessage()+"---connection error 3");
    }
    catch(NullPointerException ne)
    {
        System.err.println(ne.getMessage()+"---connection error 4");
    }

when I execute, i get the following error:
Dell/172.16.3.24---connection error 1
this is generated by the IOException catch statement.
Can anyone tell me why this is happening and also how to rectify it?
thanks a lot.

A: IOException definition from javadoc

Signals that an I/O exception of some sort has occurred. This class is the general class of exceptions produced by failed or interrupted I/O operations.

While I don't have access to your full stacktrace, the statement Dell/127.16.3.24 let me believe that this is the IP address that was given when creating the socket.
I think you might want to try using InetAddress.getLocalHost().getHostAddress which will return only the IP while InetAddress.getLocalHost() will also return the hostname of the system.
InetAddress.getLocalHost from javadoc

Returns the address of the local host. This is achieved by retrieving
  the name of the host from the system, then resolving that name into an
  InetAddress.

Note that if you already know that you want local host ip, you can simply pass "127.0.0.1" when creating the socket and it should also fix the problem.
You should also consider adding the flush statement in a finally block to make sure the stream is flushed even if exception occurs. And for sure add a close statement in that block too.


Q: Deploy asp.net to iis i try to publish my asp.net application to iis (v10.0), i get error in logs when running the application, maybe there is a problem with the database connection, but when I run my application on visual studio code 2022 there is no problem,
the logs info is, :
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Production
info: Microsoft.Hosting.Lifetime[0]
      Content root path: C:\inetpub\wwwroot\mytubesite\
warn: Microsoft.AspNetCore.HttpsPolicy.HttpsRedirectionMiddleware[3]
      Failed to determine the https port for redirect.
info: Microsoft.EntityFrameworkCore.Infrastructure[10403]
      Entity Framework Core 6.0.2 initialized 'ApplicationDBContext' using provider 'Microsoft.EntityFrameworkCore.SqlServer:6.0.2' with options: None
fail: Microsoft.EntityFrameworkCore.Database.Connection[20004]
      An error occurred using the connection to database 'ASP.NETCoreIdentityCustom' on server 'DESKTOP-MA0E5C6'.

this my ApplicationDBContext :
using ASP.NETCoreIdentityCustom.Areas.Identity.Data;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using ASP.NETCoreIdentityCustom.Models;
namespace ASP.NETCoreIdentityCustom.Areas.Identity.Data;

public class ApplicationDBContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDBContext(DbContextOptions<ApplicationDBContext> options)
        : base(options)
    {
    }

    public DbSet<Movie> Movie { get; set; }
    public DbSet<Comment> Comment { get; set; }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        // Customize the ASP.NET Identity model and override the defaults if needed.
        // For example, you can rename the ASP.NET Identity table names and more.
        // Add your customizations after calling base.OnModelCreating(builder);

        builder.ApplyConfiguration(new ApplicationUserEntityConfiguration());
    }
}

public class ApplicationUserEntityConfiguration : IEntityTypeConfiguration<ApplicationUser>
{
    public void Configure(EntityTypeBuilder<ApplicationUser> builder)
    {
        builder.Property(u => u.FirstName).HasMaxLength(255);
        builder.Property(u => u.LastName).HasMaxLength(255);
    }
}

and the program.cs :
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using ASP.NETCoreIdentityCustom.Areas.Identity.Data;
using Microsoft.Extensions.DependencyInjection;
var builder = WebApplication.CreateBuilder(args);

var connectionString = builder.Configuration.GetConnectionString("ApplicationDBContextConnection");builder.Services.AddDbContext<ApplicationDBContext>(options =>
    options.UseSqlServer(connectionString));builder.Services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddEntityFrameworkStores<ApplicationDBContext>();
// Add services to the container.

//builder.Services.AddControllers();
builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();

//app.UseDefaultFiles();
//app.UseStaticFiles();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

//app.MapControllers();

app.MapRazorPages();

app.Run();

and the appsetting.json:
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "ApplicationDBContextConnection": "Data Source=DESKTOP-MA0E5C6;Initial Catalog=ASP.NETCoreIdentityCustom;Integrated Security=True",
    "MvcMovieContext": "Server=(localdb)\\mssqllocaldb;Database=MvcMovieContext-cb93973d-d78f-4665-bef9-e5d55c116ab1;Trusted_Connection=True;MultipleActiveResultSets=true"
  }
}


Q: python script won't run at startup ubuntu I try to run my python scrip at startup but it doesn't work.
Here is my python script(doesn't work):
#!/usr/bin/env python

import paho.mqtt.publish as publish
from datetime import datetime

t = str(datetime.now())
print t
with open("/home/james/mqtt/log.txt", "a+") as f:
    f.write("it works " + t + "\n")

Here is my python script(works):
#!/usr/bin/env python

from datetime import datetime

t = str(datetime.now())
print t
with open("/home/james/mqtt/log.txt", "a+") as f:
    f.write("it works " + t + "\n")

Here is my rc.local files(also try crontab and setting up service in /ect/init.d):
#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.

# /bin/mqtt_test.py &
# mosquitto_sub -t "mqtt"

/home/james/mqtt/script.sh
# /etc/mqtt/mqtt_test.py

exit 0

It look like by importing paho.mqtt.publish can make my script stop working, I am new to Linux, I have no idea why. Can someone help me out? Thanks for your help.
Ubuntu 16.04
Let me know if you need more info.

A: I have faced this problem myself. For me the problem was path. I could get it working by using a shell script to launch a python script and launch the shell script from crontab.
Here is my launcher.sh. You may not use sudo if you do not want. home/pi/record_data is the path where my file resides.
cd /
cd home/pi/record_data
sudo python record_video.py

In this case record_video.py is the python file I want to run at startup. In the crontab edit, I added this line below.
@reboot sh /home/pi/record_data/launcher.sh &

Do try this out if it work for you :) Good luck.
I have not got the logging the error into files working yet though.

A: it looks to me like you need to set/change the write permissions of the file before your python scrypt do this:
f.write("it works " + t + "\n")

for you is working because (maybe you are the owner of the file).
typical linux file permission is described as:

do use the chmod with the property flags, so linux has the rights to write the file too, please refer to the ubuntu help :)


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: 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: 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: 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: 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: 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