text:
Q: Issue with visual studio template & directory creation I'm trying to make a Visual Studio (2010) template (multi-project). Everything seems good, except that the projects are being created in a sub-directory of the solution. This is not the behavior I'm looking for.
The zip file contains:
Folder1
+-- Project1
    +-- Project1.vstemplate
+-- Project2
    +-- Project2.vstemplate
myapplication.vstemplate

Here's my root template:
<VSTemplate Version="3.0.0" Type="ProjectGroup" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005">
    <TemplateData>
        <Name>My application</Name>
        <Description></Description>
        <Icon>Icon.ico</Icon>
        <ProjectType>CSharp</ProjectType>
  <RequiredFrameworkVersion>4.0</RequiredFrameworkVersion>
  <DefaultName>MyApplication</DefaultName>
  <CreateNewFolder>false</CreateNewFolder>
    </TemplateData>
    <TemplateContent>
        <ProjectCollection>
   <SolutionFolder Name="Folder1">
    <ProjectTemplateLink ProjectName="$safeprojectname$.Project1">Folder1\Project1\Project1.vstemplate</ProjectTemplateLink>
    <ProjectTemplateLink ProjectName="$safeprojectname$.Project2">Folder2\Project2\Project2.vstemplate</ProjectTemplateLink>
   </SolutionFolder>
        </ProjectCollection>
    </TemplateContent>
</VSTemplate>

And, when creating the solution using this template, I end up with directories like this:
Projects
+-- MyApplication1
    +-- MyApplication1 // I'd like to have NOT this directory
        +-- Folder1
            +-- Project1
            +-- Project2
    solution file

Any help?
EDIT:
It seems that modifying <CreateNewFolder>false</CreateNewFolder>, either to true or false, doesn't change anything.

A: To create solution at root level (not nest them in subfolder) you must create two templates:
1) ProjectGroup stub template with your wizard inside that will create new project at the end from your
2) Project template
use the following approach for that
1. Add template something like this
  <VSTemplate Version="2.0.0" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005" Type="ProjectGroup">
    <TemplateData>
      <Name>X Application</Name>
      <Description>X Shell.</Description>
      <ProjectType>CSharp</ProjectType>
      <Icon>__TemplateIcon.ico</Icon>
    </TemplateData>
    <TemplateContent>
    </TemplateContent>
    <WizardExtension>
    <Assembly>XWizard, Version=1.0.0.0, Culture=neutral</Assembly>
    <FullClassName>XWizard.FixRootFolderWizard</FullClassName>
    </WizardExtension>
  </VSTemplate>

2. Add code to wizard
// creates new project at root level instead of subfolder.
public class FixRootFolderWizard : IWizard
{
    #region Fields

    private string defaultDestinationFolder_;
    private string templatePath_;
    private string desiredNamespace_;

    #endregion

    #region Public Methods
    ...
    public void RunFinished()
    {
        AddXProject(
            defaultDestinationFolder_,
            templatePath_,
            desiredNamespace_);
    }

    public void RunStarted(object automationObject,
        Dictionary<string, string> replacementsDictionary,
        WizardRunKind runKind, object[] customParams)
    {
        defaultDestinationFolder_ = replacementsDictionary["$destinationdirectory$"];
        templatePath_ =
            Path.Combine(
                Path.GetDirectoryName((string)customParams[0]),
                @"Template\XSubProjectTemplateWizard.vstemplate");

         desiredNamespace_ = replacementsDictionary["$safeprojectname$"];

         string error;
         if (!ValidateNamespace(desiredNamespace_, out error))
         {
             controller_.ShowError("Entered namespace is invalid: {0}", error);
             controller_.CancelWizard();
         }
     }

     public bool ShouldAddProjectItem(string filePath)
     {
         return true;
     }

     #endregion
 }

 public void AddXProject(
     string defaultDestinationFolder,
     string templatePath,
     string desiredNamespace)
 {
     var dte2 = (DTE) System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE.10.0");
     var solution = (EnvDTE100.Solution4) dte2.Solution;

     string destinationPath =
         Path.Combine(
             Path.GetDirectoryName(defaultDestinationFolder),
             "X");

     solution.AddFromTemplate(
         templatePath,
         destinationPath,
         desiredNamespace,
         false);
     Directory.Delete(defaultDestinationFolder);
}

A: This is based on @drweb86 answer with some improvments and explanations.
Please notice few things:

*

*The real template with projects links is under some dummy folder since you can't have more than one root vstemplate. (Visual studio will not display your template at all at such condition).

*All the sub projects\templates have to be located under the real template file folder.
Zip template internal structure example:
RootTemplateFix.vstemplate
-> Template Folder
   YourMultiTemplate.vstemplate
        -->Sub Project Folder 1
           SubProjectTemplate1.vstemplate
        -->Sub Project Folder 2
           SubProjectTemplate2.vstemplate
        ...

*On the root template wizard you can run your user selection form and add them into a static variable. Sub wizards can copy these Global Parameters into their private dictionary.
Example:
   public class WebAppRootWizard : IWizard
   {
    private EnvDTE._DTE _dte;
    private string _originalDestinationFolder;
    private string _solutionFolder;
    private string _realTemplatePath;
    private string _desiredNamespace;

    internal readonly static Dictionary<string, string> GlobalParameters = new Dictionary<string, string>();

    public void BeforeOpeningFile(ProjectItem projectItem)
    {
    }

    public void ProjectFinishedGenerating(Project project)
    {
    }

    public void ProjectItemFinishedGenerating(ProjectItem
        projectItem)
    {
    }

    public void RunFinished()
    {
        //Run the real template
        _dte.Solution.AddFromTemplate(
            _realTemplatePath,
            _solutionFolder,
            _desiredNamespace,
            false);

        //This is the old undesired folder
        ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(DeleteDummyDir), _originalDestinationFolder);
    }

    private void DeleteDummyDir(object oDir)
    {
        //Let the solution and dummy generated and exit...
        System.Threading.Thread.Sleep(2000);

        //Delete the original destination folder
        string dir = (string)oDir;
        if (!string.IsNullOrWhiteSpace(dir) && Directory.Exists(dir))
        {
            Directory.Delete(dir);
        }
    }

    public void RunStarted(object automationObject,
        Dictionary<string, string> replacementsDictionary,
        WizardRunKind runKind, object[] customParams)
    {
        try
        {
            this._dte = automationObject as EnvDTE._DTE;

            //Create the desired path and namespace to generate the project at
            string temlateFilePath = (string)customParams[0];
            string vsixFilePath = Path.GetDirectoryName(temlateFilePath);
            _originalDestinationFolder = replacementsDictionary["$destinationdirectory$"];
            _solutionFolder = replacementsDictionary["$solutiondirectory$"];
            _realTemplatePath = Path.Combine(
                vsixFilePath,
                @"Template\BNHPWebApplication.vstemplate");
            _desiredNamespace = replacementsDictionary["$safeprojectname$"];

            //Set Organization
            GlobalParameters.Add("$registeredorganization$", "My Organization");

            //User selections interface
            WebAppInstallationWizard inputForm = new WebAppInstallationWizard();
            if (inputForm.ShowDialog() == DialogResult.Cancel)
            {
                throw new WizardCancelledException("The user cancelled the template creation");
            }

            // Add user selection parameters.
            GlobalParameters.Add("$my_user_selection$",
                inputForm.Param1Value);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    public bool ShouldAddProjectItem(string filePath)
    {
        return true;
    }
}

*Notice that the original destination folder deletion is done via a different thread.
The reason is that the solution is generated after your wizard ends and this destination folder will get recreated.
By using ohter thread we assume that the solution and final destination folder will get created and only then we can safely delete this folder.

A: Another solution with using a Wizard alone:
    public void RunStarted(object automationObject, Dictionary<string, string> replacementsDictionary, WizardRunKind runKind, object[] customParams)
    {
        try
        {
            _dte = automationObject as DTE2;
            _destinationDirectory = replacementsDictionary["$destinationdirectory$"];
            _safeProjectName = replacementsDictionary["$safeprojectname$"];

            //Add custom parameters
        }
        catch (WizardCancelledException)
        {
            throw;
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex + Environment.NewLine + ex.StackTrace, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            throw new WizardCancelledException("Wizard Exception", ex);
        }
    }

    public void RunFinished()
    {
        if (!_destinationDirectory.EndsWith(_safeProjectName + Path.DirectorySeparatorChar + _safeProjectName))
            return;

        //The projects were created under a seperate folder -- lets fix it
        var projectsObjects = new List<Tuple<Project,Project>>();
        foreach (Project childProject in _dte.Solution.Projects)
        {
            if (string.IsNullOrEmpty(childProject.FileName)) //Solution Folder
            {
                projectsObjects.AddRange(from dynamic projectItem in childProject.ProjectItems select new Tuple<Project, Project>(childProject, projectItem.Object as Project));
            }
            else
            {
                projectsObjects.Add(new Tuple<Project, Project>(null, childProject));
            }
        }

        foreach (var projectObject in projectsObjects)
        {
            var projectBadPath = projectObject.Item2.FileName;
            var projectGoodPath = projectBadPath.Replace(
                _safeProjectName + Path.DirectorySeparatorChar + _safeProjectName + Path.DirectorySeparatorChar,
                _safeProjectName + Path.DirectorySeparatorChar);

            _dte.Solution.Remove(projectObject.Item2);

            Directory.Move(Path.GetDirectoryName(projectBadPath), Path.GetDirectoryName(projectGoodPath));

            if (projectObject.Item1 != null) //Solution Folder
            {
                var solutionFolder = (SolutionFolder)projectObject.Item1.Object;
                solutionFolder.AddFromFile(projectGoodPath);
            }
            else
            {
                _dte.Solution.AddFromFile(projectGoodPath);
            }
        }

        ThreadPool.QueueUserWorkItem(dir =>
        {
            System.Threading.Thread.Sleep(2000);
            Directory.Delete(_destinationDirectory, true);
        }, _destinationDirectory);
    }

This supports one level of solution folder (if you want you can make my solution recursive to support every levels)
Make Sure to put the projects in the <ProjectCollection> tag in order of most referenced to least referenced. because of the removal and adding of projects.

A: Multi-project templates are very tricky. I've found that the handling of $safeprojectname$ makes it almost impossible to create a multi-project template and have the namespace values replaced correctly. I've had to create a custom wizard which light up a new variable $saferootprojectname$ which is always the value that the user enters into the name for the new project.
In SideWaffle (which is a template pack with many templates) we have a couple multi-project templates. SideWaffle uses the TemplateBuilder NuGet package. TemplateBuilder has the wizards that you'll need for your multi-project template.
I have a 6 minute video on creating project templates with TemplateBuilder. For multi-project templates the process is a bit more cumbersome (but still much better than w/o TemplateBuilder. I have a sample multi-project template in the SideWaffle sources at https://github.com/ligershark/side-waffle/tree/master/TemplatePack/ProjectTemplates/Web/_Sample%20Multi%20Project.

A: Actually there is a workaround, it is ugly, but after diggin' the web I couldnt invent anything better. So, when creating a new instance of multiproject solution, you have to uncheck the 'create new folder' checkbox in the dialog. And before you start the directory structure should be like
 Projects
{no dedicated folder yet}

After you create a solution a structure would be the following:
Projects
    +--MyApplication1
         +-- Project1
         +-- Project2
    solution file

So the only minor difference from the desired structure is the place of the solution file. So the first thing you should do after the new solution is generated and shown - select the solution and select "Save as" in menu, then move the file into the MyApplication1 folder. Then delete the previous solution file and here you are, the file structure is like this:
Projects
    +--MyApplication1
         +-- Project1
         +-- Project2
         solution file

A: I made a project that keys off the YouTube tutorial of Joche Ojeda and the answer by EliSherer above that addresses the question at the top of this article, and also allows us to create a dialog box that shows check boxes to toggle which sub-projects get generated.
Please click here for my GitHub repo that does the dialog box and tries to fix the folder issue in this question.
The README.md at the Repository root goes into excruciating depth as to the solution.
EDIT 1: Relevant Code
I want to add to this post the relevant code that addresses the OP's question.
First, we have to deal with folder naming conventions for solutions.  Note, that my code is only designed to deal with the case where we are NOT putting the .csproj and .sln in the same folder; i.e., the following checkbox should be left blank:
Leaving the Place Solution and Project in the Same Directory check box blank
NOTE: The construct /* ... */ is used to signify other code that is not relevant to this answer.  Also, the try/catch block structure I utilize is pretty much identical to that of EliSherer, so I won't reproduce that here, either.
We need to put the following fields in the beginning of the WizardImpl class in the MyProjectWizard DLL (this is the Root DLL that is called during the generation of the Solution).  Please note that all code snippets are taken from my GitHub Repo I am linking to, and I am only going to show the pieces that have to deal with answering the OP's question.  I will, however, echo all using's where relevant:
using Core.Config;
using Core.Files;
using EnvDTE;
using Microsoft.VisualStudio.TemplateWizard;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;

namespace MyProjectWizard
{
    /// <summary>
    /// Implements a new project wizard in Visual Studio.
    /// </summary>
    public class WizardImpl : IWizard
    {
        /// <summary>
        /// String containing the fully-qualified pathname
        /// of the erroneously-generated sub-folder of the
        /// Solution that is going to contain the individual
        /// projects' folders.
        /// </summary>
        private string _erroneouslyCreatedProjectContainerFolder;

        /// <summary>
        /// String containing the name of the folder that
        /// contains the generated <c>.sln</c> file.
        /// </summary>
        private string _solutionFileContainerFolderName;

        /* ... */
    }
}

Here's how we initialize these fields (in the RunStarted method of the same class):
using Core.Config;
using Core.Files;
using EnvDTE;
using Microsoft.VisualStudio.TemplateWizard;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;

namespace MyProjectWizard
{
    /// <summary>
    /// Implements a new project wizard in Visual Studio.
    /// </summary>
    public class WizardImpl : IWizard
    {

        /* ... */

        public void RunStarted(object automationObject,
            Dictionary<string, string> replacementsDictionary,
            WizardRunKind runKind, object[] customParams)
        {
            /* ... */

           // Grab the path to the folder that
           // is erroneously created to contain the sub-projects.
           _erroneouslyCreatedProjectContainerFolder =
               replacementsDictionary["$destinationdirectory$"];

            // Here, in the 'root' wizard, the $safeprojectname$ variable
            // contains the name of the containing folder of the .sln file
            // generated by the process.
            _solutionFileContainerFolderName =
                replacementsDictionary["$safeprojectname$"];

            /* ... */
        }
    }
}

To be fair, I don't think that the value in the _solutionFileContainerFolderName field is ever used, but I wanted to put it there so you can see what value $safeprojectname$ takes on in the Root Wizard.
In the screen shots in this article and in the GitHub, I call the example dummy project BrianApplication1 and the solution is named the same.  In this example, then, the _solutionFileContainerFolderName field will have the value of BrianApplication1.
If I tell Visual Studio I want to create the solution and project (really, the multi-project template) in the C:\temp folder, then $destinationdirectory$ gets filled with C:\temp\BrianApplication1\BrianApplication1.
The projects in the multi-project template all get initially generated underneath the C:\temp\BrianApplication1\BrianApplication1 folder, like so:
C:\
    |
    --- temp
         |
         --- BrianApplication1
              |
              --- BrianApplication1.sln
              |
              --- BrianApplication1  <-- extra folder that needs to go away
                   |
                   --- BrianApplication1.DAL
                   |    |
                   |    --- BrianApplication1.DAL.csproj
                   |    |
                   |    --- <other project files and folders>
                   --- BrianApplication1.WindowsApp
                   |    |
                   |    --- BrianApplication1.WindowsApp.csproj
                   |    |
                   |    --- <other project files and folders>

The whole point of the OP's post, and my solution, is to create a folder structure that hews to convention; i.e.:
C:\
    |
    --- temp
         |
         --- BrianApplication1
              |
              --- BrianApplication1.sln
              |
              --- BrianApplication1.DAL
              |    |
              |    --- BrianApplication1.DAL.csproj
              |    |
              |    --- <other project files and folders>
              --- BrianApplication1.WindowsApp
              |    |
              |    --- BrianApplication1.WindowsApp.csproj
              |    |
              |    --- <other project files and folders>

We are almost done with the Root implementation of IWizard's job.  We still need to implement the RunFinished method (btw, the other IWizard methods are irrelevant to this solution).
The job of the RunFinished method is to simply remove the erroneously-created container folder for the sub-projects, now that they've all been moved up one level in the file system:
using Core.Config;
using Core.Files;
using EnvDTE;
using Microsoft.VisualStudio.TemplateWizard;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;

namespace MyProjectWizard
{
    /// <summary>
    /// Implements a new project wizard in Visual Studio.
    /// </summary>
    public class WizardImpl : IWizard
    {
        /* ... */

        /// <summary>Runs custom wizard logic when the wizard
        /// has completed all tasks.</summary>
        public void RunFinished()
        {
            // Here, _erroneouslyCreatedProjectContainerFolder holds the path to the
            // erroneously-created container folder for the
            // sub projects. When we get here, this folder should be
            // empty by now, so just remove it.

            if (!Directory.Exists(_erroneouslyCreatedProjectContainerFolder) ||
                !IsDirectoryEmpty(_erroneouslyCreatedProjectContainerFolder))
                return; // If the folder does not exist or is not empty, then do nothing

            if (Directory.Exists(_erroneouslyCreatedProjectContainerFolder))
                Directory.Delete(
                    _erroneouslyCreatedProjectContainerFolder, true
                );
        }

        /* ... */

        /// <summary>
        /// Checks whether the folder having the specified <paramref name="path" /> is
        /// empty.
        /// </summary>
        /// <param name="path">
        /// (Required.) String containing the fully-qualified pathname of the folder to be
        /// checked.
        /// </param>
        /// <returns>
        /// <see langword="true" /> if the folder contains no files nor
        /// subfolders; <see langword="false" /> otherwise.
        /// </returns>
        /// <exception cref="T:System.ArgumentException">
        /// Thrown if the required parameter,
        /// <paramref name="path" />, is passed a blank or <see langword="null" /> string
        /// for a value.
        /// </exception>
        /// <exception cref="T:System.IO.DirectoryNotFoundException">
        /// Thrown if the folder whose path is specified by the <paramref name="path" />
        /// parameter cannot be located.
        /// </exception>
        private static bool IsDirectoryEmpty(string path)
        {
            if (string.IsNullOrWhiteSpace(path))
                throw new ArgumentException(
                    "Value cannot be null or whitespace.", nameof(path)
                );
            if (!Directory.Exists(path))
                throw new DirectoryNotFoundException(
                    $"The folder having path '{path}' could not be located."
                );

            return !Directory.EnumerateFileSystemEntries(path)
                             .Any();
        }

        /* ... */

        }
    }
}

The implementation for the IsDirectoryEmpty method was inspired by a Stack Overflow answer and validated by my own knowledge; unfortunately, I lost the link to the appropriate article; if I can find it, I'll make an update.
OKAY, so now we've handled the job of the Root Wizard.  Next is the Child Wizard.  This where we add (a slight variation of) EliSherer's answer.
First, the fields we need to declare are:
using Core.Common;
using Core.Config;
using Core.Files;
using EnvDTE;
using EnvDTE80;
using Microsoft.VisualStudio.TemplateWizard;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using Thread = System.Threading.Thread;

namespace ChildWizard
{
    /// <summary>
    /// Implements a wizard for the generation of an individual project in the
    /// solution.
    /// </summary>
    public class WizardImpl : IWizard
    {
        /* ... */

        /// <summary>
        /// Contains the name of the folder that was erroneously
        /// generated in order to contain the generated sub-projects,
        /// which we assume has the same name as the solution (without
        /// the <c>.sln</c> file extension, so we are giving it a
        /// descriptive name as such.
        /// </summary>
        private string _containingSolutionName;

        /// <summary>
        /// Reference to an instance of an object that implements the
        /// <see cref="T:EnvDTE.DTE" /> interface.
        /// </summary>
        private DTE _dte;

        /// <summary>
        /// String containing the fully-qualified pathname of the
        /// sub-folder in which this particular project (this Wizard
        /// is called once for each sub-project in a multi-project
        /// template) is going to live in.
        /// </summary>
        private string _generatedSubProjectFolder;

        /// <summary>
        /// String containing the name of the project that is safe to use.
        /// </summary>
        private string _subProjectName;

        /* ... */
    }
}

We initialize these fields in the RunStarted method thusly:
using Core.Common;
using Core.Config;
using Core.Files;
using EnvDTE;
using EnvDTE80;
using Microsoft.VisualStudio.TemplateWizard;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using Thread = System.Threading.Thread;

namespace ChildWizard
{
    /// <summary>
    /// Implements a wizard for the generation of an individual project in the
    /// solution.
    /// </summary>
    public class WizardImpl : IWizard
    {
        /* ... */

         /// <summary>Runs custom wizard logic at the beginning of a template wizard run.</summary>
        /// <param name="automationObject">
        /// The automation object being used by the template
        /// wizard.
        /// </param>
        /// <param name="replacementsDictionary">
        /// The list of standard parameters to be
        /// replaced.
        /// </param>
        /// <param name="runKind">
        /// A
        /// <see cref="T:Microsoft.VisualStudio.TemplateWizard.WizardRunKind" /> indicating
        /// the type of wizard run.
        /// </param>
        /// <param name="customParams">
        /// The custom parameters with which to perform
        /// parameter replacement in the project.
        /// </param>
        public void RunStarted(object automationObject,
            Dictionary<string, string> replacementsDictionary,
            WizardRunKind runKind, object[] customParams)
        {

            /* ... */

            _dte = automationObject as DTE;

            _generatedSubProjectFolder =
                replacementsDictionary["$destinationdirectory$"];

            _subProjectName = replacementsDictionary["$safeprojectname$"];

            // Assume that the name of the solution is the same as that of the folder
            // one folder level up from this particular sub-project.
            _containingSolutionName = Path.GetFileName(
                Path.GetDirectoryName(_generatedSubProjectFolder)
            );

            /* ... */
        }

        /* ... */
    }
}

When this Child Wizard is called, e.g., to generate the BrianApplication1.DAL project, the fields get the following values:

*

*_dte = Reference to the automation object exposed by the EnvDTE.DTE interface

*_generatedSubProjectFolder = C:\temp\BrianApplication1\BrianApplication1\BrianApplication1.DAL

*_subProjectName = BrianApplication1.DAL

*_containingSolutionName = BrianApplcation1
Relevant to the OP's answer, initializing these fields is all the work that RunStarted needs to do.  Now, let's see how I needed to adapt EliSherer's answer in the RunFinished method of the Child Wizard's code:
using Core.Common;
using Core.Config;
using Core.Files;
using EnvDTE;
using EnvDTE80;
using Microsoft.VisualStudio.TemplateWizard;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using Thread = System.Threading.Thread;

namespace ChildWizard
{
    /// <summary>
    /// Implements a wizard for the generation of an individual project in the
    /// solution.
    /// </summary>
    public class WizardImpl : IWizard
    {
        /* ... */

        /// <summary>Runs custom wizard logic when the
        /// wizard has completed all tasks.</summary>
        public void RunFinished()
        {
            try
            {
                if (!_generatedSubProjectFolder.Contains(
                    _containingSolutionName + Path.DirectorySeparatorChar +
                    _containingSolutionName
                ))
                    return;

                //The projects were created under a separate folder -- lets fix
                //it
                var projectsObjects = new List<Tuple<Project, Project>>();
                foreach (Project childProject in _dte.Solution.Projects)
                    if (string.IsNullOrEmpty(
                        childProject.FileName
                    )) //Solution Folder
                        projectsObjects.AddRange(
                            from dynamic projectItem in
                                childProject.ProjectItems
                            select new Tuple<Project, Project>(
                                childProject, projectItem.Object as Project
                            )
                        );
                    else
                        projectsObjects.Add(
                            new Tuple<Project, Project>(null, childProject)
                        );

                foreach (var projectObject in projectsObjects)
                {
                    var projectBadPath = projectObject.Item2.FileName;
                    if (!projectBadPath.Contains(_subProjectName))
                        continue; // wrong project

                    var projectGoodPath = projectBadPath.Replace(
                        _containingSolutionName + Path.DirectorySeparatorChar +
                        _containingSolutionName + Path.DirectorySeparatorChar,
                        _containingSolutionName + Path.DirectorySeparatorChar
                    );

                    _dte.Solution.Remove(projectObject.Item2);

                    var projectBadPathDirectory =
                        Path.GetDirectoryName(projectBadPath);
                    var projectGoodPathDirectory =
                        Path.GetDirectoryName(projectGoodPath);

                    if (Directory.Exists(projectBadPathDirectory) &&
                        !string.IsNullOrWhiteSpace(projectGoodPathDirectory))
                        Directory.Move(
                            projectBadPathDirectory, projectGoodPathDirectory
                        );

                    if (projectObject.Item1 != null) //Solution Folder
                    {
                        var solutionFolder =
                            (SolutionFolder)projectObject.Item1.Object;
                        solutionFolder.AddFromFile(projectGoodPath);
                    }
                    else
                    {
                        // TO BE COMPLETELY ROBUST, we should do
                        // File.Exists() on the projectGoodPath; since
                        // we are in a try/catch and Directory.Move would
                        // have otherwise thrown an exception if the
                        // folder move operation failed, it can be safely
                        // assumed here that projectGoodPath refers to a
                        // file that actually exists on the disk.

                        _dte.Solution.AddFromFile(projectGoodPath);
                    }
                }

                ThreadPool.QueueUserWorkItem(
                    dir =>
                    {
                        Thread.Sleep(2000);
                        if (Directory.Exists(_generatedSubProjectFolder))
                            Directory.Delete(_generatedSubProjectFolder, true);
                    }, _generatedSubProjectFolder
                );
            }
            catch (Exception ex)
            {
                DumpToLog(ex);
            }
        }

        /* ... */
    }
}

More or less, this is the same answer as EliSherer, except, where he uses the expression _safeProjectName + Path.DirectorySeparatorChar + _safeProjectName, I substitute _safeProjectName with _containingSolutionName, which, if you look above the listing to the fields and their descriptive comments and example values, makes more sense in this context.
NOTE: I thought about explaining the RunFinished code in the Child Wizard line-by-line but I think I will leave that to the reader to figure out.  Let me do some broad-brush:

*

*We check whether the path of the generated sub-project folder contains <solution-name>\<solution-name> such as is shown in the example value of the _generatedSubProjectFolder field and the OP's issue.   If not, then stop as there is nothing to do.

NOTE: I use a Contains search and not an EndsWith as in EliSherer's original answer, due to the example value being what it is (and what I actually encountered during the crafting of this project).

*The next loop, through the solution's Projects, is basically copied straight from EliSherer.  We sort out which Projects are merely Solution Folders and which are actual, well, bona-fide .csproj-based project entries.  Like EliSherer, we just go one level down in Solution Folders.  Recursion is left as an exercise for the reader.

*The loop that follows, which is over the List<Tuple<Project, Project>> that is built up in #2, is again, almost identical to EliSherer's answer, but with two important modifications:

*

*We check the projectBadPath whether it contains the _subProjectName; if not, then we actually are iterating over one of the OTHER projects in the solution BESIDES the one that this particular call to the Child Wizard is dealing with; if so, we use a continue statement to skip it.

*In the EliSherer answer, everywhere he used the contents of $safeprojectname$ in his pathname parsing expressions, I am using the "solution name" I derived from parsing the folder path in RunStarted, via the _containingSolutionName field.

*Then DTE is used to remove the project from the Solution being generated, temporarily.  We then move the project's folder up on level in the file system.  For robustness' sake, I test whether the projectBadPathDirectory (the "source" folder for the Directory.Move call) exists (pretty reasonable) and I also use string.IsNullOrWhiteSpace on the projectGoodPathDirectory just in case Path.GetDirectoryName does not return a valid value when called on the projectGoodPath for some reason.

*I then again, adapted the EliSherer code for dealing with a SolutionFolder or a project with a .csproj pathname to have DTE add the project BACK to the Solution being generated, this time, from the correct file system path.
I am fairly certain this code works because I did LOTS of logging (which then got removed, otherwise it would be like trying to see the trees through the forest).  The logging infrastructure functions are still there in the body of the WizardImpl classes in both MyProjectWizard and ChildWizard, if you care to use them again.
As always, I make no promises regarding edge cases... =)
I tried many iterations of the EliSherer code before I could get all the test cases to work.  By the way, which reminds me:
Test Cases
In each case, the desired outcome is the same: the folder structure of the generated .sln and .csproj should match convention, i.e., in the second folder-structure fence diagram above.
Each case simply says which project(s) to toggle on and off in the Wizard as shown in the GitHub repo.

*

*Generate DAL: True, Generate UI Layer: True

*Generate DAL: False, Generate UI Layer: True

*Generate DAL: True, Generate UI Layer: False
Since it's pointless to even run the generation process if both are set to False, then we simply do not include that as a fourth test case.
With the code I supply both above and in the repo linked, all test cases pass.  With "passing" meaning, Visual Studio Solutions are generated with only the sub-project(s) selected, and the folder structure matches the conventional folder layout that solves the OP's original issue.


text:
Q: DynamoDb Data modeling with mutable data I'm trying to define a single table data structure for my data, I have come up with a set of access patterns and an ERD. For simplicity I'll name a few of those access patterns that I'm having issues modeling the data in the single table.
Relationships

*

*Users have Teams and Players.

*Team can have many Players.

*Player can be in many Teams.

Team

*

*id

*name (mutable, can change often)

*modifiedTime (mutable, can change often)

Player

*

*id

*name (mutable, can change often)

*modifiedTime (mutable, can change often)

Access Patterns

*

*Given userId and teamId get all players sorted by name

*Given userId and teamId get all players sorted by modifiedTime

*Given userId and playerId get all teams sorted by name

*Given userId and playerId get all teams sorted by modifiedTime

Given these access patterns and the data is mutable, I'm not sure if DynamoDb is a good use case for this problem. I'm trying to avoid doing many updates when a player or team is updated(since in the worst case scenarios teams can have up to unlimited players).
I cant seem to come up with a good approach on how to structure the data in a single table. And how to efficiently query such data.
I was thinking Aurora might be a better use case for this.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Apply table style to all columns except first column I am creating an HTML table dynamically with JavaScript so that the number of columns can vary (between 1 and 10).
Is there a way in CSS that I can automatically apply a class style to all columns of this table except the first column without having to add a class manually to each column ?
I thought maybe there is a trick with using the nth-child but couldn't get this working.

A: There are several ways. One of them is
th:nth-child(n+2), td:nth-child(n+2) { ... }

A different one:
th + th, th + td, td + th, td + td { ... }

The browser coverage for these is good, but not quite 100%. To cover all CSS-enabled browsers, I'm afraid you would need to do this indirectly:
th, td { /* your settings here */ }
th:first-child, td:first-child { /* "overwriting" settings here */ }

Here "overwriting settings" mean settings that override the settings in the first rule. But this requires information about the desired rendering for the first column.

A: Try this:
td:not(:first-child){color:green;}

Here is the fiddle.


text:
Q: Cannot find symbol error in Test Class This is my student class.
public class Student {
    private String name;
    private long id;
    private double gpa;
    private PersonalData pd;

    public Student(String name, long id, double gpa, PersonalData pd){
        this.name= name;
        this.id=id;
        this.gpa= gpa;
        this.pd= pd;
    }

    public String getName(){
        return name;
    }

    public long getID(){
        return id;
    }

    public double getGPA(){
        return gpa;
    }

    public PersonalData getPersonalData(){
        return pd;
    }

    public String toString(){
        String result= "Name: "+ name+ ", ID: "+ id+ ", GPA: "+gpa+", Personal Data: "+ pd;
        return result;
    }
}

Here is the test class:
public class Test {

    public static void main(String[] args) {

        // TODO, add your application code
        PersonalData a= new PersonalData(80,4,1,1232154687);
        Student b= new Student(Ali,123,20,a);
    }
}

It gives this error:
cannot find symbol
        Student b= new Student(Ali,123,20,a);
                               ^
  symbol:   variable Ali
  location: class Test
1 error

I don't know what is wrong. Is there anyone can see?

A: Make it like below
student b= new Student("Ali",123,20,a);

Your Student class constructor requires String as name either you have to pass it as in "" or Make a String variable like String Ali="" then pass Ali as
student b= new Student(Ali,123,20,a);


text:
Q: Extension Methods and generics - How should I be doing this? I'm in the middle of overhauling some code and I hit a bit of a snag.
This is the method which I currently have, it needs reworking to support some structure changes:
/// <summary>
/// Recreates a dashboard control based off of its settings.
/// </summary>
/// <typeparam name="T"> The type of control to be recreated. </typeparam>
/// <param name="settings"> The known settings needed to recreate the control.</param>
/// <returns> The recreated control. </returns>
public static T Recreate<T>(ISetting<T> settings) where T : new()
{
    T _control = new T();
    settings.SetSettings(_control);
    Logger.DebugFormat("Recreated control {0}", (_control as Control).ID);
    return _control;
}

ISetting is being removed completely in favor of an extension method known to _control.
So, I have now:
public static class RadControlExtensions
{
    public static RadDockZoneSetting GetSettings(this RadDockZone dockZone)
    {
        RadDockZoneSetting radDockZoneSetting = new RadDockZoneSetting(dockZone.UniqueName, dockZone.ID, dockZone.Skin, dockZone.MinHeight,
            dockZone.HighlightedCssClass, dockZone.BorderWidth, dockZone.Parent.ID);

        return radDockZoneSetting;
    }

    public static RadTabSetting GetSettings(this RadTab tab, int index)
    {
        RadTabSetting radTabSetting = new RadTabSetting(tab.Text, tab.Value, index);
        return radTabSetting;
    }

    //Continued
}

The control that is being recreated is guaranteed to have this extension method (would be nice to enforce this, though.)
I'm now at:
public static T Recreate<T>() where T : new()
{
    T _control = new T();
    //Not right -- you can't cast a control to an extension method, obviously, but
    //this captures the essence of what I would like to accomplish.
    (_control as RadControlExtension).SetSettings();
    Logger.DebugFormat("Recreated control {0}", (_control as Control).ID);
    return _control;
}

What should I be looking into to support this, if possible?

A: If you know that every _control that gets passed will be a RadDockZone (or derived from RadDockZone) just do this:
T _control = new T();
(RadDockZone)_control.SetSettings();
Logger.DebugFormat("Recreated control ... //rest of code here

If it's not always going to be a RadDockZone, you'll need to do some type checking to get the right type to call the extension method.  I'm presuming, there, that you have a .SetSettings() extension method on all the possible Types that could be passed to your Recreate method.

A: You need to cast your T to something that is supported by your extension method.
(_control as RadDockZone).GetSettings
Extension methods operate on a type they are not a type in the traditional sense.  The 'SomeFn(string this)'  makes your extension work on things that are strings which would be strings and anything derived from them.

A: If I understand correctly what you are trying to do, just put a constraint on T:
public static T Recreate<T>() where T : RadControl, new() {
    // etc.
}

You might have to use double dispatch and define
public static RadControl GetSettings(this RadControl control) {

}

which will invoke the appropriate GetSettings method.

A: No, Jason's answer is the cleaner way to go. The accepted solution killed the type safety and made use of generics pointless. You could switch to generic-less design (having a RadControlFactory) and had the job done.


text:
Q: Is this code signing certificate valid for signing applets? We purchased a code signing certificate for signing applets, but we get the following error when signing an applet.
    C:\CM\WEB-INF>jarsigner -keystore code_signing.keystore C:\CM\SweetApplet.jar code_signing_real
Enter Passphrase for keystore:
    jarsigner: Certificate chain not found for: code_signing_real.  code_signing_real must reference a valid KeyStore key entry containing a private key and corresponding public key certificate chain.

Is our certificate not correct? Here's the certificate in question below. The error message seems to suggest the certificate must contain a private key, but we don't understand how this can be since the private key is never supposed to get exposed to anyone but us.
C:\CM\WEB-INF>keytool -list -keystore code_signing.keystore -alias code_signing_real -v
Enter keystore password:
Alias name: code_signing_real
Creation date: Mar 13, 2014
Entry type: trustedCertEntry

Owner: CN=CE, OU=CE, O=CE, L=PAL
O ALTO, ST=California, C=US
Issuer: CN=Thawte Code Signing CA - G2, O="Thawte, Inc.", C=US
Serial number: 728b78e4ded46af26494c59690e428f0
Valid from: Wed Mar 12 17:00:00 PDT 2014 until: Fri Mar 11 15:59:59 PST 2016
Certificate fingerprints:
         MD5:  E0:DB:9E:DC:37:1E:C2:A9:EA:C0:A8:21:22:61:9F:DD
         SHA1: F9:C3:75:37:CA:86:4D:E2:11:BE:52:79:CE:FA:B3:6B:32:F0:CF:D2
         Signature algorithm name: SHA1withRSA
         Version: 3

Extensions:

#1: ObjectId: 2.5.29.19 Criticality=true
BasicConstraints:[
  CA:false
  PathLen: undefined
]

#2: ObjectId: 1.3.6.1.5.5.7.1.1 Criticality=false
AuthorityInfoAccess [
  [accessMethod: 1.3.6.1.5.5.7.48.1
   accessLocation: URIName: http://ocsp.thawte.com]
]

#3: ObjectId: 2.5.29.4 Criticality=false

#4: ObjectId: 2.5.29.31 Criticality=false
CRLDistributionPoints [
  [DistributionPoint:
     [URIName: http://cs-g2-crl.thawte.com/ThawteCSG2.crl]
]]

#5: ObjectId: 2.5.29.37 Criticality=false
ExtendedKeyUsages [
  codeSigning
  1.3.6.1.4.1.311.2.1.22
]

#6: ObjectId: 2.16.840.1.113730.1.1 Criticality=false
NetscapeCertType [
   Object Signing
]

A: It doesn't say the certificate must contain a private key. Certificates don't contain private keys. Read it again. It says the key entry must contain a private key and a certificate.
So however you constructed this KeyStore, it is invalid. Probably you just imported the signed certificate into a new KeyStore, or with a new alias. You must import it into the original KeyStore where the private key is, with the same alias as the private key.
You must also import the certificate chain, as trusted CA certificates, with another alias.


text:
Q: Making a custom class's buttons trigger the parent class I've got a UIViewController called "MainViewController" which uses a custom class 'CustomController' to control one of it's sub-views. The custom class instantiates UIButtons  in code. How would I get these buttons to trigger methods in the MainViewController?

A: I think delegation is the way to go there.

*

*Define the protocol CustomControllerDelegate inside CustomController.h with a method like this for example:
- (void) customControllerButtonPressed(id)sender; // BTW: you can use `CustomController` instead of `id` if you make a forward declaration for this class

*Add a delegate property and synthesize it in the .m file
@property (assign) id<CustomControllerDelgate> delegate;

*Now when your button is pressed you simply call the delegate:
[self.delegate customControllerButtonPressed:self];

*In your MainViewController you make it conform to the specified protocol and set the CustomControllers delegate like so:
CustomViewController *customVC = [[CustomViewController alloc] init];
customVC.delegate = self;

*Now when the button is pressed, the MainViewController's implementation of the specified method is called.


text:
Q: Woocommerce listing products by author effecting all shortcodes I'm attempting to create a page that lists products from woocommerce that have been posted by a specific editor. The below code works great, however it effects all shop and category pages. Is there any way I can make this a stand alone shortcode?
function htdat_shortcode_atts_products( $out, $pairs, $atts, $shortcode ) {
    if ( isset ( $atts['author'] ) ) $out['author'] = $atts['author'];
    return $out;
}
add_filter('shortcode_atts_products', 'htdat_shortcode_atts_products', 10, 4);

function htdat_woocommerce_shortcode_products_query( $query_args, $attributes ) {
    $query_args = array(
    'author'    => $attributes['author'],
    'post_status'    => 'publish',
        'post_type'      => 'product',
    'post_per_page'      => 12,
    );
    return $query_args;
 }
add_filter( 'woocommerce_shortcode_products_query', 'htdat_woocommerce_shortcode_products_query', 10, 2 );

I expected the shortcode to default to normal if an author id wasnt set. Like so: [products author=0] - but it would just be easier to have two seperate shortcodes such as [products-author] and [products]


text:
Q: How to reorder MenuItems in a MenuBar in Python Gtk3? Given a Gtk.MenuBar with some MenuItems, I'm looking for a way to rearrange the order in which the MenuItems appear.
Here's a basic MenuBar with two MenuItems "foo" and "bar":
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk

win= Gtk.Window()
mbar= Gtk.MenuBar()
win.add(mbar)

m1= Gtk.MenuItem('foo')
mbar.append(m1)
m2= Gtk.MenuItem('bar')
mbar.append(m2)

win.connect('destroy', Gtk.main_quit)
win.show_all()
Gtk.main()

The "foo" MenuItem will be left of "bar". I want to now move "bar" to the left of "foo".

Unlike the Menu class, MenuBar does not have a reorder_child method:
mbar.reorder_child(m2, 0)
# throws: 'MenuBar' object has no attribute 'reorder_child'

Neither does it have a "position" child property like many other container widgets.
mbar.child_set_property(m2, 'position', 0)
# shows warning: container class 'GtkMenuBar' has no child property named 'position'

So the only solution I could think of was to remove "bar" and then insert it at the desired location:
mbar.remove(m2)
mbar.insert(m2, 0)
# works

So my question is: Is there no better way to reorder MenuItems in a MenuBar? Other container widgets provide a method to reorder their children, so surely the MenuBar should as well?


text:
Q: NDSolve for system of PDEs -Error: fewer dependent variables! I am trying to solve the equations below to find the breakthrough curve in an adsorption process:
∂C/∂t+u* ∂C/∂z+ρ/ϵ * ∂q/∂t=  0
∂q/∂t= -Ks * (q-(qm* b*C)/(1+ b*C))

the IC and BCs are:
q(t=0,z)=0
C(t,z=0)=C0
C(t=0,z) = 0

The parameters are given as:
eps = 0.373
ueps = 6.66
C0 = 892
Ks = 0.0872
rho = 390.04
qm = 7.0136
b = 0.05313

I wrote the equation in Mathematica as below:
s=NDSolve[{∂_t C[t,z]==-ueps*∂_z C[t,z]+(rho⁄eps)*Ks*(q[t,z]-(qm*b*(C[t,z])⁄((1+b*C[t,z])))),∂_t q[t,z]==-Ks*(q[t,z]-(qm*b*(C[t,z])⁄((1+b*C[t,z])))),DirichletCondition[{C[t,0]==C0},True],C[0,z]==0,q[0,z]==0},{C,q},{t,0,60},{z,0,22}]

After evaluating the notebook, I receive this error:
NDSolve: There are fewer dependent variables, {q[t,z]}, than equations, so the system is overdetermined.
I have been trying to fix this problem by rearranging the equations, but no success yet.
I appreciate it if you could please help me solve this issue.
Thanks

A: Update:  Mass Transport Tutorial
In my answer, I adapted the Heat Transfer Tutorial to handle Mass Transport.  There is a new and fairly extensive Mass Transport Tutorial that you can use directly.  In my answer
227821, I extended the Mass Transport functions in the tutorial to include axisymmetric and optional porosity.
Update: Extended Answer
To use the FEM method it is good to cast your equations into coefficient form as shown FEM Tutorial.
$$\frac{{{\partial ^2}}}{{\partial {t^2}}}u + d\frac{\partial }{{\partial t}}u + \nabla \cdot\left( { - c\nabla u - \alpha u + \gamma } \right) + \beta \cdot\nabla u + au - f = 0$$
The benefits of coefficient form include:

*

*Standardization so others can quickly interpret your equations

*Avoidance of sign errors

*Nice one-to-one mapping with other FEM codes such as COMSOL

For advective-diffusive problems with and without source terms, the Heat transfer tutorial is a good place to start to learn how to set up these types of problems. It shows how to properly setup the PDE operators in coefficient form. The TimeHeatTransferModel function in the Heat Transfer Tutorial can help guide you on how to setup the problem.
Create Fluid and Solid PDE Operators Using Heat Transfer Tutorial
The following shows how one can setup your coupled system of interphase transport of the fluid and solid using the TimeHeatTransferModel :
(* From Vitaliy Kaurov for nice display of operators *)
pdConv[f_] :=
 TraditionalForm[
  f /. Derivative[inds__][g_][vars__] :>
    Apply[Defer[D[g[vars], ##]] &,
     Transpose[{{vars}, {inds}}] /. {{var_, 0} :>
        Sequence[], {var_, 1} :> {var}}]]
(*PDEModels/tutorial/HeatTransfer/HeatTransferVerificationTests#\
463435833*)
ClearAll[HeatTransferModel]
HeatTransferModel[T_, X_List, k_, ρ_, Cp_, Velocity_, Source_] :=
  Module[{V, Q, a = k},
  V = If[Velocity === "NoFlow",
    0, ρ*Cp*Velocity.Inactive[Grad][T, X]];
  Q = If[Source === "NoSource", 0, Source];
  If[ FreeQ[a, _?VectorQ], a = a*IdentityMatrix[Length[X]]];
  If[ VectorQ[a], a = DiagonalMatrix[a]];
  (* Note the - sign in the operator *)
  a = PiecewiseExpand[Piecewise[{{-a, True}}]];
  Inactive[Div][a.Inactive[Grad][T, X], X] + V - Q]
TimeHeatTransferModel[T_, TimeVar_, X_List, k_, ρ_, Cp_,
  Velocity_, Source_] := ρ*Cp*D[T, {TimeVar, 1}] +
  HeatTransferModel[T, X, k, ρ, Cp, Velocity, Source]
(* Create Parametric PDE Operators for Fluid and Solid *)
(* Include Small Diffusive Term to Fluid Otherwise MMA Might Complain \
about Being Convection Dominated *)
parmfop =
  TimeHeatTransferModel[c[t, x], t, {x}, {d}, 1,
   1, {u}, -(ρ/ϵ) Q];
parmsop =
  TimeHeatTransferModel[q[t, x], t, {x}, {0}, 1, 1, "NoFlow", Q];
parmfop // pdConv
parmsop // pdConv

Slight rearrangement shows the operators follow coefficient form:
$$\begin{matrix}
m\frac{{{\partial ^2}}}{{\partial {t^2}}}u & +\ \ d\frac{\partial }{{\partial t}}u & + \ \ \nabla \cdot\left( { - c\nabla u - \alpha u + \gamma } \right) u &  + \ \ \beta \cdot\nabla u & + \ \ au & -\ \ f & =0 & \ \ (1) \\
 & & & & & & \\
 & +\ \ \frac{{\partial c(t,x)}}{{\partial t}} & + \ \  {\nabla _{\left\{ x \right\}}}\cdot\left( {\left( {\begin{array}{*{20}{c}}
  { - d}
\end{array}} \right).{\nabla _{\left\{ x \right\}}}c\left( {t,x} \right)} \right) &  + \ \ \left\{ u \right\}.{\nabla _{\left\{ x \right\}}}c\left( {t,x} \right) &  & +\ \ \frac{{\rho Q}}{\varepsilon } & =0 & \ \ (2) \\
 & & & & & & \\
 & +\ \ \frac{{\partial q(t,x)}}{{\partial t}} &   &   & & -\ \ Q
 & =0 & \ \ (3)
\end{matrix}$$
New Workflow
The following workflow uses the PDE operators defined above and produces an annotated plots that can be scrolled frame-by-frame with manipulate.
(* Define Parameters *)
eps = 0.373;
ueps = 6.66;
c0 = 892;
Ks = 0.0872;
rho = 390.04;
qm = 7.0136;
b = 0.05313;
tend = 60;
xend = 22;
Qsource = -Ks*(q[t, x] - (qm*b*c[t, x])/(1 + b*c[t, x]));
timeinc = 0.25; (* Output times *)
(* Critical Breakthrough Fraction *)
btfrac = 0.05;
(* Use CombinePlots For Secondary Axis *)
cp = ResourceFunction["CombinePlots", "Function"];
(* Setup PDE System *)
pdef = (parmfop == 0) /. {ϵ -> eps, u -> ueps, ρ -> rho,
     d -> 1, Q -> Qsource};
pdes = (parmsop == 0) /. {Q -> Qsource};
dc = DirichletCondition[c[t, x] == c0 (1 - Exp[-40 t]), x == 0];
icf = c[0, x] == 0;
ics = q[0, x] == 0;
(* Solve PDE *)
{cifn, qifn} =
  NDSolveValue[{pdef, pdes, dc, icf, ics}, {c, q}, {t, 0, tend}, {x,
    0, xend},
   Method -> {"MethodOfLines", "TemporalVariable" -> t,
     "SpatialDiscretization" -> {"FiniteElement",
       "MeshOptions" -> {"MaxCellMeasure" -> 0.5}}}];
(* Plot Solutions *)
(* Define Plot Function Using Combine Plots *)
bfn = Function[{t},
   If[cifn[t, xend] >= btfrac c0, xend,
    x /. FindRoot[cifn[t + 0.01, x] - btfrac c0, {x, 0, xend},
      Method -> "Brent"]]];
bttemp = With[{xbt = #},
    If[xbt == xend, "Sat",
     StringTemplate["x=``"][ToString@PaddedForm[xbt, {4, 2}]]]] &;
pltfn = Function[{t}, cp[
    With[{xbt = bfn[t]},
     Plot[Callout[cifn[t, x], bttemp[xbt], xbt, RoundingRadius -> 5,
       Appearance -> "SlantedLabel"], {x, 0, xend},
      PlotRange -> {{-2, xend + 1}, {-10, 1.1 c0}}, Frame -> True,
      FrameLabel -> {"x", "c"},
      PlotLabel ->
       Style[StringTemplate[
          "Fluid and Solid Concentrations @ time=``"][
         ToString@PaddedForm[t, {4, 2}]], 12],
      Epilog -> {Green, Thick, Dashed,
        Line[{{xbt, -10}, {xbt, 1.1 c0}}]}]],
    Plot[qifn[t, x], {x, 0, xend}, PlotPoints -> 100,
     PlotRange -> {0, 7},
     Frame -> True, FrameStyle -> Red, PlotStyle -> Red,
     FrameLabel -> {"x", "q"}],
    "AxesSides" -> "TwoY"
    ], Listable];
(* Create Image List and Manipulate *)
imgs = Rasterize[#, ImageSize -> 340] & /@
   pltfn[Range[0, tend, timeinc]];
Manipulate[imgs[[i]], {i, 1, tend/timeinc, 1},
 ControlPlacement -> Top]

Original Answer
I would cast the problem using the following workflow:
(* Define Parameters *)
eps = 0.373;
ueps = 6.66;
c0 = 892;
Ks = 0.0872;
rho = 390.04;
qm = 7.0136;
b = 0.05313;
tend = 60;
xend = 22;
Qsource = -Ks*(q[t, x] - (qm*b*c[t, x])/(1 + b*c[t, x]));
(* Use CombinePlots For Secondary Axis *)
cp = ResourceFunction["CombinePlots"];
(* Define Parametric PDE operators *)
(* Include Small Diffusive Term to Fluid Otherwise MMA Might Complain \
about Being Convection Dominated *)
parmfop =
  D[c[t, x], t] +  D[-d D[c[t, x], x], x] + u  D[c[t, x], x] + (
   Q ρ)/ϵ;
parmsop = D[q[t, x], t] - Q;
(* Setup PDE System *)
pdef = (parmfop == 0) /. {ϵ -> eps, u -> ueps, ρ -> rho,
     d -> 1, Q -> Qsource};
pdes = (parmsop == 0) /. {Q -> Qsource};
dc = DirichletCondition[c[t, x] == c0 (1 - Exp[-40 t]), x == 0];
icf = c[0, x] == 0;
ics = q[0, x] == 0;
(* Solve PDE *)
{cifn, qifn} =
  NDSolveValue[{pdef, pdes, dc, icf, ics}, {c, q}, {t, 0, tend}, {x,
    0, xend},
   Method -> {"MethodOfLines", "TemporalVariable" -> t,
     "SpatialDiscretization" -> {"FiniteElement",
       "MeshOptions" -> {"MaxCellMeasure" -> 0.5}}}];
(* Plot Solutions *)
(* Define Plot Function Using Combine Plots *)
pltfn = Function[{t}, cp[
    Plot[cifn[t, x], {x, 0, xend}, PlotRange -> {0, 1.1 c0},
     Frame -> True, FrameLabel -> {"x", "c"}],
    Plot[qifn[t, x], {x, 0, xend}, PlotPoints -> 100,
     PlotRange -> {0, 7},
     Frame -> True, FrameStyle -> Red, PlotStyle -> Red,
     FrameLabel -> {"x", "q"}],
    "AxesSides" -> "TwoY"
    ], Listable];
(* Create Image List and Animate *)
imgs = Rasterize /@ pltfn[Range[0, tend, 0.25]];
ListAnimate[imgs, ControlPlacement -> Top]


text:
Q: Populate a vector with all multimap values with a given key Given a multimap<A,B> M what's a neat way to create a vector<B> of all values in M with a specific key.
e.g given a multimap how can I get a vector of all strings mapped to the value 123?
An answer is easy, looping from lower->upper bound, but is there a neat loop-free method?

A: Here's the way to do it STL style :
// The following define is needed for select2nd with DinkumWare STL under VC++
#define _HAS_TRADITIONAL_STL 1

#include <algorithm>
#include <vector>
#include <map>
#include <string>
#include <functional>
#include <map>
#include <iterator>
#include <iostream>

using namespace std;

void main()
{
    typedef multimap<string, int> MapType;
    MapType m;
    vector<int> v;

    // Test data
    for(int i = 0; i < 10; ++i)
    {
        m.insert(make_pair("123", i * 2));
        m.insert(make_pair("12", i));
    }

    MapType::iterator i = m.lower_bound("123");
    MapType::iterator j = m.upper_bound("123");

    transform(i, j, back_inserter(v), select2nd<MapType::value_type>());

    copy(v.begin(), v.end(),  ostream_iterator<int>(cout, ","));

}

A: Let's go lambda
given: multimap<A,B> M
requested: vector<B> (of all values in M with a specific key 'a'.)
method:
std::pair<M::iterator, M::iterator> aRange = M.equal_range('a')
std::vector<B> aVector;
std::transform(aRange.first, aRange.second,std::back_inserter(aVector), [](std::pair<A,B> element){return element.second;});

System environment:

*

*compiler: gcc (Ubuntu 5.3.1-14ubuntu2.1) 5.3.1 20160413 (with -std=c++11)

*os: ubuntu 16.04

Code example:
#include <algorithm>
#include <vector>
#include <map>
#include <string>
#include <functional>
#include <iostream>

int main()
{
    typedef std::multimap<std::string, int> MapType;
    MapType m;
    std::vector<int> v;

    /// Test data
    for(int i = 0; i < 10; ++i)
    {
        m.insert(std::make_pair("123", i * 2));
        m.insert(std::make_pair("12", i));
    }

    std::pair<MapType::iterator,MapType::iterator> aRange = m.equal_range("123");

    std::transform(aRange.first, aRange.second, std::back_inserter(v), [](std::pair<std::string,int> element){return element.second;});

    for(auto & elem: v)
    {
        std::cout << elem << std::endl;
    }
    return 0;
}

A: You need a loop anyway. All "loop-free" methods just abstract the loop away.
#include <map>
#include <vector>
#include <algorithm>
#include <ext/functional>
using namespace std;

int main () {
    multimap<int, double> mm;
    mm.insert(make_pair(1, 2.2));
    mm.insert(make_pair(4, 2.6));
    mm.insert(make_pair(1, 9.1));
    mm.insert(make_pair(1, 3.1));

    vector<double> v;
    transform(mm.lower_bound(1), mm.upper_bound(1),
              back_inserter(v), __gnu_cxx::select2nd<pair<int, double> >());
    // note: select2nd is an SGI extension.

    for (vector<double>::const_iterator cit = v.begin(); cit != v.end(); ++ cit)
        printf("%g, ", *cit);   // verify that you've got 2.2, 9.1, 3.1
    return 0;
}

A: template <class Key, class Val>
vector<Val>& getValues(multimap<Key, Val>& multi, Key& key)
{
    typedef multimap<Key, Val>::iterator imm;
    static vector<Val> vect;
    static struct
    {
        void operator()(const pair<Key, Val>& p) const
        {
            vect.push_back(p.second);
        }
    } Push;

    vect.clear();
    pair<imm, imm> range = multi.equal_range(key);
    for_each(range.first, range.second, Push);
    return vect;
}

This is a bit contrived because of your 'no loop' requirement.
I prefer:
template <class Key, class Val>
vector<Val> getValues(multimap<Key, Val>& map, Key& key)
{
    vector<Val> result;
    typedef multimap<Key, Val>::iterator imm;
    pair<imm, imm> range = map.equal_range(key);
    for (imm i = range.first; i != range.second; ++i)
        result.push_back(i->second);
    return result;
}

A: You could initialise the vector by giving it two iterators, like this:
std::multimap<std::string, std::string> bar;

...

std::vector<pair<string,string> > foo(bar.lower_bound("123"), bar.upper_bound("123"));

but that would give you a vector of pairs (ie, with both the key and value).
Another option would be to use std::copy with something like a back_inserter, which is another way to hide the loop, but with the same downside as above.
std::copy(bar.lower_bound("123"), bar.upper_bound("123"), std::back_inserter(foo));

This would append the elements (if any) to the vector foo.
For extracting the values only, I can't think of any way but to loop over the results as I'm not aware of a standard way to get only the value out of a range.

A: Just some addenda to the other answers here…
std::mem_fn (from #include <functional>) can be used as a shorthand for the transform operator:
// previously we might've used this longhand
[](pair<int,string> element){return element.second;}

And we can use vector::resize and std::distance to allocate space for the vector in one go, rather than repeatedly resizing it with back_inserter.
#include <algorithm>
#include <vector>
#include <map>
#include <string>
#include <functional>
#include <iterator>
#include <iostream>

using namespace std;

typedef multimap<int, string> MapType;

int main()
{
    MapType multimap;
    vector<string> valuesForKey123;

    multimap.emplace(0,   "red");
    multimap.emplace(123, "hello");
    multimap.emplace(123, "world");
    multimap.emplace(0,   "herring");

    MapType::iterator lower{multimap.lower_bound(123)};
    MapType::iterator upper{multimap.upper_bound(123)};
    valuesForKey123.resize(distance(lower, upper));

    transform(
        lower,
        upper,
        valuesForKey123.begin(),
        mem_fn(&MapType::value_type::second));

    copy(
        valuesForKey123.begin(),
        valuesForKey123.end(),
        ostream_iterator<string>(cout, " "));
}
// outputs "hello world "


text:
Q: Threading pattern search I am working on a program that essentially searches for patterns in a file.  It starts at level 1 which searches for all the different characters in a text file.  Then the algorithm takes those patterns and using the location of the previous patterns to find new patterns.  It is essentially a tree search of patterns.  I recently tried to thread the application and I am finding that it actually takes longer to process the more threads I add to the algorithm.  I did a performance test and noticed most of my time is being spent calling new.  That new could include my own explicit calls and internalized new called for vector resizes and push_backs.  Even the cpu usage goes up drastically when I use more cores but still translate to a quicker completion of the search.  Seems like the cpu is just working harder for no reason at all.  I am stuck at this point and I am not sure what to change but I think getting another set of eyes on this would be really helpful.  Sorry this is a bit vague and not a specific question.  I did not include the TreeNode class because I wanted to see if anyone would notice any bottlenecks in this function.  I can add the rest of the code later if nothing is apparent in this function.  Thanks
Here is the code that is threaded...
void ThreadedSpanLevelTreeSearch(long level, long startPatternIndex, long numPatternsToSearch){

Timing threadTimer;
threadTimer.setTime();

string localStream = fileStreamBuffer.str();
vector<TreeNode*> localTree;
TreeNode *leaf;
for(int i = startPatternIndex; i < numPatternsToSearch + startPatternIndex; i++)
{
    //countMutex->lock();
    //computationCount++;
    //countMutex->unlock();

    leaf = prevVectorizedTree[i];
    if(leaf != NULL)
    {
        vector<long> pList = leaf->GetPList();
        long pListLength = leaf->GetPListCount();

        for(int k = 0; k < pListLength; k++)
        {
            //If pattern is past end of string stream then stop counting this pattern
            if(pList[k] < localStream.size())
            {
                unsigned char value = localStream[pList[k]];
                //
                switch(currPattern)
                {
                    case PATTERNTYPE::NUMBERS:
                    {
                        if(value >= 48 && value <= 57)
                        {
                            leaf->addLeaf(value, level, pList[k]+1);
                        }
                        break;
                    }
                    case PATTERNTYPE::ALPHABET:
                    {
                        if((value >= 32 && value <= 126))
                        {
                            leaf->addLeaf(value, level, pList[k]+1);
                        }
                        break;
                    }
                    case PATTERNTYPE::EVERYTHING:
                    {
                        leaf->addLeaf(value, level, pList[k]+1);
                        break;
                    }
                    default:
                    {
                        break;
                    }
                };

            }
        }

        for(int z = 0; z < patternArrayLength; z++)
        {
            if(leaf->GetLeaf(patternArray[z]) != NULL)
            {

                if(leaf->GetLeaf(patternArray[z])->GetPListCount() > 1)
                {
                    localTree.push_back(leaf->GetLeaf(patternArray[z]));
                }
                //deallocate
                else if(leaf->GetLeaf(patternArray[z])->GetPListCount() <= 1)
                {
                    delete leaf->GetLeaf(patternArray[z]);
                }
            }
        }
    }
    delete leaf;
}
countMutex->lock();
globalVectorizedTree.insert(globalVectorizedTree.end(), localTree.begin(), localTree.end());
countMutex->unlock();

//cout << "thread " << ceil(startPatternIndex/numPatternsToSearch) << " finished" << endl;
//cout << "time taken for core: " << threadTimer.getTime() << endl;

}

A: The pool from which different threads allocate resources is the same. It is protected against concurrent accesses but using it from different threads causes this data to bound back and forth between the different CPU's caches, which costs performance.
There a few things to change:

*

*Avoid unnecessary allocations. Unless really necessary, avoid dynamic allocation. Also, a simple array or vector performs better than a linked list in almost all cases, they tend to have a large n_0 in Big-O notation.

*Avoid copying. For example, localStream pList shouldn't be required.

*Avoid unnecessary reallocations, e.g. for vectors use reserve(). There is a point where the overhead for allocating too much outweighs the overhead of copying. This point also depends on the general use in your program.

*You could use an allocator that uses thread-specific pools.

*Avoid uselessly starting threads. If the amount of work for each thread is small, the startup and shutdown time could be dominant. In some cases, using a thread-pool could help.


text:
Q: Multiple Input and Multiple Output Tensorflow Model I am trying to build a tensorflow model which takes 3 images as an input and gives 3 output embedding for each input image.
The images are saved in a list called triplet
The part of code is given below:
def inner_model(act_func='relu', input_shape=(112,112,3):
    model_input = layers.Input(shape=input_shape)
    x = layers.Conv2D(filters=16, kernel_size=3, padding='same', activation=act_func, name='Conv1')(model_input)
    x = layers.MaxPool2D()(x)
    x = layers.Conv2D(filters=32, kernel_size=3, padding='same', activation=act_func, name='Conv2')(x)
    x = layers.MaxPool2D()(x)
    x = layers.Conv2D(filters=64, kernel_size=3, padding='same', activation=act_func, name='Conv3')(x)
    x = layers.MaxPool2D()(x)
    x = layers.Conv2D(filters=128, kernel_size=3, padding='same', activation=act_func, name='Conv4')(x)
    x = layers.MaxPool2D()(x)
    x = layers.Conv2D(filters=256, kernel_size=3, padding='same', activation=act_func, name='Conv5')(x)
    x = layers.GlobalAvgPool2D(name='GAP')(x)
    output = layers.Dense(128, activation=act_func, name='Dense1')(x)
    model = Model(inputs=model_input, outputs=output)
    model.summary()
    return model

def tripler_trainer(input_shape=(112,112,3)):
    anchor_input = layers.Input(shape=input_shape)
    positive_input = layers.Input(shape=input_shape)
    negative_input = layers.Input(shape=input_shape)

    embedder = inner_model(act_func='relu', input_shape=(112,112,3)

    anchor_embedding = embedder(anchor_input)
    positive_embedding = embedder(positive_input)
    negative_embedding = embedder(negative_input)
    outer_network = Model(inputs=(anchor_input, positive_input, negative_input),
                          outputs=(anchor_embedding, positive_embedding, negative_embedding))
    return outer_network

triplet_model = tripler_trainer(input_shape=(112,112,3))
triplets = triplet_model(triplet[0], triplet[1], triplet[2])

When I try to run the code I get the following error:
Traceback (most recent call last):
  File "C:/Users/G5205GK/Desktop/Working Dir/code/con_learning/main.py", line 35, in <module>
    main()
  File "C:/Users/G5205GK/Desktop/Working Dir/code/con_learning/main.py", line 31, in main
    training_instance.train()
  File "C:\Users\G5205GK\Desktop\Working Dir\code\con_learning\train.py", line 36, in train
    anchor_embedding = self.model(triplet[0], triplet[1], triplet[2])
  File "C:\Users\G5205GK\Anaconda3\envs\my_gpu_env\lib\site-packages\tensorflow\python\keras\engine\base_layer.py", line 1013, in __call__
    input_spec.assert_input_compatibility(self.input_spec, inputs, self.name)
  File "C:\Users\G5205GK\Anaconda3\envs\my_gpu_env\lib\site-packages\tensorflow\python\keras\engine\input_spec.py", line 200, in assert_input_compatibility
    raise ValueError('Layer ' + layer_name + ' expects ' +
ValueError: Layer model_1 expects 3 input(s), but it received 1 input tensors. Inputs received: [<tf.Tensor: shape=(112, 112, 3), dtype=float32,

Can any one please suggest where the problem is. Also the code provided, is simplified for stack overflow. so it may have syntax issue.
Thanks in advance.

A: You should provide multiple inputs and outputs to your model with square brackets, since your model expects a list of inputs instead of a tuple of inputs. Try this:
import tensorflow as tf

def inner_model(act_func='relu', input_shape=(112,112,3)):
    model_input = tf.keras.layers.Input(shape=input_shape)
    x = tf.keras.layers.Conv2D(filters=16, kernel_size=3, padding='same', activation=act_func, name='Conv1')(model_input)
    x = tf.keras.layers.MaxPool2D()(x)
    x = tf.keras.layers.Conv2D(filters=32, kernel_size=3, padding='same', activation=act_func, name='Conv2')(x)
    x = tf.keras.layers.MaxPool2D()(x)
    x = tf.keras.layers.Conv2D(filters=64, kernel_size=3, padding='same', activation=act_func, name='Conv3')(x)
    x = tf.keras.layers.MaxPool2D()(x)
    x = tf.keras.layers.Conv2D(filters=128, kernel_size=3, padding='same', activation=act_func, name='Conv4')(x)
    x = tf.keras.layers.MaxPool2D()(x)
    x = tf.keras.layers.Conv2D(filters=256, kernel_size=3, padding='same', activation=act_func, name='Conv5')(x)
    x = tf.keras.layers.GlobalAvgPool2D(name='GAP')(x)
    output = tf.keras.layers.Dense(128, activation=act_func, name='Dense1')(x)
    model = tf.keras.Model(inputs=model_input, outputs=output)
    model.summary()
    return model

def tripler_trainer(input_shape=(112,112,3)):
    anchor_input = tf.keras.layers.Input(shape=input_shape)
    positive_input = tf.keras.layers.Input(shape=input_shape)
    negative_input = tf.keras.layers.Input(shape=input_shape)

    embedder = inner_model(act_func='relu', input_shape=(112,112,3))

    anchor_embedding = embedder(anchor_input)
    positive_embedding = embedder(positive_input)
    negative_embedding = embedder(negative_input)
    outer_network = tf.keras.Model(inputs=[anchor_input, positive_input, negative_input],
                          outputs=[anchor_embedding, positive_embedding, negative_embedding])
    return outer_network

triplet_model = tripler_trainer(input_shape=(112,112,3))
triplet1, triplet2, triplet3 = tf.random.normal((1,112,112,3)), tf.random.normal((1,112,112,3)), tf.random.normal((1,112,112,3))
triplets = triplet_model([triplet1, triplet2, triplet3])
print(triplets[0].shape, triplets[1].shape, triplets[2].shape)
# (1, 128) (1, 128) (1, 128)


text:
Q: How important is it to digitally sign our executables? We produce a content management system. It's a database-based system, used only by businesses and organizations, and never downloadable from the Internet. That is, it's not the kind of software someone might stumble upon and wonder what it is and whether it's safe to run. Over the 20+ years our system is being sold, its executables have never been digitally signed. Is it time for us to start signing them?
For starters, I can think of a few pros and cons:

*

*Pro: If using Verisign certificates, Windows Error Reporting can be used

*Pro: When Windows Vista and Windows 7 show one of those annoying UAC messages, signed applications are presented a bit more nicely

*Con: Certificates cost money. Not a lot, but if they're useless it's too much

*Con: Signing has some maintenance overhead, how much I don't know.

A:
Pro: If using Verisign certificates, Windows Error Reporting can be used

Actually, to use Windows Error Reporting you need Verisign or other code accepted signing certificate, but you need the certificate only to access the WinQual system. The exe itself does not have to be signed at all, the error reporting works absolutely fine on unsigned exes as well.

Con: Signing has some maintenance overhead, how much I don't know. Would love to here from you...

The maintenance overhead highly depends on the quality of your build pipeline. If you build your application manually, then yes, it means a few more steps. However, if you have a build pipeline and your builds are automated, code signing means adding a few lines into the build scripts and storing the private key of the code signing certificate so that the build can access it (if you have a build server, your code signing certificate will most likely need to be stored on it).

Pro: When Vista/7 show one of those annoying UAC messages, signed apps are presented a bit more nicely

As for UAC prompt - does you application really need elevated or admin privileges to run? The best way to avoid this prompt is not to require any elevated privileges at all.

A: From the tech side you already stated the pros/cons.
From the business point of view it depends on your users, maybe if you are selling B2B it wouldn't matter as if you were selling B2C or to less savvy users whom would appreciate more a nicer UAC message.
Honestly, I wouldn't worry.... If you haven't had the urge and can't find a really good reason, then it's not important yet.
I'd rather spend those efforts improving something else.

A:
Signing has some maintenance overhead, how much I don't know.

I believe if you distribute signed executables, all dependent libraries have to be signed as well. If you're using some third-party modules over which you have no control, you can get an issue.


text:
Q: Error with initializer_list> I want to initialize my own class similar to this:
vector< Point3f >={{1f,2f,3f},{2f,3f,1f},{2f,2f,2f}};

but there is an error shown:

can't convert "initializer list" to "std::vector<LB::Point3f,std::allocator<LB::Point3f>>...

I want to know what the right way is to initialize my own class with lists in braces.
This is my code:
#pragma once
#ifndef POINT_HPP
#define POINT_HPP

#include<initializer_list>

namespace LB
{
    using namespace std;

    template< typename T,unsigned length>
    class Point
    {
        T data[length];
    public:
        Point(){}
        Point(const initializer_list<T>& t)
        {
            int min = t.size() < length ? t.size() : length;
            int i = 0;
            for (auto& each : t)
            {
                if (i >= min)
                    break;
                data[i] = each;
                i++;
            }
        }
        Point(Point<T, length>& other)
        {
            for (int i = 0; i < length; i++)
            {
                data[i] = other[i];
            }
        }
/*
   other operation function
*/
    };

    using Point2i = Point<int, 2>;
    using Point2f = Point<float, 2>;
    using Point2d = Point<double, 2>;
    using Point3i = Point<int, 3>;
    using Point3f = Point<float, 3>;
    using Point3d = Point<double, 3>;
    using Point4i = Point<int, 4>;
    using Point4f = Point<float, 4>;
    using Point4d = Point<double, 4>;
}

#endif

A: Basically it's failing because your current implementation of `Point<T,unsigned> doesn't have a working copy constructor.
The copy constructor needs to take a const Point<T, length>& since the initializer list is const, and it will need a const version of operator[], given your current implementation of copy, because the argument of the copy constructor is a reference to your custom point class, not an array.
Code below:
#include <iostream>
#include<initializer_list>
#include <vector>

namespace LB
{
    template< typename T, unsigned length>
    class Point
    {
        T data[length];
    public:
        Point() {}
        Point(const std::initializer_list<T>& t)
        {
            int min = t.size() < length ? t.size() : length;
            int i = 0;
            for (auto& each : t)
            {
                if (i >= min)
                    break;
                data[i] = each;
                i++;
            }
        }

        Point(const Point<T, length>& other)
        {
            for (size_t i = 0; i < length; i++)
            {
                data[i] = other[i];
            }
        }

        T& operator[](size_t i) {
            return data[i];
        }

        const T& operator[](size_t i) const {
            return const_cast<const T&>(
                const_cast<Point&>(*this)[i]
            );
        }
    };

    using Point3f = Point<float, 3>;
}

int main() {
    std::vector<LB::Point3f> vec = { {1.0f,2.0f,3.0f},{2.0f,3.0f,1.0f},{2.0f,2.0f,2.0f} };
    std::cout << vec[1][0] << " , " << vec[1][1] << " , " << vec[1][2] << "\n";
}


text:
Q: Default Date incrementation I want to create table with time column like that:
time TIMESTAMP NOT NULL DEFAULT CURRENT TIMESTAMP

But I need to add next week date as default value. I was trying to do this:
time TIMESTAMP NOT NULL DEFAULT DATE(CURRENT TIMESTAMP)+7

But it's not working. What should I do?


text:
Q: select unique rows based on single distinct column - Django I want a unique row based on timesheet_users. But now the problem is that it is only displaying timesheet_users values in template. And  even if i add other fields in `values('...', '...',....) then select unique row does'nt work.
I'm using MySQL so i can't use distinct('timsheet_user')- It gives error

DISTINCT ON fields is not supported by this database backend

TimesheetEntry.objects.filter(
    timesheet_jobs__job_company = self.request.user.userprofile.user_company
    ).values(
        'timesheet_users'
    ).distinct()

Models.py
class TimesheetEntry(models.Model):
    timesheet_users = models.ForeignKey(User, on_delete=models.CASCADE,related_name='timesheet_users')
    timesheet_jobs = models.ForeignKey(Jobs, on_delete=models.CASCADE,related_name='timesheet_jobs')
    timesheet_clock_in_date = models.DateField()
    timesheet_clock_in_time = models.TimeField()
    timesheet_clock_on = models.DateTimeField(auto_now_add=True)
    timesheet_clock_in_by = models.ForeignKey(User, on_delete=models.CASCADE,related_name='timesheet_user_clock_in_by')

A: As @AnupYadav suggested for raw query. I came with this MySQL Query
SELECT * FROM timesheet_entry t1 INNER JOIN ( SELECT timesheet_users_id, MAX(id) AS latest_id FROM timesheet_entry GROUP BY timesheet_users_id ) t2 ON t1.timesheet_users_id = t2.timesheet_users_id AND t1.id = t2.latest_id

This is my View where i used the query
class ReportView(LoginRequiredMixin, generic.TemplateView):
    template_name = 'admin/clock/report.html'

    def get_context_data(self, **kwargs):
        context = super(ReportView, self).get_context_data(**kwargs)
        context['reports'] =  TimesheetEntry.objects.raw('SELECT * FROM timesheet_entry t1 INNER JOIN ( SELECT timesheet_users_id, MAX(id) AS latest_id FROM timesheet_entry GROUP BY timesheet_users_id ) t2 ON t1.timesheet_users_id = t2.timesheet_users_id AND t1.id = t2.latest_id')
        return context


text:
Q: Android Emulator doesn't match phone I have a layout with graphics drawn in custom Views using the Canvas drawing primitives, plus a TextView and 2 buttons.    The emulator is set to the same pixel width as the phone (400 pixels) and the 2D graphics are specified in pixel dimensions.
    (Emulator on the left, phone on the right.)
Note the the graphics match.  (the actual content of the graphics are different because the data is different )   But the TextView and buttons are radically different.  Here's the XML -
    <LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="horizontal"
  android:background="#303080"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content">
   <TextView android:id="@+id/eventSummary"
    android:layout_width="250dp"
    android:background="#202090"
    android:layout_height="fill_parent"
    android:minLines="4"
    android:singleLine="false"
    android:text="text" />
   <Button android:id="@+id/PrevButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="prevButtonHandler"
    android:text="<"
   />
   <Button android:id="@+id/NextButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="nextButtonHandler"
    android:text=">"
   />
 </LinearLayout>

... I've tried specifying the TextView width using SP's and DP's.    Why is there such a big difference and how can I get the Emulator and phone to match?  (FWIW the phone is an HTC Droid Incredible).
Thanks in advance!

A: Try setting the layout_width in dp in the LinearLayout, then using android:layout_weight="1" in the TextView.
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:background="#303080"
    android:layout_width="280dp"
    android:layout_height="wrap_content">
    <TextView android:id="@+id/eventSummary"
        android:layout_width="wrap_content"
        android:background="#202090"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:minLines="4"
        android:singleLine="false"
        android:text="text" />
    <Button android:id="@+id/PrevButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="prevButtonHandler"
        android:text="<"
    />
    <Button android:id="@+id/NextButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="nextButtonHandler"
        android:text=">"
    />
</LinearLayout>

A: I'm late, but its probably because of pixel density.  Check out this link and see if it helps: http://developer.android.com/guide/practices/screens_support.html


text:
Q: Fastify async try catch does not resolve I have simple route:
fastify.post('/subscribe', {
  schema: subscribeSchema,
  handler: async (req, reply) => {

    try {
      const events = req.body.events;
      const allEventsProcessingData = await Promise.all(events.map(async (ev) => {
        return {
          event: ev,
          feedEventsData: await getFeedEventData(ev),
          feedMainMarketsData: await getFeedEventMainMarketsData(ev),
        }
      }));

      // process HTML by events data
      // allEventsProcessingData
      const compiledHTML = '';

      return reply.send(compiledHTML);
    } catch (e) {
      console.log('e', e);
      return reply.send(HTTP_RESPONSES.FAIL);
    }
  }
});

When error happens, the response does not send, why is it? And how to send it? Tried this https://github.com/fastify/fastify/issues/1864#issuecomment-534233381, but it did not work.


text:
Q: What environment variables are available while starting the script using init.d boot process? My problem is like this (OS is Sun Solaris):

*

*At the boot time I want to start a process using a specific script. I am doing this by putting this script in /etc/init.d (and following other K and S rules).

*The program which will be called by the script is located at $HOME/xxx/yyy location.

*I am using 'su - {myuser} -c "{full path of the program}"' in order to execute the script as {myuser}.

*I don't want to hardcode the value of $HOME in the script, but I want to use the $HOME environment variable only. How can I get this $HOME environment variable in the shell script? Also what other variables will be available to me?

A: Just put
env > env.txt

in the script. After running your script the env.txt file contains all environment variables.

A: To get the home variable of any user, try this hack:
HOME=`sudo -u myuser -s "cd ~; pwd"`

A: 2) Which user's $HOME?  root's $HOME or myuser's $HOME
If it's myuser's home, just use $HOME in the child script, and don't use it in the init.d script.  This will be set for you by the shell process you are starting.  When you do su - {myuser} you are instructing su to run myuser's login shell (as defined in /etc/passwd).  The login shell will set the default environment variables based on what shell it is.  See your shell's documentation for details. On Solaris this is probably ksh or bourne shell.
3) Do su - myuser -c /usr/bin/env.  That will print out the environment variables that will be set in the child script.


text:
Q: I can't load many images with Picasso (with target) I have about 200 images in my web storage. When I try to download them with Picasso, I get only about 30 of them. I checked many cases and every time I get the different quantity of images and images are different too.
LogCat said that getPicassoImage() always called, but onBitmapLoaded() called only about 30 times and never called onBitmapFailed().
In LogCat I also saw (After first click - first warning and I can't get at least 1 image. This always on the first click):

W/Settings: Setting airplane_mode_on has moved from android.provider.Settings.A system to android.provider.Settings.Global, returning read-only value.
W/SQLiteConnectionPool: A SQLiteConnection object for database 'path' was leaked!  Please fix your application to end transactions in progress properly and to close the database when it is no longer needed.

void getPicassoImage(final String imageName){
    Log.d("myLogs", "try to get "+ imageName);
    Target target = new Target() {
        @Override
        public void onPrepareLoad(Drawable placeHolderDrawable) {
        }

        @Override
        public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
            /*Log.d("myLogs", "onBitmapLoaded");*/

            try {
                File file = new File(IMAGE_PATH + imageName);

                FileOutputStream outputStream = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);

                outputStream.flush();
                outputStream.close();

                Log.d("myLogs", imageName + " image saved");
            } catch (Exception e) {
                Log.d("myLogs", "Picasso error");
            }

        }

        @Override
        public void onBitmapFailed(Drawable errorDrawable) {
            Log.d("myLogs", "onBitmapFailed");
        }
    };

    /*Log.d("myLogs","Load from " + storageUrl + imageName);*/
    Picasso.with(getApplicationContext()).load(storageUrl+imageName).into(target);

}


text:
Q: How to accomplish this layout in HTML/CSS? Why are the floating elements are not properly arranged? My images have some white space and I have no idea from where it comes from.
The desired look:

The code:

.inner-wrapper { float: left; width: 100%; color: #000; }

.feature-1 { float: right; margin: 0 auto; width: 50%; height: auto; }
.aside-image-1 { float: left; margin: 0 auto; height: auto; width: 50%; }

.feature-2 { float: left; margin: 0 auto; width: 50%; height: auto; }
.aside-image-2 { float: right; margin: 0 auto; height: auto; width: 50%; }

.feature-3 { float: right; margin: 0 auto; width: 50%; height: auto; }
.aside-image-3 { float: left; margin: 0 auto; height: auto; width: 50%; clear: both; }

In-Store Interactive Tablet

Shoppers can use Sellr's Help Me Choose feature to

In-Store Interactive Tablet

Shoppers can use Sellr's Help Me Choose feature to

In-Store Interactive Tablet

Shoppers can use Sellr's Help Me Choose feature to

A: Check this...
Make the image's width 100% and Text-align center

.inner-wrapper {
  float: left;
  width: 100%;
  color: #000;
}
.feature-1 {
  float: right;
  margin: 0 auto;
  width: 50%;
  height: auto;
  text-align: center;
}
.aside-image-1 {
  float: left;
  margin: 0 auto;
  height: auto;
  width: 50%;
}
.feature-2 {
  float: left;
  margin: 0 auto;
  width: 50%;
  text-align: center;
  height: auto;
}
.aside-image-2 {
  float: right;
  margin: 0 auto;
  height: auto;
  width: 50%;
}
.feature-3 {
  float: right;
  margin: 0 auto;
  width: 50%;
  height: auto;
  text-align: center;
}
.aside-image-3 {
  float: left;
  margin: 0 auto;
  height: auto;
  width: 50%;
  clear: both;
}
.aside-image-1 img {
  width: 100%;
  float: left;
}
.aside-image-2 img {
  width: 100%;
  float: left;
}
.aside-image-3 img {
  width: 100%;
  float: left;
}

In-Store Interactive Tablet

Shoppers can use Sellr's Help Me Choose feature to

In-Store Interactive Tablet

Shoppers can use Sellr's Help Me Choose feature to

In-Store Interactive Tablet

Shoppers can use Sellr's Help Me Choose feature to

A: add some property to your image tag
img{
  width:100%;
  }

.inner-wrapper { float: left; width: 100%; color: #000; }

.feature-1 { float: right; margin: 0 auto; width: 50%; height: auto; }
.aside-image-1 { float: left; margin: 0 auto; height: auto; width: 50%; }

.feature-2 { float: left; margin: 0 auto; width: 50%; height: auto; }
.aside-image-2 { float: right; margin: 0 auto; height: auto; width: 50%; }

.feature-3 { float: right; margin: 0 auto; width: 50%; height: auto; }
.aside-image-3 { float: left; margin: 0 auto; height: auto; width: 50%; clear: both; }
img{
  width:100%;
  }

In-Store Interactive Tablet

Shoppers can use Sellr's Help Me Choose feature to

In-Store Interactive Tablet

Shoppers can use Sellr's Help Me Choose feature to

In-Store Interactive Tablet

Shoppers can use Sellr's Help Me Choose feature to

A: body{
margin:0px;
padding:0px;
}

and images width should be 100%;

.inner-wrapper { float: left; width: 100%; color: #000; }

.feature-1 { float: right; margin: 0 auto; width: 50%; height: auto; }
.aside-image-1 { float: left; margin: 0 auto; height: auto; width: 50%; }

.feature-2 { float: left; margin: 0 auto; width: 50%; height: auto; }
.aside-image-2 { float: right; margin: 0 auto; height: auto; width: 50%; }

.feature-3 { float: right; margin: 0 auto; width: 50%; height: auto; }
.aside-image-3 { float: left; margin: 0 auto; height: auto; width: 50%; clear: both; }

In-Store Interactive Tablet

Shoppers can use Sellr's Help Me Choose feature to

In-Store Interactive Tablet

Shoppers can use Sellr's Help Me Choose feature to

In-Store Interactive Tablet

Shoppers can use Sellr's Help Me Choose feature to


text:
Q: Column Not Found Access Database I am creating an address book application, and I am working on the search function. Whenever I search I get a "Column not found" exception. Here is my code:
else if(actionCommand.contentEquals("search"))
        {
        String searchInput = searchBar.getText();
        //String[] searchSplit = searchInput.split("\\s");
        //String searchFirst = searchSplit[0];
        //String searchLast = searchSplit[1];
        personID = null;
        try
        {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            Connection connection = DriverManager.getConnection("jdbc:odbc:address_book");
            Statement statement = connection.createStatement();

            ResultSet resultSet = statement.executeQuery("SELECT (personID) FROM names WHERE (lastName) LIKE ('"+searchInput+"')");
            if(resultSet.next())
                personID = resultSet.getString("personID");

            ResultSet firstQuery = statement.executeQuery("SELECT (firstName) FROM names WHERE (personID) LIKE ('"+personID+"')");
            if(firstQuery.next())
                firstNameOutput = firstQuery.getString("firstName");

            ResultSet lastQuery = statement.executeQuery("SELECT (lastName) FROM names WHERE (personID) LIKE ('"+personID+"')");
            if(lastQuery.next())
                lastNameOutput = lastQuery.getString("lastName");

            ResultSet address1Query = statement.executeQuery("SELECT (address1) FROM addresses WHERE (personID) LIKE ('"+personID+"')");
            if(address1Query.next())
                address1Output = address1Query.getString("address1");

            ResultSet address2Query = statement.executeQuery("SELECT (address2) FROM addresses WHERE (personID) LIKE ('"+personID+"')");
            if(address2Query.next())
                address2Output = address2Query.getString("address1");

            ResultSet cityQuery = statement.executeQuery("SELECT (city) FROM addresses WHERE (personID) LIKE ('"+personID+"')");
            if(cityQuery.next())
                cityOutput = cityQuery.getString("city");

            ResultSet stateQuery = statement.executeQuery("SELECT (state) FROM addresses WHERE (personID) LIKE ('"+personID+"')");
            if(stateQuery.next())
                stateOutput = stateQuery.getString("state");

            ResultSet zipcodeQuery = statement.executeQuery("SELECT (zipcode) FROM addresses WHERE (personID) LIKE ('"+personID+"')");
            if(zipcodeQuery.next())
                zipcodeOutput = zipcodeQuery.getString("zipcode");

            ResultSet phoneQuery = statement.executeQuery("SELECT (phoneNumber) FROM phoneNumbers WHERE (personID) LIKE ('"+personID+"')");
            if(phoneQuery.next())
                phoneOutput = phoneQuery.getString("phoneNumber");

            ResultSet emailQuery = statement.executeQuery("SELECT (emailAddress) FROM emailAddresses WHERE (personID) LIKE ('"+personID+"')");
            if(emailQuery.next())
                emailOutput = emailQuery.getString("emailAddress");

            newFunctionWindow();
            personIDBar.setText(personID);
            firstNameBar.setText(firstNameOutput);
            lastNameBar.setText(lastNameOutput);
            address1Bar.setText(address1Output);
            address2Bar.setText(address2Output);
            cityBar.setText(cityOutput);
            stateBar.setText(stateOutput);
            zipcodeBar.setText(zipcodeOutput);
            phoneBar.setText(phoneOutput);
            emailBar.setText(emailOutput);
            statement.close();
            connection.close();
        }

        catch (SQLException sqlException)
        {
            JOptionPane.showMessageDialog(null, sqlException.getMessage(), "Database Error", JOptionPane.ERROR_MESSAGE);
            System.exit(1);
        }

        catch (ClassNotFoundException classNotFound)
        {
            JOptionPane.showMessageDialog(null, classNotFound.getMessage(), "Driver Not Found", JOptionPane.ERROR_MESSAGE);
            System.exit(1);
        }

I triple checked all of the column names and there are no typos. I believe all my SQL statements are correct as well, so I am not quite sure what the issue is! Thank you for your help.

A:         ResultSet address1Query = statement.executeQuery("SELECT (address1) FROM addresses WHERE (personID) LIKE ('"+personID+"')");
        if(address1Query.next())
            address1Output = address1Query.getString("address1");

        ResultSet address2Query = statement.executeQuery("SELECT (address2) FROM addresses WHERE (personID) LIKE ('"+personID+"')");
        if(address2Query.next())
            address2Output = address2Query.getString("address1");

Whoops - address1 from the address2 field? That won't work. (last line quoted)