问:
Convert HTML to a string
I have a string writer function which captures a HTMl and returns as a string. for example

"\r\n\r\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\r\n\r\n\r\n\r\n    <link rel=\"Stylesheet\" href=\"../../Content/style.css\" type=\"text/css\" />\r\n    <title>Cover Page</title>\r\n    \r\n\r\n\r\n
\r\n        Ssotest Ssotest, \r\n
 \r\n\r\n\r\n"

when I pass this to a PDF generating tool it throws an error.But when I copy the output of the String writer ( the same HTML string above") from the Locals window in VS2010 and hardcode it like

```<code> string test ="\r\n\r\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\r\n\r\n<html xmlns=\"http://www.w3.org/1999/xhtml\" >\r\n<head>\r\n    <link rel=\"Stylesheet\" href=\"../../Content/style.css\" type=\"text/css\" />\r\n    <title>Cover Page</title>\r\n    <style type=\"text/css\">\r\n        html, body\r\n        {\r\n\t        font-family: Arial, Helvetica, sans-serif;\r\n\t        font-size: 13pt;\r\n\t        padding: 0px;\r\n\t        margin: 0px;\r\n\t        background-color: #FFFFFF;\r\n\t        color: black;\r\n\t        width: 680px;\r\n        }\r\n    </style>\r\n</head>\r\n<body>\r\n    <div>\r\n        Ssotest Ssotest, \r\n    </div> \r\n</body>\r\n</html>\r\n"
</code>```

and pass to the tool it works fine. In the both cases the string is same. I wonder what makes the difference? Is that something gets converted when I copy the text and hardcode?? Any suggestions??

Just a update..
I used this code to format

```<code> public class ReplaceString
        {
            static readonly IDictionary<string, string> m_replaceDict
                = new Dictionary<string, string>();

            const string ms_regexEscapes = @"[\a\b\f\n\r\t\v\\""]";

            public static string StringLiteral(string i_string)
            {
                return Regex.Replace(i_string, ms_regexEscapes, match);
            }

            public static string CharLiteral(char c)
            {
                return c == '\'' ? @"'\''" : string.Format("'{0}'", c);
            }

            private static string match(Match m)
            {
                string match = m.ToString();
                if (m_replaceDict.ContainsKey(match))
                {
                    return m_replaceDict[match];
                }

                throw new NotSupportedException();
            }

            static ReplaceString()
            {
                m_replaceDict.Add("\a", @"\a");
                m_replaceDict.Add("\b", @"\b");
                m_replaceDict.Add("\f", @"\f");
                m_replaceDict.Add("\n", @"\n");
                m_replaceDict.Add("\r", @"\r");
                m_replaceDict.Add("\t", @"\t");
                m_replaceDict.Add("\v", @"\v");

                m_replaceDict.Add("\\", @"\\");
                m_replaceDict.Add("\0", @"\0");

                //The SO parser gets fooled by the verbatim version
                //of the string to replace - @"\"""
                //so use the 'regular' version
                m_replaceDict.Add("\"", "\\\"");
            }

            static void Main(string[] args)
            {

                string s = "here's a \"\n\tstring\" to test";
                Console.WriteLine(ReplaceString.StringLiteral(s));
                Console.WriteLine(ReplaceString.CharLiteral('c'));
                Console.WriteLine(ReplaceString.CharLiteral('\''));

            }
        }
</code>```

but the string gets returned like

```<code>\\r\\n\\r\\n<!DOCTYPE html PUBLIC \\\"-//W3C//DTD XHTML 1.0 Transitional//EN\\\" \\\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\\\">\\r\\n\\r\\n<html xmlns=\\\"http://www.w3.org/1999/xhtml\\\" >\\r\\n<head>\\r\\n    <link rel=\\\"Stylesheet\\\...."
</code>```

which dosent make sense..
the code of PDF generator I am using

```<code>string test="\r\n\r\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\r\n\r\n<html xmlns=\"http://www.w3.org/1999/xhtml\" >\r\n<head>\r\n <link rel=\"Stylesheet\" href=\"../../Content/style.css\" type=\"text/css\" />\r\n <title>Cover Page</title>\r\n <style type=\"text/css\">\r\n html, body\r\n {\r\n\t font-family: Arial, Helvetica, sans-serif;\r\n\t font-size: 13pt;\r\n\t padding: 0px;\r\n\t margin: 0px;\r\n\t background-color: #FFFFFF;\r\n\t color: black;\r\n\t width: 680px;\r\n }\r\n </style>\r\n</head>\r\n<body>\r\n <div>\r\n Ssotest Ssotest, \r\n </div> \r\n</body>\r\n</html>\r\n"

           FileStreamResponseContext response = new FileStreamResponseContext();
 Document doc = new Document();
            doc.DocumentInformation.CreationDate = DateTime.Now;
            doc.DocumentInformation.Title = "Test Plan";
            doc.DocumentInformation.Subject = "Test Plan";
            doc.CompressionLevel = CompressionLevel.NormalCompression;
            doc.Margins = new Margins(0, 0, 0, 0);
            doc.Security.CanPrint = true;
            doc.ViewerPreferences.HideToolbar = false;
            doc.ViewerPreferences.FitWindow = false;

string baseUrl = String.Format("http://localhost{0}/", Request.Url.Port == 80?"":":" + Request.Url.Port.ToString());

PdfPage docTestPlan = doc.AddPage(PageSize.Letter, new Margins(0, 0, 0, 0), PageOrientation.Portrait);
// passing the string test returned from the string writer

   HtmlToPdfElement htmlToPdf = new HtmlToPdfElement(test, baseUrl);
            htmlToPdf.FitWidth = false;
            docTestPlan.AddElement(htmlToPdf);

            /******************************************
             * put doc in a memory stream for return */
            response.FileDataStream = new MemoryStream();
            doc.Save(response.FileDataStream);
            doc.Close();
            response.FileDataStream.Position = 0;

            return new FileStreamResult(response.FileDataStream, "application/pdf");
</code>```

答:
protected void btnExport_Click(object sender, EventArgs e)
    {
        HtmlForm form = new HtmlForm();
       // form.Controls.Add(GridView1);
        StringWriter sw = new StringWriter();
        HtmlTextWriter hTextWriter = new HtmlTextWriter(sw);
        //form.Controls[0].RenderControl(hTextWriter);
        string htmlDisplayText = @"

Dear bishnu2

 your address pdp    is

An early version of the patterns was workshopped at PLoP After several internal workshops and updates, a later version was

workshopped at PLoP  The patterns are now mature enough that I teach a class based on the patterns at AG Communication

Systems.
                    Copyright © 1999 AG Communication Systems Corporation

";
       // string htmlDisplayText = sw.ToString();
        Document Doc = new Document();

```<code>    //PdfWriter.GetInstance
    //(Doc, new FileStream(Request.PhysicalApplicationPath
    //+ "\\AmitJain.pdf", FileMode.Create));

    PdfWriter.GetInstance(Doc, new FileStream(Environment.GetFolderPath
    (Environment.SpecialFolder.Desktop)+ "\\AmitJain.pdf", FileMode.Create));
    Doc.Open();

    System.Xml.XmlTextReader xmlReader =
    new System.Xml.XmlTextReader(new StringReader(htmlDisplayText));
    HtmlParser.Parse(Doc, xmlReader);

    Doc.Close();
    string Path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)+ "\\AmitJain.pdf";

    ShowPdf(Path);

}

private void ShowPdf(string strS)
{
    Response.ClearContent();
    Response.ClearHeaders();
    Response.ContentType = "application/pdf";
    Response.AddHeader("Content-Disposition","attachment; filename=" + strS);
    Response.TransmitFile(strS);
    Response.End();
    //Response.WriteFile(strS);
    Response.Flush();
    Response.Clear();

}
</code>```

Title: Convert HTML to a string

Body:
I have a string writer function which captures a HTMl and returns as a string. for example

"\r\n\r\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\r\n\r\n\r\n\r\n    <link rel=\"Stylesheet\" href=\"../../Content/style.css\" type=\"text/css\" />\r\n    <title>Cover Page</title>\r\n    \r\n\r\n\r\n
\r\n        Ssotest Ssotest, \r\n
 \r\n\r\n\r\n"

when I pass this to a PDF generating tool it throws an error.But when I copy the output of the String writer ( the same HTML string above") from the Locals window in VS2010 and hardcode it like

 string test ="\r\n\r\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\r\n\r\n\r\n\r\n    <link rel=\"Stylesheet\" href=\"../../Content/style.css\" type=\"text/css\" />\r\n    <title>Cover Page</title>\r\n    \r\n\r\n\r\n
\r\n        Ssotest Ssotest, \r\n
 \r\n\r\n\r\n"

and pass to the tool it works fine. In the both cases the string is same. I wonder what makes the difference? Is that something gets converted when I copy the text and hardcode?? Any suggestions??

Just a update..
I used this code to format

 public class ReplaceString
        {
            static readonly IDictionary<string, string> m_replaceDict
                = new Dictionary<string, string>();

            const string ms_regexEscapes = @"[\a\b\f\n\r\t\v\\""]";

            public static string StringLiteral(string i_string)
            {
                return Regex.Replace(i_string, ms_regexEscapes, match);
            }

            public static string CharLiteral(char c)
            {
                return c == '\'' ? @"'\''" : string.Format("'{0}'", c);
            }

            private static string match(Match m)
            {
                string match = m.ToString();
                if (m_replaceDict.ContainsKey(match))
                {
                    return m_replaceDict[match];
                }

                throw new NotSupportedException();
            }

            static ReplaceString()
            {
                m_replaceDict.Add("\a", @"\a");
                m_replaceDict.Add("\b", @"\b");
                m_replaceDict.Add("\f", @"\f");
                m_replaceDict.Add("\n", @"\n");
                m_replaceDict.Add("\r", @"\r");
                m_replaceDict.Add("\t", @"\t");
                m_replaceDict.Add("\v", @"\v");

                m_replaceDict.Add("\\", @"\\");
                m_replaceDict.Add("\0", @"\0");

                //The SO parser gets fooled by the verbatim version
                //of the string to replace - @"\"""
                //so use the 'regular' version
                m_replaceDict.Add("\"", "\\\"");
            }

            static void Main(string[] args)
            {

                string s = "here's a \"\n\tstring\" to test";
                Console.WriteLine(ReplaceString.StringLiteral(s));
                Console.WriteLine(ReplaceString.CharLiteral('c'));
                Console.WriteLine(ReplaceString.CharLiteral('\''));

            }
        }

but the string gets returned like

\\r\\n\\r\\n<!DOCTYPE html PUBLIC \\\"-//W3C//DTD XHTML 1.0 Transitional//EN\\\" \\\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\\\">\\r\\n\\r\\n\\r\\n\\r\\n    <link rel=\\\"Stylesheet\\\...."

which dosent make sense..
the code of PDF generator I am using

string test="\r\n\r\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\r\n\r\n\r\n\r\n <link rel=\"Stylesheet\" href=\"../../Content/style.css\" type=\"text/css\" />\r\n <title>Cover Page</title>\r\n \r\n\r\n\r\n
\r\n Ssotest Ssotest, \r\n
 \r\n\r\n\r\n"

           FileStreamResponseContext response = new FileStreamResponseContext();
 Document doc = new Document();
            doc.DocumentInformation.CreationDate = DateTime.Now;
            doc.DocumentInformation.Title = "Test Plan";
            doc.DocumentInformation.Subject = "Test Plan";
            doc.CompressionLevel = CompressionLevel.NormalCompression;
            doc.Margins = new Margins(0, 0, 0, 0);
            doc.Security.CanPrint = true;
            doc.ViewerPreferences.HideToolbar = false;
            doc.ViewerPreferences.FitWindow = false;

string baseUrl = String.Format("http://localhost{0}/", Request.Url.Port == 80?"":":" + Request.Url.Port.ToString());

PdfPage docTestPlan = doc.AddPage(PageSize.Letter, new Margins(0, 0, 0, 0), PageOrientation.Portrait);
// passing the string test returned from the string writer

   HtmlToPdfElement htmlToPdf = new HtmlToPdfElement(test, baseUrl);
            htmlToPdf.FitWidth = false;
            docTestPlan.AddElement(htmlToPdf);

            /******************************************
             * put doc in a memory stream for return */
            response.FileDataStream = new MemoryStream();
            doc.Save(response.FileDataStream);
            doc.Close();
            response.FileDataStream.Position = 0;

            return new FileStreamResult(response.FileDataStream, "application/pdf");

Body:
protected void btnExport_Click(object sender, EventArgs e)
    {
        HtmlForm form = new HtmlForm();
       // form.Controls.Add(GridView1);
        StringWriter sw = new StringWriter();
        HtmlTextWriter hTextWriter = new HtmlTextWriter(sw);
        //form.Controls[0].RenderControl(hTextWriter);
        string htmlDisplayText = @"

<html>
<body bgcolor="red">
<h4>Dear bishnu2</h4>

 your address pdp    is

An early version of the patterns was workshopped at PLoP After several internal workshops and updates, a later version was

workshopped at PLoP  The patterns are now mature enough that I teach a class based on the patterns at AG Communication

Systems.
                    Copyright © 1999 AG Communication Systems Corporation

</body></html>
";
       // string htmlDisplayText = sw.ToString();
        Document Doc = new Document();

    //PdfWriter.GetInstance
    //(Doc, new FileStream(Request.PhysicalApplicationPath
    //+ "\\AmitJain.pdf", FileMode.Create));

    PdfWriter.GetInstance(Doc, new FileStream(Environment.GetFolderPath
    (Environment.SpecialFolder.Desktop)+ "\\AmitJain.pdf", FileMode.Create));
    Doc.Open();

    System.Xml.XmlTextReader xmlReader =
    new System.Xml.XmlTextReader(new StringReader(htmlDisplayText));
    HtmlParser.Parse(Doc, xmlReader);

    Doc.Close();
    string Path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)+ "\\AmitJain.pdf";

    ShowPdf(Path);

}

private void ShowPdf(string strS)
{
    Response.ClearContent();
    Response.ClearHeaders();
    Response.ContentType = "application/pdf";
    Response.AddHeader("Content-Disposition","attachment; filename=" + strS);
    Response.TransmitFile(strS);
    Response.End();
    //Response.WriteFile(strS);
    Response.Flush();
    Response.Clear();

}


来源: stackexchange

问:
Pass inner template class as template argument in C++
I am trying to pass an inner template class (of a regular class) to another class that accepts templates as arguments.

The class that accepts templates is:

```<code>template <typename... T> struct TypeList {
  template <template <typename...> typename P> using Apply = P<T...>;
};
</code>```

So when I have something like using List = TypeList<int, float, double>; I can do

```<code>static_assert(std::is_same<List::template Apply<std::tuple>,
                           std::tuple<int, float, double>>::value);
</code>```

But if I change std::tuple so an inner template class, it stops working. I.e.,

```<code>struct Outer {
  template <typename... P> struct Inner {};
};

static_assert(std::is_same<List::template Apply<typename Outer::Inner>,
                           Outer::Inner<int, float, double>>::value);
</code>```

doesn't work.

My compiler complains about

error: invalid use of template-name ‘Outer::Inner’ without an argument list

It works if I "flatten" the inner template class with template <typename... P> using Flat = Outer::Inner
;.

My question is, is there a way to make the inner template class work, without aliasing it and flattening it? Am I missing the typename or template keyword somewhere?

Complete example is:

```<code>#include <tuple>
#include <type_traits>

template <typename... T> struct TypeList {
  template <template <typename...> typename P> using Apply = P<T...>;
};

struct Outer {
  template <typename... P> struct Inner {};
};

template <typename... P> using Flat = Outer::Inner<P...>;

int main() {
  using List = TypeList<int, float, double>;
  static_assert(std::is_same<List::template Apply<std::tuple>,
                             std::tuple<int, float, double>>::value);
  static_assert(std::is_same<List::template Apply<Flat>,
                             Outer::Inner<int, float, double>>::value);
  static_assert(std::is_same<List::template Apply<typename Outer::Inner>,
                             Outer::Inner<int, float, double>>::value);
}
</code>```

答:
typename Outer::Inner is wrong as Inner is not a type but a template.

You can even remove all typename/template here as there is no dependent type issue.

```<code>static_assert(std::is_same<List::Apply<Outer::Inner>,
                           Outer::Inner<int, float, double>>::value);
</code>```

In dependent context, it would be

```<code>// template <typename OuterT> /*..*/
static_assert(std::is_same<List::Apply<OuterT::template Inner>,
                           typename OuterT::template Inner<int, float, double>>::value);
</code>```

Demo

ContentLicense: CC BY-SA 4.0

Body:
I am trying to pass an inner template class (of a regular class) to another class that accepts templates as arguments.

The class that accepts templates is:

template <typename... T> struct TypeList {
  template <template <typename...> typename P> using Apply = P<T...>;
};

So when I have something like using List = TypeList<int, float, double>; I can do

static_assert(std::is_same<List::template Apply<std::tuple>,
                           std::tuple<int, float, double>>::value);

But if I change std::tuple so an inner template class, it stops working. I.e.,

struct Outer {
  template <typename... P> struct Inner {};
};

static_assert(std::is_same<List::template Apply<typename Outer::Inner>,
                           Outer::Inner<int, float, double>>::value);

doesn't work.

My compiler complains about

error: invalid use of template-name ‘Outer::Inner’ without an argument list

It works if I "flatten" the inner template class with template <typename... P> using Flat = Outer::Inner
;.

My question is, is there a way to make the inner template class work, without aliasing it and flattening it? Am I missing the typename or template keyword somewhere?

Complete example is:

#include <tuple>
#include <type_traits>

template <typename... T> struct TypeList {
  template <template <typename...> typename P> using Apply = P<T...>;
};

struct Outer {
  template <typename... P> struct Inner {};
};

template <typename... P> using Flat = Outer::Inner
;

int main() {
  using List = TypeList<int, float, double>;
  static_assert(std::is_same<List::template Apply<std::tuple>,
                             std::tuple<int, float, double>>::value);
  static_assert(std::is_same<List::template Apply<Flat>,
                             Outer::Inner<int, float, double>>::value);
  static_assert(std::is_same<List::template Apply<typename Outer::Inner>,
                             Outer::Inner<int, float, double>>::value);
}

Body:
typename Outer::Inner is wrong as Inner is not a type but a template.

You can even remove all typename/template here as there is no dependent type issue.

static_assert(std::is_same<List::Apply<Outer::Inner>,
                           Outer::Inner<int, float, double>>::value);

In dependent context, it would be

// template <typename OuterT> /*..*/
static_assert(std::is_same<List::Apply<OuterT::template Inner>,
                           typename OuterT::template Inner<int, float, double>>::value);

Demo


问:
no matching function for call to 'TiXmlElement::TiXmlElement(std::_cxx11::string&)
```<code>    for (int i = g, x=0; i < counter - 1 && x < 99; i++,x++){
std::string point = std::to_string(i);
std::string pointx = std::to_string(point_vec[i].x);
std::string pointy= std::to_string(point_vec[i].y);

TiXmlElement* P = new TiXmlElement( point );
TiXmlText* X = new TiXmlText(pointx);
doc.LinkEndChild(X);
TiXmlText* Y = new TiXmlText(pointy);
doc.LinkEndChild(Y);
doc.LinkEndChild(P);
}
</code>```

Above is my example code which I am trying to work on right now, my issue is that it tells me the following:

"error: no matching function for call to 'TiXmlElement::TiXmlElement(std::_cxx11::string&)"  this is using wxwidgets on c++, the idea behind using tinyxml is to be able to store the arrays and reuse them after.

Solvved this : I had to go into tinyxml.h and add this at the top : #define TIXML_USE_STL

答:
There are two constructors for string/char type as below:

```<code>TiXmlElement::TiXmlElement (const char * _value)
</code>```

or

```<code>#ifdef TIXML_USE_STL
TiXmlElement::TiXmlElement( const std::string& _value )
</code>```

So you have to define TIXML_USE_STL if you want to use std::string else use const char *

Refer the tinyxml.cpp

Body:
    for (int i = g, x=0; i < counter - 1 && x < 99; i++,x++){
std::string point = std::to_string(i);
std::string pointx = std::to_string(point_vec[i].x);
std::string pointy= std::to_string(point_vec[i].y);

TiXmlElement* P = new TiXmlElement( point );
TiXmlText* X = new TiXmlText(pointx);
doc.LinkEndChild(X);
TiXmlText* Y = new TiXmlText(pointy);
doc.LinkEndChild(Y);
doc.LinkEndChild(P);
}

Above is my example code which I am trying to work on right now, my issue is that it tells me the following:

"error: no matching function for call to 'TiXmlElement::TiXmlElement(std::_cxx11::string&)"  this is using wxwidgets on c++, the idea behind using tinyxml is to be able to store the arrays and reuse them after.

Solvved this : I had to go into tinyxml.h and add this at the top : #define TIXML_USE_STL

Body:
There are two constructors for string/char type as below:

TiXmlElement::TiXmlElement (const char * _value)

or

#ifdef TIXML_USE_STL
TiXmlElement::TiXmlElement( const std::string& _value )

So you have to define TIXML_USE_STL if you want to use std::string else use const char *

Refer the tinyxml.cpp


问:
Zend Framework module structure routing
I have the following structure of my system:

```<code>application/
   configs/
     application.ini
     router.php
   layouts/
   modules/
      default/
        controllers/
        forms/
        models/
        views/
        Bootstrap.php
      test/
        controllers/
        forms/
        models/
        views/
        Bootstrap.php
    Bootstrap.php
</code>```

routes.php file:

```<code>$useDefaultRoutes = false;

$routes['index'] = new Zend_Controller_Router_Route(
                       '',
                       array('controller' => 'index',
                       'action' => 'index',
                       'module' => 'default'));
</code>```

Main Bootstrap.php file

```<code>class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{

    public static function setRoutes(){

        $frontController = Zend_Controller_Front::getInstance();
        $router = $frontController->getRouter();

        $routes = array();

        if(file_exists('../application/configs/routes.php'))
        {

            require_once "configs/routes.php";

            foreach($routes as $routeName => $routeValue){
                $router->addRoute($routeName, $routeValue);
            }

            if($useDefaultRoutes == false)
            {
                $router->removeDefaultRoutes();
            }

        }

    }

    protected function _initFrontModules() {
        $this->bootstrap('frontController');
        $front = $this->getResource('frontController');
        $this->setRoutes();
    }

}
</code>```

Problem

When I type in browser http://address, then default module launches IndexController and
everything seems to be ok. But if I type http://address/test, then I get error - page not found. If I remove routes.php file, then it works. So what is the problem with my routing ?

Your help would be appreciated.

答:
Try this new way of routing...

Include this in your bootstrap.php

```<code>protected function _initAutoloadModules()
{
    $autoloader = new Zend_Application_Module_Autoloader(
        array(
            'namespace' => '',
            'basePath'  => APPLICATION_PATH . '/modules/default'
        ),
        array(
            'namespace' => 'Admin',
            'basePath'  => APPLICATION_PATH . '/modules/test'
        )
      );
    return $autoloader;
}
</code>```

This is your application.ini

```<code>phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
resources.frontController.params.displayExceptions = 1
includePaths.library = APPLICATION_PATH "/../library"
appnamespace = "Default"
bootstrap.path = APPLICATION_PATH "/Bootstrap.php"
bootstrap.class = "Bootstrap"
resources.frontController.defaultModule = "default"
resources.frontController.defaultController = "index"
resources.frontController.defaultAction = "index"
resources.frontController.moduleDirectory = APPLICATION_PATH "/modules"
resources.layout.layoutPath = APPLICATION_PATH "/layouts/scripts"
resources.layout.layout = "layout"
resources.modules = ""
resources.view[] =
resources.session.remember_me_seconds = 864000
resources.session.use_only_cookies = on
includePaths.models = APPLICATION_PATH "/models/"
resources.layout.layoutPath = APPLICATION_PATH "/layouts/scripts/"
</code>```

and in module/default/bootstrap.php add below given variable

```<code>protected $_moduleName="default";
</code>```

and in module/test/bootstrap.php add below given variable

```<code>protected $_moduleName="test";
</code>```

ContentLicense: CC BY-SA 3.0

Title: Zend Framework module structure routing

Body:
I have the following structure of my system:

application/
   configs/
     application.ini
     router.php
   layouts/
   modules/
      default/
        controllers/
        forms/
        models/
        views/
        Bootstrap.php
      test/
        controllers/
        forms/
        models/
        views/
        Bootstrap.php
    Bootstrap.php

routes.php file:

$useDefaultRoutes = false;

$routes['index'] = new Zend_Controller_Router_Route(
                       '',
                       array('controller' => 'index',
                       'action' => 'index',
                       'module' => 'default'));

Main Bootstrap.php file

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{

    public static function setRoutes(){

        $frontController = Zend_Controller_Front::getInstance();
        $router = $frontController->getRouter();

        $routes = array();

        if(file_exists('../application/configs/routes.php'))
        {

            require_once "configs/routes.php";

            foreach($routes as $routeName => $routeValue){
                $router->addRoute($routeName, $routeValue);
            }

            if($useDefaultRoutes == false)
            {
                $router->removeDefaultRoutes();
            }

        }

    }

    protected function _initFrontModules() {
        $this->bootstrap('frontController');
        $front = $this->getResource('frontController');
        $this->setRoutes();
    }

}

Problem

When I type in browser http://address, then default module launches IndexController and
everything seems to be ok. But if I type http://address/test, then I get error - page not found. If I remove routes.php file, then it works. So what is the problem with my routing ?

Your help would be appreciated.

Body:
Try this new way of routing...

Include this in your bootstrap.php

protected function _initAutoloadModules()
{
    $autoloader = new Zend_Application_Module_Autoloader(
        array(
            'namespace' => '',
            'basePath'  => APPLICATION_PATH . '/modules/default'
        ),
        array(
            'namespace' => 'Admin',
            'basePath'  => APPLICATION_PATH . '/modules/test'
        )
      );
    return $autoloader;
}

This is your application.ini

phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
resources.frontController.params.displayExceptions = 1
includePaths.library = APPLICATION_PATH "/../library"
appnamespace = "Default"
bootstrap.path = APPLICATION_PATH "/Bootstrap.php"
bootstrap.class = "Bootstrap"
resources.frontController.defaultModule = "default"
resources.frontController.defaultController = "index"
resources.frontController.defaultAction = "index"
resources.frontController.moduleDirectory = APPLICATION_PATH "/modules"
resources.layout.layoutPath = APPLICATION_PATH "/layouts/scripts"
resources.layout.layout = "layout"
resources.modules = ""
resources.view[] =
resources.session.remember_me_seconds = 864000
resources.session.use_only_cookies = on
includePaths.models = APPLICATION_PATH "/models/"
resources.layout.layoutPath = APPLICATION_PATH "/layouts/scripts/"

and in module/default/bootstrap.php add below given variable

protected $_moduleName="default";

and in module/test/bootstrap.php add below given variable

protected $_moduleName="test";


问:
Handling big JSONs in Azure Data Factory
I'm trying to use ADF for the following scenario:

a JSON is uploaded to a Azure Storage Blob, containing an array of similar objects

this JSON is read by ADF with a Lookup Activity and uploaded via a Web Activity to an external sink

I cannot use the Copy Activity, because I need to create a JSON payload for the Web Activity, so I have to lookup the array and paste it like this (payload of the Web Activity):

```<code>{
   "some field": "value",
   "some more fields": "value",
   ...
   "items": @{activity('GetJsonLookupActivity').output.value}
}
</code>```

The Lookup activity has a known limitation of an upper limit of 5000 rows at a time. If the JSON is larger, only 5000 top rows will be read and all else will be ignored.

I know this, so I have a system that chops payloads into chunks of 5000 rows before uploading to storage. But I'm not the only user, so there's a valid concern that someone else will try uploading bigger files and the pipeline will silently pass with a partial upload, while the user would obviously expect all rows to be uploaded.

I've come up with two concepts for a workaround, but I don't see how to implement either:

Is there any way for me to check if the JSON file is too large and fail the pipeline if so? The Lookup Activity doesn't seem to allow row counting, and the Get Metadata Activity only returns the size in bytes.

Alternatively, the MSDN docs propose a workaround of copying data in a foreach loop. But I cannot figure out how I'd use Lookup to first get rows 1-5000 and then 5001-10000 etc. from a JSON. It's easy enough with SQL using OFFSET N FETCH NEXT 5000 ROWS ONLY, but how to do it with a JSON?

答:
You can't set any index range(1-5,000,5,000-10,000) when you use LookUp Activity.The workaround mentioned in the doc doesn't means you could use LookUp Activity with  pagination,in my opinion.

My workaround is writing an azure function to get the total length of json array before data transfer.Inside azure function,divide the data into different sub temporary files with pagination like sub1.json,sub2.json....Then output an array contains file names.

Grab the array with ForEach Activity, execute lookup activity in the loop. The file path could be set as dynamic value.Then do next Web Activity.

Surely,my idea could be improved.For example,you get the total length of json array and it is under 5000 limitation,you could just return {"NeedIterate":false}.Evaluate that response by IfCondition Activity to decide which way should be next.It the value is false,execute the LookUp activity directly.All can be divided in the branches.

Body:
I'm trying to use ADF for the following scenario:

a JSON is uploaded to a Azure Storage Blob, containing an array of similar objects

this JSON is read by ADF with a Lookup Activity and uploaded via a Web Activity to an external sink

I cannot use the Copy Activity, because I need to create a JSON payload for the Web Activity, so I have to lookup the array and paste it like this (payload of the Web Activity):

{
   "some field": "value",
   "some more fields": "value",
   ...
   "items": @{activity('GetJsonLookupActivity').output.value}
}

The Lookup activity has a known limitation of an upper limit of 5000 rows at a time. If the JSON is larger, only 5000 top rows will be read and all else will be ignored.

I know this, so I have a system that chops payloads into chunks of 5000 rows before uploading to storage. But I'm not the only user, so there's a valid concern that someone else will try uploading bigger files and the pipeline will silently pass with a partial upload, while the user would obviously expect all rows to be uploaded.

I've come up with two concepts for a workaround, but I don't see how to implement either:

Is there any way for me to check if the JSON file is too large and fail the pipeline if so? The Lookup Activity doesn't seem to allow row counting, and the Get Metadata Activity only returns the size in bytes.

Alternatively, the MSDN docs propose a workaround of copying data in a foreach loop. But I cannot figure out how I'd use Lookup to first get rows 1-5000 and then 5001-10000 etc. from a JSON. It's easy enough with SQL using OFFSET N FETCH NEXT 5000 ROWS ONLY, but how to do it with a JSON?


答: As described, there is no matching function to TiXmlElement(std::_cxx11::string&) which as I understand correctly is some string class from c11 standarisation. In this case it will be exactly point string. Try to check if there is a way of using strings that are meant for TiXmlElement as obviously, as the error is saying, you're providing an instance of wrong class std::_cxx11::string&

Title: no matching function for call to 'TiXmlElement::TiXmlElement(std::_cxx11::string&)


问:
FM to convert time from 24hr to 12hr format?
I have to format a DateTime which is in UTC based on user settings which include its time zone (CET/IST etc) and time format (24hr/12hr).

I could find CONVERT TIME STAMP statement which takes only TIME ZONE as a parameter and does that conversion:

```<code>DATA: lv_timestampl TYPE timestampl VALUE '20200219095959.0000000',
      lv_date       TYPE d,
      lv_time       TYPE t.
CONVERT TIME STAMP lv_timestampl TIME ZONE sy-zonlo INTO DATE lv_date TIME lv_time.
</code>```

My objective is to convert this lv_timestampl based on TimeZone and TimeFormat together.

PS: I could just do that -12 manipulation on lv_time after CONVERT TIME STAMP statement and append PM/AM but I am looking for a standard way of doing it.

答:
FM HRVE_CONVERT_TIME can be used to convert in both ways (Convert 12hr-to 24h and 24hr to 12hr).

You can combine the results with the FM you already found.

Body:
I have to format a DateTime which is in UTC based on user settings which include its time zone (CET/IST etc) and time format (24hr/12hr).

I could find CONVERT TIME STAMP statement which takes only TIME ZONE as a parameter and does that conversion:

DATA: lv_timestampl TYPE timestampl VALUE '20200219095959.0000000',
      lv_date       TYPE d,
      lv_time       TYPE t.
CONVERT TIME STAMP lv_timestampl TIME ZONE sy-zonlo INTO DATE lv_date TIME lv_time.

My objective is to convert this lv_timestampl based on TimeZone and TimeFormat together.

PS: I could just do that -12 manipulation on lv_time after CONVERT TIME STAMP statement and append PM/AM but I am looking for a standard way of doing it.


问:
Tensorflow crash with CUDNN_STATUS_ALLOC_FAILED
Been searching the web for hours with no results, so figured I'd ask here.

I'm trying to make a self driving car following Sentdex's tutorial, but when running the model, I get a bunch of fatal errors. I've searched all over the internet for the solution, and many seem to have the same problem. However, none of the solutions I've found (Including this Stack-post), work for me.

Here is my software:

Tensorflow: 1.5, GPU version

CUDA: 9.0, with the patch

CUDnn: 7

Windows 10 Pro

Python 3.6

Hardware:

Nvidia 1070ti, with latest drivers

Intel i5 7600K

Here is the crash log:

2018-02-04 16:29:33.606903: E C:\tf_jenkins\workspace\rel-win\M\windows-gpu\PY\36\tensorflow\stream_executor\cuda\cuda_blas.cc:444] failed to create cublas handle: CUBLAS_STATUS_ALLOC_FAILED
2018-02-04 16:29:33.608872: E C:\tf_jenkins\workspace\rel-win\M\windows-gpu\PY\36\tensorflow\stream_executor\cuda\cuda_blas.cc:444] failed to create cublas handle: CUBLAS_STATUS_ALLOC_FAILED
2018-02-04 16:29:33.609308: E C:\tf_jenkins\workspace\rel-win\M\windows-gpu\PY\36\tensorflow\stream_executor\cuda\cuda_blas.cc:444] failed to create cublas handle: CUBLAS_STATUS_ALLOC_FAILED
2018-02-04 16:29:35.145249: E C:\tf_jenkins\workspace\rel-win\M\windows-gpu\PY\36\tensorflow\stream_executor\cuda\cuda_dnn.cc:385] could not create cudnn handle: CUDNN_STATUS_ALLOC_FAILED
2018-02-04 16:29:35.145563: E C:\tf_jenkins\workspace\rel-win\M\windows-gpu\PY\36\tensorflow\stream_executor\cuda\cuda_dnn.cc:352] could not destroy cudnn handle: CUDNN_STATUS_BAD_PARAM
2018-02-04 16:29:35.149896: F C:\tf_jenkins\workspace\rel-win\M\windows-gpu\PY\36\tensorflow\core\kernels\conv_ops.cc:717] Check failed: stream->parent()->GetConvolveAlgorithms( conv_parameters.ShouldIncludeWinogradNonfusedAlgo<T>(), &algorithms)

Here's my code:

```<code> import tensorflow as tf
    import numpy as np
    import cv2
    import time
    from PIL import ImageGrab
    from getkeys import key_check
    from alexnet import alexnet
    import os
    from sendKeys import PressKey, ReleaseKey, W,A,S,D,Sp

    import random

    WIDTH = 80
    HEIGHT = 60
    LR = 1e-3
    EPOCHS = 10
    MODEL_NAME = 'DiRT-AI-Driver-{}-{}-{}-epochs.model'.format(LR, 'alexnetv2', EPOCHS)

    def straight():
        PressKey(W)
        ReleaseKey(A)
        ReleaseKey(S)
        ReleaseKey(D)
        ReleaseKey(Sp)
    def left():
        PressKey(A)
        ReleaseKey(W)
        ReleaseKey(S)
        ReleaseKey(D)
        ReleaseKey(Sp)
    def right():
        PressKey(D)
        ReleaseKey(A)
        ReleaseKey(S)
        ReleaseKey(W)
        ReleaseKey(Sp)
    def brake():
        PressKey(S)
        ReleaseKey(A)
        ReleaseKey(W)
        ReleaseKey(D)
        ReleaseKey(Sp)
    def handbrake():
        PressKey(Sp)
        ReleaseKey(A)
        ReleaseKey(S)
        ReleaseKey(D)
        ReleaseKey(W)

    model = alexnet(WIDTH, HEIGHT, LR)
    model.load(MODEL_NAME)

    def main():
        last_time = time.time()
        for i in list(range(4))[::-1]:
            print(i+1)
            time.sleep(1)

    paused = False
    while(True):
            if not paused:
                screen = np.array(ImageGrab.grab(bbox=(0,40,1024,768)))
                screen = cv2.cvtColor(screen,cv2.COLOR_BGR2GRAY)
                screen = cv2.resize(screen,(80,60))
                print('Loop took {} seconds'.format(time.time()-last_time))
                last_time = time.time()
                print('took time')
                prediction = model.predict([screen.reshape(WIDTH,HEIGHT,1)])[0]
                print('predicted')
                moves = list(np.around(prediction))
                print('got moves')
                print(moves,prediction)

                if moves == [1,0,0,0,0]:
                    straight()
                elif moves == [0,1,0,0,0]:
                    left()
                elif moves == [0,0,1,0,0]:
                    brake()
                elif moves == [0,0,0,1,0]:
                    right()
                elif moves == [0,0,0,0,1]:
                    handbrake()

            keys = key_check()

            if 'T' in keys:
                if paused:
                    pased = False
                    time.sleep(1)
                else:
                    paused = True
                    ReleaseKey(W)
                    ReleaseKey(A)
                    ReleaseKey(S)
                    ReleaseKey(D)
                    ReleaseKey(Sp)
                    time.sleep(1)

main()
</code>```

I've found that the line that crashes python and spawns the first three bugs is this line:

prediction = model.predict([screen.reshape(WIDTH,HEIGHT,1)])[0]

When running the code, the CPU goes up to a whopping 100%, suggesting that something is seriously off. GPU goes to about 40-50%

I've tried Tensorflow 1.2 and 1.3, as well as CUDA 8, to no good. When installing CUDA I do not install the specific drivers, since they are too old for my GPU. Tried different CUDnn's too, did no good.

答:
Probably you're running out of GPU memory.

If you're using TensorFlow 1.x:

1st option) set allow_growth to true.

```<code>import tensorflow as tf
config = tf.ConfigProto()
config.gpu_options.allow_growth=True
sess = tf.Session(config=config)
</code>```

2nd option) set memory fraction.

```<code># change the memory fraction as you want

import tensorflow as tf
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.3)
sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))
</code>```

If you're using TensorFlow 2.x:

1st option) set set_memory_growth to true.

```<code># Currently the ‘memory growth’ option should be the same for all GPUs.
# You should set the ‘memory growth’ option before initializing GPUs.

import tensorflow as tf
gpus = tf.config.experimental.list_physical_devices('GPU')
if gpus:
  try:
    for gpu in gpus:
      tf.config.experimental.set_memory_growth(gpu, True)
  except RuntimeError as e:
    print(e)
</code>```

2nd option) set memory_limit as you want.
Just change the index of gpus and memory_limit in this code below.

```<code>import tensorflow as tf
gpus = tf.config.experimental.list_physical_devices('GPU')
if gpus:
  try:
    tf.config.experimental.set_virtual_device_configuration(gpus[0], [tf.config.experimental.VirtualDeviceConfiguration(memory_limit=1024)])
  except RuntimeError as e:
    print(e)
</code>```

Body:
Been searching the web for hours with no results, so figured I'd ask here.

I'm trying to make a self driving car following Sentdex's tutorial, but when running the model, I get a bunch of fatal errors. I've searched all over the internet for the solution, and many seem to have the same problem. However, none of the solutions I've found (Including this Stack-post), work for me.

Here is my software:

Tensorflow: 1.5, GPU version

CUDA: 9.0, with the patch

CUDnn: 7

Windows 10 Pro

Python 3.6

Hardware:

Nvidia 1070ti, with latest drivers

Intel i5 7600K

Here is the crash log:

2018-02-04 16:29:33.606903: E C:\tf_jenkins\workspace\rel-win\M\windows-gpu\PY\36\tensorflow\stream_executor\cuda\cuda_blas.cc:444] failed to create cublas handle: CUBLAS_STATUS_ALLOC_FAILED
2018-02-04 16:29:33.608872: E C:\tf_jenkins\workspace\rel-win\M\windows-gpu\PY\36\tensorflow\stream_executor\cuda\cuda_blas.cc:444] failed to create cublas handle: CUBLAS_STATUS_ALLOC_FAILED
2018-02-04 16:29:33.609308: E C:\tf_jenkins\workspace\rel-win\M\windows-gpu\PY\36\tensorflow\stream_executor\cuda\cuda_blas.cc:444] failed to create cublas handle: CUBLAS_STATUS_ALLOC_FAILED
2018-02-04 16:29:35.145249: E C:\tf_jenkins\workspace\rel-win\M\windows-gpu\PY\36\tensorflow\stream_executor\cuda\cuda_dnn.cc:385] could not create cudnn handle: CUDNN_STATUS_ALLOC_FAILED
2018-02-04 16:29:35.145563: E C:\tf_jenkins\workspace\rel-win\M\windows-gpu\PY\36\tensorflow\stream_executor\cuda\cuda_dnn.cc:352] could not destroy cudnn handle: CUDNN_STATUS_BAD_PARAM
2018-02-04 16:29:35.149896: F C:\tf_jenkins\workspace\rel-win\M\windows-gpu\PY\36\tensorflow\core\kernels\conv_ops.cc:717] Check failed: stream->parent()->GetConvolveAlgorithms( conv_parameters.ShouldIncludeWinogradNonfusedAlgo<T>(), &algorithms)

Here's my code:

 import tensorflow as tf
    import numpy as np
    import cv2
    import time
    from PIL import ImageGrab
    from getkeys import key_check
    from alexnet import alexnet
    import os
    from sendKeys import PressKey, ReleaseKey, W,A,S,D,Sp

    import random

    WIDTH = 80
    HEIGHT = 60
    LR = 1e-3
    EPOCHS = 10
    MODEL_NAME = 'DiRT-AI-Driver-{}-{}-{}-epochs.model'.format(LR, 'alexnetv2', EPOCHS)

    def straight():
        PressKey(W)
        ReleaseKey(A)
        ReleaseKey(S)
        ReleaseKey(D)
        ReleaseKey(Sp)
    def left():
        PressKey(A)
        ReleaseKey(W)
        ReleaseKey(S)
        ReleaseKey(D)
        ReleaseKey(Sp)
    def right():
        PressKey(D)
        ReleaseKey(A)
        ReleaseKey(S)
        ReleaseKey(W)
        ReleaseKey(Sp)
    def brake():
        PressKey(S)
        ReleaseKey(A)
        ReleaseKey(W)
        ReleaseKey(D)
        ReleaseKey(Sp)
    def handbrake():
        PressKey(Sp)
        ReleaseKey(A)
        ReleaseKey(S)
        ReleaseKey(D)
        ReleaseKey(W)

    model = alexnet(WIDTH, HEIGHT, LR)
    model.load(MODEL_NAME)

    def main():
        last_time = time.time()
        for i in list(range(4))[::-1]:
            print(i+1)
            time.sleep(1)

    paused = False
    while(True):
            if not paused:
                screen = np.array(ImageGrab.grab(bbox=(0,40,1024,768)))
                screen = cv2.cvtColor(screen,cv2.COLOR_BGR2GRAY)
                screen = cv2.resize(screen,(80,60))
                print('Loop took {} seconds'.format(time.time()-last_time))
                last_time = time.time()
                print('took time')
                prediction = model.predict([screen.reshape(WIDTH,HEIGHT,1)])[0]
                print('predicted')
                moves = list(np.around(prediction))
                print('got moves')
                print(moves,prediction)

                if moves == [1,0,0,0,0]:
                    straight()
                elif moves == [0,1,0,0,0]:
                    left()
                elif moves == [0,0,1,0,0]:
                    brake()
                elif moves == [0,0,0,1,0]:
                    right()
                elif moves == [0,0,0,0,1]:
                    handbrake()

            keys = key_check()

            if 'T' in keys:
                if paused:
                    pased = False
                    time.sleep(1)
                else:
                    paused = True
                    ReleaseKey(W)
                    ReleaseKey(A)
                    ReleaseKey(S)
                    ReleaseKey(D)
                    ReleaseKey(Sp)
                    time.sleep(1)

main()

I've found that the line that crashes python and spawns the first three bugs is this line:

prediction = model.predict([screen.reshape(WIDTH,HEIGHT,1)])[0]

When running the code, the CPU goes up to a whopping 100%, suggesting that something is seriously off. GPU goes to about 40-50%

I've tried Tensorflow 1.2 and 1.3, as well as CUDA 8, to no good. When installing CUDA I do not install the specific drivers, since they are too old for my GPU. Tried different CUDnn's too, did no good.

Body:
Probably you're running out of GPU memory.

If you're using TensorFlow 1.x:

1st option) set allow_growth to true.

import tensorflow as tf
config = tf.ConfigProto()
config.gpu_options.allow_growth=True
sess = tf.Session(config=config)

2nd option) set memory fraction.

# change the memory fraction as you want

import tensorflow as tf
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.3)
sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))

If you're using TensorFlow 2.x:

1st option) set set_memory_growth to true.

# Currently the ‘memory growth’ option should be the same for all GPUs.
# You should set the ‘memory growth’ option before initializing GPUs.

import tensorflow as tf
gpus = tf.config.experimental.list_physical_devices('GPU')
if gpus:
  try:
    for gpu in gpus:
      tf.config.experimental.set_memory_growth(gpu, True)
  except RuntimeError as e:
    print(e)

2nd option) set memory_limit as you want.
Just change the index of gpus and memory_limit in this code below.

import tensorflow as tf
gpus = tf.config.experimental.list_physical_devices('GPU')
if gpus:
  try:
    tf.config.experimental.set_virtual_device_configuration(gpus[0], [tf.config.experimental.VirtualDeviceConfiguration(memory_limit=1024)])
  except RuntimeError as e:
    print(e)


问:
Reactjs: How do I remove the page-not-found component from every existing URL?
I am building react app.

If a user types the wrong URL, the NoMatch component is shown (which is fine).

Challenge is that when a user types an existing URL, two components are shown. The NoMatch component and the expected component both appear.

Note: I found some questions about this on stackoverflow, but non of the solutions worked for me. I am using a <PrivateRoute> and react-router-dom.

App.js

<Provider store={store}>
    <Router>
        <Switch>
            <Route exact path="/login" component={Login}/>
            <Fragment>
                <Navigationbar/>

                    <Sidebar/>

                        <PrivateRoute path="/" exact component={Home}/>
                        <PrivateRoute path="/files" exact component={Files}/>
                        <PrivateRoute path="/new_app" exact component={NewApp}/>
                        <PrivateRoute path="/applications/:app_name" exact component={Application} />
                        <PrivateRoute path="*" component={NoMatch}/>

            </Fragment>
        </Switch>
    </Router>
</Provider>
```

<p>PrivateRoute.js</p>

<pre class="lang-js prettyprint-override"><code>const PrivateRoute = ({component: Component, auth, ...rest}) => (
    <Route
        {...rest}
        render={props =>
            auth.isAuthenticated ? (
                <Component {...props} />
            ) : (
                <Redirect
                    to={{
                        pathname: "/login",
                        state: {from: props.location}
                    }}
                />
            )
        }
    />
);
</code>```

That is the problem that I have.

Any idea what I am doing wrong that I do not get the result that I want?

答:
One way is to add a wrapping component for the "correct" paths, that has a check that if the pathname is one of the correct paths, you render its children, otherwise render  component. Quick example:

```<code><WrappingComponent>
  <Route component={Home} exact path='/' />
  <Route component={SomePage} path='/some-page' />
</WrappingComponent>
</code>```

Then in the wrapping component pathname check:

```<code>  if (this.props.location.pathname === '/' ||
    this.props.location.pathname === '/some-page') {
      return this.props.children;
  } else {
    return <NoMatch />;
  }
</code>```

Body:
I am building react app.

If a user types the wrong URL, the NoMatch component is shown (which is fine).

Challenge is that when a user types an existing URL, two components are shown. The NoMatch component and the expected component both appear.

Note: I found some questions about this on stackoverflow, but non of the solutions worked for me. I am using a <PrivateRoute> and react-router-dom.

App.js

<Provider store={store}>
    <Router>
        <Switch>
            <Route exact path="/login" component={Login}/>
            <Fragment>
                <Navigationbar/>

                    <Sidebar/>

                        <PrivateRoute path="/" exact component={Home}/>
                        <PrivateRoute path="/files" exact component={Files}/>
                        <PrivateRoute path="/new_app" exact component={NewApp}/>
                        <PrivateRoute path="/applications/:app_name" exact component={Application} />
                        <PrivateRoute path="*" component={NoMatch}/>

            </Fragment>
        </Switch>
    </Router>
</Provider>

PrivateRoute.js

const PrivateRoute = ({component: Component, auth, ...rest}) => (
    <Route
        {...rest}
        render={props =>
            auth.isAuthenticated ? (
                <Component {...props} />
            ) : (
                <Redirect
                    to={{
                        pathname: "/login",
                        state: {from: props.location}
                    }}
                />
            )
        }
    />
);

That is the problem that I have.

Any idea what I am doing wrong that I do not get the result that I want?

Body:
One way is to add a wrapping component for the "correct" paths, that has a check that if the pathname is one of the correct paths, you render its children, otherwise render  component. Quick example:

<WrappingComponent>
  <Route component={Home} exact path='/' />
  <Route component={SomePage} path='/some-page' />
</WrappingComponent>

Then in the wrapping component pathname check:

  if (this.props.location.pathname === '/' ||
    this.props.location.pathname === '/some-page') {
      return this.props.children;
  } else {
    return <NoMatch />;
  }


问:
SQL function for FIND and MID as excel
Can someone help me how to write this in SQL?

I have excel formula to update one column using "K5" where "K5" is a column name.

```<code>=MID(K5,7,FIND(" ",K5,7)-7)
</code>```

I want to apply this on my MS access table to update one column.

答:
You can use the function MID() in Access too.

Instead of FIND() Access provides the function INSTR() with different syntax.

So use this:

```<code>= MID(columnname, 7, INSTR(7, columnname, ' ') - 7)
</code>```

Title: SQL function for FIND and MID as excel

Body:
Can someone help me how to write this in SQL?

I have excel formula to update one column using "K5" where "K5" is a column name.

=MID(K5,7,FIND(" ",K5,7)-7)

I want to apply this on my MS access table to update one column.

Body:
You can use the function MID() in Access too.

Instead of FIND() Access provides the function INSTR() with different syntax.

So use this:

= MID(columnname, 7, INSTR(7, columnname, ' ') - 7)


问:
Google Data studio -Default filter on last month when data is at month level
I have a report with one data source in Google Data Studio. The data is at month level inside the BigQuery table YYYYMM (for example 202001). I have a filter that is set on the year-month dimension which works ok but I would like to add a default value which changes to last month(max(year_month)) available in the table.
Is this possible? I only found the option to hard-code the default selection but this can't be updated dynamically

as in this screen shot

Jaishree's suggestion

答:
It can be achieved by setting the Date Range (at the chart, report level, Date Range Control, etc) to Last Month.

First, a YYYYMMDD Date field needs to be created at the Data Source. This can be done using the CONCAT function to add a Day (the 15th is used in the formula) and then using the TODATE function (although in this case the TODATE function is not required, however, adding it as best practice):

```<code>TODATE(CONCAT(Date, "15"), "%Y%m%d", "%Y%m%d" )
</code>```

Adding a link to post on the Google Forums (Nimantha; 10 Feb 2020) which also has a GIF to demonstrate the process above as well as adding the Date field at the Report Level.

Body:
It can be achieved by setting the Date Range (at the chart, report level, Date Range Control, etc) to Last Month.

First, a YYYYMMDD Date field needs to be created at the Data Source. This can be done using the CONCAT function to add a Day (the 15th is used in the formula) and then using the TODATE function (although in this case the TODATE function is not required, however, adding it as best practice):

TODATE(CONCAT(Date, "15"), "%Y%m%d", "%Y%m%d" )

Adding a link to post on the Google Forums (Nimantha; 10 Feb 2020) which also has a GIF to demonstrate the process above as well as adding the Date field at the Report Level.


问:
Reference classes in Android APK
I'm working on test automation for an android app. We only receive an apk to test. The app uses some custom views. I need to reference the apk like a library so I can reference the classes in apk. How do I do it in eclipse?

I tried adding it to build path like a normal jar. Package explorer can see all the assets but none of the classes.

答:
How do I do it in eclipse?

You don't. It is not possible. Demand the source code for the project you are testing.

Title: Reference classes in Android APK


问:
XamlCompiler error WMC1006: Cannot resolve Assembly or Windows Metadata file 'Microsoft.Win32.Registry.dll'
I upgraded my UWP Project to Fall Creator Update with the Windows SDK 10.1.16299.15.

When I compile or create a Store Package I get:

C:\Users...\Visual Studio 2017\Projects\FileRenamer\Get.the.solution.FileRenamer.App\Get.the.solution.FileRenamer.App.csproj : XamlCompiler error WMC1006: Cannot resolve Assembly or Windows Metadata file 'Microsoft.Win32.Registry.dll'
  3>C:\Program Files (x86)\Windows Kits\10\bin\10.0.16299.0\XamlCompiler\Microsoft.Windows.UI.Xaml.Common.targets(263,5): Xaml Internal Error error WMC9999: Type universe cannot resolve assembly: Microsoft.Win32.Registry, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a.

I never referenced Microsoft.Win32.Registry.dll so I think it's Windows SDK Bug?

Where can I report such a Bug and how can I fix it?

PS: My Windows machine got the Fall Creators update and Visual Studio is up to date too.

答:
There is a known issue in VS2017 Ver. 15.6 related to how NuGet restores packages using FallBackFolders. You can workaround this issue by running restore with the following command:

```<code>msbuild.exe /t:Restore /p:RestoreAdditionalProjectFallbackFolders=""
</code>```

You also can run he above command in your solution path or for a specific project (See following command template) or add them to your build batch file if you are using such a file to build your solution (for example on a Build Server):

```<code>msbuild.exe /t:Restore /p:RestoreAdditionalProjectFallbackFolders="" "[Your Project|Solution Path]\[Your Project|Solution Name].csproj|sln"
</code>```

For more information please check the following lead:
MS Developer Community

Body:
There is a known issue in VS2017 Ver. 15.6 related to how NuGet restores packages using FallBackFolders. You can workaround this issue by running restore with the following command:

msbuild.exe /t:Restore /p:RestoreAdditionalProjectFallbackFolders=""

You also can run he above command in your solution path or for a specific project (See following command template) or add them to your build batch file if you are using such a file to build your solution (for example on a Build Server):

msbuild.exe /t:Restore /p:RestoreAdditionalProjectFallbackFolders="" "[Your Project|Solution Path]\[Your Project|Solution Name].csproj|sln"

For more information please check the following lead:
MS Developer Community


问:
dyld: Library not loaded: @rpath/GTMSessionFetcher.framework/GTMSessionFetcher SIGABRT
The application runs on all other simulators and devices except my own.

dyld: Library not loaded:
  @rpath/GTMSessionFetcher.framework/GTMSessionFetcher   Referenced
  from:
  /private/var/containers/Bundle/Application/EA88F6D8-9D62-465E-A106-CF1198B06F3E/LeafLabel.app/LeafLabel
  Reason: no suitable image found.  Did find:
    /private/var/containers/Bundle/Application/EA88F6D8-9D62-465E-A106-CF1198B06F3E/LeafLabel.app/Frameworks/GTMSessionFetcher.framework/GTMSessionFetcher:
  code signature invalid for
  '/private/var/containers/Bundle/Application/EA88F6D8-9D62-465E-A106-CF1198B06F3E/LeafLabel.app/Frameworks/GTMSessionFetcher.framework/GTMSessionFetcher'

/private/var/containers/Bundle/Application/EA88F6D8-9D62-465E-A106-CF1198B06F3E/LeafLabel.app/Frameworks/GTMSessionFetcher.framework/GTMSessionFetcher:
  stat() failed with errno=25
    /private/var/containers/Bundle/Application/EA88F6D8-9D62-465E-A106-CF1198B06F3E/LeafLabel.app/Frameworks/GTMSessionFetcher.framework/GTMSessionFetcher:
  code signature invalid for
  '/private/var/containers/Bundle/Application/EA88F6D8-9D62-465E-A106-CF1198B06F3E/LeafLabel.app/Frameworks/GTMSessionFetcher.framework/GTMSessionFetcher'

/private/var/containers/Bundle/Application/EA88F6D8-9D62-465E-A106-CF1198B06F3E/LeafLabel.app/Frameworks/GTMSessionFetcher.framework/GTMSessionFetcher:
  stat() failed with errno=1
    /private/var/containers/Bundle/Application/EA88F6D8-9D62-465E-A106-CF1198B06F3E/LeafLabel.app/Frameworks/GTMSessionFetcher.framework/GTMSessionFetcher:
  code signature invalid for
  '/private/var/containers/Bundle/Application/EA88F6D8-9D62-465E-A106-CF1198B06F3E/LeafLabel.app/Frameworks/GTMSessionFetcher.framework/GTMSessionFetcher'

/private/var/containers/Bundle/Application/EA88F6D8-9D62-465E-A106-CF1198B06F3E/LeafLabel.app/Frameworks/GTMSessionFetcher.framework/GTMSessionFetcher:
  stat() failed with errno=1

答:
This seems to be related to apple not supporting external frameworks since 13.3.1, if you don't have a developer license.

Try the actions mentioned here: Running iOS apps causes runtime error for frameworks "code signature invalid"


问:
Splitting words in a list
How to split a list into separate words. I know that you can split strings with split but I need to split a list.

Here is my code:

```<code>text = ['a,b', 'c,d']
text = text.replace(',', ' ')
for i in text:
  print(text.split())
</code>```

When I run it, an error pops up and when I try to convert the list into a string there are random extras like \n, ' and [] that shouldn't be there.

Expected result: I want the outcome to be a list that contains ['a', 'b', 'c', 'd'] that when I print, comes up with that.

The error comes up on line two and says:

AttributeError: 'list' object has no attribute 'replace'

答:
Well you can do that easily but first you should read what does the split function exactly do.

```<code>newList = []
for i in text:
    words = i.split(',')
    newList.extend(words)
print(newList)
</code>```

Here are some useful information, Python list extend, Iterating over a list.

Plus, There is no method called replace for lists, this method works for Strings.

Title: Splitting words in a list

Body:
How to split a list into separate words. I know that you can split strings with split but I need to split a list.

Here is my code:

text = ['a,b', 'c,d']
text = text.replace(',', ' ')
for i in text:
  print(text.split())

When I run it, an error pops up and when I try to convert the list into a string there are random extras like \n, ' and [] that shouldn't be there.

Expected result: I want the outcome to be a list that contains ['a', 'b', 'c', 'd'] that when I print, comes up with that.

The error comes up on line two and says:

AttributeError: 'list' object has no attribute 'replace'

Body:
Well you can do that easily but first you should read what does the split function exactly do.

newList = []
for i in text:
    words = i.split(',')
    newList.extend(words)
print(newList)

Here are some useful information, Python list extend, Iterating over a list.

Plus, There is no method called replace for lists, this method works for Strings.


问:
Cannot inline bytecode built with JVM target 1.8 into bytecode that is being built with JVM target 1.6
When trying to run the Example CorDapp (GitHub CorDapp) via IntelliJ, I receive the following error:

Cannot inline bytecode built with JVM target 1.8 into bytecode that is
being built with JVM target 1.6

How can I modify the IntelliJ settings so that all the bytecode is built with the same JVM target?

答:
Another hint for Eclipse users. After double checking the jvm target settings pointed out by other users, I still had the same problem, and that was caused by missing Kotlin Runtime Library. For eg, when creating a project with spring initializr, it is not added automatically. For adding it: right click on your project -> Build path -> Add libraries... -> User Library, and simply add org.jetbrains.kotlin.core.KOTLIN_CONTAINER

Make sure you refresh your gradle project afterwards (right click -> Gradle -> Refresh gradle project)


问:
Convert string to GUID with sscanf
I'm trying to convert a string to GUID with sscanf:

```<code>GUID guid;
sscanf( "11111111-2222-3333-4455-667788995511", "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
        &guid.Data1, &guid.Data2, &guid.Data3,
        &guid.Data4[0], &guid.Data4[1], &guid.Data4[2],
        &guid.Data4[3], &guid.Data4[4], &guid.Data4[5],
        &guid.Data4[6], &guid.Data4[7]);
</code>```

However, in runtime, it fails and exits with "Error: Command failed". Why? How to fix it?

I do not want to compile with /clr so cannot use System.

答:
Working & not damaging the stack:

GUID guid;

sscanf_s(AliasName.c_str(), "{%08lX-%04hX-%04hX-%02hhX%02hhX-%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX}",
        &guid.Data1, &guid.Data2, &guid.Data3,
        &guid.Data4[0], &guid.Data4[1], &guid.Data4[2],
        &guid.Data4[3], &guid.Data4[4], &guid.Data4[5],
        &guid.Data4[6], &guid.Data4[7]);
```

ContentLicense: CC BY-SA 2.5

Title: Convert string to GUID with sscanf

Body:
I'm trying to convert a string to GUID with sscanf:

GUID guid;
sscanf( "11111111-2222-3333-4455-667788995511", "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
        &guid.Data1, &guid.Data2, &guid.Data3,
        &guid.Data4[0], &guid.Data4[1], &guid.Data4[2],
        &guid.Data4[3], &guid.Data4[4], &guid.Data4[5],
        &guid.Data4[6], &guid.Data4[7]);

However, in runtime, it fails and exits with "Error: Command failed". Why? How to fix it?

I do not want to compile with /clr so cannot use System.


问:
How to remove this $.getScript("https://activeitzone.com/check/larashop.js") from ACTIVE IT ZONE
this making problem creating API
this script files attached to every single page in laravel view but unable to
find it by a search.
also append to API please help to remove it </p>

```<code>{
    "fail": "Wrong Credentials"
}
</code>```

<p>$(function(){$.getScript("https://activeitzone.com/check/larashop.js");
    });$(function(){$.getScript("https://activeitzone.com/check/larashop.js");
    });</p>

答:
Can you Open file: vendor/symfony/http-foundation/Response.php

Remove content: public function _string_header($header). $_string_header =

Body:
this making problem creating API
this script files attached to every single page in laravel view but unable to
find it by a search.
also append to API please help to remove it

{
    "fail": "Wrong Credentials"
}

$(function(){$.getScript("https://activeitzone.com/check/larashop.js");
    });$(function(){$.getScript("https://activeitzone.com/check/larashop.js");
    });


答:
Remove path from it</p>

```<code><Provider store={store}>
    <Router>
        <Switch>
            <Route exact path="/login" component={Login}/>
            <Fragment>
                <Navigationbar/>
                <div className="main-part">
                    <Sidebar/>
                    <main className="content shrunk-sidebar">
                        <PrivateRoute path="/" exact component={Home}/>
                        <PrivateRoute path="/files" exact component={Files}/>
                        <PrivateRoute path="/new_app" exact component={NewApp}/>
                        <PrivateRoute path="/applications/:app_name" exact component={Application} />
                        <PrivateRoute  component={NoMatch}/>
                    </main>
                </div>
            </Fragment>
        </Switch>
    </Router>
</Provider>
</code>```

Title: Reactjs: How do I remove the page-not-found component from every existing URL?

Body:
Remove path from it

<Provider store={store}>
    <Router>
        <Switch>
            <Route exact path="/login" component={Login}/>
            <Fragment>
                <Navigationbar/>
                <div className="main-part">
                    <Sidebar/>
                    <main className="content shrunk-sidebar">
                        <PrivateRoute path="/" exact component={Home}/>
                        <PrivateRoute path="/files" exact component={Files}/>
                        <PrivateRoute path="/new_app" exact component={NewApp}/>
                        <PrivateRoute path="/applications/:app_name" exact component={Application} />
                        <PrivateRoute  component={NoMatch}/>
                    </main>
                </div>
            </Fragment>
        </Switch>
    </Router>
</Provider>


问:
Overwrite resource file with maven assembly plugin
I use maven-assembly-plugin with "jar-with-dependencies" to package jar. There are 2 dependencies artifact having log-back.xml. The second artifact is depend on the first one. I want to have log-back.xml of the second artifact in final jar, but it always contain log-back.xml of the first one. So how can I control this?

Thanks

答:
You can use the unpackOptions to achieve this.  Try something like the following:</p>

```<code><assembly>
...
    <dependencySets>
        <dependencySet>
            <outputDirectory>/</outputDirectory>
            <includes>
                <include>${groupId}:${artifact.whose.logback.is.to.be.excluded} </include>
            </includes>
            <unpack>true</unpack>
            <unpackOptions>
                <excludes>
                    <exclude>**/logback.xml</exclude>
                </excludes>
            </unpackOptions>
        </dependencySet>
        <dependencySet>
            <outputDirectory>/</outputDirectory>
            <excludes>
                <exclude>${groupId}:${artifact.whose.logback.is.to.be.excluded}</exclude>
            </excludes>
            <unpack>true</unpack>
        </dependencySet>
    </dependencySets>
</assembly>
</code>```

Body:
You can use the unpackOptions to achieve this.  Try something like the following:

<assembly>
...
    <dependencySets>
        <dependencySet>
            <outputDirectory>/</outputDirectory>
            <includes>
                <include>${groupId}:${artifact.whose.logback.is.to.be.excluded} </include>
            </includes>
            <unpack>true</unpack>
            <unpackOptions>
                <excludes>
                    <exclude>**/logback.xml</exclude>
                </excludes>
            </unpackOptions>
        </dependencySet>
        <dependencySet>
            <outputDirectory>/</outputDirectory>
            <excludes>
                <exclude>${groupId}:${artifact.whose.logback.is.to.be.excluded}</exclude>
            </excludes>
            <unpack>true</unpack>
        </dependencySet>
    </dependencySets>
</assembly>


问:
Can't access microphone while running Dialog demo in sphinx4 5prealpha
I am trying to run the dialog demo of sphinx 4 pre aplha but it gives errors.

I am creating a live speech application.

I imported the project using maven and followed this guide on stack overflow: https://stackoverflow.com/a/25963020/2653162

The error says about issues regarding the 16 khz and channel being mono. So clearly its about the sampling stuff. And is also says about microphone.

I looked on how change the microphone settings to 16 khz and 16 bit but there is no such option in windows 7

:

The thing is that the HelloWorld and dialog demo worked fine in sphinx4 1.06 beta but after I tried the latest release it gives following  errors:

```<code>Exception in thread "main" java.lang.IllegalStateException: javax.sound.sampled.LineUnavailableException: line with format PCM_SIGNED 16000.0 Hz, 16 bit, mono, 2 bytes/frame, little-endian not supported.
    at edu.cmu.sphinx.api.Microphone.<init>(Microphone.java:38)
    at edu.cmu.sphinx.api.SpeechSourceProvider.getMicrophone(SpeechSourceProvider.java:18)
    at edu.cmu.sphinx.api.LiveSpeechRecognizer.<init>(LiveSpeechRecognizer.java:34)
    at edu.cmu.sphinx.demo.dialog.Dialog.main(Dialog.java:145)
Caused by: javax.sound.sampled.LineUnavailableException: line with format PCM_SIGNED 16000.0 Hz, 16 bit, mono, 2 bytes/frame, little-endian not supported.
    at com.sun.media.sound.DirectAudioDevice$DirectDL.implOpen(DirectAudioDevice.java:513)
    at com.sun.media.sound.AbstractDataLine.open(AbstractDataLine.java:121)
    at com.sun.media.sound.AbstractDataLine.open(AbstractDataLine.java:413)
    at edu.cmu.sphinx.api.Microphone.<init>(Microphone.java:36)
    ... 3 more
</code>```

Cant figure out what to do to resolve the issue.

答:
For me with this change, the problem was as long as i was staying in a context of cmusphinx it was good the line can be reused many times. But if i begin to reuse the mic for another work (like recording) it was not available!

I see that the stream was open in Microphone class but never close!

So first I change in class Microphone the following attributes from static to dynamic :

```<code>private TargetDataLine line;
private InputStream inputStream;
</code>```

After i change the method stopRecording for closing stream before line:

```<code>  /**
 * close the stream and line
 */
public void stopRecording() {

    if (inputStream != null )
        try {
            inputStream.close();
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }

    line.stop();
</code>```

}

And now with no more change (class SpeechSourceProvider is original), i can reuse alternatively mic for cmupsphinx and another recording task

Body:
I am trying to run the dialog demo of sphinx 4 pre aplha but it gives errors.

I am creating a live speech application.

I imported the project using maven and followed this guide on stack overflow: https://stackoverflow.com/a/25963020/2653162

The error says about issues regarding the 16 khz and channel being mono. So clearly its about the sampling stuff. And is also says about microphone.

I looked on how change the microphone settings to 16 khz and 16 bit but there is no such option in windows 7

:

The thing is that the HelloWorld and dialog demo worked fine in sphinx4 1.06 beta but after I tried the latest release it gives following  errors:

Exception in thread "main" java.lang.IllegalStateException: javax.sound.sampled.LineUnavailableException: line with format PCM_SIGNED 16000.0 Hz, 16 bit, mono, 2 bytes/frame, little-endian not supported.
    at edu.cmu.sphinx.api.Microphone.<init>(Microphone.java:38)
    at edu.cmu.sphinx.api.SpeechSourceProvider.getMicrophone(SpeechSourceProvider.java:18)
    at edu.cmu.sphinx.api.LiveSpeechRecognizer.<init>(LiveSpeechRecognizer.java:34)
    at edu.cmu.sphinx.demo.dialog.Dialog.main(Dialog.java:145)
Caused by: javax.sound.sampled.LineUnavailableException: line with format PCM_SIGNED 16000.0 Hz, 16 bit, mono, 2 bytes/frame, little-endian not supported.
    at com.sun.media.sound.DirectAudioDevice$DirectDL.implOpen(DirectAudioDevice.java:513)
    at com.sun.media.sound.AbstractDataLine.open(AbstractDataLine.java:121)
    at com.sun.media.sound.AbstractDataLine.open(AbstractDataLine.java:413)
    at edu.cmu.sphinx.api.Microphone.<init>(Microphone.java:36)
    ... 3 more

Cant figure out what to do to resolve the issue.

Body:
For me with this change, the problem was as long as i was staying in a context of cmusphinx it was good the line can be reused many times. But if i begin to reuse the mic for another work (like recording) it was not available!

I see that the stream was open in Microphone class but never close!

So first I change in class Microphone the following attributes from static to dynamic :

private TargetDataLine line;
private InputStream inputStream;

After i change the method stopRecording for closing stream before line:

  /**
 * close the stream and line
 */
public void stopRecording() {

    if (inputStream != null )
        try {
            inputStream.close();
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }

    line.stop();

}

And now with no more change (class SpeechSourceProvider is original), i can reuse alternatively mic for cmupsphinx and another recording task


问:
How to limit(control) the number of tabs of ngx-bootstrap dynamic tabs-angular 2+
I am using the dynamic tabs using ngx-bootstrap,

My UI flow:

step1:- Have to use the tree table which contains policy, category and subcategory.

step2:- clicking on Policy opens the categories.

step3: clicking on category opens the subcategories.

step4: clicking on categories opens the ngx-bootstrap dynamic tabs.

Here is my stackblitz example

https://stackblitz.com/edit/angular-hdw4fh?file=src%2Fapp%2Fapp.component.html

Problem:-

I have to limit the tabs controls. Which means I have to open the tabs upto 10 (not more than 10). But in this case the tabs opening is going unlimited.

Is there any way to limit the number of tabs??
Can anybody help me??

答:
Add the below code to the beginning of the addNewTab:

```<code>if (this.tabs.length == 10) {
  alert("Max 10 tabs");
  return;
}
</code>```

Updated stackblitz sample:

https://stackblitz.com/edit/angular-homrum?file=src/app/app.component.ts

Instead of browser alert, you can use the alert component of ngx-bootstrap for better user experience:

https://valor-software.com/ngx-bootstrap/#/alerts

Body:
Add the below code to the beginning of the addNewTab:

if (this.tabs.length == 10) {
  alert("Max 10 tabs");
  return;
}

Updated stackblitz sample:

https://stackblitz.com/edit/angular-homrum?file=src/app/app.component.ts

Instead of browser alert, you can use the alert component of ngx-bootstrap for better user experience:

https://valor-software.com/ngx-bootstrap/#/alerts


问:
image created in scala does not look as expected. not sure why
i start by creating a 2d array all with a value of 2. then setting a few values from the bottom right of the array to 5

```<code>var map = Array.fill(5, 10)(2);
map(4)(9) = 5
map(3)(9) = 5
map(4)(8) = 5
map(3)(8) = 5
</code>```

this array will be represented by an image. each number 2 should be a blue square. the rest should just be white

```<code>import scala.io.Source
import java.io._
import java.awt.image.BufferedImage
import java.awt.{Graphics2D,Color,Font,BasicStroke}
import java.awt.geom._

object DRAWPROB {
 def draw(map : Array[Array[Int]]){

        val size = (30 * (map(0).length-1), 30 * (map.length-1))
        val canvas = new BufferedImage(size._1, size._2, BufferedImage.TYPE_INT_RGB)
        val g = canvas.createGraphics()
        g.setColor(Color.WHITE)
        g.fillRect(0, 0, canvas.getWidth, canvas.getHeight)
        g.setRenderingHint(java.awt.RenderingHints.KEY_ANTIALIASING,java.awt.RenderingHints.VALUE_ANTIALIAS_ON)
        var d = 0;
            for(d <- 0 to map.length-1){
                  var e = 0;
                  for(e <- 0 to map(0).length-1){
                  g.setColor(Color.BLUE)

                    if(map(d)(e) == 2){ g.fill(new Rectangle2D.Double(d*30.0, e*30.0, 30.0, 30.0));} // ill find a way to do this once i can load the image
                    else {println("not at "+ d + " " + e)}
                                                                                }
                                                                    }
g.dispose()
javax.imageio.ImageIO.write(canvas, "png", new java.io.File("island_drawing.png"))
}
</code>```

it just makes 1 large blue square but i wanted a section missing from the bottom right

expectation vs reality

why am i getting this

答:
Your main issue with this code part: new Rectangle2D.Double(d*30.0, e*30.0... - the first argument is x coordinate so it should be multiplied on map column value, rather on row , and same with second argument e*30 which is y so it should by multiplied on map row value.

I've refactored your code for better understanding, at least for myself, so please take a look as an example:

```<code>import java.awt.image.BufferedImage
import java.awt.{Color, Rectangle, RenderingHints}

import javax.imageio.ImageIO

import scala.reflect.ClassTag

/**
 * Immutable table model, possibly empty inside
 */
class Table[T](underlying: Array[Array[T]]) {
  def columnsCount: Int = underlying.headOption.map(_.length).getOrElse(0)
  def rowsCount: Int = underlying.length

  def rows: Seq[Int] = underlying.indices
  def columns: Seq[Int] = underlying.headOption.map(_.indices).getOrElse(Nil)

  def apply(row: Int, column: Int): Option[T] = {
    val rowExists = row < rowsCount && row >= 0
    val columnExists = column < columnsCount && column >= 0
    if(rowExists && columnExists) Some(underlying(row)(column)) else None
  }

  def update(row: Int, column: Int, value: T): Table[T] = {
    val copy = underlying.clone()
    copy(row)(column) = value
    new Table[T](copy)
  }

  def foreach[U](f: ((Int, Int, T)) => U): Unit = {
    val rowColumnValue = for {
      row <- rows
      column <- columns
      value <- apply(row, column)
    } yield (row, column, value)

    rowColumnValue.foreach[U](f)
  }

  override def toString: String = underlying.map(_.mkString(",")).mkString("\n")
}

object Table {
  def apply[T: ClassTag](rows: Int, columns: Int, initValue: T): Table[T] = {
    new Table[T](Array.fill(rows, columns)(initValue))
  }
}

class Draw(cellSize: Int) {

  def draw(table: Table[Int]) {
    val width = cellSize * table.columnsCount
    val height = cellSize * table.rowsCount

    val canvas = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB)
    val graphics = canvas.createGraphics()
    graphics.setColor(Color.WHITE)
    graphics.fillRect(0, 0, canvas.getWidth, canvas.getHeight)
    graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)

    table.foreach { case (row, column, value) =>
      if (value == 2) {
        graphics.setColor(Color.BLUE)
        // This is main fix part
        val x = column * cellSize
        val y = row * cellSize
        graphics.fill(new Rectangle(x, y, cellSize, cellSize))
      }
    }

    graphics.dispose()
    ImageIO.write(canvas, "png", new java.io.File("island_drawing.png"))
  }
}

object DrawApp {
  def main(args: Array[String]): Unit = {
    val draw = new Draw(30)
    val table = Table(5, 10, 2)
      .update(4 ,9, 5)
      .update(4, 8, 5)
      .update(3, 9, 5)
      .update(3, 8, 5)
    println(table)

    draw.draw(table)
  }
}

</code>```

This produced expected image. Hope this helps!

Body:
i start by creating a 2d array all with a value of 2. then setting a few values from the bottom right of the array to 5

var map = Array.fill(5, 10)(2);
map(4)(9) = 5
map(3)(9) = 5
map(4)(8) = 5
map(3)(8) = 5

this array will be represented by an image. each number 2 should be a blue square. the rest should just be white

import scala.io.Source
import java.io._
import java.awt.image.BufferedImage
import java.awt.{Graphics2D,Color,Font,BasicStroke}
import java.awt.geom._

object DRAWPROB {
 def draw(map : Array[Array[Int]]){

        val size = (30 * (map(0).length-1), 30 * (map.length-1))
        val canvas = new BufferedImage(size._1, size._2, BufferedImage.TYPE_INT_RGB)
        val g = canvas.createGraphics()
        g.setColor(Color.WHITE)
        g.fillRect(0, 0, canvas.getWidth, canvas.getHeight)
        g.setRenderingHint(java.awt.RenderingHints.KEY_ANTIALIASING,java.awt.RenderingHints.VALUE_ANTIALIAS_ON)
        var d = 0;
            for(d <- 0 to map.length-1){
                  var e = 0;
                  for(e <- 0 to map(0).length-1){
                  g.setColor(Color.BLUE)

                    if(map(d)(e) == 2){ g.fill(new Rectangle2D.Double(d*30.0, e*30.0, 30.0, 30.0));} // ill find a way to do this once i can load the image
                    else {println("not at "+ d + " " + e)}
                                                                                }
                                                                    }
g.dispose()
javax.imageio.ImageIO.write(canvas, "png", new java.io.File("island_drawing.png"))
}

it just makes 1 large blue square but i wanted a section missing from the bottom right

expectation vs reality

why am i getting this

Body:
Your main issue with this code part: new Rectangle2D.Double(d*30.0, e*30.0... - the first argument is x coordinate so it should be multiplied on map column value, rather on row , and same with second argument e*30 which is y so it should by multiplied on map row value.

I've refactored your code for better understanding, at least for myself, so please take a look as an example:

import java.awt.image.BufferedImage
import java.awt.{Color, Rectangle, RenderingHints}

import javax.imageio.ImageIO

import scala.reflect.ClassTag

/**
 * Immutable table model, possibly empty inside
 */
class Table[T](underlying: Array[Array[T]]) {
  def columnsCount: Int = underlying.headOption.map(_.length).getOrElse(0)
  def rowsCount: Int = underlying.length

  def rows: Seq[Int] = underlying.indices
  def columns: Seq[Int] = underlying.headOption.map(_.indices).getOrElse(Nil)

  def apply(row: Int, column: Int): Option[T] = {
    val rowExists = row < rowsCount && row >= 0
    val columnExists = column < columnsCount && column >= 0
    if(rowExists && columnExists) Some(underlying(row)(column)) else None
  }

  def update(row: Int, column: Int, value: T): Table[T] = {
    val copy = underlying.clone()
    copy(row)(column) = value
    new Table[T](copy)
  }

  def foreach[U](f: ((Int, Int, T)) => U): Unit = {
    val rowColumnValue = for {
      row <- rows
      column <- columns
      value <- apply(row, column)
    } yield (row, column, value)

    rowColumnValue.foreach[U](f)
  }

  override def toString: String = underlying.map(_.mkString(",")).mkString("\n")
}

object Table {
  def apply[T: ClassTag](rows: Int, columns: Int, initValue: T): Table[T] = {
    new Table[T](Array.fill(rows, columns)(initValue))
  }
}

class Draw(cellSize: Int) {

  def draw(table: Table[Int]) {
    val width = cellSize * table.columnsCount
    val height = cellSize * table.rowsCount

    val canvas = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB)
    val graphics = canvas.createGraphics()
    graphics.setColor(Color.WHITE)
    graphics.fillRect(0, 0, canvas.getWidth, canvas.getHeight)
    graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)

    table.foreach { case (row, column, value) =>
      if (value == 2) {
        graphics.setColor(Color.BLUE)
        // This is main fix part
        val x = column * cellSize
        val y = row * cellSize
        graphics.fill(new Rectangle(x, y, cellSize, cellSize))
      }
    }

    graphics.dispose()
    ImageIO.write(canvas, "png", new java.io.File("island_drawing.png"))
  }
}

object DrawApp {
  def main(args: Array[String]): Unit = {
    val draw = new Draw(30)
    val table = Table(5, 10, 2)
      .update(4 ,9, 5)
      .update(4, 8, 5)
      .update(3, 9, 5)
      .update(3, 8, 5)
    println(table)

    draw.draw(table)
  }
}

This produced expected image. Hope this helps!


问:
How to multiply array elements by condition
I have a array and want to multiply the elements greater than 9 by 2 and lesser than or equal to 9 by 3.

```<code>  List<Integer> list = Arrays.asList(3, 6, 9, 12, 15);
  list.stream().map(number -> number * 3).forEach(System.out::println);
</code>```

This one multiplies everything by 3 , where

```<code>list.stream().filter(number -> number>3).map(number -> number * 3).forEach(System.out::println);
</code>```

this one multiplies but also filters.

I want 3 ,6 ,9 multiplied by 3 and 12, 15 multiplied by 2.

Any help is appreciated.

答:
In case someone don't like the ternary operator in Eran's answer, you could use a block instead, like this:

```<code>list.stream()
  .map(n -> {
     if (n > 9){
        return n * 2;
      }
      else {
        return n * 3;
      }
    })
  .forEach(System.out::println);
</code>```

I think the solution with ternary operator is cleaner in this specific case but this is an option as well. It might be useful if there are more conditions.

Body:
I have a array and want to multiply the elements greater than 9 by 2 and lesser than or equal to 9 by 3.

  List<Integer> list = Arrays.asList(3, 6, 9, 12, 15);
  list.stream().map(number -> number * 3).forEach(System.out::println);

This one multiplies everything by 3 , where

list.stream().filter(number -> number>3).map(number -> number * 3).forEach(System.out::println);

this one multiplies but also filters.

I want 3 ,6 ,9 multiplied by 3 and 12, 15 multiplied by 2.

Any help is appreciated.

Body:
In case someone don't like the ternary operator in Eran's answer, you could use a block instead, like this:

list.stream()
  .map(n -> {
     if (n > 9){
        return n * 2;
      }
      else {
        return n * 3;
      }
    })
  .forEach(System.out::println);

I think the solution with ternary operator is cleaner in this specific case but this is an option as well. It might be useful if there are more conditions.


问:
Generic XQuery to recursively traverse the XML
I am trying to convert the XML input given below to the output format using generic Xquery without calling any parent/child elements. If the parent has two or more recurring child then that should be grouped as an array.

XML:

```<code><root>
<name>xxx</name>
<id>1</id>
<tasks>
    <job>
        <id>1</id>
        <val>2</val>
    </job>
    <job>
        <id>2</id>
        <val>12</val>
    </job>
    <job>
        <id>3</id>
        <val>22</val>
    </job>
</tasks>
</root>
</code>```

Expected result:

```<code><map>
<string key="name">xxx</string>
<string key="id">1</string>
<array key="tasks">
    <map key="job">
        <string key="id">1</string>
        <string key="val">2</string>
    </map>
    <map key="job">
        <string key="id">2</string>
        <string key="val">12</string>
    </map>
    <map key="job">
        <string key="id">3</string>
        <string key="val">22</string>
    </map>
</array>
</map>
</code>```

XQuery I tried:

```<code>declare default element namespace "http://www.w3.org/2005/xpath-functions";
for $a in /*[1]
let $retval :=
<map>
    {
    for $z in $a//*
    return if ($z/*/text()) then
    (
    <map>
        {
        for $zz in $z/child::*
        return if ($zz/text()) then
        (
        <string key="{lower-case(name($zz))}">{data($zz)}</string>
        )
        else ()
        }</map>
    )
    else ()
    }
</map>
return $retval
</code>```

答:
You can try this

```<code>declare function local:create_structure($child)
{
    for $input in $child
    return
        element {
            (if ($input/*/*) then
                'array'
            else
                if ($input/*) then
                    'map'
                else
                    'string')
        } {
            attribute {'key'} {local-name($input)},
            if ($input/*) then
                local:create_structure($input/*)
            else
                $input/node()
        }
};

let $Output := <map>{local:create_structure(/*)}</map>
return
    $Output
</code>```

See Transformation at https://xqueryfiddle.liberty-development.net/bFDbxkW/1

Body:
I am trying to convert the XML input given below to the output format using generic Xquery without calling any parent/child elements. If the parent has two or more recurring child then that should be grouped as an array.

XML:

<root>
<name>xxx</name>
<id>1</id>
<tasks>
    <job>
        <id>1</id>
        <val>2</val>
    </job>
    <job>
        <id>2</id>
        <val>12</val>
    </job>
    <job>
        <id>3</id>
        <val>22</val>
    </job>
</tasks>
</root>

Expected result:

<map>
<string key="name">xxx</string>
<string key="id">1</string>
<array key="tasks">
    <map key="job">
        <string key="id">1</string>
        <string key="val">2</string>
    </map>
    <map key="job">
        <string key="id">2</string>
        <string key="val">12</string>
    </map>
    <map key="job">
        <string key="id">3</string>
        <string key="val">22</string>
    </map>
</array>
</map>

XQuery I tried:

declare default element namespace "http://www.w3.org/2005/xpath-functions";
for $a in /*[1]
let $retval :=
<map>
    {
    for $z in $a//*
    return if ($z/*/text()) then
    (
    <map>
        {
        for $zz in $z/child::*
        return if ($zz/text()) then
        (
        <string key="{lower-case(name($zz))}">{data($zz)}</string>
        )
        else ()
        }</map>
    )
    else ()
    }
</map>
return $retval

Body:
You can try this

declare function local:create_structure($child)
{
    for $input in $child
    return
        element {
            (if ($input/*/*) then
                'array'
            else
                if ($input/*) then
                    'map'
                else
                    'string')
        } {
            attribute {'key'} {local-name($input)},
            if ($input/*) then
                local:create_structure($input/*)
            else
                $input/node()
        }
};

let $Output := <map>{local:create_structure(/*)}</map>
return
    $Output

See Transformation at https://xqueryfiddle.liberty-development.net/bFDbxkW/1


问:
How to generate uniformly distributed random numbers between 0 and 1 in a C code using OpenMP?
I am trying to write an OpenMP code in which each thread will work on big arrays of uniformly distributed random numbers between 0 and 1. Each thread needs to have different and independent random number distributions. In addition, the random number distributions need to be different every time the code is called. This is what I am using right now. Does this always guarantee each thread has its own/different random number sequences? Will the sequences be different every time the code is called? What is the correct way of doing this? The following code has each thread generating 5 samples but in an actual run it will be order of millions.</p>

```<code>#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
#include <time.h>

int main(int argc, char* argv[])
{
    int numthreads,i;
    #pragma omp parallel private(i)
    {
        int id;
        id=omp_get_thread_num();
        if(id==0) numthreads = omp_get_num_threads();
        printf("thread %d \n",id);
        srand(time(0)^omp_get_thread_num());
        for (i=0; i<5; i++)
        {
            printf("thread %d: %d %.6f \n",id,i,(double)rand()/(double)RAND_MAX);
        }
    }
    return 0;
}
</code>```

答:
Ideally you should use a random number generator which is designed for parallel use, where you can guarantee that each thread is sampling a different part of the random number sequence. (Providing arbitrary but different seeds to most generators does not guarantee that, since they make no guarantees about how the choice of seed affects where in the sequence you are. Thus you might just be offset by one.)

I suggest that you read the Parallel Random Numbers as Easy as 1,2,3 paper, and then use one of their algorithms, which are implemented in, for instance, Intel MKL (which is available free to everyone).

(MKL supports :-

Philox4x32-10 counter-based pseudorandom number generator with a
period of 2**128 PHILOX4X32X10[Salmon11].

ARS-5 counter-based pseudorandom number generator with a period of 2**128, which uses instructions from the AES-NI set
ARS5[Salmon11].
)

By using that you can trivially ensure that each thread's generator will generate an independent sequence so you are not sampling the same series in multiple threads.

Intel MKL can be downloaded from https://software.intel.com/en-us/mkl/choose-download

Body:
I am trying to write an OpenMP code in which each thread will work on big arrays of uniformly distributed random numbers between 0 and 1. Each thread needs to have different and independent random number distributions. In addition, the random number distributions need to be different every time the code is called. This is what I am using right now. Does this always guarantee each thread has its own/different random number sequences? Will the sequences be different every time the code is called? What is the correct way of doing this? The following code has each thread generating 5 samples but in an actual run it will be order of millions.

#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
#include <time.h>

int main(int argc, char* argv[])
{
    int numthreads,i;
    #pragma omp parallel private(i)
    {
        int id;
        id=omp_get_thread_num();
        if(id==0) numthreads = omp_get_num_threads();
        printf("thread %d \n",id);
        srand(time(0)^omp_get_thread_num());
        for (i=0; i<5; i++)
        {
            printf("thread %d: %d %.6f \n",id,i,(double)rand()/(double)RAND_MAX);
        }
    }
    return 0;
}