问:
Next.js Redux integration Could not find "store" in either the context or props
I am currently trying to integrate my redux store to my Next.js react applcation. The only issue now is when I try to call connect inside my index.js file.

Maybe it has something to do with the way my app is laid out? I tried console.log(this.props) inside index.js but it doesn't seem to have anything sent down from provider.

Error:
Could not find "store" in either the context or props of "Connect(Page)". Either wrap the root component in a , or explicitly pass "store" as a prop to "Connect(Page)".

page.js

```<code>import React from 'react';
import { Provider } from 'react-redux';
import store from '../store/store';
import Head from './head'
import Nav from './nav'

const childPage = (ChildPage) => {
    return (
        class Page extends React.Component {
            render() {
                return (
                    <Provider store={store}>
                        <div>
                            <Head />
                            <Nav />
                            <ChildPage />
                        </div>
                    </Provider>
                )
            }
        }
    )
}

export default childPage;
</code>```

index.js

```<code>import React from 'react';
import { connect } from 'react-redux'
import Page from '../components/page';

export class Index extends React.Component {
  render() {
    return (
      <div>
        <div className="hero">

        </div>
        <style jsx>{`

        `}</style>
      </div>
    )
  }
}

export default connect(state => state)(Page(Index));
</code>```

答:
The structure order was incorrect.

```<code>export default connect(state=>state)(Page(Index));
</code>```

This leads to connect() > Provider > Index

```<code>export default Page(connect(state=>state)(Index));
</code>```

This leads to Provider > connect() > Index

So the answer is to do it like this:

```<code>export default Page(connect(state=>state)(Index));
</code>```

Body:
I am currently trying to integrate my redux store to my Next.js react applcation. The only issue now is when I try to call connect inside my index.js file.

Maybe it has something to do with the way my app is laid out? I tried console.log(this.props) inside index.js but it doesn't seem to have anything sent down from provider.

Error:
Could not find "store" in either the context or props of "Connect(Page)". Either wrap the root component in a , or explicitly pass "store" as a prop to "Connect(Page)".

page.js

import React from 'react';
import { Provider } from 'react-redux';
import store from '../store/store';
import Head from './head'
import Nav from './nav'

const childPage = (ChildPage) => {
    return (
        class Page extends React.Component {
            render() {
                return (
                    <Provider store={store}>

                            <ChildPage />

                    </Provider>
                )
            }
        }
    )
}

export default childPage;

index.js

import React from 'react';
import { connect } from 'react-redux'
import Page from '../components/page';

export class Index extends React.Component {
  render() {
    return (

    )
  }
}

export default connect(state => state)(Page(Index));

Body:
The structure order was incorrect.

export default connect(state=>state)(Page(Index));

This leads to connect() > Provider > Index

export default Page(connect(state=>state)(Index));

This leads to Provider > connect() > Index

So the answer is to do it like this:

export default Page(connect(state=>state)(Index));


来源: stackexchange

问:
Get element from tab in protractor

```<code><div class="tab"><br>
  <div class="main-icon-container">
    <div class="flex-container">
         <!---->
      <div class="flex-item text-center"
         ng-repeat="icon in ctrl.data.icons | filter: tab"
           ng-class="{ 'icon-selected': ctrl.data.selectedIcon === icon.icon }"
              ng-click="ctrl.data.selectIcon(icon.icon)">
               <div class="icon-container">
                 <span class="cursor icon icon-location_apartment_block grey-bg">::before
            </span>
         </div>
       <p> Apartment block </p>
     </div>
    <!---->
</code>```

How can I locate the above first element from tab in Protractor ??
Tab has 15 elements,this one above this is first element from tab.I want to click on the element,doesn't matter which one.

```<code><div class="tab-pane active"
           ng-repeat="tab in tabset.tabs"
              ng-class="{active: tabset.active === tab.index}" uib-tab-content-transclude="tab" style>
</code>```

答:
Man, you can use XPath, and talk the way you go through the HTML document, it's a bit more work, but sometimes it's the only way.

```<code>FindElement(By.XPath(//tagname//tagname[@atrinbuto: value]));
</code>```

you can use this to get at the element you want

ContentLicense: CC BY-SA 3.0

Title: Get element from tab in protractor

Body:
                 ::before

 Apartment block

How can I locate the above first element from tab in Protractor ??
Tab has 15 elements,this one above this is first element from tab.I want to click on the element,doesn't matter which one.

Body:
Man, you can use XPath, and talk the way you go through the HTML document, it's a bit more work, but sometimes it's the only way.

FindElement(By.XPath(//tagname//tagname[@atrinbuto: value]));

you can use this to get at the element you want


问:
c# create word document with openXML : XML Parsing Error (when replacement string contains spaces)
I am trying to create a word document using a word template in my C# application using openXML. Here is my code so far:

```<code>DirectoryInfo tempDir = new DirectoryInfo(Server.MapPath("~\\Files\\WordTemplates\\"));

DirectoryInfo docsDir = new DirectoryInfo(Server.MapPath("~\\Files\\FinanceDocuments\\"));

string ype = "test Merge"; //if ype string contains spaces then I get this error
string sourceFile = tempDir + "\\PaymentOrderTemplate.dotx";
string destinationFile = docsDir + "\\" + "PaymentOrder.doc";

// Create a copy of the template file and open the copy
File.Copy(sourceFile, destinationFile, true);

// create key value pair, key represents words to be replace and
//values represent values in document in place of keys.
Dictionary<string, string> keyValues = new Dictionary<string, string>();
keyValues.Add("ype", ype);
SearchAndReplace(destinationFile, keyValues);
Process.Start(destinationFile);
</code>```

And the SearchAndReplace funtion:

```<code>public static void SearchAndReplace(string document, Dictionary<string, string> dict)
{
    using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(document, true))
    {
        string docText = null;

        using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
        {
            docText = sr.ReadToEnd();
        }

        foreach (KeyValuePair<string, string> item in dict)
        {
            Regex regexText = new Regex(item.Key);
            docText = regexText.Replace(docText, item.Value);
        }

        using (StreamWriter sw = new StreamWriter(
                  wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
        {
            sw.Write(docText);
        }
    }
}
</code>```

But when I try to open the exported file I get this error:

XML parsing error

Location: Part: /word/document.xml, line: 2, Column: 2142

Document.xml first lines:

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>

<w:document xmlns:wpc="http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas" xmlns:cx="http://schemas.microsoft.com/office/drawing/2014/chartex" xmlns:cx1="http://schemas.microsoft.com/office/drawing/2015/9/8/chartex" xmlns:cx2="http://schemas.microsoft.com/office/drawing/2015/10/21/chartex" xmlns:cx3="http://schemas.microsoft.com/office/drawing/2016/5/9/chartex" xmlns:cx4="http://schemas.microsoft.com/office/drawing/2016/5/10/chartex" xmlns:cx5="http://schemas.microsoft.com/office/drawing/2016/5/11/chartex" xmlns:cx6="http://schemas.microsoft.com/office/drawing/2016/5/12/chartex" xmlns:cx7="http://schemas.microsoft.com/office/drawing/2016/5/13/chartex" xmlns:cx8="http://schemas.microsoft.com/office/drawing/2016/5/14/chartex" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:aink="http://schemas.microsoft.com/office/drawing/2016/ink" xmlns:am3d="http://schemas.microsoft.com/office/drawing/2017/model3d" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:wp14="http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:w10="urn:schemas-microsoft-com:office:word" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" xmlns:w15="http://schemas.microsoft.com/office/word/2012/wordml" xmlns:w16cid="http://schemas.microsoft.com/office/word/2016/wordml/cid" xmlns:w16se="http://schemas.microsoft.com/office/word/2015/wordml/symex" xmlns:wpg="http://schemas.microsoft.com/office/word/2010/wordprocessingGroup" xmlns:wpi="http://schemas.microsoft.com/office/word/2010/wordprocessingInk" xmlns:wne="http://schemas.microsoft.com/office/word/2006/wordml" xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape" mc:Ignorable="w14 w15 w16se w16cid wp14">

<w:body>

<w:tbl>

<w:tblPr>

<w:tblW w:w="10348" w:ttest Merge="dxa"/>

<w:tblInd w:w="108" w:ttest Merge="dxa"/>

<w:tblBorders>
</code>```

Edit
I found out that the problem occured because I was using mergefields in the word template. If I use plain text it works. But in this case it will be slow because it has to check every single word in the template and if matches replace it. Is it possible to do it in another way?

答:
Disclaimer: You seem to be using the OpenXML SDK, because your code looks virtually identical to that found here: https://msdn.microsoft.com/en-us/library/bb508261(v=office.12).aspx - I've never in my life used this SDK and I'm basing this answer on an educated guess at what's happening

It seems that the operation you're carrying out on this Word document is affecting parts of the document that you didn't intend.

I believe that calling document.MainDocumentPart.GetStream() just giving you more or less raw direct access to the XML of the document, and you're then treating it as a plain xml file, manipulating it as text, and carrying out a list of straight text replacements? I think it's thus likely the cause of the problem because you're intending to edit document text, but accidentally damaging xml node structure in the process

By way of an example, here is a simple HTML document:

```<code><html>
 <head><title>Damage report</title></head>
 <body>
  <p>The soldier was shot once in the body and twice in the head</p>
 </body>
</html>
</code>```

You decide to run a find/replace to make the places the soldier was shot, a bit more specific:

```<code>var html = File.ReadAllText(@"c:\my.html");
html = html.Replace("body", "chest");
html = html.Replace("head", "forehead");
File.WriteAllText(@"c:\my.html");
</code>```

Only thing, your document is now ruined:

```<code><html>
 <forehead><title>Damage report</title></forehead>
 <chest>
  <p>The soldier was shot once in the chest and twice in the forehead</p>
 </chest>
</html>
</code>```

A browser can't parse it (well, it's still valid I suppose, but it's meaningless) any more because the replacement operation broke some things.

You're replacing "ype" with "test Merge" but this seems to be clobbering an occurrence of the word "type" - something that it seems pretty likely would appear in the XML attribute or element names - and turning it into "ttest Merge".

To correctly change the content of an XML document's node texts, it should be parsed from text to an XML document object model representation, the nodes iterated, the texts altered, and the whole thing re-serialized back to xml text. Office SDK does seem to provide ways to do this, because you can treat a document like a collection of class object instances, and say things like this code snippet (also from MSDN):

```<code>// Create a Wordprocessing document.
using (WordprocessingDocument myDoc = WordprocessingDocument.Create(docName, WordprocessingDocumentType.Document))
{
   // Add a new main document part.
   MainDocumentPart mainPart = myDoc.AddMainDocumentPart();
   //Create DOM tree for simple document.
   mainPart.Document = new Document();
   Body body = new Body();
   Paragraph p = new Paragraph();
   Run r = new Run();
   Text t = new Text("Hello World!");
   //Append elements appropriately.
   r.Append(t);
   p.Append(r);
   body.Append(p);
   mainPart.Document.Append(body);
   // Save changes to the main document part.
   mainPart.Document.Save();
}
</code>```

You should be looking for another way, not using streams/direct low level xml access, to access the document elements. Something like these:

```<code>https://blogs.msdn.microsoft.com/brian_jones/2009/01/28/traversing-in-the-open-xml-dom/
https://www.gemboxsoftware.com/document/articles/find-replace-word-csharp
</code>```

Or possibly starting with a related SO question like this: Search And Replace Text in OPENXML (Added file) (though the answer you need may be in the something linked inside this question)

Body:
I am trying to create a word document using a word template in my C# application using openXML. Here is my code so far:

DirectoryInfo tempDir = new DirectoryInfo(Server.MapPath("~\\Files\\WordTemplates\\"));

DirectoryInfo docsDir = new DirectoryInfo(Server.MapPath("~\\Files\\FinanceDocuments\\"));

string ype = "test Merge"; //if ype string contains spaces then I get this error
string sourceFile = tempDir + "\\PaymentOrderTemplate.dotx";
string destinationFile = docsDir + "\\" + "PaymentOrder.doc";

// Create a copy of the template file and open the copy
File.Copy(sourceFile, destinationFile, true);

// create key value pair, key represents words to be replace and
//values represent values in document in place of keys.
Dictionary<string, string> keyValues = new Dictionary<string, string>();
keyValues.Add("ype", ype);
SearchAndReplace(destinationFile, keyValues);
Process.Start(destinationFile);

And the SearchAndReplace funtion:

public static void SearchAndReplace(string document, Dictionary<string, string> dict)
{
    using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(document, true))
    {
        string docText = null;

        using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
        {
            docText = sr.ReadToEnd();
        }

        foreach (KeyValuePair<string, string> item in dict)
        {
            Regex regexText = new Regex(item.Key);
            docText = regexText.Replace(docText, item.Value);
        }

        using (StreamWriter sw = new StreamWriter(
                  wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
        {
            sw.Write(docText);
        }
    }
}

But when I try to open the exported file I get this error:

XML parsing error

Location: Part: /word/document.xml, line: 2, Column: 2142

Document.xml first lines:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>

<w:document xmlns:wpc="http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas" xmlns:cx="http://schemas.microsoft.com/office/drawing/2014/chartex" xmlns:cx1="http://schemas.microsoft.com/office/drawing/2015/9/8/chartex" xmlns:cx2="http://schemas.microsoft.com/office/drawing/2015/10/21/chartex" xmlns:cx3="http://schemas.microsoft.com/office/drawing/2016/5/9/chartex" xmlns:cx4="http://schemas.microsoft.com/office/drawing/2016/5/10/chartex" xmlns:cx5="http://schemas.microsoft.com/office/drawing/2016/5/11/chartex" xmlns:cx6="http://schemas.microsoft.com/office/drawing/2016/5/12/chartex" xmlns:cx7="http://schemas.microsoft.com/office/drawing/2016/5/13/chartex" xmlns:cx8="http://schemas.microsoft.com/office/drawing/2016/5/14/chartex" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:aink="http://schemas.microsoft.com/office/drawing/2016/ink" xmlns:am3d="http://schemas.microsoft.com/office/drawing/2017/model3d" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:wp14="http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:w10="urn:schemas-microsoft-com:office:word" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" xmlns:w15="http://schemas.microsoft.com/office/word/2012/wordml" xmlns:w16cid="http://schemas.microsoft.com/office/word/2016/wordml/cid" xmlns:w16se="http://schemas.microsoft.com/office/word/2015/wordml/symex" xmlns:wpg="http://schemas.microsoft.com/office/word/2010/wordprocessingGroup" xmlns:wpi="http://schemas.microsoft.com/office/word/2010/wordprocessingInk" xmlns:wne="http://schemas.microsoft.com/office/word/2006/wordml" xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape" mc:Ignorable="w14 w15 w16se w16cid wp14">

<w:body>

<w:tbl>

<w:tblPr>

<w:tblW w:w="10348" w:ttest Merge="dxa"/>

<w:tblInd w:w="108" w:ttest Merge="dxa"/>

<w:tblBorders>

Edit
I found out that the problem occured because I was using mergefields in the word template. If I use plain text it works. But in this case it will be slow because it has to check every single word in the template and if matches replace it. Is it possible to do it in another way?

Body:
Disclaimer: You seem to be using the OpenXML SDK, because your code looks virtually identical to that found here: https://msdn.microsoft.com/en-us/library/bb508261(v=office.12).aspx - I've never in my life used this SDK and I'm basing this answer on an educated guess at what's happening

It seems that the operation you're carrying out on this Word document is affecting parts of the document that you didn't intend.

I believe that calling document.MainDocumentPart.GetStream() just giving you more or less raw direct access to the XML of the document, and you're then treating it as a plain xml file, manipulating it as text, and carrying out a list of straight text replacements? I think it's thus likely the cause of the problem because you're intending to edit document text, but accidentally damaging xml node structure in the process

By way of an example, here is a simple HTML document:

<html>
 <head><title>Damage report</title></head>
 <body>
  <p>The soldier was shot once in the body and twice in the head</p>
 </body>
</html>

You decide to run a find/replace to make the places the soldier was shot, a bit more specific:

var html = File.ReadAllText(@"c:\my.html");
html = html.Replace("body", "chest");
html = html.Replace("head", "forehead");
File.WriteAllText(@"c:\my.html");

Only thing, your document is now ruined:

<html>
 <forehead><title>Damage report</title></forehead>
 <chest>
  <p>The soldier was shot once in the chest and twice in the forehead</p>
 </chest>
</html>

A browser can't parse it (well, it's still valid I suppose, but it's meaningless) any more because the replacement operation broke some things.

You're replacing "ype" with "test Merge" but this seems to be clobbering an occurrence of the word "type" - something that it seems pretty likely would appear in the XML attribute or element names - and turning it into "ttest Merge".

To correctly change the content of an XML document's node texts, it should be parsed from text to an XML document object model representation, the nodes iterated, the texts altered, and the whole thing re-serialized back to xml text. Office SDK does seem to provide ways to do this, because you can treat a document like a collection of class object instances, and say things like this code snippet (also from MSDN):

// Create a Wordprocessing document.
using (WordprocessingDocument myDoc = WordprocessingDocument.Create(docName, WordprocessingDocumentType.Document))
{
   // Add a new main document part.
   MainDocumentPart mainPart = myDoc.AddMainDocumentPart();
   //Create DOM tree for simple document.
   mainPart.Document = new Document();
   Body body = new Body();
   Paragraph p = new Paragraph();
   Run r = new Run();
   Text t = new Text("Hello World!");
   //Append elements appropriately.
   r.Append(t);
   p.Append(r);
   body.Append(p);
   mainPart.Document.Append(body);
   // Save changes to the main document part.
   mainPart.Document.Save();
}

You should be looking for another way, not using streams/direct low level xml access, to access the document elements. Something like these:

https://blogs.msdn.microsoft.com/brian_jones/2009/01/28/traversing-in-the-open-xml-dom/
https://www.gemboxsoftware.com/document/articles/find-replace-word-csharp

Or possibly starting with a related SO question like this: Search And Replace Text in OPENXML (Added file) (though the answer you need may be in the something linked inside this question)


问:
Selenium WebDriver click child element
I'm using selenium and I want to click a child element with 2 as value.

This is the full code:

```<code><div class="dialer-keypad">
    <div class="dialpad-row">
        <div class="key">
            <div class="value">1</div>
            <div class="letters"></div>
        </div>
        <div class="key">
            <div class="value">2</div>
            <div class="letters">ABC</div>
        </div>
        <div class="key">
            <div class="value">3</div>
            <div class="letters">DEF</div>
        </div>
    </div>
    <div class="dialpad-row">
        <div class="key">
            <div class="value">4</div>
            <div class="letters">GHI</div>
        </div>
        <div class="key">
            <div class="value">5</div>
            <div class="letters">JKL</div>
        </div>
        <div class="key">
            <div class="value">6</div>
            <div class="letters">MNO</div>
        </div>
    </div>
</div>
</code>```

So my question is How can I click this element?

```<code><div class="value">2</div>
</code>```

答:
You should be able do this quite succinctly with XPath:

//*[contains(@class, 'value') and text()='2']

Alternatively, assuming that the markup was static you could target the element using specific indices. For example:

.dialpad-row:first-child .key:nth-child(2) .value

Title: Selenium WebDriver click child element

Body:
I'm using selenium and I want to click a child element with 2 as value.

This is the full code:

1

2

ABC

3

DEF

4

GHI

5

JKL

6

MNO

So my question is How can I click this element?

2


问:
In TFS, how can I cherry-pick a changeset to an unrelated branch?
I have a very messy TFS structure that I am trying to clean up (thanks to my predecessor).  I now have a situation where I need to bring changesets selectively from one branch to another where they don't have a parent/child relationship and I don't want those changes to pass through their shared trunk.  How can I do this?

I have tried a baseless merge - In TFS, how do I do a baseless merge on specific changesets? - which told me that there were no changes to merge.

What I want to achieve is something like this TFS : Can a shelveset be restored to another location? except with a changeset.

In GIT I think this would be a simple cherry-pick.

My structure looks something like:

```<code>   Y-C1-C2-C3
  /
X-------------
    \
     Z
</code>```

And the question is how do I get C2 from Y into Z without passing through X?

答:
Its simpler to do it using Visual studio.

In Visual studio use the Source Control Merge wizard to merge the unrelated branches.

It has an option to merge selective changesets. The only restriction is that the changesets must be consecutive

ContentLicense: CC BY-SA 2.5

Body:
I have a very messy TFS structure that I am trying to clean up (thanks to my predecessor).  I now have a situation where I need to bring changesets selectively from one branch to another where they don't have a parent/child relationship and I don't want those changes to pass through their shared trunk.  How can I do this?

I have tried a baseless merge - In TFS, how do I do a baseless merge on specific changesets? - which told me that there were no changes to merge.

What I want to achieve is something like this TFS : Can a shelveset be restored to another location? except with a changeset.

In GIT I think this would be a simple cherry-pick.

My structure looks something like:

   Y-C1-C2-C3
  /
X-------------
    \
     Z

And the question is how do I get C2 from Y into Z without passing through X?


问:
Spring Integration: Persistent and transactional QueueChannel
In Spring Integration we have a Setup that looks something like this:

```<code>                                                     --->
                                                     --->
(dispatcher) Messages --> Gateway ----> QueueChannel ---> MessageHandler (worker)
                                                     --->
                                                     --->
</code>```

So we have one Dispatcher Thread that takes Messages from a MQTT-Broker and forwards them into the Queue. The Poller for the Queue is provided with a TaskExecuter, so the Consumer is multithreaded.
We managed to implement all the functionalities. So the just described setup is already implemented.

Now to guarantee no data loss we want to make two things:

1.:
We want our queue to persist the data, so when the Programm shuts down ungracefully, all the data in the queue will still be there.
This also worked for us, we are using MongoDB as a database because we read somewhere in your docs that this is the recommended way to do it.

2.:
The second thing we want to assure is that the worker threads are working transactional. So only if the worker threads return correctly the messages will permanently be deleted from the queue (and therefore the persistent MessageStore). If the program shuts down during the processing of a message (by the worker thread) the message will still be in the queue at the next startup.
Also if the worker, for example, thows an exception during the processing of the message, it will be put back into the queue.

Our implementation:

As explained before, the basic setup of the program is already implemented. We then extended the basic implementation with a message store implementation for the queue.

QueueChannel:

```<code>@Bean
public PollableChannel inputChannel(BasicMessageGroupStore mongoDbChannelMessageStore) {
    return new QueueChannel(new MessageGroupQueue(mongoDbChannelMessageStore, "inputChannel"));
}
</code>```

backed by a Messagestore:

```<code>@Bean
public BasicMessageGroupStore mongoDbChannelMessageStore(MongoDbFactory mongoDbFactory) {
    MongoDbChannelMessageStore store = new MongoDbChannelMessageStore(mongoDbFactory);
    store.setPriorityEnabled(true);
    return store;
}
</code>```

the matching Poller:

```<code>@Bean(name = PollerMetadata.DEFAULT_POLLER)
public PollerMetadata poller() {
    PollerMetadata poll = Pollers.fixedDelay(10).get();
    poll.setTaskExecutor(consumer);
    return poll;
}
</code>```

Executor:

```<code>private Executor consumer = Executors.newFixedThreadPool(5);
</code>```

What we have tried?
As explained now we want to extend this implementation with a transactional functionality. We tried using the setTransactionSynchronizationFactory like explained here but it wasn't working (didn't get errors or anything but the behavior was still as it was before we added the TransactionSynchronizer):

```<code>@Bean(name = PollerMetadata.DEFAULT_POLLER)
public PollerMetadata poller() {
    PollerMetadata poll = Pollers.fixedDelay(10).get();
    poll.setTaskExecutor(consumer);

    BeanFactory factory = mock(BeanFactory.class);
    ExpressionEvaluatingTransactionSynchronizationProcessor etsp = new ExpressionEvaluatingTransactionSynchronizationProcessor();
    etsp.setBeanFactory(factory);
    etsp.setAfterRollbackChannel(inputChannel());
    etsp.setAfterRollbackExpression(new SpelExpressionParser().parseExpression("#bix"));
    etsp.setAfterCommitChannel(inputChannel());
    etsp.setAfterCommitExpression(new SpelExpressionParser().parseExpression("#bix"));
    DefaultTransactionSynchronizationFactory dtsf = new DefaultTransactionSynchronizationFactory(etsp);

    poll.setTransactionSynchronizationFactory(dtsf);

    return poll;
}
</code>```

What would be the best way to realize our requirements in spring integration?

EDIT:
As recommended in the answer I chose to do this with the JdbcChannelMessageStore. So I tried converting the XML Implementation described here (18.4.2) into Java.  I wasn't quite sure on how to do it, this is what I have tried so far:

I created H2 database and run the script shown here on it.

Created JDBCChannelMessageStore Bean:

```<code>@Bean
public JdbcChannelMessageStore store() {
    JdbcChannelMessageStore ms =  new JdbcChannelMessageStore();
    ms.setChannelMessageStoreQueryProvider(queryProvider());
    ms.setUsingIdCache(true);
    ms.setDataSource(dataSource);
    return ms;
}
</code>```

Created H2ChannelMessageStoreQueryProvider

```<code>    @Bean
    public ChannelMessageStoreQueryProvider queryProvider() {
        return new H2ChannelMessageStoreQueryProvider();
    }
</code>```

Adapted the poller:

```<code>@Bean(name = PollerMetadata.DEFAULT_POLLER)
public PollerMetadata poller() throws Exception {
    PollerMetadata poll = Pollers.fixedDelay(10).get();
    poll.setTaskExecutor(consumer);
    poll.setAdviceChain(Collections.singletonList(transactionInterceptor()));

    return poll;
}
</code>```

Autowired my PlaatformTransactionManager:

```<code>@Autowired
PlatformTransactionManager transactionManager;
</code>```

And created TransactionInterceptor from the TransactonManager:

```<code>@Bean
public PollableChannel inputChannel(BasicMessageGroupStore mongoDbChannelMessageStore) {
    return new QueueChannel(new MessageGroupQueue(mongoDbChannelMessageStore, "inputChannel"));
}
</code>```0

答:
Thanks to Artem Bilan for your great support. I finally found the solution. It seemed like there was another bean with the name transactionManager and transactionInterceptor active. This resulted in the strange behavior, that my trans-manager was never initialized, instead the other transactionmanager (null) was used for the transactioninterceptor and the PollingConsumer. Thats why my Transactionmanager in PollingConsumer was null, and why my Transactions were never working.

The solution was to rename all my beans, for some beans I also used the annotation @Primary to tell spring to always use this speciffic bean when autowired.

I also downgraded two 4.3, just to make sure this wasn't an error related to Version 5. I haven't testet if it would work with V 5 yet,  but I think it should work also.

Body:
In Spring Integration we have a Setup that looks something like this:

                                                     --->
                                                     --->
(dispatcher) Messages --> Gateway ----> QueueChannel ---> MessageHandler (worker)
                                                     --->
                                                     --->

So we have one Dispatcher Thread that takes Messages from a MQTT-Broker and forwards them into the Queue. The Poller for the Queue is provided with a TaskExecuter, so the Consumer is multithreaded.
We managed to implement all the functionalities. So the just described setup is already implemented.

Now to guarantee no data loss we want to make two things:

1.:
We want our queue to persist the data, so when the Programm shuts down ungracefully, all the data in the queue will still be there.
This also worked for us, we are using MongoDB as a database because we read somewhere in your docs that this is the recommended way to do it.

2.:
The second thing we want to assure is that the worker threads are working transactional. So only if the worker threads return correctly the messages will permanently be deleted from the queue (and therefore the persistent MessageStore). If the program shuts down during the processing of a message (by the worker thread) the message will still be in the queue at the next startup.
Also if the worker, for example, thows an exception during the processing of the message, it will be put back into the queue.

Our implementation:

As explained before, the basic setup of the program is already implemented. We then extended the basic implementation with a message store implementation for the queue.

QueueChannel:

@Bean
public PollableChannel inputChannel(BasicMessageGroupStore mongoDbChannelMessageStore) {
    return new QueueChannel(new MessageGroupQueue(mongoDbChannelMessageStore, "inputChannel"));
}

backed by a Messagestore:

@Bean
public BasicMessageGroupStore mongoDbChannelMessageStore(MongoDbFactory mongoDbFactory) {
    MongoDbChannelMessageStore store = new MongoDbChannelMessageStore(mongoDbFactory);
    store.setPriorityEnabled(true);
    return store;
}

the matching Poller:

@Bean(name = PollerMetadata.DEFAULT_POLLER)
public PollerMetadata poller() {
    PollerMetadata poll = Pollers.fixedDelay(10).get();
    poll.setTaskExecutor(consumer);
    return poll;
}

Executor:

private Executor consumer = Executors.newFixedThreadPool(5);

What we have tried?
As explained now we want to extend this implementation with a transactional functionality. We tried using the setTransactionSynchronizationFactory like explained here but it wasn't working (didn't get errors or anything but the behavior was still as it was before we added the TransactionSynchronizer):

@Bean(name = PollerMetadata.DEFAULT_POLLER)
public PollerMetadata poller() {
    PollerMetadata poll = Pollers.fixedDelay(10).get();
    poll.setTaskExecutor(consumer);

    BeanFactory factory = mock(BeanFactory.class);
    ExpressionEvaluatingTransactionSynchronizationProcessor etsp = new ExpressionEvaluatingTransactionSynchronizationProcessor();
    etsp.setBeanFactory(factory);
    etsp.setAfterRollbackChannel(inputChannel());
    etsp.setAfterRollbackExpression(new SpelExpressionParser().parseExpression("#bix"));
    etsp.setAfterCommitChannel(inputChannel());
    etsp.setAfterCommitExpression(new SpelExpressionParser().parseExpression("#bix"));
    DefaultTransactionSynchronizationFactory dtsf = new DefaultTransactionSynchronizationFactory(etsp);

    poll.setTransactionSynchronizationFactory(dtsf);

    return poll;
}

What would be the best way to realize our requirements in spring integration?

EDIT:
As recommended in the answer I chose to do this with the JdbcChannelMessageStore. So I tried converting the XML Implementation described here (18.4.2) into Java.  I wasn't quite sure on how to do it, this is what I have tried so far:

I created H2 database and run the script shown here on it.

Created JDBCChannelMessageStore Bean:

@Bean
public JdbcChannelMessageStore store() {
    JdbcChannelMessageStore ms =  new JdbcChannelMessageStore();
    ms.setChannelMessageStoreQueryProvider(queryProvider());
    ms.setUsingIdCache(true);
    ms.setDataSource(dataSource);
    return ms;
}

Created H2ChannelMessageStoreQueryProvider

    @Bean
    public ChannelMessageStoreQueryProvider queryProvider() {
        return new H2ChannelMessageStoreQueryProvider();
    }

Adapted the poller:

@Bean(name = PollerMetadata.DEFAULT_POLLER)
public PollerMetadata poller() throws Exception {
    PollerMetadata poll = Pollers.fixedDelay(10).get();
    poll.setTaskExecutor(consumer);
    poll.setAdviceChain(Collections.singletonList(transactionInterceptor()));

    return poll;
}

Autowired my PlaatformTransactionManager:

@Autowired
PlatformTransactionManager transactionManager;

And created TransactionInterceptor from the TransactonManager:

@Bean
public TransactionInterceptor transactionInterceptor() {
    return new TransactionInterceptorBuilder(true)
                .transactionManager(transactionManager)
                .isolation(Isolation.READ_COMMITTED)
                .propagation(Propagation.REQUIRED)
                .build();
}


问:
How can I drill down a stacked bar chart in Powerbi
How can I drill down a stacked bar chart in powerbi, I read that in axis field I have to use the column which I want to drill through, but it is displaying X-axis 0,1,2,3,4 its not making much sense, can somebody share any example here which you have done so that I can get much more clarity on this.</p>

答:
You're right, add the drilldown columns as the axis columns. Then you're able to drill down using the controls on the top of the bar chart.

For example, in this picture I have selected the Category and SubCatecory as the Axis-fields (the Value-field is selected as the Value-field):

At the top of the chart, there are arrows pointing up and down. Using those controls, you can drill down in the hierarchy.


问:
React not overwriting state
I'm usign setState to change the state of my component.

It works fine until i need to delete an element from the state.

Let's pretend i have this on my store:

```<code>{
    0: {name: foo},
    1: {name: bar}
}
</code>```

If I add another element, it works just fine:

```<code>store[2] = {name: hohoho};
setState(store, console.log(this.state));
</code>```

With the code above, I end up with the expected state:

```<code>{
    0: {name: foo},
    1: {name: bar},
    2: {name: hohoho},
}
</code>```

But if I delete one of the elements from the store and change the state again, it doesn't delete from the state:

```<code>delete store[2]
</code>```

If I console.log(store), I get:

```<code>{
    0: {name: foo},
    1: {name: bar}
}
</code>```

then:

```<code>setState(store, console.log(this.state))
</code>```

gives me:

```<code>{
    0: {name: foo},
    1: {name: bar},
    2: {name: hohoho},
}
</code>```

But stranger than this, is if I add another element to the store, and set the state after:

```<code>store[3] = {name: heyheyhey};
setState(store, console.log(this.state));
</code>```

I end up with the following state:

```<code>{
    0: {name: foo},
    1: {name: bar},
    2: {name: hohoho},
    3: {name: heyheyhey}
}
</code>```

Even if console.log(store) gives me the following:

```<code>{
    0: {name: foo},
    1: {name: bar},
    3: {name: heyheyhey}
}
</code>```

Can someone please help me understand whats going on?

EDIT

Since some comments said delete might be the problem, i changed the way I'm deleting from my store:

```<code>var temp = {};
for (var x in store) {
    if (x != id) {
        temp[x] = store[x];
    }
}
store= temp;
</code>```

But I'm still experiencing the same problem.

答:
I think you are using the second setState param mistakenly..
You should be aware that:

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.

and setState's second parameter is the callback:

In addition, you can supply an optional callback function that is executed once setState is completed and the component is re-rendered.
  So your callback should be something like:

```<code>setState(store, (newState) => console.log(newState);
</code>```

or the short version of it:

```<code>setState(store, console.log)
</code>```

Otherwise you'd just be logging current class state and returning undefined as the second param (callback)

Title: React not overwriting state

Body:
I'm usign setState to change the state of my component.

It works fine until i need to delete an element from the state.

Let's pretend i have this on my store:

{
    0: {name: foo},
    1: {name: bar}
}

If I add another element, it works just fine:

store[2] = {name: hohoho};
setState(store, console.log(this.state));

With the code above, I end up with the expected state:

{
    0: {name: foo},
    1: {name: bar},
    2: {name: hohoho},
}

But if I delete one of the elements from the store and change the state again, it doesn't delete from the state:

delete store[2]

If I console.log(store), I get:

{
    0: {name: foo},
    1: {name: bar}
}

then:

setState(store, console.log(this.state))

gives me:

{
    0: {name: foo},
    1: {name: bar},
    2: {name: hohoho},
}

But stranger than this, is if I add another element to the store, and set the state after:

store[3] = {name: heyheyhey};
setState(store, console.log(this.state));

I end up with the following state:

{
    0: {name: foo},
    1: {name: bar},
    2: {name: hohoho},
    3: {name: heyheyhey}
}

Even if console.log(store) gives me the following:

{
    0: {name: foo},
    1: {name: bar},
    3: {name: heyheyhey}
}

Can someone please help me understand whats going on?

EDIT

Since some comments said delete might be the problem, i changed the way I'm deleting from my store:

var temp = {};
for (var x in store) {
    if (x != id) {
        temp[x] = store[x];
    }
}
store= temp;

But I'm still experiencing the same problem.

Body:
I think you are using the second setState param mistakenly..
You should be aware that:

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.

and setState's second parameter is the callback:

In addition, you can supply an optional callback function that is executed once setState is completed and the component is re-rendered.
  So your callback should be something like:

setState(store, (newState) => console.log(newState);

or the short version of it:

setState(store, console.log)

Otherwise you'd just be logging current class state and returning undefined as the second param (callback)


问:
addEventListener isn't working with multi elements by getElementsByClassName
I'm trying to use addEventListener click with two buttons having the same class but it isn't working!

This is the html:

```<code><div class="share-block">
  <a href="#" class="btn-rounded share-btn"><i class="fa fa-share-alt fa-2x"></i></a>
  <div class="social-block">
    <a href="http://facebook.com/share" class="btn-rounded btn-sm social-btn btn-fb"><i class="fa fa-facebook"></i></a>
    <a href="http://twitter.com/share" class="btn-rounded btn-sm social-btn btn-tw"><i class="fa fa-twitter"></i></a>
  </div>
</div>
</code>```

And here's the javascript code:

```<code>var socialBtns = document.getElementsByClassName('social-btn');

for (var i = 0; i < socialBtns.length; i++) {
  socialBtns[i].addEventListener('click', function(event) {
    window.open(socialBtns[i].href, "Share", "width=600,height=400");
    event.preventDefault();
  });
}
</code>```

答:
Use this.href on your event handlers instead of referencing the socialBtns variable in the for-loop:

```<code>var socialBtns = document.getElementsByClassName('social-btn');

for (var i = 0; i < socialBtns.length; i++) {
    socialBtns[i].addEventListener('click', function(event) {
       window.open(this.href, "Share", "width=600,height=400");
       event.preventDefault();
    });
}
</code>```

You could also improve on the existing code by creating the event handler outside of the for-loop:

```<code>var socialBtns = document.getElementsByClassName('social-btn');

for (var i = 0; i < socialBtns.length; i++) {
  socialBtns[i].addEventListener('click', openSocialLink);
}

function openSocialLink(event) {
  window.open(this.href, "Share", "width=600,height=400");
  event.preventDefault();
}
</code>```

JSFiddle sample

Body:
I'm trying to use addEventListener click with two buttons having the same class but it isn't working!

This is the html:

And here's the javascript code:

var socialBtns = document.getElementsByClassName('social-btn');

for (var i = 0; i < socialBtns.length; i++) {
  socialBtns[i].addEventListener('click', function(event) {
    window.open(socialBtns[i].href, "Share", "width=600,height=400");
    event.preventDefault();
  });
}

Body:
Use this.href on your event handlers instead of referencing the socialBtns variable in the for-loop:

var socialBtns = document.getElementsByClassName('social-btn');

for (var i = 0; i < socialBtns.length; i++) {
    socialBtns[i].addEventListener('click', function(event) {
       window.open(this.href, "Share", "width=600,height=400");
       event.preventDefault();
    });
}

You could also improve on the existing code by creating the event handler outside of the for-loop:

var socialBtns = document.getElementsByClassName('social-btn');

for (var i = 0; i < socialBtns.length; i++) {
  socialBtns[i].addEventListener('click', openSocialLink);
}

function openSocialLink(event) {
  window.open(this.href, "Share", "width=600,height=400");
  event.preventDefault();
}

JSFiddle sample


问:
Does Javascript have anything similar to VBA's DoEvents?
I have a long running for-loop in my code and I'd like to delay to loop to handle other tasks in the event queue (like a button press). Does javascript or JQuery have anything that could help me? Basically I'm trying to do something similar to delaying loops like here (https://support.microsoft.com/en-us/kb/118468).</p>

答:
Here's a tested example of how to use Yield as a direct replacement for DoEvents.

(I've used Web Worker and it's great, but it's far removed from DoEvents and near-impossible to access global variables). This has been formatted for ease of understanding and attempts to show how the extras required (to make the function handle yield) could be treated as an insertion within the original function. "yield" has all sorts of other features, but used thus, it is a near direct replacement for DoEvents.

//'Replace DoEvents with Yield ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/yield )
var misc = 0; //'sample external var

function myfunction() { //'This is the beginning of your original function which is effectively replaced by a handler inserted as follows..
//'-----------------------------------Insert Handler..
  var obj = myfuncGen.next(); //'start it
  if (obj.done == false) {
    setTimeout(myfunction, 150); //'adjust for the amount of time you wish to yield (depends how much screen drawing is required or etc)
  }
}
var myfuncGen = myfuncSurrogate(); //'creates a "Generator" out of next.
function* myfuncSurrogate() { //'This the original function repackaged! Note asterisk.
//'-------------------------------------End Insert
  var ms;       //...your original function continues here....
  for (var i = 1; i <= 9; i++) { //'sample 9x loop
    ms = new Date().getTime();
    while (new Date().getTime() < ms + 500); //'PAUSE (get time & wait 500ms) as an example of being busy
    misc++; //'example manipulating an external var
    outputdiv.innerHTML = "Output Div
demonstrating progress.. " + misc;
    yield; //'replacement for your doevents, all internal stack state and variables effectively hibernate.
  }
  console.log("done");
}

myfunction(); //'and start by calling here. Note that you can use "return" to return a value except by call backs.```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id='outputdiv' align='center'></div></code>```

..If you are new to all this, be aware that without the insertion and the yield keyword, you would simply wait 5 seconds while nothing happened and then the progress {div} would read "9" (because all the other changes to {div} were invisible).

Body:
Here's a tested example of how to use Yield as a direct replacement for DoEvents.

(I've used Web Worker and it's great, but it's far removed from DoEvents and near-impossible to access global variables). This has been formatted for ease of understanding and attempts to show how the extras required (to make the function handle yield) could be treated as an insertion within the original function. "yield" has all sorts of other features, but used thus, it is a near direct replacement for DoEvents.

//'Replace DoEvents with Yield ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/yield )
var misc = 0; //'sample external var

function myfunction() { //'This is the beginning of your original function which is effectively replaced by a handler inserted as follows..
//'-----------------------------------Insert Handler..
  var obj = myfuncGen.next(); //'start it
  if (obj.done == false) {
    setTimeout(myfunction, 150); //'adjust for the amount of time you wish to yield (depends how much screen drawing is required or etc)
  }
}
var myfuncGen = myfuncSurrogate(); //'creates a "Generator" out of next.
function* myfuncSurrogate() { //'This the original function repackaged! Note asterisk.
//'-------------------------------------End Insert
  var ms;       //...your original function continues here....
  for (var i = 1; i <= 9; i++) { //'sample 9x loop
    ms = new Date().getTime();
    while (new Date().getTime() < ms + 500); //'PAUSE (get time & wait 500ms) as an example of being busy
    misc++; //'example manipulating an external var
    outputdiv.innerHTML = "Output Div<br>demonstrating progress.. " + misc;
    yield; //'replacement for your doevents, all internal stack state and variables effectively hibernate.
  }
  console.log("done");
}

myfunction(); //'and start by calling here. Note that you can use "return" to return a value except by call backs.

<div id='outputdiv' align='center'></div>

..If you are new to all this, be aware that without the insertion and the yield keyword, you would simply wait 5 seconds while nothing happened and then the progress {div} would read "9" (because all the other changes to {div} were invisible).


问:
Double for loop, storing created variables in a list
I've been trying to use a double for loop to create simple character vectors and saving them in a list:

```<code>exercise <- list()

for(i in 1:3){
  for (k in 1:3) {
    exercise[?] <- paste("AR", i , "MA", k)
  }
}
</code>```

the output should be:

```<code>[[1]]
[1] "AR 1 MA 1"

[[2]]
[1] "AR 1 MA 2"

[[3]]
[1] "AR 1 MA 3"

[[4]]
[1] "AR 2 MA 1"

[[5]]
[1] "AR 2 MA 2"
etc...
</code>```

The whole list should then have 9 character objects, but I just cannot figure out how to efficiently save them in the desired order. This has to have a simple answer, however I have not found any solution to this as of yet. Later, I want to store ARIMA(p,q) models in the list instead of just character vectors, but the system should be the same.

Thanks for your help!

答:
If you really want to use the double for loop, you can do the following:

```<code>for(i in 1:3){
    for (k in 1:3) {
        exercise[length(exercise) + 1] <- paste("AR", i , "MA", k)
    }
}
</code>```

With exercise[length(exercise) + 1], we update the last element of exercise at each iteration.

Body:
I've been trying to use a double for loop to create simple character vectors and saving them in a list:

exercise <- list()

for(i in 1:3){
  for (k in 1:3) {
    exercise[?] <- paste("AR", i , "MA", k)
  }
}

the output should be:

[[1]]
[1] "AR 1 MA 1"

[[2]]
[1] "AR 1 MA 2"

[[3]]
[1] "AR 1 MA 3"

[[4]]
[1] "AR 2 MA 1"

[[5]]
[1] "AR 2 MA 2"
etc...

The whole list should then have 9 character objects, but I just cannot figure out how to efficiently save them in the desired order. This has to have a simple answer, however I have not found any solution to this as of yet. Later, I want to store ARIMA(p,q) models in the list instead of just character vectors, but the system should be the same.

Thanks for your help!

Body:
If you really want to use the double for loop, you can do the following:

for(i in 1:3){
    for (k in 1:3) {
        exercise[length(exercise) + 1] <- paste("AR", i , "MA", k)
    }
}

With exercise[length(exercise) + 1], we update the last element of exercise at each iteration.


问:
Why is my function ending (using external library)
I need your help with some error handling. I'm using an external library but have no clue of what's happening with the error.
Here's my code:

```<code>//file name = playground.js
var ccxt = require("ccxt");
    ccxt.exchanges.map(r => {
      let exchange = new ccxt[r]();
      let ticks = exchange
        .fetchTickers()
        .then(res => {
          console.log(res);
        })
        .catch(e => {
          console.log(e);
        });
    });
</code>```

To execute it correctly, you'll need to install the external library: ccxt via npm: npm i ccxt --save
and I get the following error:

```<code>.../node_modules/ccxt/js/base/Exchange.js:407
        throw new NotSupported (this.id + ' fetchTickers not supported yet')
        ^

Error: _1broker fetchTickers not supported yet
    at _1broker.fetchTickers (.../node_modules/ccxt/js/base/Exchange.js:407:15)
    at ccxt.exchanges.map.r (.../playground.js:41:6)
    at Array.map (<anonymous>)
    at Object.<anonymous> (.../playground.js:38:16)
    at Module._compile (module.js:635:30)
    at Object.Module._extensions..js (module.js:646:10)
    at Module.load (module.js:554:32)
    at tryModuleLoad (module.js:497:12)
    at Function.Module._load (module.js:489:3)
    at Function.Module.runMain (module.js:676:10)
</code>```

Basically, what the library helps me with is:

Make automatic request to different servers

Organize the responses in uniformed objects

Handle most of the errors that are returned by the servers

In my example, the error returned is related with the fact that the server doesn't support the function I'm using. To put it in simpler words:
I make a request that server1 might be able to handle but that server2 isn't able to respond to yet.

The ccxt.exhanges in the code returns an Array of the differents servers that are being handled by the library.

The problem is not so much that I get the error... I'm OK with not getting info back from every server but that my function literaly stops once it gets to the error. The .map loop doesn't go all the way to the end...

ccxt publishes some information on Error Handling but I'm not sure what I can do with it (noob in the place sorry guys).

I hope my question is clear enough and hasn't been already asked!

Thanks in advance for your help!

答:
Can you please check if this might work. I replaced map with forEach because all you are trying to do is loop though the exchanges array.

```<code>//file name = playground.js
var ccxt = require("ccxt");
ccxt.exchanges.forEach(r => {
  let exchange = new ccxt[r]();

  try {
    let ticks = exchange
    .fetchTickers()
    .then(res => {
      console.log(res);
    })
    .catch(e => {
      console.log(e);
    });
  } catch(err) {
    // PRINT THE err IF NEEDED
    console.log("CONTINUING THE LOOP BECAUSE fetchTickers is not supported");
  }
});
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need your help with some error handling. I'm using an external library but have no clue of what's happening with the error.
Here's my code:

//file name = playground.js
var ccxt = require("ccxt");
    ccxt.exchanges.map(r => {
      let exchange = new ccxt[r]();
      let ticks = exchange
        .fetchTickers()
        .then(res => {
          console.log(res);
        })
        .catch(e => {
          console.log(e);
        });
    });

To execute it correctly, you'll need to install the external library: ccxt via npm: npm i ccxt --save
and I get the following error:

.../node_modules/ccxt/js/base/Exchange.js:407
        throw new NotSupported (this.id + ' fetchTickers not supported yet')
        ^

Error: _1broker fetchTickers not supported yet
    at _1broker.fetchTickers (.../node_modules/ccxt/js/base/Exchange.js:407:15)
    at ccxt.exchanges.map.r (.../playground.js:41:6)
    at Array.map (<anonymous>)
    at Object.<anonymous> (.../playground.js:38:16)
    at Module._compile (module.js:635:30)
    at Object.Module._extensions..js (module.js:646:10)
    at Module.load (module.js:554:32)
    at tryModuleLoad (module.js:497:12)
    at Function.Module._load (module.js:489:3)
    at Function.Module.runMain (module.js:676:10)

Basically, what the library helps me with is:

Make automatic request to different servers

Organize the responses in uniformed objects

Handle most of the errors that are returned by the servers

In my example, the error returned is related with the fact that the server doesn't support the function I'm using. To put it in simpler words:
I make a request that server1 might be able to handle but that server2 isn't able to respond to yet.

The ccxt.exhanges in the code returns an Array of the differents servers that are being handled by the library.

The problem is not so much that I get the error... I'm OK with not getting info back from every server but that my function literaly stops once it gets to the error. The .map loop doesn't go all the way to the end...

ccxt publishes some information on Error Handling but I'm not sure what I can do with it (noob in the place sorry guys).

I hope my question is clear enough and hasn't been already asked!

Thanks in advance for your help!

Body:
Can you please check if this might work. I replaced map with forEach because all you are trying to do is loop though the exchanges array.

//file name = playground.js
var ccxt = require("ccxt");
ccxt.exchanges.forEach(r => {
  let exchange = new ccxt[r]();

  try {
    let ticks = exchange
    .fetchTickers()
    .then(res => {
      console.log(res);
    })
    .catch(e => {
      console.log(e);
    });
  } catch(err) {
    // PRINT THE err IF NEEDED
    console.log("CONTINUING THE LOOP BECAUSE fetchTickers is not supported");
  }
});


问:
Can dynamic SVG images have right click functionality in the browser?
I'm working on a project where I am generating an SVG image (using snap.svg) inside of a div. I am wanting to know if there is a way to make it so that users can right click on the SVG and use "copy image" to copy it to the clipboard like any other image. Thanks.

Edit:

I think I could create an img and set the source to a serialized string of the SVG, but I'm worried that wouldn't be very optimal as the SVG is changing constantly from user input. Is there something obvious that I am missing?

Edit 2:

I can successfuly create an img copy of the SVG that allows me to have the right click functionality. However, my previous concern still stands as I would have to serialize the SVG and generate a new img each time a change is made.

答: You can add a "download image" or something similar button next to the svg, which could download the svg when its needed.</p>


问:
Font stack from SCSS to LESS?
How would I write this code in LESS, from SCSS? The error it gives is "Selector matches unknown element font-stack". </p>

```<code>$font-stack: 'Raleway', 'Helvetica Neue', Verdana, Arial, sans-serif;
$font-stack-body: 'Open Sans', Trebuchet, Tahoma, sans-serif;

$color-primary: #ff7200;
$color-primary-light: #f90;
$color-primary-dark: #e51;
$color-secondary: #005790;
$color-secondary-light: #0072bc;
$color-secondary-dark: #00384a;
</code>```

答:
Exactly, as Mr Alien said, you should  do </p>

```<code>@font-stack: 'Raleway', 'Helvetica Neue', Verdana, Arial, sans-serif;
@font-stack-body: 'Open Sans', Trebuchet, Tahoma, sans-serif;

@color-primary: #ff7200;
@color-primary-light: #f90;
@color-primary-dark: #e51;
@color-secondary: #005790;
@color-secondary-light: #0072bc;
@color-secondary-dark: #00384a;
</code>```

Title: Font stack from SCSS to LESS?

Body:
How would I write this code in LESS, from SCSS? The error it gives is "Selector matches unknown element font-stack".

$font-stack: 'Raleway', 'Helvetica Neue', Verdana, Arial, sans-serif;
$font-stack-body: 'Open Sans', Trebuchet, Tahoma, sans-serif;

$color-primary: #ff7200;
$color-primary-light: #f90;
$color-primary-dark: #e51;
$color-secondary: #005790;
$color-secondary-light: #0072bc;
$color-secondary-dark: #00384a;

Body:
Exactly, as Mr Alien said, you should  do

@font-stack: 'Raleway', 'Helvetica Neue', Verdana, Arial, sans-serif;
@font-stack-body: 'Open Sans', Trebuchet, Tahoma, sans-serif;

@color-primary: #ff7200;
@color-primary-light: #f90;
@color-primary-dark: #e51;
@color-secondary: #005790;
@color-secondary-light: #0072bc;
@color-secondary-dark: #00384a;


问:
SQL DB2 - arithmetic overflow (cannot multiply 3 columns together)
I am trying to multiply 3 columns by each other, but I keep receiving an arithmetic overflow error. 2 columns multiplied by each other are fine, but when I try to multiply another, I receive the error.

```<code>select
account AS ACCOUNT,
amount * fee AS "TOTAL AMOUNT",
(amount * fee) * rate AS "FINAL AMOUNT"
</code>```

In this code, the FINAL AMOUNT does not compute. I thought it might be cast or convert or my syntax, but I'm not sure. The first field (amount), is stored as decimal (24,6), and the fee and rate fields are stored as decimal (15,9)

Please help!

答:
Decimal arithmetic follows certain rules...

Multiplication and division in particular can greatly increase the precision and scale of your results.

Decimal arithmetic in SQL

   The following formulas define the precision and scale of the result of decimal operations in SQL.

The symbols p and s denote the precision and scale of the first operand
  and the symbols p' and s' denote the precision and scale of the second
  operand. The symbol mp denotes the maximum precision. The value of mp
  is 63 if:

  - either p or p' is greater than 31, or

  - a value of 63 was explicitly specified for the maximum precision. Otherwise, the value of mp is 31.

  The symbol ms denotes the maximum scale. The default
  value of ms is 31. ms can be explicitly set to any number from 0 to
  the maximum precision.

  Multiplication

  The precision of the result of multiplication is min (mp,p+p') and the scale is min(ms,s+s').

note mp of 63 and ms of 31 is possibly specific to Db2 for i v5.4+ ...your platform/version may be different

So for your columns (p,s)
Amount(24,6)
fee (15,9)
rate (15,9)

amount * fee = (39,15) * rate = (54,24) ...

What are the actual values you're dealing with, is it possible that your results have more than (52-24) = 30 digits to the left of the decimal?

I suspect you don't need 24 decimal places...

Take a look at TRUNC() or CAST() to trim decimal positions, possibly in conjunction with ROUND().

Body:
I am trying to multiply 3 columns by each other, but I keep receiving an arithmetic overflow error. 2 columns multiplied by each other are fine, but when I try to multiply another, I receive the error.

select
account AS ACCOUNT,
amount * fee AS "TOTAL AMOUNT",
(amount * fee) * rate AS "FINAL AMOUNT"

In this code, the FINAL AMOUNT does not compute. I thought it might be cast or convert or my syntax, but I'm not sure. The first field (amount), is stored as decimal (24,6), and the fee and rate fields are stored as decimal (15,9)

Please help!


问:
Angular and NGINX permission denied
I'm trying the setup NGINX to access angular /dist folder but can't make it works despite chmod -R 755 /path/to/dist ...

in my NGINX http block:

```<code>server {
  listen 80;
  server_name dashboard.example.local;

  ssl off;

  gzip on;
  root /path/to/dist/;
  index index.html;

  location /api/ {
    proxy_pass http://127.0.0.1:3000/;
  }
}
</code>```

I'm still getting this error "dist/index.html" is forbidden (13: Permission denied)

I already tried all the existing solutions I found on the internet.

EDIT: files that nginx are trying to access are 755

答:
Already compiled angular source served as file it will send to the browser to be renderer (client side). that proxy pass function will only works on development, i assume you run it using angular cli ng serve. this might what you looking for on production or dist folder.

```<code>server{
    ...
    root /path/to/dist

    index index.html index.htm index.nginx-debian.html;

    location / {
            try_files $uri /index.html;
    }
}
</code>```

if the permission still denied try change that folder owner into nginx user with chown command..

Title: Angular and NGINX permission denied

Body:
I'm trying the setup NGINX to access angular /dist folder but can't make it works despite chmod -R 755 /path/to/dist ...

in my NGINX http block:

server {
  listen 80;
  server_name dashboard.example.local;

  ssl off;

  gzip on;
  root /path/to/dist/;
  index index.html;

  location /api/ {
    proxy_pass http://127.0.0.1:3000/;
  }
}

I'm still getting this error "dist/index.html" is forbidden (13: Permission denied)

I already tried all the existing solutions I found on the internet.

EDIT: files that nginx are trying to access are 755

Body:
Already compiled angular source served as file it will send to the browser to be renderer (client side). that proxy pass function will only works on development, i assume you run it using angular cli ng serve. this might what you looking for on production or dist folder.

server{
    ...
    root /path/to/dist

    index index.html index.htm index.nginx-debian.html;

    location / {
            try_files $uri /index.html;
    }
}

if the permission still denied try change that folder owner into nginx user with chown command..


答:
An object-oriented approach would serve you better in the long run. Before I try to mock-up a possible solution, I'd like to point out the following:

Your original array, arr containing Strings is actually just one large array. It looks structured in lines, but it really has no structure in reality. This questions why you would use an array to fetch your data from the file.

In my opinion, a model class or classes representing your entire system would be better. Just as an example, you could have a class like this:

```<code>public class HotelRoom {
   private String roomId;
   private String roomType;
}

public class Booking {
   private HotelRoom room;
   private String purpose;
   private Date bookingDate;
}
</code>```

These models are not complete, but they paint a picture of what I mean. So booking information might be what is contained in your file, hence you could create your models as you read from the file, create these objects, then put it in the array list. That kind of structure helps. You can ask questions where you need clarity. Enjoy

Title: Copy elements from an array to an array list but skip element if some elements have been previously entered

Body:
I am trying to loop through the array below and then add elements from it to an array list using the format below.

This is the array:

    String[] arr = {
            "room1", "10.11.2017", "17:00-18:00", "meeting event",
            "room2", "12.11.2017", "19:00-20:00", "meeting event",
            "room3", "20.11.2017", "20:00:21:00", "meeting event",
            "room1", "10.11.2017", "18:00-19:00", "meeting event",
            "room1", "15.11.2017", "10:00-11:00", "meeting event",
            "room2", "12.11.2017", "21:00-22:00", "meeting event",
            "room2", "12.11.2017", "22:00-23:00", "meeting event",
            "room3", "20.11.2017", "21:00:22:00", "meeting event",
            "room1", "10.11.2017", "19:00-20:00", "meeting event",
            "room4", "30.11.2017", "09:00-10:00", "meeting event"
    };

I would like to get a new array list containing the following string elements:

room1 , 10.11.2017 , 17:00-18:00 , 18:00-19:00 , 19:00-20:00 , meeting event
room2 , 12.11.2017 , 19:00-20:00 , 21:00-22:00 , 22:00-23:00 , meeting event
room3 , 20.11.2017 , 20:00:21:00 , 21:00:22:00 , meeting event
room1 , 15.11.2017 , 10:00-11:00 , meeting event
room4 , 30.11.2017 , 09:00-10:00 , meeting event

But instead I get:

room1 , 10.11.2017 , 17:00-18:00 , 18:00-19:00 , 19:00-20:00 , meeting event
room2 , 12.11.2017 , 19:00-20:00 , 21:00-22:00 , 22:00-23:00 , meeting event
room3 , 20.11.2017 , 20:00:21:00 , 21:00:22:00 , meeting event
room1 , 10.11.2017 , 18:00-19:00 , 19:00-20:00 , meeting event
room1 , 15.11.2017 , 10:00-11:00 , meeting event
room2 , 12.11.2017 , 21:00-22:00 , 22:00-23:00 , meeting event
room2 , 12.11.2017 , 22:00-23:00 , meeting event
room3 , 20.11.2017 , 21:00:22:00 , meeting event
room1 , 10.11.2017 , 19:00-20:00 , meeting event
room4 , 30.11.2017 , 09:00-10:00 , meeting event

Is there a way to change the code below such that to get the result I need?

ArrayList<String> arr2 = new ArrayList<String>();

    String roomNumber= new String();
    String bookedDate = new String();
    String bookedTime = new String();
    String event = new String();

    for (int i = 0; i < arr.length; i+=4) {
        roomNumber = arr[i];
        bookedDate = arr[i+1];
        bookedTime = arr[i+2];
        event = arr[i+3];

        for (int j = i + 4; j < arr.length; j+=4) {
                if (arr[i].equals(arr[j]) && arr[i+1].equals(arr[j+1]) && !arr[i+2].equals(arr[j+2])){
                    bookedTime = bookedTime + " , " + arr[j+2];
                }
            }

        arr2.add(roomNumber +  " , " + bookedDate + " , " + bookedTime +  " , " + event);
        }

    for (int k =  0; k <arr2.size(); k++) {
        System.out.println(arr2.get(k));
    }

Thank you.

Body:
An object-oriented approach would serve you better in the long run. Before I try to mock-up a possible solution, I'd like to point out the following:

Your original array, arr containing Strings is actually just one large array. It looks structured in lines, but it really has no structure in reality. This questions why you would use an array to fetch your data from the file.

In my opinion, a model class or classes representing your entire system would be better. Just as an example, you could have a class like this:

public class HotelRoom {
   private String roomId;
   private String roomType;
}

public class Booking {
   private HotelRoom room;
   private String purpose;
   private Date bookingDate;
}

These models are not complete, but they paint a picture of what I mean. So booking information might be what is contained in your file, hence you could create your models as you read from the file, create these objects, then put it in the array list. That kind of structure helps. You can ask questions where you need clarity. Enjoy


问:
Extract columns from text based table output
qfarm /load command shows me the load from my servers.
Output:

```<code>PS> qfarm /load

Server Name           Server Load  Load Throttling Load  Logon Mode
--------------------  -----------  --------------------  ------------------
SERVER-01             400          0                     AllowLogons
SERVER-02             1364         OFF                   AllowLogons
SERVER-03             1364         OFF                   AllowLogons
SERVER-04             1000         0                     AllowLogons
SERVER-05             700          0                     AllowLogons
SERVER-06             1200         0                     AllowLogons
</code>```

I need to display only first column (Server Name) and the second one (Server Load) and loop through them, in order to make some logic later, but it seems the powershell doesn't see it as object with properties:

```<code>PS> qfarm /load | Select -ExpandProperty "Server Name"
Select-Object : Property "Server Name" cannot be found.
</code>```

Is there any other possibility, like a table or something?

答:
Command-line utilities return their outputs as a string array.  This should work:</p>

```<code>qfarm /load | ForEach-Object { $_.Substring(0,33) }
</code>```

Body:
qfarm /load command shows me the load from my servers.
Output:

PS> qfarm /load

Server Name           Server Load  Load Throttling Load  Logon Mode
--------------------  -----------  --------------------  ------------------
SERVER-01             400          0                     AllowLogons
SERVER-02             1364         OFF                   AllowLogons
SERVER-03             1364         OFF                   AllowLogons
SERVER-04             1000         0                     AllowLogons
SERVER-05             700          0                     AllowLogons
SERVER-06             1200         0                     AllowLogons

I need to display only first column (Server Name) and the second one (Server Load) and loop through them, in order to make some logic later, but it seems the powershell doesn't see it as object with properties:

PS> qfarm /load | Select -ExpandProperty "Server Name"
Select-Object : Property "Server Name" cannot be found.

Is there any other possibility, like a table or something?

Body:
Command-line utilities return their outputs as a string array.  This should work:

qfarm /load | ForEach-Object { $_.Substring(0,33) }


问:
Foreign key not working in MySQL
I'm working on a quiz website.

There is a table called quiz which is as follows -

```<code>CREATE TABLE `quiz`(
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`quizname` VARCHAR(30) NOT NULL,
`timeinmins` INT UNSIGNED NOT NULL,
PRIMARY KEY(`id`),
UNIQUE KEY `quizname`(`quizname`)
)ENGINE=MyISAM DEFAULT CHARSET=utf8;
</code>```

Then there is a table for questions which is as follows -

```<code>CREATE TABLE `question`(
`qtnid` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`quizid` INT UNSIGNED NOT NULL,
`qtext` VARCHAR(100) NOT NULL,
PRIMARY KEY(`quizid`, `qtnid`),
CONSTRAINT fk_quiz FOREIGN KEY (`quizid`) REFERENCES quiz(`id`)
)ENGINE=MyISAM DEFAULT CHARSET=utf8;
</code>```

Inspite of quizid in the second table being a foreign key, it is still accepting rows without corresponding reference in the 1st table quz which is wrong as each question has to be associated with some quiz

pls help?

答:
For storage engines that do not support foreign keys (such as MyISAM),
  MySQL Server parses and ignores foreign key specifications.

from reference manual

also, this shows an overview of the MyISAM Storage Engine's features.

Title: Foreign key not working in MySQL

Body:
I'm working on a quiz website.

There is a table called quiz which is as follows -

CREATE TABLE `quiz`(
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`quizname` VARCHAR(30) NOT NULL,
`timeinmins` INT UNSIGNED NOT NULL,
PRIMARY KEY(`id`),
UNIQUE KEY `quizname`(`quizname`)
)ENGINE=MyISAM DEFAULT CHARSET=utf8;

Then there is a table for questions which is as follows -

CREATE TABLE `question`(
`qtnid` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`quizid` INT UNSIGNED NOT NULL,
`qtext` VARCHAR(100) NOT NULL,
PRIMARY KEY(`quizid`, `qtnid`),
CONSTRAINT fk_quiz FOREIGN KEY (`quizid`) REFERENCES quiz(`id`)
)ENGINE=MyISAM DEFAULT CHARSET=utf8;

Inspite of quizid in the second table being a foreign key, it is still accepting rows without corresponding reference in the 1st table quz which is wrong as each question has to be associated with some quiz

pls help?


问:
What service to use to send text message to user's phone?
Is anybody sending out text messages to user's phones with AppMaker?  If so, would you mind posting your preferred solution that has been tried and works with AppMaker/Google Cloud?

Thanks!

答:
Neither App Maker or App Script or Cloud Platform provide SMS services as first party.

So, you can to make market research, choose service that suits your needs best and then if you have any hurdles making it friends with App Maker come back here and ask more specific question, for instance how to authenticate 3rd party service.


问:
How I create dynamic routes separate in rails

I got link on show like below

I Want http://localhost:3000/admin/flipcart

(flipcart is company name so i want each company separate link.)

If I do http://localhost:3000/admin/flipcart so it show flipcart's show page with out login and authentication.

So how can i do.

答:
You could try something like this inside your routes.rb:

```<code>get '/admin/:company', as: :admin_company_index, to: 'admin#index'
</code>```

Then inside the controller just load the company passed through params before you perform any actions:

```<code>class AdminController < ApplicationController
  before_action :load_company

  private

  def load_company
    @company = Company.where(["name = :c", {c: params[:company]} ])
  end
end
</code>```

Body:
You could try something like this inside your routes.rb:

get '/admin/:company', as: :admin_company_index, to: 'admin#index'

Then inside the controller just load the company passed through params before you perform any actions:

class AdminController < ApplicationController
  before_action :load_company

  private

  def load_company
    @company = Company.where(["name = :c", {c: params[:company]} ])
  end
end


问:
PowerShell: Run command from script's directory
I have a PowerShell script that does some stuff using the script’s current directory. So when inside that directory, running .\script.ps1 works correctly.

Now I want to call that script from a different directory without changing the referencing directory of the script. So I want to call ..\..\dir\script.ps1 and still want that script to behave as it was called from inside its directory.

How do I do that, or how do I modify a script so it can run from any directory?

答:
I often used the following code to import a module which sit under the same directory as the running script. It will first get the directory from which powershell is running

$currentPath=Split-Path ((Get-Variable
  MyInvocation -Scope
  0).Value).MyCommand.Path

import-module "$currentPath\sqlps.ps1"


问:
Override column types when importing data using readr::read_csv() when there are many columns
I am trying to read a csv file using readr::read_csv in R. The csv file that I am importing has about 150 columns, I am just including the first few columns for the example. I am looking to override the second column from the default type (which is date when I do read_csv) to character, or other date format.

```<code>GIS Join Match Code Data File Year  State Name  State Code  County Name County   Code   Area Name   Persons: Total
G0100010    2008-2012   Alabama 1   Autauga County  1   Autauga County, Alabama 54590

df <- data.frame("GIS Join Match Code"="G0100010", "Data File" = "2008-2012", "State" = "Alabama", "County" = "Autauga County", "Population" = 54590)
</code>```

The issue is that when I use readr::read_csv, it seems I may have to use all variables while overriding in the col_types (see error below). That is need to specify overriding all the 150 columns individually(?).. The question is that : Is there a way to specify overriding the col_type of just specific columns, or a named list of objects? In my case, it would be just overriding the column "Data File Year".

I understand that any omitted columns will be automatically parsed, which is fine for my analysis. I think it gets further complex as the column names have a space in them in the file I downloaded (For e.g., "Data File Year", "State Code") etc.

```<code>tempdata <- read_csv(df, col_types = "cc")
Error: You have 135 column names, but 2 columns
</code>```

The Other option I guess, if possible, is to just skip reading the second column all together?

答:
Yes. For example to force numeric data to be treated as characters:

```<code>examplecsv = "a,b,c\n1,2,a\n3,4,d"
read_csv(examplecsv)
# A tibble: 2 x 3
#      a     b     c
#  <int> <int> <chr>
#1     1     2     a
#2     3     4     d
read_csv(examplecsv, col_types = cols(b = col_character()))
# A tibble: 2 x 3
#      a     b     c
#  <int> <chr> <chr>
#1     1     2     a
#2     3     4     d
</code>```

Choices are:

```<code>col_character()
col_date()
col_time()
col_datetime()
col_double()
col_factor() # to enforce, will never be guessed
col_integer()
col_logical()
col_number()
col_skip() # to force skip column
</code>```

More: http://readr.tidyverse.org/articles/readr.html

Body:
I am trying to read a csv file using readr::read_csv in R. The csv file that I am importing has about 150 columns, I am just including the first few columns for the example. I am looking to override the second column from the default type (which is date when I do read_csv) to character, or other date format.

GIS Join Match Code Data File Year  State Name  State Code  County Name County   Code   Area Name   Persons: Total
G0100010    2008-2012   Alabama 1   Autauga County  1   Autauga County, Alabama 54590

df <- data.frame("GIS Join Match Code"="G0100010", "Data File" = "2008-2012", "State" = "Alabama", "County" = "Autauga County", "Population" = 54590)

The issue is that when I use readr::read_csv, it seems I may have to use all variables while overriding in the col_types (see error below). That is need to specify overriding all the 150 columns individually(?).. The question is that : Is there a way to specify overriding the col_type of just specific columns, or a named list of objects? In my case, it would be just overriding the column "Data File Year".

I understand that any omitted columns will be automatically parsed, which is fine for my analysis. I think it gets further complex as the column names have a space in them in the file I downloaded (For e.g., "Data File Year", "State Code") etc.

tempdata <- read_csv(df, col_types = "cc")
Error: You have 135 column names, but 2 columns

The Other option I guess, if possible, is to just skip reading the second column all together?

Body:
Yes. For example to force numeric data to be treated as characters:

examplecsv = "a,b,c\n1,2,a\n3,4,d"
read_csv(examplecsv)
# A tibble: 2 x 3
#      a     b     c
#  <int> <int> <chr>
#1     1     2     a
#2     3     4     d
read_csv(examplecsv, col_types = cols(b = col_character()))
# A tibble: 2 x 3
#      a     b     c
#  <int> <chr> <chr>
#1     1     2     a
#2     3     4     d

Choices are:

col_character()
col_date()
col_time()
col_datetime()
col_double()
col_factor() # to enforce, will never be guessed
col_integer()
col_logical()
col_number()
col_skip() # to force skip column

More: http://readr.tidyverse.org/articles/readr.html


问:
Invalid column name even though I am only selecting if that column is not null?
I ran into this issue creating some stored procedures today. It started off with me getting a message that a column didn't exist. That's not out of the ordinary - we have hundreds of databases so sometimes things go missing.

However, when I tried to add the column to the table that was missing them, things got weird.

Check out these two code samples:

```<code>IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'MNTSetup')
BEGIN
    IF COL_LENGTH('dbo.MNTSetup','VehicleChecklistEMail') is not null
    BEGIN
       select VehicleChecklistEMail from dbo.MNTSetup
    END
END
</code>```

This one errors out. However, if I try to run this one:

```<code>IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'MNTSetup')
BEGIN
    IF COL_LENGTH('dbo.MNTSetup','VehicleChecklistEMail') is null
    BEGIN
       --i put code to show the db name here
    END
END
</code>```

This shows that there are NO results!

So my SQL is basically telling me that there are no existing MNTSetup tables with a missing email column and yet when I try to select on that column I get this error.

What could possibly be happening?

答: This ended up being some database corruption. If you end up experiencing the same thing I have, you will need to take steps to troubleshoot the hardware or software and get the corruption resolved.</p>

Body:
I ran into this issue creating some stored procedures today. It started off with me getting a message that a column didn't exist. That's not out of the ordinary - we have hundreds of databases so sometimes things go missing.

However, when I tried to add the column to the table that was missing them, things got weird.

Check out these two code samples:

IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'MNTSetup')
BEGIN
    IF COL_LENGTH('dbo.MNTSetup','VehicleChecklistEMail') is not null
    BEGIN
       select VehicleChecklistEMail from dbo.MNTSetup
    END
END

This one errors out. However, if I try to run this one:

IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'MNTSetup')
BEGIN
    IF COL_LENGTH('dbo.MNTSetup','VehicleChecklistEMail') is null
    BEGIN
       --i put code to show the db name here
    END
END

This shows that there are NO results!

So my SQL is basically telling me that there are no existing MNTSetup tables with a missing email column and yet when I try to select on that column I get this error.

What could possibly be happening?