问:
Login to windows domain on Linux container
My company is exclusively using Windows machines and when I login to the windows domain it gives me access to some shared drives and databases.
Now I would like to run R in a container, for instance following tutorial
https://ropenscilabs.github.io/r-docker-tutorial/02-Launching-Docker.html

My question is the following: is there a way that my R scripts executed in this container inherit from the permissions of the host OS?
It seems especially tricky for access to MSSQL databases that are using Windows authentication.....

答:
As @Technophobe01 has shown a windows container would be a more natural fit for inheriting AD permissions.

In terms of getting the R script connected to your file shares and MS SQL Databases I would recommend the following

MS SQL Connection

Connect to databases using connection strings in the R script

This is a conventional approach rather than inheriting some permissions.

See SQL Server RODBC Connection

```<code>library(RODBC)
conn <- odbcDriverConnect('driver={SQL Server};server=mysqlhost;database=mydbname;uid=user;pwd=pwd')
</code>```

You can specify any sensitive fields using ENV vars at deploy time or docker secrets and load them into the R script.

File Shares

See https://blogs.msdn.microsoft.com/stevelasker/2016/06/14/configuring-docker-for-windows-volumes/

1. Map the network drives onto your Windows docker host

2. Specify them as available to containers in docker settings, you will need to add a new user account with admin privileges.

3. Assuming network drive is mapped to d:

   docker run -v d:/somedata:/data <container> ls /data
  will mount the drive in the container at /data and list its contents.

Body:
As @Technophobe01 has shown a windows container would be a more natural fit for inheriting AD permissions.

In terms of getting the R script connected to your file shares and MS SQL Databases I would recommend the following

MS SQL Connection

Connect to databases using connection strings in the R script

This is a conventional approach rather than inheriting some permissions.

See SQL Server RODBC Connection

library(RODBC)
conn <- odbcDriverConnect('driver={SQL Server};server=mysqlhost;database=mydbname;uid=user;pwd=pwd')

You can specify any sensitive fields using ENV vars at deploy time or docker secrets and load them into the R script.

File Shares

See https://blogs.msdn.microsoft.com/stevelasker/2016/06/14/configuring-docker-for-windows-volumes/

1. Map the network drives onto your Windows docker host

2. Specify them as available to containers in docker settings, you will need to add a new user account with admin privileges.

3. Assuming network drive is mapped to d:

   docker run -v d:/somedata:/data <container> ls /data
  will mount the drive in the container at /data and list its contents.


来源: stackexchange

问:
Finding and updating XML node in Powershell
I have the following XML node in my XML document that I need to update:

```<code><ImageUrl>xxx.xxx.com/imageeditor/X.jpg</ImageUrl>
</code>```

With the following:

```<code><ImageUrl>xxx.xxx.com/image/getdvimage/X/1/false/200/200/</ImageUrl>
</code>```

where "X" in the first string is a number (9808 for example) and needs to be in the place of "X" in the second node.  This is the only node called ImageUrl in the document, and I need to update the whole document this way. So I need help finding the X in the node and replacing it with the X in the updated node and saving the file.

I am trying this code:

```<code>[xml]$xml = Get-Content 'D:\temp\feed.xml'
Foreach ($item in (Select-XML -Xml $xml -XPath '//ImageUrl'))
{
    $oldValue = $item.node.innertext #need to get the value from the last "/" to the .jpg value
    $newValue = [string]::Format('xxx.xxx.com/image/getdvimage/{0}/1/false/200/200/',$oldValue) #place the $oldValue into the new string here

    $item.node.Name = ???
}
$NewPath = 'D:\temp\FeedUpd.xml'
$xml.Save($NewPath)
</code>```

Here is the XML I am using:

```<code> <Product>
            <ExternalId>2127</ExternalId>
            <Name>test</Name>
                                <Description>
                <![CDATA[
               desc
                ]]></Description>
            <BrandExternalId>xxx</BrandExternalId>
            <CategoryExternalId>Foo</CategoryExternalId>
                                <ProductPageUrl><![CDATA[xxx.com/2127]]></ProductPageUrl>
                <ImageUrl>xxx.com/imageeditor/2127.jpg</ImageUrl>
            <ModelNumbers>
                <ModelNumber>2127</ModelNumber>
            </ModelNumbers>
            <ManufacturerPartNumbers>
                <ManufacturerPartNumber>2127</ManufacturerPartNumber>
            </ManufacturerPartNumbers>
            <UPCs>
                <UPC>841101002711</UPC>
            </UPCs>
        </Product>
</code>```

If I could pull the Model Number to insert into the new string {0} I wouldn't have to parse the old ImageUrl, just insert the Model into the string.  How would I grab the <ExternalId> and the <ImageUrl> in the loop to replace?

答:
I needed this done, so I just created a console application in c# that pull in the data and parsed it quickly for me. I used the XDocument and SelectNodes to pull in the data

```<code> XmlDocument doc = new XmlDocument();
        doc.Load(@"d:\temp\xxx.xml");
        XmlNode docElement = doc.DocumentElement;
        XmlNamespaceManager nsman = new XmlNamespaceManager(doc.NameTable);
        nsman.AddNamespace("ns", docElement.NamespaceURI);

        foreach (XmlNode row in doc.SelectNodes("//ns:Product", nsman))
        {
            string prodID = null;
            string ImageUrl = null;
            foreach (XmlNode childNode in row.ChildNodes)
            {
               //Process the node data here
            }
        }
        doc.Save(@"d:\temp\xxx.xml");
</code>```

Processed my 530 rows in less than a second.

ContentLicense: CC BY-SA 3.0

Body:
I have the following XML node in my XML document that I need to update:

<ImageUrl>xxx.xxx.com/imageeditor/X.jpg</ImageUrl>

With the following:

<ImageUrl>xxx.xxx.com/image/getdvimage/X/1/false/200/200/</ImageUrl>

where "X" in the first string is a number (9808 for example) and needs to be in the place of "X" in the second node.  This is the only node called ImageUrl in the document, and I need to update the whole document this way. So I need help finding the X in the node and replacing it with the X in the updated node and saving the file.

I am trying this code:

[xml]$xml = Get-Content 'D:\temp\feed.xml'
Foreach ($item in (Select-XML -Xml $xml -XPath '//ImageUrl'))
{
    $oldValue = $item.node.innertext #need to get the value from the last "/" to the .jpg value
    $newValue = [string]::Format('xxx.xxx.com/image/getdvimage/{0}/1/false/200/200/',$oldValue) #place the $oldValue into the new string here

    $item.node.Name = ???
}
$NewPath = 'D:\temp\FeedUpd.xml'
$xml.Save($NewPath)

Here is the XML I am using:

 <Product>
            <ExternalId>2127</ExternalId>
            <Name>test</Name>
                                <Description>
                <![CDATA[
               desc
                ]]></Description>
            <BrandExternalId>xxx</BrandExternalId>
            <CategoryExternalId>Foo</CategoryExternalId>
                                <ProductPageUrl><![CDATA[xxx.com/2127]]></ProductPageUrl>
                <ImageUrl>xxx.com/imageeditor/2127.jpg</ImageUrl>
            <ModelNumbers>
                <ModelNumber>2127</ModelNumber>
            </ModelNumbers>
            <ManufacturerPartNumbers>
                <ManufacturerPartNumber>2127</ManufacturerPartNumber>
            </ManufacturerPartNumbers>
            <UPCs>
                <UPC>841101002711</UPC>
            </UPCs>
        </Product>

If I could pull the Model Number to insert into the new string {0} I wouldn't have to parse the old ImageUrl, just insert the Model into the string.  How would I grab the <ExternalId> and the <ImageUrl> in the loop to replace?

Body:
I needed this done, so I just created a console application in c# that pull in the data and parsed it quickly for me. I used the XDocument and SelectNodes to pull in the data

 XmlDocument doc = new XmlDocument();
        doc.Load(@"d:\temp\xxx.xml");
        XmlNode docElement = doc.DocumentElement;
        XmlNamespaceManager nsman = new XmlNamespaceManager(doc.NameTable);
        nsman.AddNamespace("ns", docElement.NamespaceURI);

        foreach (XmlNode row in doc.SelectNodes("//ns:Product", nsman))
        {
            string prodID = null;
            string ImageUrl = null;
            foreach (XmlNode childNode in row.ChildNodes)
            {
               //Process the node data here
            }
        }
        doc.Save(@"d:\temp\xxx.xml");

Processed my 530 rows in less than a second.


问:
Alarm Even Application Closed in iPhone
I am working on iPhone application in which there is an option for Alarm. Is it possible to araise alarm even my application close.</p>

答: Use UILocalNotification to set the notifications. Then even your application is not in foreground you will get alerts.

ContentLicense: CC BY-SA 2.5

Title: Alarm Even Application Closed in iPhone


问:
Explicit instanciation of template linker error
I'm asking your help because I'm using templates and it seems like I misunderstood something.

Here's my code :

arbre.h

```<code>template<typename T>
class Arbre;

template<typename T>
class Noeud
{
    friend class Arbre<T>;

    public :

    Noeud();
    ~Noeud();
    T get_info()const;

    private :
    T info;
    Noeud<T> *fg, *fd;
};

template<typename T>
class Arbre
{
    public :
    //Constructors-------------------------------------------------------------
    Arbre();
    /*
      other function definitions
    */
}
</code>```

arbre.tpp

```<code>#include "arbre.h"

template <typename T>
Noeud<T>::Noeud(){
    fg = fd = 0;
}

template <typename T>
Noeud<T>::~Noeud(){
}
template <typename T>
T Noeud<T>::get_info()const{
    return info;
}

template <typename T>
Arbre<T>::Arbre(){
    racine = 0;
}
/*
  other function implementations...
*/
</code>```

The main.cpp includes "arbre.h" and creates an object like so :

```<code>Arbre<int> a;
</code>```

So following this article on explicit instantiation : http://www.cplusplus.com/forum/articles/14272/

I added those 2 lines at the end of arbre.tpp :

```<code>template class Noeud<int>;
template class Arbre<int>;
</code>```

So that the linker can compile the code for the int version of my object in arbre.o and so I could keep the implementation (arbre.tpp) apart from the header (arbre.h). My code worked with implicit instantiation (arbre.tpp included at the end of header.h) but I wanted to keep them apart.

I wonder why does the linking fail :

```<code>g++ -o main.o -c main.cpp -Wall -g -std=c++11
g++ -o arbre.o -c arbre.tpp -Wall -g -std=c++11
g++: warning: arbre.tpp: linker input file unused because linking not done
g++ -o arbre.out main.o arbre.o
g++: error: arbre.o: No such file or directory
Makefile:9: recipe for target 'arbre.out' failed
make: *** [arbre.out] Error 1
</code>```

Do you have any idea ? I'm doing the same thing as in the article I linked aren't I ?

Thanks in advance.

答:
File with template definition can not be compile separately and link. just try with the following:-

At the top of your main.ccp file include "arbre.tpp" like a header file, and compile only the main.cpp file and generate the exe.

In your main.cpp

```<code>#include"arbre.tpp"

$g++ main.cpp -o test
$./test (to run the application)
</code>```

Body:
I'm asking your help because I'm using templates and it seems like I misunderstood something.

Here's my code :

arbre.h

template<typename T>
class Arbre;

template<typename T>
class Noeud
{
    friend class Arbre<T>;

    public :

    Noeud();
    ~Noeud();
    T get_info()const;

    private :
    T info;
    Noeud<T> *fg, *fd;
};

template<typename T>
class Arbre
{
    public :
    //Constructors-------------------------------------------------------------
    Arbre();
    /*
      other function definitions
    */
}

arbre.tpp

#include "arbre.h"

template <typename T>
Noeud<T>::Noeud(){
    fg = fd = 0;
}

template <typename T>
Noeud<T>::~Noeud(){
}
template <typename T>
T Noeud<T>::get_info()const{
    return info;
}

template <typename T>
Arbre<T>::Arbre(){
    racine = 0;
}
/*
  other function implementations...
*/

The main.cpp includes "arbre.h" and creates an object like so :

Arbre<int> a;

So following this article on explicit instantiation : http://www.cplusplus.com/forum/articles/14272/

I added those 2 lines at the end of arbre.tpp :

template class Noeud<int>;
template class Arbre<int>;

So that the linker can compile the code for the int version of my object in arbre.o and so I could keep the implementation (arbre.tpp) apart from the header (arbre.h). My code worked with implicit instantiation (arbre.tpp included at the end of header.h) but I wanted to keep them apart.

I wonder why does the linking fail :

g++ -o main.o -c main.cpp -Wall -g -std=c++11
g++ -o arbre.o -c arbre.tpp -Wall -g -std=c++11
g++: warning: arbre.tpp: linker input file unused because linking not done
g++ -o arbre.out main.o arbre.o
g++: error: arbre.o: No such file or directory
Makefile:9: recipe for target 'arbre.out' failed
make: *** [arbre.out] Error 1

Do you have any idea ? I'm doing the same thing as in the article I linked aren't I ?

Thanks in advance.

Body:
File with template definition can not be compile separately and link. just try with the following:-

At the top of your main.ccp file include "arbre.tpp" like a header file, and compile only the main.cpp file and generate the exe.

In your main.cpp

#include"arbre.tpp"

$g++ main.cpp -o test
$./test (to run the application)


问:
Express - how to block invalid http methods?
I am getting invalid http methods (see below) which trigger timeout errors from my server as the route is valid. Is there any way to block all invalid requests in Express? I can't find anything on google.

答:
Take a whitelist approach

```<code>// before your other code check supported methods
// assuming these ones are, just add/remove ones to customize
if (!/^(GET|PUT|POST|DELETE)$/.test(req.method)) {
  res.status(400).end('bad request');
  return;
}

// your code goes here now
</code>```

or use middleware if using express

```<code>router.use((req, res, next) => {
  if (!/^(GET|PUT|POST|DELETE)$/.test(req.method)) {
    res.status(400).end('bad request');
    return;
  }
  next();
});
</code>```

In the words of Donald Rumsfeld...

Reports that say that something hasn't happened are always interesting to me, because as we know, there are known knowns; there are things we know we know. We also know there are known unknowns; that is to say we know there are some things we do not know. But there are also unknown unknowns – the ones we don't know we don't know. And if one looks throughout the history of our country and other free countries, it is the latter category that tend to be the difficult ones.

tl;dr Point being, you can only know what you know so use a whitelist.

Body:
Take a whitelist approach

// before your other code check supported methods
// assuming these ones are, just add/remove ones to customize
if (!/^(GET|PUT|POST|DELETE)$/.test(req.method)) {
  res.status(400).end('bad request');
  return;
}

// your code goes here now

or use middleware if using express

router.use((req, res, next) => {
  if (!/^(GET|PUT|POST|DELETE)$/.test(req.method)) {
    res.status(400).end('bad request');
    return;
  }
  next();
});

In the words of Donald Rumsfeld...

Reports that say that something hasn't happened are always interesting to me, because as we know, there are known knowns; there are things we know we know. We also know there are known unknowns; that is to say we know there are some things we do not know. But there are also unknown unknowns – the ones we don't know we don't know. And if one looks throughout the history of our country and other free countries, it is the latter category that tend to be the difficult ones.

tl;dr Point being, you can only know what you know so use a whitelist.

ContentLicense: CC BY-SA 4.0


问:
How to scroll a modal window in Capybara
I'm testing with Selenium WebDriver, RSpec and Capybara.

I let the program successfully fill in some fields in a modal window. Now I want to click on a button that is at the bottom of this modal window. At the first glance, I cannot see this button, so Capybara needs to scroll down in the modal window.

The two relevant code snippets of the webpage:

```<code><div class = “modal”> </div>
   <button class=”btn …..”> TextOnButton ::after </button>
</code>```

I tried:

```<code>within('.modal') do
      find('.btn', text: ‘TextOnButton').scrollIntoView(true)
end
</code>```

but received the error message.

Unable to find visible css ".btn" with text "TextOnButton"

I tried:

```<code>within('.modal’) do
       page.execute_script 'window.scrollBy(0,100)'
end
</code>```

but then he scrolls the main window but not the modal window.

答: I understand you are already executing code on the modal, but just wondering have you used driver.switchTo().window(handle) to switch to that modal first?</p>

Body:
I'm testing with Selenium WebDriver, RSpec and Capybara.

I let the program successfully fill in some fields in a modal window. Now I want to click on a button that is at the bottom of this modal window. At the first glance, I cannot see this button, so Capybara needs to scroll down in the modal window.

The two relevant code snippets of the webpage:

   <button class=”btn …..”> TextOnButton ::after </button>

I tried:

within('.modal') do
      find('.btn', text: ‘TextOnButton').scrollIntoView(true)
end

but received the error message.

Unable to find visible css ".btn" with text "TextOnButton"

I tried:

within('.modal’) do
       page.execute_script 'window.scrollBy(0,100)'
end

but then he scrolls the main window but not the modal window.


问:
Divide a dict by a number (int)
i have a problem, i have to create a fuction that divide my dict by a int.
This is my dict:

```<code>Counter({1: [9, 10, 1], 2: [5, 1, 1, 2, 1, 1, 9, 1, 1, 1, 3, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 10, 1, 1, 1, 1, 1, 3, 1, 1, 2, 1, 1, 1, 3, 4, 1, 1, 1, 3, 1, 4, 1, 1, 1, 1], 0: [1, 5, 1, 1, 2, 10, 1, 2, 1, 2, 2, 1, 1]})
</code>```

And this is my function:

```<code>def probabilitacondizionata(lista, sommafreq):
    lista= {k: v / sommafreq for k, v in lista.items()}
    return lista
</code>```

And this is the function, which sum the value(int) sommafreq:

```<code>def sommafrequenze(lista):
    sommafreq= sum(lista.values())
    return sommafreq
</code>```

This instruction gives me this error: unsupported operand type(s) for /: 'dict_values' and 'int' ..

The output i would is like:

```<code>Counter({1: [9/sommafreq, 10/sommafreq, 1/sommafreq], 2: [5/sommafreq, 1sommafreq, 1/sommafreq, 2/sommafreq, 1/sommafreq, 1/sommafreq, 9, 1, 1, 1, 3, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 10, 1, 1, 1, 1, 1, 3, 1, 1, 2, 1, 1, 1, 3, 4, 1, 1, 1, 3, 1, 4, 1, 1, 1, 1], 0: [1, 5, 1, 1, 2, 10, 1, 2, 1, 2, 2, 1, 1]})
</code>```

and keep on going to divide all.. Sorry for my bad english and thanks in advance!

Edit: My previous functions:

```<code>def ricercafrequenze(trainspam, testspam):
    filtratespam=Counter()
    filtratespam ={k:v for (k,v) in trainspam.items() if k in testspam}

    return filtratespam
    #main
def ricerchefrequenzeinlista(lista1,lista2):
    lista=Counter()
    i=0
    while i < len(lista2):
       lista[i]=(ricercafrequenze(lista1, lista2[i]))
       i+=1
    return lista

Counter({0: {'offer': 1, 'time': 5, 'discount': 1, 'one': 1, 'th': 2, 'subject': 10, 'special': 1, 'need': 2, 'price': 1, 'order': 2, 'product': 2, 'per': 1, 'today': 1}, 1: {'us': 9, 'subject': 10, 'buy': 1}, 2: {'time': 5, 'realist': 1, 'quickli': 1, 'give': 2, 'go': 1, 'thoma': 1, 'us': 9, 'let': 1, 'aruba': 1, 'natur': 1, 'b': 3, 'length': 1, 'ca': 1, 'one': 1, 'know': 2, 'life': 1, 'think': 1, 'girlfriend': 1, 'use': 2, 'stronger': 1, 'press': 1, 'longer': 1, 'fl': 1, 'po': 1, 'partner': 1, 'subject': 10, 'presid': 1, 'save': 1, 'nearli': 1, 'stud': 1, 'short': 1, 'everi': 3, 'gain': 1, 'citi': 1, 'product': 2, 'said': 1, 'increas': 1, 'month': 1, 'unit': 3, 'want': 4, 'must': 1, 'sex': 1, 'pleasur': 1, 'result': 3, 'matt': 1, 'name': 4, 'love': 1, 'bigger': 1, 'visitor': 1, 'oranjestad': 1}})
</code>```

答:
I often wanted to do this type of thing without using dict comprehensions. BetterDict is a little project of mine that extends Python dicts/Counters/defaultdicts/OrderedDicts, allowing them to be merged, or used in arithmetic with scalars or other dicts.
eg</p>

```<code>>>> raw_counts = BetterDict({'the': 1432, 'she': 600, 'wookie': 25})
>>> total = 10000.
>>> relative_freqs = raw_counts / total
>>> print(relative_freqs)
{'she': 0.06, 'the': 0.1432, 'wookie': 0.0025}
</code>```

Title: Divide a dict by a number (int)

Body:
i have a problem, i have to create a fuction that divide my dict by a int.
This is my dict:

Counter({1: [9, 10, 1], 2: [5, 1, 1, 2, 1, 1, 9, 1, 1, 1, 3, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 10, 1, 1, 1, 1, 1, 3, 1, 1, 2, 1, 1, 1, 3, 4, 1, 1, 1, 3, 1, 4, 1, 1, 1, 1], 0: [1, 5, 1, 1, 2, 10, 1, 2, 1, 2, 2, 1, 1]})

And this is my function:

def probabilitacondizionata(lista, sommafreq):
    lista= {k: v / sommafreq for k, v in lista.items()}
    return lista

And this is the function, which sum the value(int) sommafreq:

def sommafrequenze(lista):
    sommafreq= sum(lista.values())
    return sommafreq

This instruction gives me this error: unsupported operand type(s) for /: 'dict_values' and 'int' ..

The output i would is like:

Counter({1: [9/sommafreq, 10/sommafreq, 1/sommafreq], 2: [5/sommafreq, 1sommafreq, 1/sommafreq, 2/sommafreq, 1/sommafreq, 1/sommafreq, 9, 1, 1, 1, 3, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 10, 1, 1, 1, 1, 1, 3, 1, 1, 2, 1, 1, 1, 3, 4, 1, 1, 1, 3, 1, 4, 1, 1, 1, 1], 0: [1, 5, 1, 1, 2, 10, 1, 2, 1, 2, 2, 1, 1]})

and keep on going to divide all.. Sorry for my bad english and thanks in advance!

Edit: My previous functions:

def ricercafrequenze(trainspam, testspam):
    filtratespam=Counter()
    filtratespam ={k:v for (k,v) in trainspam.items() if k in testspam}

    return filtratespam
    #main
def ricerchefrequenzeinlista(lista1,lista2):
    lista=Counter()
    i=0
    while i < len(lista2):
       lista[i]=(ricercafrequenze(lista1, lista2[i]))
       i+=1
    return lista

Counter({0: {'offer': 1, 'time': 5, 'discount': 1, 'one': 1, 'th': 2, 'subject': 10, 'special': 1, 'need': 2, 'price': 1, 'order': 2, 'product': 2, 'per': 1, 'today': 1}, 1: {'us': 9, 'subject': 10, 'buy': 1}, 2: {'time': 5, 'realist': 1, 'quickli': 1, 'give': 2, 'go': 1, 'thoma': 1, 'us': 9, 'let': 1, 'aruba': 1, 'natur': 1, 'b': 3, 'length': 1, 'ca': 1, 'one': 1, 'know': 2, 'life': 1, 'think': 1, 'girlfriend': 1, 'use': 2, 'stronger': 1, 'press': 1, 'longer': 1, 'fl': 1, 'po': 1, 'partner': 1, 'subject': 10, 'presid': 1, 'save': 1, 'nearli': 1, 'stud': 1, 'short': 1, 'everi': 3, 'gain': 1, 'citi': 1, 'product': 2, 'said': 1, 'increas': 1, 'month': 1, 'unit': 3, 'want': 4, 'must': 1, 'sex': 1, 'pleasur': 1, 'result': 3, 'matt': 1, 'name': 4, 'love': 1, 'bigger': 1, 'visitor': 1, 'oranjestad': 1}})

Body:
I often wanted to do this type of thing without using dict comprehensions. BetterDict is a little project of mine that extends Python dicts/Counters/defaultdicts/OrderedDicts, allowing them to be merged, or used in arithmetic with scalars or other dicts.
eg

>>> raw_counts = BetterDict({'the': 1432, 'she': 600, 'wookie': 25})
>>> total = 10000.
>>> relative_freqs = raw_counts / total
>>> print(relative_freqs)
{'she': 0.06, 'the': 0.1432, 'wookie': 0.0025}


问:
Dealing with bugs that only appear right after boot
I dealt with a bug today that only appeared when I ran my program right after booting my computer.  The cold start exposed a race condition which triggered the bug.  I managed to fix it, but it took a long time because I had to reboot my machine several times to figure out what was going on.  Can anybody suggest better ways of debugging problems like this in the future?  Can I somehow quickly put the computer into a "just booted" state?

Running Python 2.6 on Windows XP.

答: Use virtual machine (f.e. VirtualBox) and save state (make snapshot) just before booting is finished. Test freely and restore just booted state according to your needs.


问:
how to make pseudo element visible and clickable using css on firefox
I have a button followed by a pseudo element. The button displays 'next' and the pseudo element displays '>'. This is used for pagination.

I have hidden the button but made the pseudo element visible by using css properties

```<code>button{
    visibility: hidden;
}
button::pseudoElement{
    visibility: visible;
}
</code>```

Now the button is hidden and element is visible. It is also clickable. It works in chrome,safari and ie. But it does not click on firefox. What do I change?

EDIT
This hack worked

```<code>  button{
        color: transparent;
    }
    button::pseudoElement{
        color: black;
    }
</code>```

Any better approach?

答:
Pseudo elements aren't actually inserted before or after the element itself. They are inserted as the first/last child element. So if you hide the "parent" element, their ::before/::after pseudo elements will be hidden as well.

In your case, I would just do the old text-indent: -9999px or font-size: 0 trick on the parent element and reset the pseudo element (text-indent: 0).

With your color: transparent solution, the element will retain its size. With the text-indent trick it's just using the space the pseudo element needs.

Body:
I have a button followed by a pseudo element. The button displays 'next' and the pseudo element displays '>'. This is used for pagination.

I have hidden the button but made the pseudo element visible by using css properties

button{
    visibility: hidden;
}
button::pseudoElement{
    visibility: visible;
}

Now the button is hidden and element is visible. It is also clickable. It works in chrome,safari and ie. But it does not click on firefox. What do I change?

EDIT
This hack worked

  button{
        color: transparent;
    }
    button::pseudoElement{
        color: black;
    }

Any better approach?


问:
Typo3 Bootstrap Package 7.1 / missing option "Pic in Text" / "Bild im Text"
since updating Bootstrap package to 7.1 we miss the option to have the textflow around our pictures.

is there a way to reactivate this feature..

regards
Leo

答:
Take a look at /Configuration/PageTS/TCEFORM.txt :

```<code>TCEFORM.tt_content.imageorient.removeItems = 1,2,9,10,17,18
</code>```

I think you could restore the values you want by overriding this setting.

Body:
Take a look at /Configuration/PageTS/TCEFORM.txt :

TCEFORM.tt_content.imageorient.removeItems = 1,2,9,10,17,18

I think you could restore the values you want by overriding this setting.


问:
Nginx 404 or default page
I've developed an Angular 2 app on my mac and have it running locally using Nginx as the websever. I'm having trouble now that I'm deploying this onto an AWS EC2 instance. It's a Linux Red Hat 7 instance.

I've installed Nginx and copied my working config from my mac, making sure to change the server_name value and root, but I either get the default nginx page or 404 errors.

I have setup my app at /var/www/dist and given chmod 755 permissions to that path and files in dist. Below is my config (note the angle brackets for server_name aren't in the actual config, I'm just hiding the instance name for this post).

Any attempt at myhost/index.html or myhost/someapppath all return 404. Using myhost/ returns the default nginx page. I've even tried checking my root by creating the html dir and putting a file there to test but even that doesn't get picked up. I've restarted nginx after each config too but still get the same.

Any ideas?

```<code>user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;
    server_names_hash_bucket_size 128;
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                  '$status $body_bytes_sent "$http_referer" '
                  '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       80;
        server_name  <hiding instance for this post>.ap-southeast-2.compute.amazonaws.com;
        root /var/www/dist;
        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            index  index.html index.htm;
            try_files $uri $uri$args $uri/index.html /index.html =404;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
       error_page   500 502 503 504  /50x.html;
       location = /50x.html {
         root   html;
       }

    # proxy the PHP scripts to Apache listening on 127.0.0.1:80
    #
    #location ~ \.php$ {
    #    proxy_pass   http://127.0.0.1;
    #}

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    #location ~ \.php$ {
    #    root           html;
    #    fastcgi_pass   127.0.0.1:9000;
    #    fastcgi_index  index.php;
    #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
    #    include        fastcgi_params;
    #}

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /\.ht {
    #    deny  all;
    #}
}
#include /etc/nginx/conf.d/*.conf;
}
</code>```

UPDATE

After tinkering with the config again and then looking at the error logs I now see the following:

2017/11/16 17:12:14 [crit] 23126#23126: *2 stat() "/var/www/dist/index.html" failed (13: Permission denied)

This makes more sense. I've ran sudo chown nginx: var/ and sudo chown -R nginx: /var/www for the nginx user and restarted nginx but I still get permission denied. Am I setting the permissions correctly?

答:
Fixed it, very tricky issue. Solved using comment from @jsina in this post: https://stackoverflow.com/a/36389001/2313746.

Effectively, if you mv a directory from /home it doesn't update the context for permissions.

Title: Nginx 404 or default page

Body:
I've developed an Angular 2 app on my mac and have it running locally using Nginx as the websever. I'm having trouble now that I'm deploying this onto an AWS EC2 instance. It's a Linux Red Hat 7 instance.

I've installed Nginx and copied my working config from my mac, making sure to change the server_name value and root, but I either get the default nginx page or 404 errors.

I have setup my app at /var/www/dist and given chmod 755 permissions to that path and files in dist. Below is my config (note the angle brackets for server_name aren't in the actual config, I'm just hiding the instance name for this post).

Any attempt at myhost/index.html or myhost/someapppath all return 404. Using myhost/ returns the default nginx page. I've even tried checking my root by creating the html dir and putting a file there to test but even that doesn't get picked up. I've restarted nginx after each config too but still get the same.

Any ideas?

user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;
    server_names_hash_bucket_size 128;
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                  '$status $body_bytes_sent "$http_referer" '
                  '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       80;
        server_name  <hiding instance for this post>.ap-southeast-2.compute.amazonaws.com;
        root /var/www/dist;
        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            index  index.html index.htm;
            try_files $uri $uri$args $uri/index.html /index.html =404;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
       error_page   500 502 503 504  /50x.html;
       location = /50x.html {
         root   html;
       }

    # proxy the PHP scripts to Apache listening on 127.0.0.1:80
    #
    #location ~ \.php$ {
    #    proxy_pass   http://127.0.0.1;
    #}

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    #location ~ \.php$ {
    #    root           html;
    #    fastcgi_pass   127.0.0.1:9000;
    #    fastcgi_index  index.php;
    #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
    #    include        fastcgi_params;
    #}

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /\.ht {
    #    deny  all;
    #}
}
#include /etc/nginx/conf.d/*.conf;
}

UPDATE

After tinkering with the config again and then looking at the error logs I now see the following:

2017/11/16 17:12:14 [crit] 23126#23126: *2 stat() "/var/www/dist/index.html" failed (13: Permission denied)

This makes more sense. I've ran sudo chown nginx: var/ and sudo chown -R nginx: /var/www for the nginx user and restarted nginx but I still get permission denied. Am I setting the permissions correctly?


问:
Using webrtc-58 in Android NDK project - "Undefined reference to CopyOnWriteBuffer" when building with QT
I am trying to build a shared library for Android NDK which is referencing libjingle_peerconnection.so built for Android from webrtc-58, but linker errors appearing:

```<code>MyProject\Libs\webrtc-58\include\webrtc\api\datachannelinterface.h:64: error: undefined reference to 'rtc::CopyOnWriteBuffer::~CopyOnWriteBuffer()'
MyProject\Libs\webrtc-58\include\webrtc\base\copyonwritebuffer.h:48: error: undefined reference to 'rtc::CopyOnWriteBuffer::CopyOnWriteBuffer(unsigned int, unsigned int)'
</code>```

The same output I have building the project on Ubuntu as well as  Windows. When building on Ubuntu, I configured QT Creator to use Android SDK/NDK from webrtc build tools(which were used to build the libjingle_peerconnection

QT Creator 4.4.1 on Qt5.9.2
 webrtc-58 was built on Ubuntu using follwoing configuration

```<code>gn gen out/Debug/arm-v7 --args='target_os="android" is_component_build=false rtc_include_tests=false target_cpu="arm"'
</code>```

I've dumped the unstripped libjingle_peerconnection.so and noticed that contains CopyOnWriteBuffer class implementation:

```<code>001b2bbd t void rtc::CopyOnWriteBuffer::AppendData<unsigned char, (void*)0>(unsigned char const*, unsigned int)
000ee055 t rtc::CopyOnWriteBuffer::EnsureCapacity(unsigned int)
000edf51 t rtc::CopyOnWriteBuffer::CloneDataIfReferenced(unsigned int)
000fafd9 t char* rtc::CopyOnWriteBuffer::data<char, (void*)0>()
000fae61 t unsigned char* rtc::CopyOnWriteBuffer::data<unsigned char, (void*)0>()
000eddcd t rtc::CopyOnWriteBuffer::Clear()
00092cd1 t void rtc::CopyOnWriteBuffer::SetData<char, (void*)0>(char const*, unsigned int)
00092cd1 t void rtc::CopyOnWriteBuffer::SetData<unsigned char, (void*)0>(unsigned char const*, unsigned int)
000edb4d t rtc::CopyOnWriteBuffer::SetSize(unsigned int)
000fad19 t rtc::CopyOnWriteBuffer::operator=(rtc::CopyOnWriteBuffer&&)
000ed6f1 t rtc::CopyOnWriteBuffer::CopyOnWriteBuffer(unsigned int)
000ed7d9 t rtc::CopyOnWriteBuffer::CopyOnWriteBuffer(unsigned int, unsigned int)
000ed6e1 t rtc::CopyOnWriteBuffer::CopyOnWriteBuffer(rtc::CopyOnWriteBuffer&&)
0003462f t rtc::CopyOnWriteBuffer::CopyOnWriteBuffer(rtc::CopyOnWriteBuffer const&)
0002f1f7 t rtc::CopyOnWriteBuffer::CopyOnWriteBuffer()
000faa35 t rtc::CopyOnWriteBuffer::CopyOnWriteBuffer<char, (void*)0>(char const*, unsigned int)
000ed6f1 t rtc::CopyOnWriteBuffer::CopyOnWriteBuffer(unsigned int)
000ed7d9 t rtc::CopyOnWriteBuffer::CopyOnWriteBuffer(unsigned int, unsigned int)
000ed6e1 t rtc::CopyOnWriteBuffer::CopyOnWriteBuffer(rtc::CopyOnWriteBuffer&&)
0003462f t rtc::CopyOnWriteBuffer::CopyOnWriteBuffer(rtc::CopyOnWriteBuffer const&)
0002f1f7 t rtc::CopyOnWriteBuffer::CopyOnWriteBuffer()
000faa35 t rtc::CopyOnWriteBuffer::CopyOnWriteBuffer<char, (void*)0>(char const*, unsigned int)
0003452d t rtc::CopyOnWriteBuffer::~CopyOnWriteBuffer()
0003452d t rtc::CopyOnWriteBuffer::~CopyOnWriteBuffer()
</code>```

Content of the MYPROJECT_Core.Pro

```<code>QT  += core xml
QT  -= gui

TARGET = MYPROJECT_Core
TEMPLATE = lib

DEFINES += MYPROJECT_CORE_LIBRARY

DEFINES += QT_DEPRECATED_WARNINGS
DEFINES += NOMINMAX
DEFINES += ENABLE_RTC_EVENT_LOG

QMAKE_CFLAGS_WARN_ON -= -Wall
QMAKE_CXXFLAGS_WARN_ON -= -Wall
CONFIG += warn_off

android {
    CONFIG += c++11
    QMAKE_CXXFLAGS += -std=c++11

    DEFINES += NDEBUG=1
    DEFINES += WEBRTC_POSIX
    DEFINES += WEBRTC_ANDROID

    LIBS += -L$$PWD/../Libs/webrtc-58/lib/android/armeabi-v7a/jni/armeabi-v7a -ljingle_peerconnection_so
    INCLUDEPATH += $$PWD/../Libs/webrtc-58/include
    DEPENDPATH += $$PWD/../Libs/webrtc-58/include
}

SOURCES += \
    main.cpp \
</code>```

答:
My colleague solved this problem today.
He replaced libjingle_peerconnection.so with another libraries from webrtc build output

```<code>obj/webrtc/api/libjingle_peerconnection_api.a
ob/webrtc/base/librtc_base_approved.a
</code>```

Also there was a compatibility problem with QT Android Kit and webrtc build system, so Android Kit is building with gnustl, while webrtc was build with libc++, so he included libc++_shared.so from Android NDK bundle.
Entire Pro file will look like this

```<code>QT       -= gui

TARGET = WebRtcDependantLib
TEMPLATE = lib

#CONFIG += c++11
QMAKE_CXXFLAGS += -fno-rtti -fno-exceptions
DEFINES += MY_TEST_LIBRARY

android {
    DEFINES += WEBRTC_POSIX
    DEFINES += WEBRTC_ANDROID

    DEFINES += NDEBUG

    WEBRTC = /home/user/Dev/src  #WEBRTC-M58 sources directory
    WEBRTCBUILD = $$WEBRTC/out/Debug/arm-v7/obj
    #android NDK bundled by webrtc build system
    WEBRTCNDK = $$WEBRTC/third_party/android_tools/ndk

    LIBS += -Wl,--start-group
    LIBS += $$WEBRTCBUILD/webrtc/api/libjingle_peerconnection_api.a
    LIBS += $$WEBRTCBUILD/webrtc/base/librtc_base_approved.a
    LIBS += -Wl,--end-group

    LIBS += $$WEBRTCNDK/sources/cxx-stl/llvm-libc++/libs/armeabi-v7a/libc++_shared.so

    INCLUDEPATH += $$WEBRTC
    DEPENDPATH += $$WEBRTC
}
SOURCES += \
        main.cpp
</code>```

Body:
I am trying to build a shared library for Android NDK which is referencing libjingle_peerconnection.so built for Android from webrtc-58, but linker errors appearing:

MyProject\Libs\webrtc-58\include\webrtc\api\datachannelinterface.h:64: error: undefined reference to 'rtc::CopyOnWriteBuffer::~CopyOnWriteBuffer()'
MyProject\Libs\webrtc-58\include\webrtc\base\copyonwritebuffer.h:48: error: undefined reference to 'rtc::CopyOnWriteBuffer::CopyOnWriteBuffer(unsigned int, unsigned int)'

The same output I have building the project on Ubuntu as well as  Windows. When building on Ubuntu, I configured QT Creator to use Android SDK/NDK from webrtc build tools(which were used to build the libjingle_peerconnection

QT Creator 4.4.1 on Qt5.9.2
 webrtc-58 was built on Ubuntu using follwoing configuration

gn gen out/Debug/arm-v7 --args='target_os="android" is_component_build=false rtc_include_tests=false target_cpu="arm"'

I've dumped the unstripped libjingle_peerconnection.so and noticed that contains CopyOnWriteBuffer class implementation:

001b2bbd t void rtc::CopyOnWriteBuffer::AppendData<unsigned char, (void*)0>(unsigned char const*, unsigned int)
000ee055 t rtc::CopyOnWriteBuffer::EnsureCapacity(unsigned int)
000edf51 t rtc::CopyOnWriteBuffer::CloneDataIfReferenced(unsigned int)
000fafd9 t char* rtc::CopyOnWriteBuffer::data<char, (void*)0>()
000fae61 t unsigned char* rtc::CopyOnWriteBuffer::data<unsigned char, (void*)0>()
000eddcd t rtc::CopyOnWriteBuffer::Clear()
00092cd1 t void rtc::CopyOnWriteBuffer::SetData<char, (void*)0>(char const*, unsigned int)
00092cd1 t void rtc::CopyOnWriteBuffer::SetData<unsigned char, (void*)0>(unsigned char const*, unsigned int)
000edb4d t rtc::CopyOnWriteBuffer::SetSize(unsigned int)
000fad19 t rtc::CopyOnWriteBuffer::operator=(rtc::CopyOnWriteBuffer&&)
000ed6f1 t rtc::CopyOnWriteBuffer::CopyOnWriteBuffer(unsigned int)
000ed7d9 t rtc::CopyOnWriteBuffer::CopyOnWriteBuffer(unsigned int, unsigned int)
000ed6e1 t rtc::CopyOnWriteBuffer::CopyOnWriteBuffer(rtc::CopyOnWriteBuffer&&)
0003462f t rtc::CopyOnWriteBuffer::CopyOnWriteBuffer(rtc::CopyOnWriteBuffer const&)
0002f1f7 t rtc::CopyOnWriteBuffer::CopyOnWriteBuffer()
000faa35 t rtc::CopyOnWriteBuffer::CopyOnWriteBuffer<char, (void*)0>(char const*, unsigned int)
000ed6f1 t rtc::CopyOnWriteBuffer::CopyOnWriteBuffer(unsigned int)
000ed7d9 t rtc::CopyOnWriteBuffer::CopyOnWriteBuffer(unsigned int, unsigned int)
000ed6e1 t rtc::CopyOnWriteBuffer::CopyOnWriteBuffer(rtc::CopyOnWriteBuffer&&)
0003462f t rtc::CopyOnWriteBuffer::CopyOnWriteBuffer(rtc::CopyOnWriteBuffer const&)
0002f1f7 t rtc::CopyOnWriteBuffer::CopyOnWriteBuffer()
000faa35 t rtc::CopyOnWriteBuffer::CopyOnWriteBuffer<char, (void*)0>(char const*, unsigned int)
0003452d t rtc::CopyOnWriteBuffer::~CopyOnWriteBuffer()
0003452d t rtc::CopyOnWriteBuffer::~CopyOnWriteBuffer()

Content of the MYPROJECT_Core.Pro

QT  += core xml
QT  -= gui

TARGET = MYPROJECT_Core
TEMPLATE = lib

DEFINES += MYPROJECT_CORE_LIBRARY

DEFINES += QT_DEPRECATED_WARNINGS
DEFINES += NOMINMAX
DEFINES += ENABLE_RTC_EVENT_LOG

QMAKE_CFLAGS_WARN_ON -= -Wall
QMAKE_CXXFLAGS_WARN_ON -= -Wall
CONFIG += warn_off

android {
    CONFIG += c++11
    QMAKE_CXXFLAGS += -std=c++11

    DEFINES += NDEBUG=1
    DEFINES += WEBRTC_POSIX
    DEFINES += WEBRTC_ANDROID

    LIBS += -L$$PWD/../Libs/webrtc-58/lib/android/armeabi-v7a/jni/armeabi-v7a -ljingle_peerconnection_so
    INCLUDEPATH += $$PWD/../Libs/webrtc-58/include
    DEPENDPATH += $$PWD/../Libs/webrtc-58/include
}

SOURCES += \
    main.cpp \

Body:
My colleague solved this problem today.
He replaced libjingle_peerconnection.so with another libraries from webrtc build output

obj/webrtc/api/libjingle_peerconnection_api.a
ob/webrtc/base/librtc_base_approved.a

Also there was a compatibility problem with QT Android Kit and webrtc build system, so Android Kit is building with gnustl, while webrtc was build with libc++, so he included libc++_shared.so from Android NDK bundle.
Entire Pro file will look like this

QT       -= gui

TARGET = WebRtcDependantLib
TEMPLATE = lib

#CONFIG += c++11
QMAKE_CXXFLAGS += -fno-rtti -fno-exceptions
DEFINES += MY_TEST_LIBRARY

android {
    DEFINES += WEBRTC_POSIX
    DEFINES += WEBRTC_ANDROID

    DEFINES += NDEBUG

    WEBRTC = /home/user/Dev/src  #WEBRTC-M58 sources directory
    WEBRTCBUILD = $$WEBRTC/out/Debug/arm-v7/obj
    #android NDK bundled by webrtc build system
    WEBRTCNDK = $$WEBRTC/third_party/android_tools/ndk

    LIBS += -Wl,--start-group
    LIBS += $$WEBRTCBUILD/webrtc/api/libjingle_peerconnection_api.a
    LIBS += $$WEBRTCBUILD/webrtc/base/librtc_base_approved.a
    LIBS += -Wl,--end-group

    LIBS += $$WEBRTCNDK/sources/cxx-stl/llvm-libc++/libs/armeabi-v7a/libc++_shared.so

    INCLUDEPATH += $$WEBRTC
    DEPENDPATH += $$WEBRTC
}
SOURCES += \
        main.cpp


问:
python flask with json
I am trying to get user's input and return the details as json.
But I get an error and I can't find why.
Hers is my python code:

```<code>from flask import Flask, request, render_template,jsonify
import json
@app.route('/user_input')
def user_input():
    return render_template('user-input.html')

@app.route('/user_input',methods = ['POST'])
def result():
    NAME = request.form['Book_Name']
    PAGE = request.form['Page']
    TEXT = request.form['Text']
    TOPIC = request.form['Topic']
    pythonDictionary = {'bookName': NAME, 'page': PAGE, 'text': TEXT, 'topic': TOPIC}
    dictionaryToJson = json.dumps(pythonDictionary)
    return jsonify(dictionaryToJson)
</code>```

and my HTML file:

```<code><html>
   <body>

      <form action = "http://localhost:5000/result" method = "POST">
         <p>Book Name <input type = "text" name = "Book_Name" /></p>
         <p>Page <input type = "text" name = "Page" /></p>
         <p>Text <input type = "text" name = "Text" /></p>
         <p>Topic <input type ="text" name = "Topic" /></p>
         <p><input type = "submit" value = "submit" /></p>
      </form>

   </body>
</html>
</code>```

How can I return the values properly?

答:
0) Do not use uppercase for vars. Uppercase is always for constants.

1) Use routes with "/" at the end to avoid additional redirects which flask does:

```<code>@app.route('/user_input/', methods = ['POST'])
</code>```

2) Use the same route and the same function to get what you need:

```<code>from flask import Flask, request, render_template, jsonify

def json_response(status_code, data):
    res = jsonify(data)
    res.status_code = status_code
    return res

app = Flask(__name__)

@app.route('/user_input/', methods=["GET", "POST"])
def user_input():
    if request.method == "GET":
        return render_template('user-input.html')
    else:
        python_dictionary = {'bookName': request.form.get('Book_Name'),
                             'page': request.form.get('Page'),
                             'text': request.form.get('Text'),
                             'topic': request.form.get('Topic')}
        return json_response(200, python_dictionary)

app.run()
</code>```

3) And yes, you don't need to use json.dumps(pythonDictionary) before passing dictionary to jsonify

4) Consider to use request.form.get('key') rather than request.form['key'] because get() function returns None if there is no such key:value instead of raising key error exception.

Title: python flask with json

Body:
I am trying to get user's input and return the details as json.
But I get an error and I can't find why.
Hers is my python code:

from flask import Flask, request, render_template,jsonify
import json
@app.route('/user_input')
def user_input():
    return render_template('user-input.html')

@app.route('/user_input',methods = ['POST'])
def result():
    NAME = request.form['Book_Name']
    PAGE = request.form['Page']
    TEXT = request.form['Text']
    TOPIC = request.form['Topic']
    pythonDictionary = {'bookName': NAME, 'page': PAGE, 'text': TEXT, 'topic': TOPIC}
    dictionaryToJson = json.dumps(pythonDictionary)
    return jsonify(dictionaryToJson)

and my HTML file:

      <form action = "http://localhost:5000/result" method = "POST">

Book Name <input type = "text" name = "Book_Name" />

Page <input type = "text" name = "Page" />

Text <input type = "text" name = "Text" />

Topic <input type ="text" name = "Topic" />

<input type = "submit" value = "submit" />

      </form>

How can I return the values properly?

Body:
0) Do not use uppercase for vars. Uppercase is always for constants.

1) Use routes with "/" at the end to avoid additional redirects which flask does:

@app.route('/user_input/', methods = ['POST'])

2) Use the same route and the same function to get what you need:

from flask import Flask, request, render_template, jsonify

def json_response(status_code, data):
    res = jsonify(data)
    res.status_code = status_code
    return res

app = Flask(__name__)

@app.route('/user_input/', methods=["GET", "POST"])
def user_input():
    if request.method == "GET":
        return render_template('user-input.html')
    else:
        python_dictionary = {'bookName': request.form.get('Book_Name'),
                             'page': request.form.get('Page'),
                             'text': request.form.get('Text'),
                             'topic': request.form.get('Topic')}
        return json_response(200, python_dictionary)

app.run()

3) And yes, you don't need to use json.dumps(pythonDictionary) before passing dictionary to jsonify

4) Consider to use request.form.get('key') rather than request.form['key'] because get() function returns None if there is no such key:value instead of raising key error exception.


问:
Browser compatibility error
I create one web page (which display details in table) using html & js. Which works on firefox but not in IE.

```<code>function frontEnd()
{
try{
th1 = document.getElementById('th1');
th1.firstChild.nodeValue = "Technology";

th2 = document.getElementById('th2');
th2.firstChild.nodeValue = "Level of knowledge";

t1 = document.getElementById('t1');
t1.firstChild.nodeValue = "HTML";

tl1 = document.getElementById('tl1');
tl1.firstChild.nodeValue = "5";

document.getElementById('MyTab').style.visibility="visible";
}
catch(e)
{
alert(e);
}
    }
</code>```

th1 is an id of table heading, t1,tl1 are data id. Actually am trying to display static values in table when user clicks button. It works sucessfully in firefox, not in IE. When click button using IE it reflects an error "[Object Error]"
Please tel me how to made the same code to work in IE.

Thanks,
Naveen

答:
Why don't you use JQuery or Prototype JavaScript library  , they are cross browser compatible.

Jquery

http://api.jquery.com/first-child-selector/

Title: Browser compatibility error

Body:
I create one web page (which display details in table) using html & js. Which works on firefox but not in IE.

function frontEnd()
{
try{
th1 = document.getElementById('th1');
th1.firstChild.nodeValue = "Technology";

th2 = document.getElementById('th2');
th2.firstChild.nodeValue = "Level of knowledge";

t1 = document.getElementById('t1');
t1.firstChild.nodeValue = "HTML";

tl1 = document.getElementById('tl1');
tl1.firstChild.nodeValue = "5";

document.getElementById('MyTab').style.visibility="visible";
}
catch(e)
{
alert(e);
}
    }

th1 is an id of table heading, t1,tl1 are data id. Actually am trying to display static values in table when user clicks button. It works sucessfully in firefox, not in IE. When click button using IE it reflects an error "[Object Error]"
Please tel me how to made the same code to work in IE.

Thanks,
Naveen


问:
Why my If condition is returning wrong result?
I'm a student currently studying VBA in one of my classes, where the current assignment is to pull data from a .txt file and display it, as well as total it, and then grade the total. using arrays I've been successful in the first two parts using arrays, but when trying to factor in the total for a grade the array only takes the starting numbers into account. Any thoughts? Code below</p>

```<code>Sub Categories()

Dim Locale As String, State(1 To 50) As Variant
Dim Serial(1 To 50) As Single, i As Single
Dim path As String, j As Single
Dim Score(1 To 50, 1 To 7) As Single
Dim IndexGrade(1 To 50) As Single
Dim Total(1 To 50) As Single
Locale = ActiveWorkbook.path

path = Locale & "US_States.txt"

Open path For Input As #1

For i = 1 To 50 Step 1
    Input #1, Serial(i), State(i)
    Sheet1.Cells(1 + i, 1).Value = Serial(i)
    Sheet1.Cells(1 + i, 2).Value = State(i)
         For j = 1 To 7 Step 1
            Input #1, Score(i, j)
            Total(i) = Total(i) + Score(i, j)
            Sheet1.Cells(1 + i, 3).Value = Total(i)
        Next j
   Total(i) = Sheet1.Cells(1 + i, 3).Value
   If 0 <= Total(i) < 100 Then
    Sheet1.Cells(1 + i, 4).Value = "A"
    ElseIf 100 <= Total(i) < 200 Then
    Sheet1.Cells(1 + i, 4).Value = "B"
    ElseIf 200 <= Total(i) < 300 Then
    Sheet1.Cells(1 + i, 4).Value = "C"
    ElseIf 300 <= Total(i) Then
    Sheet1.Cells(1 + i, 4).Value = "D"
    End If
Next i

Close #1

End Sub
</code>```

答:
Problem is with your If condition. In VBA 1 < 2 < 1 evaluates to true. That's why even if your total(i) is more than 100, it always evaluates to true and your elseif is not coming into play.

In VBA/VB6, type conversion is simply evil.

You nee to rewrite your If and elseif conditions

Example:

```<code>Sub test()

    Dim x   As Long
    Dim y   As Long

    x = 101
    y = 99

    '/ What you are doing
    If 0 <= x < 1 Then
        MsgBox "This is not python."
    End If

    '/ How you should do it.
    If y >= 0 And y < 100 Then
        MsgBox "This is how you do it in VBA."
    End If

End Sub
</code>```

Body:
I'm a student currently studying VBA in one of my classes, where the current assignment is to pull data from a .txt file and display it, as well as total it, and then grade the total. using arrays I've been successful in the first two parts using arrays, but when trying to factor in the total for a grade the array only takes the starting numbers into account. Any thoughts? Code below

Sub Categories()

Dim Locale As String, State(1 To 50) As Variant
Dim Serial(1 To 50) As Single, i As Single
Dim path As String, j As Single
Dim Score(1 To 50, 1 To 7) As Single
Dim IndexGrade(1 To 50) As Single
Dim Total(1 To 50) As Single
Locale = ActiveWorkbook.path

path = Locale & "US_States.txt"

Open path For Input As #1

For i = 1 To 50 Step 1
    Input #1, Serial(i), State(i)
    Sheet1.Cells(1 + i, 1).Value = Serial(i)
    Sheet1.Cells(1 + i, 2).Value = State(i)
         For j = 1 To 7 Step 1
            Input #1, Score(i, j)
            Total(i) = Total(i) + Score(i, j)
            Sheet1.Cells(1 + i, 3).Value = Total(i)
        Next j
   Total(i) = Sheet1.Cells(1 + i, 3).Value
   If 0 <= Total(i) < 100 Then
    Sheet1.Cells(1 + i, 4).Value = "A"
    ElseIf 100 <= Total(i) < 200 Then
    Sheet1.Cells(1 + i, 4).Value = "B"
    ElseIf 200 <= Total(i) < 300 Then
    Sheet1.Cells(1 + i, 4).Value = "C"
    ElseIf 300 <= Total(i) Then
    Sheet1.Cells(1 + i, 4).Value = "D"
    End If
Next i

Close #1

End Sub

Body:
Problem is with your If condition. In VBA 1 < 2 < 1 evaluates to true. That's why even if your total(i) is more than 100, it always evaluates to true and your elseif is not coming into play.

In VBA/VB6, type conversion is simply evil.

You nee to rewrite your If and elseif conditions

Example:

Sub test()

    Dim x   As Long
    Dim y   As Long

    x = 101
    y = 99

    '/ What you are doing
    If 0 <= x < 1 Then
        MsgBox "This is not python."
    End If

    '/ How you should do it.
    If y >= 0 And y < 100 Then
        MsgBox "This is how you do it in VBA."
    End If

End Sub


问:
MySQL select result inside JS function
I found a simple JS script that works as a chatbot.
in the script itself the results of lastUserMessage are predefined inline like

```<code>if (lastUserMessage === 'name') {
   botMessage = 'My name is ' + botName;
}
</code>```

What I am trying to achieve is if the JS to search for lastUserMessage within a db and to provide botMessage from there.

I am sure it should't be that hard, but I cant figure out how to do it.

Here is the JS code:

```<code>nlp = window.nlp_compromise;
var messages = [], //array that hold the record of each string in chat
  lastUserMessage = "", //keeps track of the most recent input string from the user
  botMessage = "", //var keeps track of what the chatbot is going to say
  botName = 'Bot Name', //name of the chatbot
  talking = true; //when false the speach function doesn't work

//edit this function to change what the chatbot says
function chatbotResponse() {
  talking = true;
  botMessage = "Ops... didn't get this"; //the default message

  if (lastUserMessage === 'name') {
    botMessage = 'My name is ' + botName;
  }

}

//this runs each time enter is pressed.
//It controls the overall input and output
function newEntry() {
  //if the message from the user isn't empty then run
  if (document.getElementById("chatbox").value != "") {
    //pulls the value from the chatbox ands sets it to lastUserMessage
    lastUserMessage = document.getElementById("chatbox").value;
    //sets the chat box to be clear
    document.getElementById("chatbox").value = "";
    //adds the value of the chatbox to the array messages
    messages.push(lastUserMessage);
    //Speech(lastUserMessage);  //says what the user typed outloud
    //sets the variable botMessage in response to lastUserMessage
    chatbotResponse();
    //add the chatbot's name and message to the array messages
    messages.push("<b>" + botName + ":</b> " + botMessage);
    // says the message using the text to speech function written below
    Speech(botMessage);
    //outputs the last few array elements of messages to html
    for (var i = 1; i < 8; i++) {
      if (messages[messages.length - i])
        document.getElementById("chatlog" + i).innerHTML = messages[messages.length - i];
    }
  }
}

//runs the keypress() function when a key is pressed
document.onkeypress = keyPress;
//if the key pressed is 'enter' runs the function newEntry()
function keyPress(e) {
  var x = e || window.event;
  var key = (x.keyCode || x.which);
  if (key == 13 || key == 3) {
    //runs this function when enter is pressed
    newEntry();
  }
  if (key == 38) {
    console.log('hi')
      //document.getElementById("chatbox").value = lastUserMessage;
  }
}

//clears the placeholder text ion the chatbox
//this function is set to run when the users brings focus to the chatbox, by clicking on it
function placeHolder() {
  document.getElementById("chatbox").placeholder = "";
}
</code>```

Here is the HTML code

```<code><div id='bodybox'>
  <div id='chatborder'>
    <p id="chatlog2" class="chatlog"> </p>
    <p id="chatlog1" class="chatlog"> </p>
    <input type="text" name="chat" id="chatbox" placeholder="Hi there! Type here to talk to me." onfocus="placeHolder()">
  </div>
</code>```

What need to happen?

Ideally, the script should take the values "lastUserMessage" and
  "botMessage" from a db that has 2 columns "lastUserMessage" and
  "botMessage".

What I tried to to do is following Ghost's comment below... but didn't work.

```<code>    nlp = window.nlp_compromise;
var messages = [], //array that hold the record of each string in chat
  lastUserMessage = "", //keeps track of the most recent input string from the user
  botMessage = "", //var keeps track of what the chatbot is going to say
  botName = 'Bot Name', //name of the chatbot
  talking = true; //when false the speach function doesn't work

//edit this function to change what the chatbot says
function chatbotResponse() {
  talking = true;
  botMessage = "Ops... didn't get this"; //the default message

      $.ajax({
  url: 'db_query.php',
  data: "lastUserMessag=lastUserMessag",
  dataType: 'json',
  success: function(data)
  {
    var lastUserMessage_db = data[0];
    var botMessage_db= data[1];

if (lastUserMessage === lastUserMessage_db) {
    botMessage = botMessage_db;
  }
  }
});

}

//this runs each time enter is pressed.
//It controls the overall input and output
function newEntry() {
  //if the message from the user isn't empty then run
  if (document.getElementById("chatbox").value != "") {
    //pulls the value from the chatbox ands sets it to lastUserMessage
    lastUserMessage = document.getElementById("chatbox").value;
    //sets the chat box to be clear
    document.getElementById("chatbox").value = "";
    //adds the value of the chatbox to the array messages
    messages.push(lastUserMessage);
    //Speech(lastUserMessage);  //says what the user typed outloud
    //sets the variable botMessage in response to lastUserMessage
    chatbotResponse();
    //add the chatbot's name and message to the array messages
    messages.push("<b>" + botName + ":</b> " + botMessage);
    // says the message using the text to speech function written below
    Speech(botMessage);
    //outputs the last few array elements of messages to html
    for (var i = 1; i < 8; i++) {
      if (messages[messages.length - i])
        document.getElementById("chatlog" + i).innerHTML = messages[messages.length - i];
    }
  }
}

//runs the keypress() function when a key is pressed
document.onkeypress = keyPress;
//if the key pressed is 'enter' runs the function newEntry()
function keyPress(e) {
  var x = e || window.event;
  var key = (x.keyCode || x.which);
  if (key == 13 || key == 3) {
    //runs this function when enter is pressed
    newEntry();
  }
  if (key == 38) {
    console.log('hi')
      //document.getElementById("chatbox").value = lastUserMessage;
  }
}

//clears the placeholder text ion the chatbox
//this function is set to run when the users brings focus to the chatbox, by clicking on it
function placeHolder() {
  document.getElementById("chatbox").placeholder = "";
}
</code>```

And in DB_query.php I have

```<code>$p = $_GET['lastUserMessag'];
      $query=mysql_query("SELECT lastUserMessag, botMessage FROM `aiml` WHERE lastUserMessag='$p'");
      $array = mysql_fetch_row($query);
    echo json_encode($array);
</code>```

答:
Javascript runs in the Client's browser.  MySQL runs in the Server.  So, something else is needed to connect them.

I use PHP and AJAX as the conduit between them.  JS issues an AJAX call.  (Note:  "A" stands for "Asynchronous".)  Then JS gets the results via a "callback".  Meanwhile, the target of the AJAX 'call' is a PHP program (or Java or VB or ...) which connects to the database (MySQL) and performs the SELECT and builds the JSON to deliver back to JS.

Title: MySQL select result inside JS function

Body:
I found a simple JS script that works as a chatbot.
in the script itself the results of lastUserMessage are predefined inline like

if (lastUserMessage === 'name') {
   botMessage = 'My name is ' + botName;
}

What I am trying to achieve is if the JS to search for lastUserMessage within a db and to provide botMessage from there.

I am sure it should't be that hard, but I cant figure out how to do it.

Here is the JS code:

nlp = window.nlp_compromise;
var messages = [], //array that hold the record of each string in chat
  lastUserMessage = "", //keeps track of the most recent input string from the user
  botMessage = "", //var keeps track of what the chatbot is going to say
  botName = 'Bot Name', //name of the chatbot
  talking = true; //when false the speach function doesn't work

//edit this function to change what the chatbot says
function chatbotResponse() {
  talking = true;
  botMessage = "Ops... didn't get this"; //the default message

  if (lastUserMessage === 'name') {
    botMessage = 'My name is ' + botName;
  }

}

//this runs each time enter is pressed.
//It controls the overall input and output
function newEntry() {
  //if the message from the user isn't empty then run
  if (document.getElementById("chatbox").value != "") {
    //pulls the value from the chatbox ands sets it to lastUserMessage
    lastUserMessage = document.getElementById("chatbox").value;
    //sets the chat box to be clear
    document.getElementById("chatbox").value = "";
    //adds the value of the chatbox to the array messages
    messages.push(lastUserMessage);
    //Speech(lastUserMessage);  //says what the user typed outloud
    //sets the variable botMessage in response to lastUserMessage
    chatbotResponse();
    //add the chatbot's name and message to the array messages
    messages.push("" + botName + ": " + botMessage);
    // says the message using the text to speech function written below
    Speech(botMessage);
    //outputs the last few array elements of messages to html
    for (var i = 1; i < 8; i++) {
      if (messages[messages.length - i])
        document.getElementById("chatlog" + i).innerHTML = messages[messages.length - i];
    }
  }
}

//runs the keypress() function when a key is pressed
document.onkeypress = keyPress;
//if the key pressed is 'enter' runs the function newEntry()
function keyPress(e) {
  var x = e || window.event;
  var key = (x.keyCode || x.which);
  if (key == 13 || key == 3) {
    //runs this function when enter is pressed
    newEntry();
  }
  if (key == 38) {
    console.log('hi')
      //document.getElementById("chatbox").value = lastUserMessage;
  }
}

//clears the placeholder text ion the chatbox
//this function is set to run when the users brings focus to the chatbox, by clicking on it
function placeHolder() {
  document.getElementById("chatbox").placeholder = "";
}

Here is the HTML code

    <input type="text" name="chat" id="chatbox" placeholder="Hi there! Type here to talk to me." onfocus="placeHolder()">

What need to happen?

Ideally, the script should take the values "lastUserMessage" and
  "botMessage" from a db that has 2 columns "lastUserMessage" and
  "botMessage".

What I tried to to do is following Ghost's comment below... but didn't work.

    nlp = window.nlp_compromise;
var messages = [], //array that hold the record of each string in chat
  lastUserMessage = "", //keeps track of the most recent input string from the user
  botMessage = "", //var keeps track of what the chatbot is going to say
  botName = 'Bot Name', //name of the chatbot
  talking = true; //when false the speach function doesn't work

//edit this function to change what the chatbot says
function chatbotResponse() {
  talking = true;
  botMessage = "Ops... didn't get this"; //the default message

      $.ajax({
  url: 'db_query.php',
  data: "lastUserMessag=lastUserMessag",
  dataType: 'json',
  success: function(data)
  {
    var lastUserMessage_db = data[0];
    var botMessage_db= data[1];

if (lastUserMessage === lastUserMessage_db) {
    botMessage = botMessage_db;
  }
  }
});

}

//this runs each time enter is pressed.
//It controls the overall input and output
function newEntry() {
  //if the message from the user isn't empty then run
  if (document.getElementById("chatbox").value != "") {
    //pulls the value from the chatbox ands sets it to lastUserMessage
    lastUserMessage = document.getElementById("chatbox").value;
    //sets the chat box to be clear
    document.getElementById("chatbox").value = "";
    //adds the value of the chatbox to the array messages
    messages.push(lastUserMessage);
    //Speech(lastUserMessage);  //says what the user typed outloud
    //sets the variable botMessage in response to lastUserMessage
    chatbotResponse();
    //add the chatbot's name and message to the array messages
    messages.push("" + botName + ": " + botMessage);
    // says the message using the text to speech function written below
    Speech(botMessage);
    //outputs the last few array elements of messages to html
    for (var i = 1; i < 8; i++) {
      if (messages[messages.length - i])
        document.getElementById("chatlog" + i).innerHTML = messages[messages.length - i];
    }
  }
}

//runs the keypress() function when a key is pressed
document.onkeypress = keyPress;
//if the key pressed is 'enter' runs the function newEntry()
function keyPress(e) {
  var x = e || window.event;
  var key = (x.keyCode || x.which);
  if (key == 13 || key == 3) {
    //runs this function when enter is pressed
    newEntry();
  }
  if (key == 38) {
    console.log('hi')
      //document.getElementById("chatbox").value = lastUserMessage;
  }
}

//clears the placeholder text ion the chatbox
//this function is set to run when the users brings focus to the chatbox, by clicking on it
function placeHolder() {
  document.getElementById("chatbox").placeholder = "";
}

And in DB_query.php I have

$p = $_GET['lastUserMessag'];
      $query=mysql_query("SELECT lastUserMessag, botMessage FROM `aiml` WHERE lastUserMessag='$p'");
      $array = mysql_fetch_row($query);
    echo json_encode($array);


问:
Is componentDidMount supposed to run with shallow rendering in Enzyme?
From my understanding and from what I have read so far in various answers, not all lifecycle methods are supposed to be run with shallow rendering. Especially componentDidMount

However, I notice that when I do

```<code>  beforeEach(function () {
    fakeComponentDidMount = sinon.stub(Component.prototype, 'componentDidMount');
    fakeComponentDidMount.callsFake(function () {});
    wrapper = shallow(<Component {...props} />);
  });

  afterEach(function () {
    fakeComponentDidMount.restore();
  });

  it('calls componentDidMount', function () {
    expect(fakeComponentDidMount.called).to.equal(true);
  });
</code>```

the test passes.

So, am I doing something wrong here or have I understood something wrong?

For reference

答:
Yes it is in enzyme 3.0.

https://github.com/airbnb/enzyme/blob/master/CHANGELOG.md#300

LifeCycleExperimental which was previously an option that you had to manually set to true on shallow is now enabled by default because it is now stable.

This is much nicer than having to resort to mount when wanting to test lifecycles.

There is absolutely no excuse to not use shallow for unit tests now :)... Well apart from when you need to test refs :(.

Body:
From my understanding and from what I have read so far in various answers, not all lifecycle methods are supposed to be run with shallow rendering. Especially componentDidMount

However, I notice that when I do

  beforeEach(function () {
    fakeComponentDidMount = sinon.stub(Component.prototype, 'componentDidMount');
    fakeComponentDidMount.callsFake(function () {});
    wrapper = shallow(<Component {...props} />);
  });

  afterEach(function () {
    fakeComponentDidMount.restore();
  });

  it('calls componentDidMount', function () {
    expect(fakeComponentDidMount.called).to.equal(true);
  });

the test passes.

So, am I doing something wrong here or have I understood something wrong?

For reference


问:
How can I Loop copy/paste across worksheets?
I'm trying to write a loop which will go through a workbook and do the following:
1.Select a worksheet
2.Copy a selection of cells on selected worksheet
3.Return to a Master or "home" sheet
4.Paste the copied values in the next empty row of this master sheet
5.Go to the next worksheet and start the process again.

I've tried to get this rolling with the below code, but I'm afraid I'm still new to VBA, looping, and dynamic range selection.

```<code>Sub Create_One_Table()

Dim wrksht As Worksheet
Dim c As Range, rng

For Each wrksht In ThisWorkbook.Worksheets

    With wrksht

            Range("BB2").Select
            Range(Selection, Selection.End(xlToRight)).Select
            Range(Selection, Selection.End(xlDown)).Select
            Selection.Copy
            Sheets("05").Select
            Range("BB17").Select
           Range("B" & Rows.Count).End(xlUp).Offset(1).Select
            Sheets("05").Paste
    End With

Next wrksht

End Sub
</code>```

My question is how can I change the above code to do the actions I specified at first? The above code as is copies and pastes only portions of what I need it to (meaning it's incomplete).Any help would be greatly appreciated, I've spent a lot of time fumbling through this so far. Thanks,

答:
It looks like you have the basics there.  I have a few pointers:

When using with blocks, access properties of the with object by starting them with a ..  I've updated the Range calls below to .Range to demonstrate.  As it is the first three usages of Range in your with block are accessing whatever sheet is selected, since you also never select each wrksht in the loop.

There is no need to use .select to hold your place.  You can refer to the Range(ref) directly, and you can chain .end together also.  This makes execution much faster and also prevents the need to switch to the sheet you are getting data from.  See how I copied the range with one command and no selections.

You can refer to sheets labels such as Sheets("Master").  I find this easier than their numbers.

I've incorporated this into the below code.  It's not actually tested because I don't know your layout, but I hope it helps.

```<code>Sub Create_One_Table()
Dim wrksht As Worksheet
Dim c As Range, rng
'Make sure "Master" is selected because this is the only one you need to select cells on (to paste)
Sheets("Master").Select
For Each wrksht In ThisWorkbook.Worksheets
    With wrksht
            .Range(.Range("BB2"), .Range("BB2").End(xlToRight).End(xlDown)).Copy
    End With
    Range("B" & Rows.Count).End(xlUp).Offset(1).Select
    ActiveSheet.Paste
Next wrksht
End Sub
</code>```

Body:
I'm trying to write a loop which will go through a workbook and do the following:
1.Select a worksheet
2.Copy a selection of cells on selected worksheet
3.Return to a Master or "home" sheet
4.Paste the copied values in the next empty row of this master sheet
5.Go to the next worksheet and start the process again.

I've tried to get this rolling with the below code, but I'm afraid I'm still new to VBA, looping, and dynamic range selection.

Sub Create_One_Table()

Dim wrksht As Worksheet
Dim c As Range, rng

For Each wrksht In ThisWorkbook.Worksheets

    With wrksht

            Range("BB2").Select
            Range(Selection, Selection.End(xlToRight)).Select
            Range(Selection, Selection.End(xlDown)).Select
            Selection.Copy
            Sheets("05").Select
            Range("BB17").Select
           Range("B" & Rows.Count).End(xlUp).Offset(1).Select
            Sheets("05").Paste
    End With

Next wrksht

End Sub

My question is how can I change the above code to do the actions I specified at first? The above code as is copies and pastes only portions of what I need it to (meaning it's incomplete).Any help would be greatly appreciated, I've spent a lot of time fumbling through this so far. Thanks,

Body:
It looks like you have the basics there.  I have a few pointers:

When using with blocks, access properties of the with object by starting them with a ..  I've updated the Range calls below to .Range to demonstrate.  As it is the first three usages of Range in your with block are accessing whatever sheet is selected, since you also never select each wrksht in the loop.

There is no need to use .select to hold your place.  You can refer to the Range(ref) directly, and you can chain .end together also.  This makes execution much faster and also prevents the need to switch to the sheet you are getting data from.  See how I copied the range with one command and no selections.

You can refer to sheets labels such as Sheets("Master").  I find this easier than their numbers.

I've incorporated this into the below code.  It's not actually tested because I don't know your layout, but I hope it helps.

Sub Create_One_Table()
Dim wrksht As Worksheet
Dim c As Range, rng
'Make sure "Master" is selected because this is the only one you need to select cells on (to paste)
Sheets("Master").Select
For Each wrksht In ThisWorkbook.Worksheets
    With wrksht
            .Range(.Range("BB2"), .Range("BB2").End(xlToRight).End(xlDown)).Copy
    End With
    Range("B" & Rows.Count).End(xlUp).Offset(1).Select
    ActiveSheet.Paste
Next wrksht
End Sub


问:
Batch commands for rds
I have a project for my Radio Station where I copy the text within a .wsx file of what is on air and parse it to a Audio Processor in my private network for RDS Display using a wget command like

```<code>set /p TEXTO= 0<R:\40.wsx
wget -q "http://x.x.x.x:7380/parameter/fm/rds/rds_rt=%TEXTO%" -O NUL
</code>```

It works great but it won't filter if it's music or promotions.

My challenge is to be able to filter and only parse music names.

For the process I marked the Files that i don't want to show  up like commercial, or promotions to start with a "@-" without the quotes.

So the text will show like @-Promo1

My Code:

```<code>for /F "delims=" %%a in ('FINDSTR "\<@-.*"  C:\RDS\PRUEBAS\txt1.wsx') do set
"VAR=%%a"
  echo %VAR%
 if "%VAR%" == "true" (
    set /p VAR=0<C:\FILEPATH\LOS40.wsx & wget -q
"http://x.x.x.x:7380/parameter/fm/rds/rds_rt=%VAR%" -O NUL
) else (
    set /p TEXTO=0<C:\FILEPATH\ENVIVO.wsx & wget -q
"http://x.x.x.x:7380/parameter/fm/rds/rds_rt=%TEXTO%" -O NUL
)
</code>```

I can't seem to find a correct way to filter it.

pls Heelpp..

答:
First of all thanks for your help.. I don't have experience in coding.

Let me explain a little bit more..

As I said before its a radio station which will provide text to the Car o home stereos using the RDS Protocol which allow me to send text like song name, title, etc.

Im My case the Audio Processor that let me send the text will receive the info as a URL where I add at the end the text I want to send.

For Example:

http://x.x.x.x:7380/parameter/fm/rds/rds_rt=%TEXTO%

%TEXTO% will be the text Im sending.

C:\RDS\PRUEBAS\txt1.wsx  Contains the text of what it being played at the moment and which is being read to see if the @- for the script to avoid sending those titles.

I have a Pc running a Directory Monitor Program that will monitor events on file C:\RDS\PRUEBAS\txt1.wsx and that as soon as being modified, it will execute the batch file CHECKRDS.cmd.

After testing I decided to run a code in CHECKRDS.cmd like:

```<code>for /F "delims=" %%a in ('FINDSTR /v "@-"  R:\40PPALES.wsx') do (
  START "" RDS.bat
 )
EXIT
</code>```

RDS.bat contains code and it works fine:

```<code>set /p TEXTO= 0<C:\RDS\PRUEBAS\txt1.wsx
wget -q "http://x.x.x.x:7380/parameter/fm/rds/rds_rt=%TEXTO%" -O NUL
EXIT
</code>```

As far as the set /p I test it from What does /p mean in set /p?

AS I said before Im new at coding and I just googled everything and started to assable the pieces of the puzzle.

Pls, If you think I should be doing these process diferently, pls let me know..

And sorry for my bad english..

regards

Title: Batch commands for rds

Body:
I have a project for my Radio Station where I copy the text within a .wsx file of what is on air and parse it to a Audio Processor in my private network for RDS Display using a wget command like

set /p TEXTO= 0<R:\40.wsx
wget -q "http://x.x.x.x:7380/parameter/fm/rds/rds_rt=%TEXTO%" -O NUL

It works great but it won't filter if it's music or promotions.

My challenge is to be able to filter and only parse music names.

For the process I marked the Files that i don't want to show  up like commercial, or promotions to start with a "@-" without the quotes.

So the text will show like @-Promo1

My Code:

for /F "delims=" %%a in ('FINDSTR "\<@-.*"  C:\RDS\PRUEBAS\txt1.wsx') do set
"VAR=%%a"
  echo %VAR%
 if "%VAR%" == "true" (
    set /p VAR=0<C:\FILEPATH\LOS40.wsx & wget -q
"http://x.x.x.x:7380/parameter/fm/rds/rds_rt=%VAR%" -O NUL
) else (
    set /p TEXTO=0<C:\FILEPATH\ENVIVO.wsx & wget -q
"http://x.x.x.x:7380/parameter/fm/rds/rds_rt=%TEXTO%" -O NUL
)

I can't seem to find a correct way to filter it.

pls Heelpp..

Body:
First of all thanks for your help.. I don't have experience in coding.

Let me explain a little bit more..

As I said before its a radio station which will provide text to the Car o home stereos using the RDS Protocol which allow me to send text like song name, title, etc.

Im My case the Audio Processor that let me send the text will receive the info as a URL where I add at the end the text I want to send.

For Example:

http://x.x.x.x:7380/parameter/fm/rds/rds_rt=%TEXTO%

%TEXTO% will be the text Im sending.

C:\RDS\PRUEBAS\txt1.wsx  Contains the text of what it being played at the moment and which is being read to see if the @- for the script to avoid sending those titles.

I have a Pc running a Directory Monitor Program that will monitor events on file C:\RDS\PRUEBAS\txt1.wsx and that as soon as being modified, it will execute the batch file CHECKRDS.cmd.

After testing I decided to run a code in CHECKRDS.cmd like:

for /F "delims=" %%a in ('FINDSTR /v "@-"  R:\40PPALES.wsx') do (
  START "" RDS.bat
 )
EXIT

RDS.bat contains code and it works fine:

set /p TEXTO= 0<C:\RDS\PRUEBAS\txt1.wsx
wget -q "http://x.x.x.x:7380/parameter/fm/rds/rds_rt=%TEXTO%" -O NUL
EXIT

As far as the set /p I test it from What does /p mean in set /p?

AS I said before Im new at coding and I just googled everything and started to assable the pieces of the puzzle.

Pls, If you think I should be doing these process diferently, pls let me know..

And sorry for my bad english..

regards


问:
Output should be String when Condition is right SQL
I have a little problem here. I have the following Select

```<code>SELECT ProjektName, Budget  FROM projekt p1  WHERE p1.Budget=(
    SELECT MAX(p2.Budget) FROM projekt p2
)
UNION
SELECT ProjektName, Budget   FROM projekt p1  WHERE p1.Budget=(
    SELECT MIN(p2.Budget) FROM projekt p2
)
</code>```

which delivers this result:

```<code>Projektname     Budget
projekt1        100000
projekt2        30000
</code>```

But instead of the Value I want to write a string which says something like "this is the max Budget"

Like this:

```<code>Projektname     Budget
projekt1        This is the max Budget
projekt2        This is the min Budget
</code>```

Searched everywhere but only found solutions for changing the Budget in the Select but not the result.

Thank you in advance!

答:
Use CONCAT :

```<code>SELECT ProjektName, CONCAT ('This ' , Budget , ' is the max Budget') as Budget  FROM projekt p1  WHERE p1.Budget=(
    SELECT MAX(p2.Budget) FROM projekt p2
)
UNION
SELECT ProjektName, CONCAT ('This ' , Budget , ' is the min Budget') as Budget   FROM projekt p1  WHERE p1.Budget=(
    SELECT MIN(p2.Budget) FROM projekt p2
)
</code>```

Body:
I have a little problem here. I have the following Select

SELECT ProjektName, Budget  FROM projekt p1  WHERE p1.Budget=(
    SELECT MAX(p2.Budget) FROM projekt p2
)
UNION
SELECT ProjektName, Budget   FROM projekt p1  WHERE p1.Budget=(
    SELECT MIN(p2.Budget) FROM projekt p2
)

which delivers this result:

Projektname     Budget
projekt1        100000
projekt2        30000

But instead of the Value I want to write a string which says something like "this is the max Budget"

Like this:

Projektname     Budget
projekt1        This is the max Budget
projekt2        This is the min Budget

Searched everywhere but only found solutions for changing the Budget in the Select but not the result.

Thank you in advance!

Body:
Use CONCAT :

SELECT ProjektName, CONCAT ('This ' , Budget , ' is the max Budget') as Budget  FROM projekt p1  WHERE p1.Budget=(
    SELECT MAX(p2.Budget) FROM projekt p2
)
UNION
SELECT ProjektName, CONCAT ('This ' , Budget , ' is the min Budget') as Budget   FROM projekt p1  WHERE p1.Budget=(
    SELECT MIN(p2.Budget) FROM projekt p2
)


问:
Compile time safety of derived classes virtual functions?
I have this code, the question is below the code:

```<code>public class MainProgram
{
    public static void Main()
    {
        List<Animal> Animals = new List<Animal>();
        Animals.Add(new Dog());
        Animals.Add(new Poodle());
        Animals.Add(new Poodle());
        Animals.Add(new Beagle());
        Animals.Add(new Cat());

        Bark[] JustTheBarks = Dog.GetBarkList(Animals);
        foreach (Bark B in JustTheBarks)
        {
            Console.WriteLine(B.ToString());
        }
    }
}

abstract class Animal
{
    public abstract Noise GetNoise();
}

class Dog : Animal
{
    public override Noise GetNoise()
    {
        return new Bark("bark");
    }

    public static Bark[] GetBarkList(List<Animal> List)
    {
        return List
            .OfType<Dog>()
            .Select(r => r.GetNoise())
            .Cast<Bark>()
            .ToArray();
    }
}

class Beagle : Dog
{
    public override Noise GetNoise()
    {
        return new Woof("woof", 7);
    }
}

class Poodle : Dog
{
    public override Noise GetNoise()
    {
        return new Purr();
    }
}

class Cat : Animal
{
    public override Noise GetNoise()
    {
        throw new NotImplementedException();
    }
}

class Noise
{
}

class Bark : Noise
{
    protected string Text;
    public Bark(string Text)
    {
        this.Text = Text;
    }

    public override string ToString()
    {
        return $"{Text}";
    }
}

class Woof : Bark
{
    protected int Pitch;

    public Woof(string Text, int Pitch) : base(Text)
    {
        this.Pitch = Pitch;
    }
    public override string ToString()
    {
        return $"{Text}->{Pitch}";
    }
}

class Purr : Noise { }
</code>```

}

In plain text, Animals and Noises, each animal returns its own type of noise, the noises correspond to the animal class, although sometimes an animal might return different Noises based on some variable (but for a dog only some form of Bark).

This code crashes of course. The Poodle returns a Purr(), and it "should" return something of type Bark.  I have the abstract function GetNoise() which just returns a Noise. What I want/need is to write

```<code>class Dog
{
    public override Bark GetNoise();
}
</code>```

But this is not allowed, the return type must be the same. I don't want to write a second layer of GetBark() functions in every Dog class, etc.

What I want is to re-write this such that there is no casting, and everything that is derived from Dog is forced to return a Bark in its GetNoise() function such that I can safely write:

```<code>Bark B = Dog.GetNoise();
</code>```

答:
This is a classic mis-application of OO.

Beagle and Poodle are not sub-classes of "Dog".  Rather they are collectively different types of dog that share similar characteristics.  They both have the same properties but the values of those properties identify groups of similar instances not sub-classes.

This is similar to the confusion of "Square" and "Rectangle" as sub-classes of shape when in fact they are both instances of a polygon.  The properties they have in common (4 vertices, 4 equal internal angles of 90 degrees) do not constitute different classes of shape but different values of the properties of those shapes.

In your example the issue extends deeper into the differentiation of different characteristics of noise as sub-classes.  A Purr and a Bark are both instances of a noise differentiated only by the waveform and/or the method of production.

What is missing is the nature of the noise (vocal, sub-vocal or other - e.g. insects rubbing legs/wing-cases together etc) or the purpose of the noise (warning, pleasure, anger, anxiety, pain, attracting a mate etc)

The reduction of noise making on an animal to a single method then compounds the problem.

Assuming that Cat and Dog are (more) legitimate subclasses of Animal:  Cat's have the ability (a method) to Purr() but a Dog does not.  A Dog has the ability to Bark() but a Cat does not.  A Cat() has the ability to Meow() however and in some cases a Meow() might be considered the equivalent to a Bark() but in other cases a Hiss() might be more nearly equivalent.  Yet again, when a Dog Growls() is this akin to a Cat Hiss()ing or Purr()ing (physiologically the latter, contextually the former) ?

And then there is Yelp()ing.  Howl()ing.  etc.

All of these are noises and independent of any particular animal type involved there is no legitimate basis for saying that if some thing is capable of making any Noise then it can only make specific sub-classes of Noise.

In short:  This object model is broken.  :)

Rather than try to contort the classes to fit a broken model it will serve you better in the long run to fix the model itself.

HOW to fix it is almost infinite in variety.

You might have specific methods for specific noises.  You might compose those methods as members of an interface.  The methods or the interfaces might be organised around the nature of the noise (IBark, IYelp, IPurr etc)

```<code>IBark.Bark()
IYelp.Yelp()
</code>```

Or may have methods that are oriented around collections of behaviours (IExpressPain, IExpressHappiness):

```<code>List<EmotionalExpression> IExpressPain.ExpressionsOfPain()
List<EmotionalExpression> IExpressPain.ExpressionsOfHappiness()
</code>```

Or these methods might add expressions to some specified and provided collection:

```<code>IExpressPain.ExpressIrritation(List<EmotionalExpression> expressions)
</code>```

Where an EmotionalExpression might be some representation of (e.g.) Wag, Twitch, Purr, Growl etc.  Where Wag and Twitch are subclasses of TailExpression and Purr and Growl are subclasses of SubVocalExpression (in turn a sub-class of AudibleExpression) etc etc.  So for any particular emotionally driven behaviour an animal might express any number of different emotional expressions of different classes (physical, audible etc).

It all depends on the needs and acceptable complexities of the application.

But what I think can be said is that GetNoise() is an over-simplification and hence your difficulty.

Body:
I have this code, the question is below the code:

public class MainProgram
{
    public static void Main()
    {
        List<Animal> Animals = new List<Animal>();
        Animals.Add(new Dog());
        Animals.Add(new Poodle());
        Animals.Add(new Poodle());
        Animals.Add(new Beagle());
        Animals.Add(new Cat());

        Bark[] JustTheBarks = Dog.GetBarkList(Animals);
        foreach (Bark B in JustTheBarks)
        {
            Console.WriteLine(B.ToString());
        }
    }
}

abstract class Animal
{
    public abstract Noise GetNoise();
}

class Dog : Animal
{
    public override Noise GetNoise()
    {
        return new Bark("bark");
    }

    public static Bark[] GetBarkList(List<Animal> List)
    {
        return List
            .OfType<Dog>()
            .Select(r => r.GetNoise())
            .Cast<Bark>()
            .ToArray();
    }
}

class Beagle : Dog
{
    public override Noise GetNoise()
    {
        return new Woof("woof", 7);
    }
}

class Poodle : Dog
{
    public override Noise GetNoise()
    {
        return new Purr();
    }
}

class Cat : Animal
{
    public override Noise GetNoise()
    {
        throw new NotImplementedException();
    }
}

class Noise
{
}

class Bark : Noise
{
    protected string Text;
    public Bark(string Text)
    {
        this.Text = Text;
    }

    public override string ToString()
    {
        return $"{Text}";
    }
}

class Woof : Bark
{
    protected int Pitch;

    public Woof(string Text, int Pitch) : base(Text)
    {
        this.Pitch = Pitch;
    }
    public override string ToString()
    {
        return $"{Text}->{Pitch}";
    }
}

class Purr : Noise { }

}

In plain text, Animals and Noises, each animal returns its own type of noise, the noises correspond to the animal class, although sometimes an animal might return different Noises based on some variable (but for a dog only some form of Bark).

This code crashes of course. The Poodle returns a Purr(), and it "should" return something of type Bark.  I have the abstract function GetNoise() which just returns a Noise. What I want/need is to write

class Dog
{
    public override Bark GetNoise();
}

But this is not allowed, the return type must be the same. I don't want to write a second layer of GetBark() functions in every Dog class, etc.

What I want is to re-write this such that there is no casting, and everything that is derived from Dog is forced to return a Bark in its GetNoise() function such that I can safely write:

Bark B = Dog.GetNoise();

Body:
This is a classic mis-application of OO.

Beagle and Poodle are not sub-classes of "Dog".  Rather they are collectively different types of dog that share similar characteristics.  They both have the same properties but the values of those properties identify groups of similar instances not sub-classes.

This is similar to the confusion of "Square" and "Rectangle" as sub-classes of shape when in fact they are both instances of a polygon.  The properties they have in common (4 vertices, 4 equal internal angles of 90 degrees) do not constitute different classes of shape but different values of the properties of those shapes.

In your example the issue extends deeper into the differentiation of different characteristics of noise as sub-classes.  A Purr and a Bark are both instances of a noise differentiated only by the waveform and/or the method of production.

What is missing is the nature of the noise (vocal, sub-vocal or other - e.g. insects rubbing legs/wing-cases together etc) or the purpose of the noise (warning, pleasure, anger, anxiety, pain, attracting a mate etc)

The reduction of noise making on an animal to a single method then compounds the problem.

Assuming that Cat and Dog are (more) legitimate subclasses of Animal:  Cat's have the ability (a method) to Purr() but a Dog does not.  A Dog has the ability to Bark() but a Cat does not.  A Cat() has the ability to Meow() however and in some cases a Meow() might be considered the equivalent to a Bark() but in other cases a Hiss() might be more nearly equivalent.  Yet again, when a Dog Growls() is this akin to a Cat Hiss()ing or Purr()ing (physiologically the latter, contextually the former) ?

And then there is Yelp()ing.  Howl()ing.  etc.

All of these are noises and independent of any particular animal type involved there is no legitimate basis for saying that if some thing is capable of making any Noise then it can only make specific sub-classes of Noise.

In short:  This object model is broken.  :)

Rather than try to contort the classes to fit a broken model it will serve you better in the long run to fix the model itself.

HOW to fix it is almost infinite in variety.

You might have specific methods for specific noises.  You might compose those methods as members of an interface.  The methods or the interfaces might be organised around the nature of the noise (IBark, IYelp, IPurr etc)

IBark.Bark()
IYelp.Yelp()

Or may have methods that are oriented around collections of behaviours (IExpressPain, IExpressHappiness):

List<EmotionalExpression> IExpressPain.ExpressionsOfPain()
List<EmotionalExpression> IExpressPain.ExpressionsOfHappiness()

Or these methods might add expressions to some specified and provided collection:

IExpressPain.ExpressIrritation(List<EmotionalExpression> expressions)

Where an EmotionalExpression might be some representation of (e.g.) Wag, Twitch, Purr, Growl etc.  Where Wag and Twitch are subclasses of TailExpression and Purr and Growl are subclasses of SubVocalExpression (in turn a sub-class of AudibleExpression) etc etc.  So for any particular emotionally driven behaviour an animal might express any number of different emotional expressions of different classes (physical, audible etc).

It all depends on the needs and acceptable complexities of the application.

But what I think can be said is that GetNoise() is an over-simplification and hence your difficulty.


问:
Pass environment variables to kubernetes at runtime
While using vanilla docker, compose or swarm, I’m able to pass “—add-env FOO=bar” as a Docker cli parameter in order to define a env var value for the container at runtime. However, In kubernetes, I’m only seeing how to hardcore the value in the .yml file at the container spec section.

Can anyone point me how to pass it at runtime? (I.e. pass a env var when using “kubectl apply ...”)

Thanks! Really appreciate any help!

Best regards,

答:
It's pretty easy to use the templating language of your choice. For example with erb you can just do erb deployment.erb.yaml | kubectl apply -f -.

For most simple use cases you can just use envsubst: cat deployment.yaml | envsubst | kubectl apply -f -


问:
can we have multiple azure active directory tenant mapped to a single subscription?
can we have multiple azure active directory tenant mapped to a single subscription? This is because we want to avoid creating multiple subscriptions for each test environment</p>

答: As discussed earlier today, it is only possible to do this on the Classic Portal, which is coming to End of Life as of November 30th. Microsoft doesn't have any plans to introduce this into the new portal anytime soon it seems, and may even plan to keep the relationship 1:1 for Azure going forward.</p>