问:
Compare two SQL Server databases with T-sql
Consider we have a database for an windows application it's for 2 years ago, now we have changed many things in database so there is differences and we don't know what are the differences.

I don't want to use compare tools like Red Gate compare tool.

What's the best way to see new columns are in new database :

Query result like :

```<code>New Db Name | Schema | Table Name | Column Name | Default Value | IsNullable | DataType
NewDb       | dbo    | myTable    | newColumn   | ''            | No         | nvarchar(30)
</code>```

Thank you

答:
Columns in old database but not in new , or default value, nullable and data type changed:

```<code>SELECT t1.*,t2.* FROM [OldDb].[INFORMATION_SCHEMA].[COLUMNS] t1
LEFT JOIN [NewDb].[INFORMATION_SCHEMA].[COLUMNS] t2
ON t1.COLUMN_NAME= t2.COLUMN_NAME
WHERE t2.COLUMN_NAME IS NULL
or
(t1.Table_name=t2.Table_name
AND t1.column_name = t2.column_name
AND (t1.data_type != t2.data_type
or t1.is_nullable != t2.is_nullable
or t1.character_maximum_length != t2.character_maximum_length
or t1.column_default != t2.column_default))
ORDER BY t1.COLUMN_NAME
</code>```

Columns in new database but not in old :

You can change [OldDb] place with [NewDb] in query

I wrote this question and answer because I've needed this and I've spent so much of time on this.

So I hope everyone can find and use this easily :).

Body:
Consider we have a database for an windows application it's for 2 years ago, now we have changed many things in database so there is differences and we don't know what are the differences.

I don't want to use compare tools like Red Gate compare tool.

What's the best way to see new columns are in new database :

Query result like :

New Db Name | Schema | Table Name | Column Name | Default Value | IsNullable | DataType
NewDb       | dbo    | myTable    | newColumn   | ''            | No         | nvarchar(30)

Thank you

Body:
Columns in old database but not in new , or default value, nullable and data type changed:

SELECT t1.*,t2.* FROM [OldDb].[INFORMATION_SCHEMA].[COLUMNS] t1
LEFT JOIN [NewDb].[INFORMATION_SCHEMA].[COLUMNS] t2
ON t1.COLUMN_NAME= t2.COLUMN_NAME
WHERE t2.COLUMN_NAME IS NULL
or
(t1.Table_name=t2.Table_name
AND t1.column_name = t2.column_name
AND (t1.data_type != t2.data_type
or t1.is_nullable != t2.is_nullable
or t1.character_maximum_length != t2.character_maximum_length
or t1.column_default != t2.column_default))
ORDER BY t1.COLUMN_NAME

Columns in new database but not in old :

You can change [OldDb] place with [NewDb] in query

I wrote this question and answer because I've needed this and I've spent so much of time on this.

So I hope everyone can find and use this easily :).


来源: stackexchange

问:
Disable Auto completion in R studio
Does anyone know how to completely disable automatic completions in Rstudio?

I don't see an option for it in Tools > Global Options; only a way to turn it to 'Manual (tab)' or 'When Triggered'. I can't enter a tab while typing code and it's driving me crazy.

答:
I agree this is very annoying. RStudio completely ignores the user preference for code completion shortcut, and I verified this in the source code. I found the following workaround, which disables TAB auto-completion in both the console and source views, while leaving intact auto-completion using the CTRL-SPACE (Control-Space) keys.

This workaround involves doing a custom build of RStudio (latest master branch at https://github.com/rstudio/rstudio.git).

Note: On Mac OS X El Capitan/Sierra, the Java SDK must be installed, and Apache Ant and OpenSSL must be installed (i.e. via Homebrew -- brew install ant; brew install openssl), in addition to the listed dependencies, before running cmake per the instructions.

For the workaround, I commented out the hard-coded TAB completion triggers in the following files, then built the release version via cmake (per instructions) and sudo make install:

In directory:
    src/gwt/src/org/rstudio/studio/client/workbench/views

./console/shell/assist/CompletionUtils.java

```<code>Lines 27-28:
return /*( event.getKeyCode() == KeyCodes.KEY_TAB && modifier == KeyboardShortcut.NONE)
        || */ (event.getKeyCode() == KeyCodes.KEY_SPACE && modifier == KeyboardShortcut.CTRL);
</code>```

=====

./console/shell/shell.java

```<code>Lines 517-518:
/* if (event.getNativeKeyCode() == KeyCodes.KEY_TAB)
   event.preventDefault(); */
</code>```

=====

./console/shell/assist/RCompletionManager.java

```<code>Line 1156:
//   if (firstLine.matches("^\\s*$"))
</code>```

=====

./source/Source.java

```<code>Lines 382-383:
/* commands.codeCompletion().setShortcut(
                               new KeyboardShortcut(KeyCodes.KEY_TAB)); */
</code>```

ContentLicense: CC BY-SA 3.0

Title: Disable Auto completion in R studio

Body:
I agree this is very annoying. RStudio completely ignores the user preference for code completion shortcut, and I verified this in the source code. I found the following workaround, which disables TAB auto-completion in both the console and source views, while leaving intact auto-completion using the CTRL-SPACE (Control-Space) keys.

This workaround involves doing a custom build of RStudio (latest master branch at https://github.com/rstudio/rstudio.git).

Note: On Mac OS X El Capitan/Sierra, the Java SDK must be installed, and Apache Ant and OpenSSL must be installed (i.e. via Homebrew -- brew install ant; brew install openssl), in addition to the listed dependencies, before running cmake per the instructions.

For the workaround, I commented out the hard-coded TAB completion triggers in the following files, then built the release version via cmake (per instructions) and sudo make install:

In directory:
    src/gwt/src/org/rstudio/studio/client/workbench/views

./console/shell/assist/CompletionUtils.java

Lines 27-28:
return /*( event.getKeyCode() == KeyCodes.KEY_TAB && modifier == KeyboardShortcut.NONE)
        || */ (event.getKeyCode() == KeyCodes.KEY_SPACE && modifier == KeyboardShortcut.CTRL);

=====

./console/shell/shell.java

Lines 517-518:
/* if (event.getNativeKeyCode() == KeyCodes.KEY_TAB)
   event.preventDefault(); */

=====

./console/shell/assist/RCompletionManager.java

Line 1156:
//   if (firstLine.matches("^\\s*$"))

=====

./source/Source.java

Lines 382-383:
/* commands.codeCompletion().setShortcut(
                               new KeyboardShortcut(KeyCodes.KEY_TAB)); */


问:
Persisting and accessing values globally in multiple components in Angular 2
I have a settings page where users can save some config variables, such as a Username. The user can also change the username on that page. But when I go to another Component (page) and back, the username isn't saved.

I also want to show the username in the other components. How do I do that? With a global variable?

Structure:
- App
    - app.ts (main)
    - setting.ts
    - someOtherComponent.ts

答:
Vladimir correctly mentioned about ngrx.

I would use a service with Subject/BehaviourSubject and Observable to set and get the state (values) that I need.

We discussed here Communication between multiple components with a service by using Observable and Subject in Angular 2 how you can share values in multiple components that do not have parent-child or child-parent relationship and without importing external library as ngrx store.


问:
Disable ComboBox and make the color of the ComboBox Gray

I have a Combobox. I would like to make the ComboBox disable and change the color to DarkGray when it's disable. I would like this operation to happen when my application launches.

Upon selection of a button, it should enable and change the color of the combobox to white again.

Any solution for option 1 would be appreciated.

Thanks in advance.

答:
In form constructor you have to disable combobox and change its back color:

```<code>public Form1()
        {
            InitializeComponent();
            comboBox1.Enabled = false;
            comboBox1.BackColor = Color.DarkGray;
        }
</code>```

When happens your option 2 (for example using event handler) add this code:

```<code>comboBox1.Enabled = true;
comboBox1.BackColor = Color.White;
</code>```

Body:
In form constructor you have to disable combobox and change its back color:

public Form1()
        {
            InitializeComponent();
            comboBox1.Enabled = false;
            comboBox1.BackColor = Color.DarkGray;
        }

When happens your option 2 (for example using event handler) add this code:

comboBox1.Enabled = true;
comboBox1.BackColor = Color.White;


问:
running async operations in c#. - basic.
Consider the following snippet:

```<code>if(form1.isLoggedIn)
{
    //Create a wait handle for the UI thread.
    //the "false" specifies that it is non-signalled
    //therefore a blocking on the waitone method.
    AutoResetEvent hold = new AutoResetEvent(false);

    filename = Path.Combine(Environment.GetFolderPath(System.Environment.SpecialFolder.CommonApplicationData), DateTime.Now.ToString("ddMMyyhhmm") + "-" + form1.username);

    Flow palm = new Flow(new FlowArguments(form1.username, filename), hold);

    System.Windows.Forms.NotifyIcon notifyIcon = new System.Windows.Forms.NotifyIcon();
    System.Windows.Forms.ContextMenuStrip notificationIconContext = new System.Windows.Forms.ContextMenuStrip();
    //Create a context menu strip
    ToolStripMenuItem contextAbout = new ToolStripMenuItem("About");
    ToolStripMenuItem contextExit = new ToolStripMenuItem("Exit");

    //properties of notifyicon that SO dosnt care for including a event handler for the mouse click events.

    //wait for the background thread to finish.
    hold.WaitOne(Timeout.Infinite);

    MessageBox.Show("Thankyou, exiting...");
    form1.Dispose();
}
</code>```

As you see  The FLOW class is pretty simple. It just has a Threading.Timer which is run. Therefore on the UI thread i have to call WaitHandle.WaitOne() method, because otherwise the UI thread finishes and therefore ending the application..

My goal: Since there's no GUI, i want to create a notify icon. It works and everything,except I can't click on it and its not responsive, this is because it is created on the UI thread. I can't put it in the flow class because the Flow class is also on the UI thread (the timer in the Flow class is in background thread).

So how can I keep my notifyicon responsive while running the timer in the Flow class? I thought waithandle was my solution but since its a blocking method it doesn't work.

Any other ideas/solutions?

edit: response to Rich's answer: The Flow class is on the background thread and everything runs the way it should. But if I don't add the waithandle in the UI thread, the main() finishes on the UI thread therefore terminating the whole program. (even though the timer is enabled on the background thread). Is there another solution to waithandle? because I have to leave it in for the Flow class to do its thing. If I take it out, the program ends, if I leave it in it blocks the UI thread therefore my notifyicon dosnt work.

答:
I'm reading between the lines a bit here, but I think Rich is right - you need to move the background processing off the UI thread:

Remove the form1.dispose call from the function above - I imagine that this is your only form, which is why once you dispose of it the application exits.

Call the flow class asynchronously - the simplest way to do this is to call ThreadPool.QueueUserWorkItem() on a delegate which calls the function (although you're not really supposed to use thread pool threads for long running operations, but I doubt it will hurt in this case)

Once the flow method is done, call back to the UI thread to let it know. You can do this by calling form1.Invoke with a suitable delegate

In the function which is then called (i.e. on the UI thread) close the form and exit your application

So the end result looks like 3 functions:

the function above, which starts the processing in the background and then returns without waiting

the background processing function, executed on a seperate thread

the function called on the UI thread when processing is complete, which closes the application

OwnerDisplayName: masfenix

Body:
Consider the following snippet:

if(form1.isLoggedIn)
{
    //Create a wait handle for the UI thread.
    //the "false" specifies that it is non-signalled
    //therefore a blocking on the waitone method.
    AutoResetEvent hold = new AutoResetEvent(false);

    filename = Path.Combine(Environment.GetFolderPath(System.Environment.SpecialFolder.CommonApplicationData), DateTime.Now.ToString("ddMMyyhhmm") + "-" + form1.username);

    Flow palm = new Flow(new FlowArguments(form1.username, filename), hold);

    System.Windows.Forms.NotifyIcon notifyIcon = new System.Windows.Forms.NotifyIcon();
    System.Windows.Forms.ContextMenuStrip notificationIconContext = new System.Windows.Forms.ContextMenuStrip();
    //Create a context menu strip
    ToolStripMenuItem contextAbout = new ToolStripMenuItem("About");
    ToolStripMenuItem contextExit = new ToolStripMenuItem("Exit");

    //properties of notifyicon that SO dosnt care for including a event handler for the mouse click events.

    //wait for the background thread to finish.
    hold.WaitOne(Timeout.Infinite);

    MessageBox.Show("Thankyou, exiting...");
    form1.Dispose();
}

As you see  The FLOW class is pretty simple. It just has a Threading.Timer which is run. Therefore on the UI thread i have to call WaitHandle.WaitOne() method, because otherwise the UI thread finishes and therefore ending the application..

My goal: Since there's no GUI, i want to create a notify icon. It works and everything,except I can't click on it and its not responsive, this is because it is created on the UI thread. I can't put it in the flow class because the Flow class is also on the UI thread (the timer in the Flow class is in background thread).

So how can I keep my notifyicon responsive while running the timer in the Flow class? I thought waithandle was my solution but since its a blocking method it doesn't work.

Any other ideas/solutions?

edit: response to Rich's answer: The Flow class is on the background thread and everything runs the way it should. But if I don't add the waithandle in the UI thread, the main() finishes on the UI thread therefore terminating the whole program. (even though the timer is enabled on the background thread). Is there another solution to waithandle? because I have to leave it in for the Flow class to do its thing. If I take it out, the program ends, if I leave it in it blocks the UI thread therefore my notifyicon dosnt work.

LastEditorDisplayName: masfenix

ContentLicense: CC BY-SA 2.5


问:
How to enable/disbale a button in mxml depending on whether count is less than 10 or not
I am trying to bind enabled property of my button to the maximum value that an integer can attain. I need this button to allow user to view next page and want to disable this button when all the components have been shown (as reflected in count).

Something like :

```<code><mx:Button label="Previous" click="nextHandler()" enabled="{count< 10}">
</code>```

But the compiler is throwing an error that '<' attribute can not be used in enabled tag.

Any ideas over this ?

Thanks in advance.

答:
The following will work:

```<code><mx:Button label="Previous" click="nextHandler()" enabled="{count < 10}"/>
</code>```

Just tested it with:

```<code>    <s:NumericStepper id="count"/>
    <mx:Button label="Previous"  enabled="{count.value < 10}"/>
</code>```

Body:
I am trying to bind enabled property of my button to the maximum value that an integer can attain. I need this button to allow user to view next page and want to disable this button when all the components have been shown (as reflected in count).

Something like :

<mx:Button label="Previous" click="nextHandler()" enabled="{count< 10}">

But the compiler is throwing an error that '<' attribute can not be used in enabled tag.

Any ideas over this ?

Thanks in advance.

Body:
The following will work:

<mx:Button label="Previous" click="nextHandler()" enabled="{count &lt; 10}"/>

Just tested it with:

    <s:NumericStepper id="count"/>
    <mx:Button label="Previous"  enabled="{count.value &lt; 10}"/>


问:
Compile Sencha EXT JS theme with SASS mapping for Chrome Canary
Chrome Canary offers some excellent SASS inspector features IF you can compile your theme with debug information. I've figure out how to do this in generic Compass styles sheets with the line:sass_options = { :debug_info=>true }, however EXT JS has build process that (no matter what it seems) always compiles the SASS files compressed. Their "testing" command can expand this file, but I still need the @media tags (or the debug info) in order to get SASS inspector to work.

Does anyone know how to alter the Sencha EXT JS theme build process to add in debug info for Canary support? Or does anyone know what build.css.preprocessor.opts.production does in build.properties as it may be related?

答:
Try to switch the mode by:

```<code>sencha package build development // or `build debug`
</code>```

As for the build.css.preprocessor.opts.production, definitely it can be used (check sencha test):

```<code>build.options=logger:${build.options.logger},
debug:${build.options.debug},
product:${build.options.product},
minVersion:${build.options.minVersion},
${build.options.default},
${build.options.custom}
</code>```

Body:
Try to switch the mode by:

sencha package build development // or `build debug`

As for the build.css.preprocessor.opts.production, definitely it can be used (check sencha test):

build.options=logger:${build.options.logger},
debug:${build.options.debug},
product:${build.options.product},
minVersion:${build.options.minVersion},
${build.options.default},
${build.options.custom}


问:
(pandas) Why does .bfill().ffill() act differently than ffill().bfill() on groups?
I think I'm missing something basic conceptually, but I'm not able to find the answer in the docs.

```<code>>>> df=pd.DataFrame({'a':[1,1,2,2,3,3], 'b':[5,np.nan, 6, np.nan, np.nan, np.nan]})
>>> df
   a    b
0  1  5.0
1  1  NaN
2  2  6.0
3  2  NaN
4  3  NaN
5  3  NaN
</code>```

Using ffill() and then bfill():

```<code>>>> df.groupby('a')['b'].ffill().bfill()
0    5.0
1    5.0
2    6.0
3    6.0
4    NaN
5    NaN
</code>```

Using bfill() and then ffill():

```<code>>>> df.groupby('a')['b'].bfill().ffill()
0    5.0
1    5.0
2    6.0
3    6.0
4    6.0
5    6.0
</code>```

Doesn't the second way break the groupings? Will the first way always make sure that the values are filled in only with other values in that group?

答:
I think you need:

```<code>print (df.groupby('a')['b'].apply(lambda x: x.ffill().bfill()))
0    5.0
1    5.0
2    6.0
3    6.0
4    NaN
5    NaN
Name: b, dtype: float64

print (df.groupby('a')['b'].apply(lambda x: x.bfill().ffill()))
0    5.0
1    5.0
2    6.0
3    6.0
4    NaN
5    NaN
Name: b, dtype: float64
</code>```

because in your sample only first ffill or bfill is DataFrameGroupBy.ffill or DataFrameGroupBy.bfill, second is working with output Series. So it break groups, because Series has no groups.

```<code>print (df.groupby('a')['b'].ffill())
0    5.0
1    5.0
2    6.0
3    6.0
4    NaN
5    NaN
Name: b, dtype: float64

print (df.groupby('a')['b'].bfill())
0    5.0
1    NaN
2    6.0
3    NaN
4    NaN
5    NaN
Name: b, dtype: float64
</code>```

Body:
I think I'm missing something basic conceptually, but I'm not able to find the answer in the docs.

>>> df=pd.DataFrame({'a':[1,1,2,2,3,3], 'b':[5,np.nan, 6, np.nan, np.nan, np.nan]})
>>> df
   a    b
0  1  5.0
1  1  NaN
2  2  6.0
3  2  NaN
4  3  NaN
5  3  NaN

Using ffill() and then bfill():

>>> df.groupby('a')['b'].ffill().bfill()
0    5.0
1    5.0
2    6.0
3    6.0
4    NaN
5    NaN

Using bfill() and then ffill():

>>> df.groupby('a')['b'].bfill().ffill()
0    5.0
1    5.0
2    6.0
3    6.0
4    6.0
5    6.0

Doesn't the second way break the groupings? Will the first way always make sure that the values are filled in only with other values in that group?

Body:
I think you need:

print (df.groupby('a')['b'].apply(lambda x: x.ffill().bfill()))
0    5.0
1    5.0
2    6.0
3    6.0
4    NaN
5    NaN
Name: b, dtype: float64

print (df.groupby('a')['b'].apply(lambda x: x.bfill().ffill()))
0    5.0
1    5.0
2    6.0
3    6.0
4    NaN
5    NaN
Name: b, dtype: float64

because in your sample only first ffill or bfill is DataFrameGroupBy.ffill or DataFrameGroupBy.bfill, second is working with output Series. So it break groups, because Series has no groups.

print (df.groupby('a')['b'].ffill())
0    5.0
1    5.0
2    6.0
3    6.0
4    NaN
5    NaN
Name: b, dtype: float64

print (df.groupby('a')['b'].bfill())
0    5.0
1    NaN
2    6.0
3    NaN
4    NaN
5    NaN
Name: b, dtype: float64


问:
Unit testing exceptions with RequestFixture and HandlingResult in Ratpack
So I know how to properly check when an exception is thrown, on my handler unit tests.

However, what is the correct approach when I want to make sure an exception was not thrown?

This is the best I've come up with so far:

```<code>def "No exception is thrown"() {
    given:
    def noExceptionThrown = false

    when:
    def result =  RequestFixture.handle(new TestEndpoint(), { fixture -> fixture.uri("path/a)})

    then:
    try {
        result.exception(CustomException)
    } catch(ratpack.test.handling.HandlerExceptionNotThrownException e) {
        noExceptionThrown = (e != null)
    }

    noExceptionThrown
}
</code>```

答:
You could reorder the code a bit, so you can use Spock's thrown method:

```<code>def "No exception is thrown"() {
    given:
    def result =  RequestFixture.handle(new TestEndpoint(), { fixture -> fixture.uri("path/a)})

    when:
    result.exception(CustomException)

    then:
    thrown(HandlerExceptionNotThrownException)
}
</code>```

Another option is to use a custom error handler in the tests and add it to the registry of the fixture. The custom error handler can have methods to indicate an exception is thrown or not.
See the following example:

```<code>package sample

import ratpack.error.ServerErrorHandler
import ratpack.handling.Context
import ratpack.handling.Handler
import ratpack.test.handling.RequestFixture
import spock.lang.Specification

class HandlerSpec extends Specification {

    def 'check exception is thrown'() {
        given:
        def errorHandler = new TestErrorHandler()

        when:
        RequestFixture.handle(new SampleHandler(true), { fixture ->
            fixture.registry.add ServerErrorHandler, errorHandler
        })

        then:
        errorHandler.exceptionThrown()

        and:
        errorHandler.throwable.message == 'Sample exception'
    }

    def 'check no exception is thrown'() {
        given:
        def errorHandler = new TestErrorHandler()

        when:
        RequestFixture.handle(new SampleHandler(false), { fixture ->
            fixture.registry.add ServerErrorHandler, errorHandler
        })

        then:
        errorHandler.noExceptionThrown()
    }

}

class SampleHandler implements Handler {

    private final boolean throwException = false

    SampleHandler(final boolean throwException) {
        this.throwException = throwException
    }

    @Override
    void handle(final Context ctx) throws Exception {
        if (throwException) {
            ctx.error(new Exception('Sample exception'))
        } else {
            ctx.response.send('OK')
        }
    }

}

class TestErrorHandler implements ServerErrorHandler {

    private Throwable throwable

    @Override
    void error(final Context context, final Throwable throwable) throws Exception {
        this.throwable = throwable
        context.response.status(500)
        context.response.send('NOK')
    }

    boolean exceptionThrown() {
        throwable != null
    }

    boolean noExceptionThrown() {
        !exceptionThrown()
    }
}
</code>```

Body:
So I know how to properly check when an exception is thrown, on my handler unit tests.

However, what is the correct approach when I want to make sure an exception was not thrown?

This is the best I've come up with so far:

def "No exception is thrown"() {
    given:
    def noExceptionThrown = false

    when:
    def result =  RequestFixture.handle(new TestEndpoint(), { fixture -> fixture.uri("path/a)})

    then:
    try {
        result.exception(CustomException)
    } catch(ratpack.test.handling.HandlerExceptionNotThrownException e) {
        noExceptionThrown = (e != null)
    }

    noExceptionThrown
}

Body:
You could reorder the code a bit, so you can use Spock's thrown method:

def "No exception is thrown"() {
    given:
    def result =  RequestFixture.handle(new TestEndpoint(), { fixture -> fixture.uri("path/a)})

    when:
    result.exception(CustomException)

    then:
    thrown(HandlerExceptionNotThrownException)
}

Another option is to use a custom error handler in the tests and add it to the registry of the fixture. The custom error handler can have methods to indicate an exception is thrown or not.
See the following example:

package sample

import ratpack.error.ServerErrorHandler
import ratpack.handling.Context
import ratpack.handling.Handler
import ratpack.test.handling.RequestFixture
import spock.lang.Specification

class HandlerSpec extends Specification {

    def 'check exception is thrown'() {
        given:
        def errorHandler = new TestErrorHandler()

        when:
        RequestFixture.handle(new SampleHandler(true), { fixture ->
            fixture.registry.add ServerErrorHandler, errorHandler
        })

        then:
        errorHandler.exceptionThrown()

        and:
        errorHandler.throwable.message == 'Sample exception'
    }

    def 'check no exception is thrown'() {
        given:
        def errorHandler = new TestErrorHandler()

        when:
        RequestFixture.handle(new SampleHandler(false), { fixture ->
            fixture.registry.add ServerErrorHandler, errorHandler
        })

        then:
        errorHandler.noExceptionThrown()
    }

}

class SampleHandler implements Handler {

    private final boolean throwException = false

    SampleHandler(final boolean throwException) {
        this.throwException = throwException
    }

    @Override
    void handle(final Context ctx) throws Exception {
        if (throwException) {
            ctx.error(new Exception('Sample exception'))
        } else {
            ctx.response.send('OK')
        }
    }

}

class TestErrorHandler implements ServerErrorHandler {

    private Throwable throwable

    @Override
    void error(final Context context, final Throwable throwable) throws Exception {
        this.throwable = throwable
        context.response.status(500)
        context.response.send('NOK')
    }

    boolean exceptionThrown() {
        throwable != null
    }

    boolean noExceptionThrown() {
        !exceptionThrown()
    }
}


问:
How does react-create-app/react-scripts find the entry point?
In this tutorial, how does npm start find the src/index/js to star the render? I can't find the configuration of this anywhere.

答: you can run npm run eject so that the project turn back to a normal webpack project. then you can find the configs.


问:
Java: Writing array to text file inconsistencies
For a class project, a group and I have been working on an application that reads in lines of text from a text file and can encrypt it, decrypt it (both using DES), and calculate an MD5 hash.  The program reads in text and encrypts it just fine, writing the array of now encrypted strings back into the text file in the order in which they were read, line by line with all requisite carriage returns.

However, when decrypting these strings, the program writes the plaintext to the file all on one line, with no spaces or carriage returns.  Both the encrypt and decrypt methods use the same fileWrite class, which uses a buffered writer.  I have added a System.out.println statement for debugging purposes to print out the contents of the arrays as they are being encrypted and decrypted to check for errors in storage, but I can't find any.

Even when I artificially insert carriage returns by way of the "\n" symbol, the text file is all one line after it's decrypted.  I cannot for the life of me figure out why the same class would behave in two different ways at different times. The code to write the array to the file is simple enough, and just proceeds element by element and probably doesn't really need to be included, but here it is anyway.

```<code>    for(int i=0;i<s.length;i++){
    bufferedWriter.write(s[i]);
    }
</code>```

From what I can gather, the issue potentially stems from how java and notepad handle new lines differently.  When it is reading the plaintext strings from the file, I'm assuming it receives the line breaks from the text file and prints out the encrypted text in this manner, but here java denotes a new line differently than it was originally in the file, leading to this spacing issue when these encrypted lines are then read and processed, but again, I'm not really sure, which is why I'm here. Any help would be appreciated.

答:
My guess is that you are using BufferedReader (which removes newline characters) and writing back the String's read without attempting to rebuild the newlines. (Or adding the newlines doesn't work because you say they are not here)

Instead of using BufferedReader you are better off treating the file as binary, reading blocks at a time and if it happens to be text, it will be unaltered. With text you have no way to guarentee \r\n or \n or \r will be recreated as they were in the original file.  If you encode and decode the text on different systems, the character encoding could be different. ;)

Body:
For a class project, a group and I have been working on an application that reads in lines of text from a text file and can encrypt it, decrypt it (both using DES), and calculate an MD5 hash.  The program reads in text and encrypts it just fine, writing the array of now encrypted strings back into the text file in the order in which they were read, line by line with all requisite carriage returns.

However, when decrypting these strings, the program writes the plaintext to the file all on one line, with no spaces or carriage returns.  Both the encrypt and decrypt methods use the same fileWrite class, which uses a buffered writer.  I have added a System.out.println statement for debugging purposes to print out the contents of the arrays as they are being encrypted and decrypted to check for errors in storage, but I can't find any.

Even when I artificially insert carriage returns by way of the "\n" symbol, the text file is all one line after it's decrypted.  I cannot for the life of me figure out why the same class would behave in two different ways at different times. The code to write the array to the file is simple enough, and just proceeds element by element and probably doesn't really need to be included, but here it is anyway.

    for(int i=0;i<s.length;i++){
    bufferedWriter.write(s[i]);
    }

From what I can gather, the issue potentially stems from how java and notepad handle new lines differently.  When it is reading the plaintext strings from the file, I'm assuming it receives the line breaks from the text file and prints out the encrypted text in this manner, but here java denotes a new line differently than it was originally in the file, leading to this spacing issue when these encrypted lines are then read and processed, but again, I'm not really sure, which is why I'm here. Any help would be appreciated.


问:
Mule Database Connector Multiple Queries
I am running multiple select queries and I want them to run one after the other.
In this example, I select account numbers then use those numbers in the following query. Will the queries run consecutively one after the other i.e. next query only runs after the previous query has finished. Do I need to wrap them in a composite-source and wrap them in a transaction? What would that look like?</p>

```<code>    <flow name="PopulateAccount">
          <db:select config-ref="dsConfig" doc:name="Get Account ID">
           <db:paramterized-query><![CDATA[

               SELECT ACC_NUM....
           </db:select>

           <custom-transformer class="com.vf.ListTransformer">

           <set-session-variable variableName="messageID" value="#[payload]"
                              doc:name="Set Account IDs"/>

         <!-- The next query depends on the Account IDS from
               previous results in the session variable -->

        <db:select config-ref="dsConfig" doc:name="Get Account Detail">
           <db:paramterized-query><![CDATA[
               SELECT ACC_NAME,....
           </db:select>
         <custom-transformer class="com.vf.AccountsTransformer">

          <!-- More database operations --->
    </flow>
</code>```

答:
Will the queries run consecutively one after the other

yes, as long as you do not take any measures to run them in parallel, like for example moving the database component in a separate flow and call it in a asynchronous way.

Do I need to wrap them in a composite-source

no, especially not if you use the result of the first query in the second query (like in your example)

and wrap them in a transaction

why? you are not inserting/updating anything in your example.

What would that look like?

just like in your example. the only thing i would change is the way how you store the result of your first query. although there is nothing wrong with using set-variable i prefer using a enricher to store result of a component in variable instead of changing the payload and setting the variable afterwards.

```<code><flow name="testFlow">
    <enricher target="#[flowVars.messageID]" doc:name="Message Enricher">
        <db:select config-ref="MySQL_Configuration" doc:name="select ACC_NUM">
            <db:parameterized-query><![CDATA[SELECT ACC_NUM ...]]></db:parameterized-query>
        </db:select>
    </enricher>
</flow>
</code>```

Body:
I am running multiple select queries and I want them to run one after the other.
In this example, I select account numbers then use those numbers in the following query. Will the queries run consecutively one after the other i.e. next query only runs after the previous query has finished. Do I need to wrap them in a composite-source and wrap them in a transaction? What would that look like?

    <flow name="PopulateAccount">
          <db:select config-ref="dsConfig" doc:name="Get Account ID">
           <db:paramterized-query><![CDATA[

               SELECT ACC_NUM....
           </db:select>

           <custom-transformer class="com.vf.ListTransformer">

           <set-session-variable variableName="messageID" value="#[payload]"
                              doc:name="Set Account IDs"/>

        <db:select config-ref="dsConfig" doc:name="Get Account Detail">
           <db:paramterized-query><![CDATA[
               SELECT ACC_NAME,....
           </db:select>
         <custom-transformer class="com.vf.AccountsTransformer">

    </flow>

Body:
Will the queries run consecutively one after the other

yes, as long as you do not take any measures to run them in parallel, like for example moving the database component in a separate flow and call it in a asynchronous way.

Do I need to wrap them in a composite-source

no, especially not if you use the result of the first query in the second query (like in your example)

and wrap them in a transaction

why? you are not inserting/updating anything in your example.

What would that look like?

just like in your example. the only thing i would change is the way how you store the result of your first query. although there is nothing wrong with using set-variable i prefer using a enricher to store result of a component in variable instead of changing the payload and setting the variable afterwards.

<flow name="testFlow">
    <enricher target="#[flowVars.messageID]" doc:name="Message Enricher">
        <db:select config-ref="MySQL_Configuration" doc:name="select ACC_NUM">
            <db:parameterized-query><![CDATA[SELECT ACC_NUM ...]]></db:parameterized-query>
        </db:select>
    </enricher>
</flow>


问:
Kivy - windows - Unable to find any valuable Window provider at all
I am starting with kivy. here is the sample code I am running.

```<code>import kivy
from kivy.app import App
from kivy.uix.button import Label
kivy.require('1.9.0')

class HelloApp(App):
    def build(self):
        return Label(text='Hello World!')

if __name__ == "__main__":
    HelloApp().run()
</code>```

and here is the traceback I am getting:

```<code>[INFO              ] [Logger      ] Record log in C:\Users\monac\.kivy\logs\kivy_16-11-23_9.txt
[INFO              ] [Kivy        ] v1.9.1
[INFO              ] [Python      ] v3.4.4 (v3.4.4:737efcadf5a6, Dec 20 2015, 20:20:57) [MSC v.1600 64 bit (AMD64)]
[INFO              ] [Factory     ] 179 symbols loaded
[INFO              ] [Image       ] Providers: img_tex, img_dds, img_gif, img_sdl2 (img_pil, img_ffpyplayer ignored)
[INFO              ] [Text        ] Provider: sdl2
[INFO              ] [OSC         ] using <thread> for socket
[INFO              ] [Window      ] Provider: sdl2
[INFO              ] [GL          ] GLEW initialization succeeded
[INFO              ] [GL          ] OpenGL version <b'4.5.0 NVIDIA 373.06'>
[INFO              ] [GL          ] OpenGL vendor <b'NVIDIA Corporation'>
[INFO              ] [GL          ] OpenGL renderer <b'GeForce GTX 960M/PCIe/SSE2'>
[INFO              ] [GL          ] OpenGL parsed version: 4, 5
[INFO              ] [GL          ] Shading version <b'4.50 NVIDIA'>
[INFO              ] [GL          ] Texture max size <16384>
[INFO              ] [GL          ] Texture max units <32>
[WARNING           ] [Image       ] Unable to load image <C:\Python34\lib\site-packages\kivy\data\glsl\default.png>
[CRITICAL          ] [Window      ] Unable to find any valuable Window provider at all!
sdl2 - Exception: SDL2: Unable to load image
  File "C:\Python34\lib\site-packages\kivy\core\__init__.py", line 67, in core_select_lib
    cls = cls()
  File "C:\Python34\lib\site-packages\kivy\core\window\window_sdl2.py", line 138, in __init__
    super(WindowSDL, self).__init__()
  File "C:\Python34\lib\site-packages\kivy\core\window\__init__.py", line 722, in __init__
    self.create_window()
  File "C:\Python34\lib\site-packages\kivy\core\window\window_sdl2.py", line 255, in create_window
    super(WindowSDL, self).create_window()
  File "C:\Python34\lib\site-packages\kivy\core\window\__init__.py", line 897, in create_window
    self.render_context = RenderContext()
  File "kivy\graphics\instructions.pyx", line 756, in kivy.graphics.instructions.RenderContext.__init__ (kivy\graphics\instructions.c:10729)
  File "C:\Python34\lib\site-packages\kivy\core\image\__init__.py", line 512, in __init__
    self.filename = arg
  File "C:\Python34\lib\site-packages\kivy\core\image\__init__.py", line 700, in _set_filename
    mipmap=self._mipmap, nocache=self._nocache)
  File "C:\Python34\lib\site-packages\kivy\core\image\__init__.py", line 430, in load
    im = loader(filename, **kwargs)
  File "C:\Python34\lib\site-packages\kivy\core\image\__init__.py", line 198, in __init__
    self._data = self.load(filename)
  File "C:\Python34\lib\site-packages\kivy\core\image\img_sdl2.py", line 42, in load
    raise Exception('SDL2: Unable to load image')

[CRITICAL          ] [App         ] Unable to get a Window, abort.
 Exception ignored in: 'kivy.properties.dpi2px'
 Traceback (most recent call last):
   File "C:\Python34\lib\site-packages\kivy\utils.py", line 513, in __get__
     retval = self.func(inst)
   File "C:\Python34\lib\site-packages\kivy\metrics.py", line 175, in dpi
     EventLoop.ensure_window()
   File "C:\Python34\lib\site-packages\kivy\base.py", line 126, in ensure_window
     sys.exit(1)
 SystemExit: 1
[CRITICAL          ] [App         ] Unable to get a Window, abort.
</code>```

I am running on windows 10 64bits. I have installed all the dependencies except gstreamer which I won't need at the moment.

I am also not sure why I am getting this error:

```<code>[WARNING           ] [Image       ] Unable to load image <C:\Python34\lib\site-packages\kivy\data\glsl\default.png>
</code>```

The file exists and I am running my code as admin to avoid access rights problems.

Thank you.

答:
You have to install the dependencies for Kivy.

Follow the instructions here

```<code>python -m pip install docutils pygments pypiwin32 kivy.deps.sdl2 kivy.deps.glew
</code>```

will do what you needed.

Body:
I am starting with kivy. here is the sample code I am running.

import kivy
from kivy.app import App
from kivy.uix.button import Label
kivy.require('1.9.0')

class HelloApp(App):
    def build(self):
        return Label(text='Hello World!')

if __name__ == "__main__":
    HelloApp().run()

and here is the traceback I am getting:

[INFO              ] [Logger      ] Record log in C:\Users\monac\.kivy\logs\kivy_16-11-23_9.txt
[INFO              ] [Kivy        ] v1.9.1
[INFO              ] [Python      ] v3.4.4 (v3.4.4:737efcadf5a6, Dec 20 2015, 20:20:57) [MSC v.1600 64 bit (AMD64)]
[INFO              ] [Factory     ] 179 symbols loaded
[INFO              ] [Image       ] Providers: img_tex, img_dds, img_gif, img_sdl2 (img_pil, img_ffpyplayer ignored)
[INFO              ] [Text        ] Provider: sdl2
[INFO              ] [OSC         ] using <thread> for socket
[INFO              ] [Window      ] Provider: sdl2
[INFO              ] [GL          ] GLEW initialization succeeded
[INFO              ] [GL          ] OpenGL version
[INFO              ] [GL          ] OpenGL vendor
[INFO              ] [GL          ] OpenGL renderer
[INFO              ] [GL          ] OpenGL parsed version: 4, 5
[INFO              ] [GL          ] Shading version
[INFO              ] [GL          ] Texture max size <16384>
[INFO              ] [GL          ] Texture max units <32>
[WARNING           ] [Image       ] Unable to load image <C:\Python34\lib\site-packages\kivy\data\glsl\default.png>
[CRITICAL          ] [Window      ] Unable to find any valuable Window provider at all!
sdl2 - Exception: SDL2: Unable to load image
  File "C:\Python34\lib\site-packages\kivy\core\__init__.py", line 67, in core_select_lib
    cls = cls()
  File "C:\Python34\lib\site-packages\kivy\core\window\window_sdl2.py", line 138, in __init__
    super(WindowSDL, self).__init__()
  File "C:\Python34\lib\site-packages\kivy\core\window\__init__.py", line 722, in __init__
    self.create_window()
  File "C:\Python34\lib\site-packages\kivy\core\window\window_sdl2.py", line 255, in create_window
    super(WindowSDL, self).create_window()
  File "C:\Python34\lib\site-packages\kivy\core\window\__init__.py", line 897, in create_window
    self.render_context = RenderContext()
  File "kivy\graphics\instructions.pyx", line 756, in kivy.graphics.instructions.RenderContext.__init__ (kivy\graphics\instructions.c:10729)
  File "C:\Python34\lib\site-packages\kivy\core\image\__init__.py", line 512, in __init__
    self.filename = arg
  File "C:\Python34\lib\site-packages\kivy\core\image\__init__.py", line 700, in _set_filename
    mipmap=self._mipmap, nocache=self._nocache)
  File "C:\Python34\lib\site-packages\kivy\core\image\__init__.py", line 430, in load
    im = loader(filename, **kwargs)
  File "C:\Python34\lib\site-packages\kivy\core\image\__init__.py", line 198, in __init__
    self._data = self.load(filename)
  File "C:\Python34\lib\site-packages\kivy\core\image\img_sdl2.py", line 42, in load
    raise Exception('SDL2: Unable to load image')

[CRITICAL          ] [App         ] Unable to get a Window, abort.
 Exception ignored in: 'kivy.properties.dpi2px'
 Traceback (most recent call last):
   File "C:\Python34\lib\site-packages\kivy\utils.py", line 513, in __get__
     retval = self.func(inst)
   File "C:\Python34\lib\site-packages\kivy\metrics.py", line 175, in dpi
     EventLoop.ensure_window()
   File "C:\Python34\lib\site-packages\kivy\base.py", line 126, in ensure_window
     sys.exit(1)
 SystemExit: 1
[CRITICAL          ] [App         ] Unable to get a Window, abort.

I am running on windows 10 64bits. I have installed all the dependencies except gstreamer which I won't need at the moment.

I am also not sure why I am getting this error:

[WARNING           ] [Image       ] Unable to load image <C:\Python34\lib\site-packages\kivy\data\glsl\default.png>

The file exists and I am running my code as admin to avoid access rights problems.

Thank you.

Body:
You have to install the dependencies for Kivy.

Follow the instructions here

python -m pip install docutils pygments pypiwin32 kivy.deps.sdl2 kivy.deps.glew

will do what you needed.


问:
Access control is not enabled for the database
I am creating an sample library app in nodejs+express+mongodb. when I run the gulp serve command the server start perfectly. when I goto specific mongodb page then it giving error insertMany is not a function.

```<code>var express = require('express');
var adminRouter = express.Router();
var mongodb = require('mongodb').MongoClient;
var books = [
   {
      title: 'world',
      genre: 'Lorem Ipsum text changing occured',
      author: 'Rakesh',
      read: false
   },
   {
      title: 'Make of the world',
      genre: 'Digital India towards occured',
      author: 'Jumanji',
      read: false
   }
];

var router = function (nav) {
   adminRouter.route('/addBooks')
      .get(function (req, res) {
         var url = 'mongodb://127.0.0.1:27017/admin';
         mongodb.connect(url, function (err, db) {
            var collections = db.collections('books');
            collections.insertMany(books,
               function (err, results) {
                  res.send(results);
                  db.close();
               }
            );
         });
      });

   return adminRouter;
};

module.exports = router;
</code>```

Mongo cmd screenshots
insertMany cmd not working

答:
There is a typo in syntax in line var collections = db.collections('books');.  The node mongo driver could only interpret a db.collection() function not db.collections() which actually is syntactically wrong.

Use db.collection('books') instead of db.collections('books'), this should fix the bug. Try it and let me know

Body:
I am creating an sample library app in nodejs+express+mongodb. when I run the gulp serve command the server start perfectly. when I goto specific mongodb page then it giving error insertMany is not a function.

var express = require('express');
var adminRouter = express.Router();
var mongodb = require('mongodb').MongoClient;
var books = [
   {
      title: 'world',
      genre: 'Lorem Ipsum text changing occured',
      author: 'Rakesh',
      read: false
   },
   {
      title: 'Make of the world',
      genre: 'Digital India towards occured',
      author: 'Jumanji',
      read: false
   }
];

var router = function (nav) {
   adminRouter.route('/addBooks')
      .get(function (req, res) {
         var url = 'mongodb://127.0.0.1:27017/admin';
         mongodb.connect(url, function (err, db) {
            var collections = db.collections('books');
            collections.insertMany(books,
               function (err, results) {
                  res.send(results);
                  db.close();
               }
            );
         });
      });

   return adminRouter;
};

module.exports = router;

Mongo cmd screenshots
insertMany cmd not working


问:
temporary column name in data.table
I want to give custom but temporary names (i.e., I dont want to alter the data.table using ":=") to the columns of a data.table after a column expression like mean. I have looked at some examples which use eval function but I want to do this in a single line of code. How can we do it? thank you!

I have this data

```<code>steps.dt = data.table(steps=rep(0:2, each=3),
date=as.factor(rep(c("10/2/2012", "10/3/2012", "10/4/2012"), each = 3)), interval = as.factor(rep(c(0,5,10), each = 3)))

steps.dt

   steps      date interval
1:     0 10/2/2012        0
2:     0 10/2/2012        0
3:     0 10/2/2012        0
4:     1 10/3/2012        5
5:     1 10/3/2012        5
6:     1 10/3/2012        5
7:     2 10/4/2012       10
8:     2 10/4/2012       10
9:     2 10/4/2012       10
</code>```

Now when I calculate means only to get a sense of the data and not modify it

```<code>steps.dt[,mean(steps), by = interval]
   interval V1
1:        0  0
2:        5  1
3:       10  2
</code>```

I get the result under a column named "V1". I want to give it a custom name like "steps.mean" without altering the data table using ":=" in the column expression.

答:
To name the column in a calculation you just need to set the name in the J expression

```<code>steps.dt[, .(steps.mean = mean(steps)), by = interval]
</code>```

And to only display the mean column, you can chain an expression onto the end to only show the column of interest

```<code>steps.dt[, .(steps.mean = mean(steps)), by = interval][, .(steps.mean)]
## or, if you only want a vector of values returned, don't use the .()
# steps.dt[, .(steps.mean = mean(steps)), by = interval][, steps.mean]
</code>```

Title: temporary column name in data.table

Body:
I want to give custom but temporary names (i.e., I dont want to alter the data.table using ":=") to the columns of a data.table after a column expression like mean. I have looked at some examples which use eval function but I want to do this in a single line of code. How can we do it? thank you!

I have this data

steps.dt = data.table(steps=rep(0:2, each=3),
date=as.factor(rep(c("10/2/2012", "10/3/2012", "10/4/2012"), each = 3)), interval = as.factor(rep(c(0,5,10), each = 3)))

steps.dt

   steps      date interval
1:     0 10/2/2012        0
2:     0 10/2/2012        0
3:     0 10/2/2012        0
4:     1 10/3/2012        5
5:     1 10/3/2012        5
6:     1 10/3/2012        5
7:     2 10/4/2012       10
8:     2 10/4/2012       10
9:     2 10/4/2012       10

Now when I calculate means only to get a sense of the data and not modify it

steps.dt[,mean(steps), by = interval]
   interval V1
1:        0  0
2:        5  1
3:       10  2

I get the result under a column named "V1". I want to give it a custom name like "steps.mean" without altering the data table using ":=" in the column expression.

Body:
To name the column in a calculation you just need to set the name in the J expression

steps.dt[, .(steps.mean = mean(steps)), by = interval]

And to only display the mean column, you can chain an expression onto the end to only show the column of interest

steps.dt[, .(steps.mean = mean(steps)), by = interval][, .(steps.mean)]
## or, if you only want a vector of values returned, don't use the .()
# steps.dt[, .(steps.mean = mean(steps)), by = interval][, steps.mean]


问:
Check whether cronjob has ran or not
I have one python script running in crontab, I want to check if it is running successfully or not? if not then send mail or another kind of notification. How do I notify based on Cron logs?

Things I already Tried:

All the Exception in python file I have already handled

Need: Notify user if Cron job is not running successfully?

答: There are monitoring services specifically for cronjobs, doing exactly what you're asking for. I'm partial to WDT.io and here're the detailed instructions: https://cookbook.wdt.io/cron.html.</p>

Title: Check whether cronjob has ran or not


问:
custom and different json date format
I have found how to customize ObjectMapper date format in order to let Spring to help to auto serialize/deserialize (serialize when I want to return object to client, deserialize when the request body is json object), but I have lot of DTO with different date format, some might need yyyy-mm-dd, some is dd-mm-yyyy, one ObjectMapper will not work for different required date format, what is the best practice solution for this issue?

```<code>@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    super.configureMessageConverters(converters);
    converters.add(mappingJacksonHttpMessageConverter());
}

MappingJacksonHttpMessageConverter mappingJacksonHttpMessageConverter() {
    MappingJacksonHttpMessageConverter mappingJacksonHttpMessageConverter = new MappingJacksonHttpMessageConverter();
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setDateFormat(new SimpleDateFormat("dd-MM-yyyy"));
    objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
    mappingJacksonHttpMessageConverter.setObjectMapper(objectMapper);
    mappingJacksonHttpMessageConverter.setPrettyPrint(true);
    return mappingJacksonHttpMessageConverter;
}
</code>```

答:
You could use custom Serializers and handle the different formats within a single Serializer. Here are a few pages that have some info on how to create custom Serializer/Deserializers:

Create Custom Serializer

Create Custom Deserializer

-- Edit --

From the documentation for MappingJacksonHttpMessageConverter (some emphasis added):

```<b>setObjectMapper</b>
public void setObjectMapper(org.codehaus.jackson.map.ObjectMapper objectMapper)

    Set the ObjectMapper for this view. If not set, a default ObjectMapper is used.

    Setting a custom-configured ObjectMapper is one way to take further control
    of the JSON serialization process. For example, an extended SerializerFactory
    can be configured that provides custom serializers for specific types.
    <i>The other option for refining the serialization process is to <b>use Jackson's
    provided annotations on the types to be serialized</b>, in which case <b>a
    custom-configured ObjectMapper is unnecessary.</b></i>
```

This means that you do not even need to call setObjectMapper if you have Serializers/Deserializers defined by annotations (as described in the links I posted above). For your benefit, here is an example:

For Serializing:

Create a StdSerializer object to handle the type you are interested in

```<code>public class ItemSerializer extends StdSerializer<Item> {
    // ...

    @Override
    public void serialize(Item value, JsonGenerator jgen, SerializerProvider provider) {
        // Write the Item data into the JsonGenerator
    }
}
</code>```

Define the Serializer for the object via annotations

```<code>@JsonSerialize(using = ItemSerializer.class)
public class Item {
    // ...
}
</code>```

For Deserialization

Create a StdDeserializer object to handle the type you are interested in

```<code>public class ItemDeserializer extends StdDeserializer<Item> {
    // ...

    @Override
    public Item deserialize(JsonParser jp, DeserializationContext ctxt)
      throws IOException, JsonProcessingException {
        // Handle the different date formats here!

        return new Item(/*parsed date object*/);
    }
}
</code>```

Define the Deserializer for the object via annotations

```<code>@JsonDeserialize(using = ItemDeserializer.class)
public class Item {
    // ...
}
</code>```

Title: custom and different json date format

Body:
I have found how to customize ObjectMapper date format in order to let Spring to help to auto serialize/deserialize (serialize when I want to return object to client, deserialize when the request body is json object), but I have lot of DTO with different date format, some might need yyyy-mm-dd, some is dd-mm-yyyy, one ObjectMapper will not work for different required date format, what is the best practice solution for this issue?

@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    super.configureMessageConverters(converters);
    converters.add(mappingJacksonHttpMessageConverter());
}

MappingJacksonHttpMessageConverter mappingJacksonHttpMessageConverter() {
    MappingJacksonHttpMessageConverter mappingJacksonHttpMessageConverter = new MappingJacksonHttpMessageConverter();
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setDateFormat(new SimpleDateFormat("dd-MM-yyyy"));
    objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
    mappingJacksonHttpMessageConverter.setObjectMapper(objectMapper);
    mappingJacksonHttpMessageConverter.setPrettyPrint(true);
    return mappingJacksonHttpMessageConverter;
}

Body:
You could use custom Serializers and handle the different formats within a single Serializer. Here are a few pages that have some info on how to create custom Serializer/Deserializers:

Create Custom Serializer

Create Custom Deserializer

-- Edit --

From the documentation for MappingJacksonHttpMessageConverter (some emphasis added):

setObjectMapper
public void setObjectMapper(org.codehaus.jackson.map.ObjectMapper objectMapper)

    Set the ObjectMapper for this view. If not set, a default ObjectMapper is used.

    Setting a custom-configured ObjectMapper is one way to take further control
    of the JSON serialization process. For example, an extended SerializerFactory
    can be configured that provides custom serializers for specific types.
    The other option for refining the serialization process is to use Jackson's
    provided annotations on the types to be serialized, in which case a
    custom-configured ObjectMapper is unnecessary.

This means that you do not even need to call setObjectMapper if you have Serializers/Deserializers defined by annotations (as described in the links I posted above). For your benefit, here is an example:

For Serializing:

Create a StdSerializer object to handle the type you are interested in

public class ItemSerializer extends StdSerializer<Item> {
    // ...

    @Override
    public void serialize(Item value, JsonGenerator jgen, SerializerProvider provider) {
        // Write the Item data into the JsonGenerator
    }
}

Define the Serializer for the object via annotations

@JsonSerialize(using = ItemSerializer.class)
public class Item {
    // ...
}

For Deserialization

Create a StdDeserializer object to handle the type you are interested in

public class ItemDeserializer extends StdDeserializer<Item> {
    // ...

    @Override
    public Item deserialize(JsonParser jp, DeserializationContext ctxt)
      throws IOException, JsonProcessingException {
        // Handle the different date formats here!

        return new Item(/*parsed date object*/);
    }
}

Define the Deserializer for the object via annotations

@JsonDeserialize(using = ItemDeserializer.class)
public class Item {
    // ...
}


问:
Display checkbox data
With Laravel Framework

I saved this checkbox to Mysql in one column

```<code><input type="checkbox" name="Sun" id="Sun" value="true"> Sun
<input type="checkbox" name="Mon" id="Mon" value="true"> Mon
<input type="checkbox" name="Thu" id="Thu" value="true"> Thu
<input type="checkbox" name="Wed" id="Wed" value="true"> Wed
<input type="checkbox" name="Thur" id="Thur" value="true"> Thur
<input type="checkbox" name="Fri" id="Fri" value="true"> Fri
<input type="checkbox" name="Sat" id="Sat" value="true"> Sat`
</code>```

And I display it in a table.It's displayed like1,0,1,0,0,0,1

Here's pic of that output

But I want to display if the value is equal to 1 like

Sun,Thu,Sat

How can I display like that?

答:
Try this ==>

```<code>$dbvalue = "1,0,1,0,0,0,1"; // value from Database
$values = explode(',', $dbvalue); // Convert String to array

$days = array("Sun","Mon","Thu","Wed","Thur","Fri","Sat"); // take a day array
$output = "";
for($i=0;$i<count($days);$i++){
   if($values[$i]==1)  // Compare value
       $output .=$days[$i].", "; // append value to $output variable
}
echo trim($output, ", ");  // output = Sun,Thu,Sat
</code>```

Check Solution here

Title: Display checkbox data

Body:
With Laravel Framework

I saved this checkbox to Mysql in one column

<input type="checkbox" name="Sun" id="Sun" value="true"> Sun
<input type="checkbox" name="Mon" id="Mon" value="true"> Mon
<input type="checkbox" name="Thu" id="Thu" value="true"> Thu
<input type="checkbox" name="Wed" id="Wed" value="true"> Wed
<input type="checkbox" name="Thur" id="Thur" value="true"> Thur
<input type="checkbox" name="Fri" id="Fri" value="true"> Fri
<input type="checkbox" name="Sat" id="Sat" value="true"> Sat`

And I display it in a table.It's displayed like1,0,1,0,0,0,1

Here's pic of that output

But I want to display if the value is equal to 1 like

Sun,Thu,Sat

How can I display like that?

Body:
Try this ==>

$dbvalue = "1,0,1,0,0,0,1"; // value from Database
$values = explode(',', $dbvalue); // Convert String to array

$days = array("Sun","Mon","Thu","Wed","Thur","Fri","Sat"); // take a day array
$output = "";
for($i=0;$i<count($days);$i++){
   if($values[$i]==1)  // Compare value
       $output .=$days[$i].", "; // append value to $output variable
}
echo trim($output, ", ");  // output = Sun,Thu,Sat

Check Solution here


问:
Unable to load the config file in angular 2
I have folder structure like below.

```<code>src
  app
    resources
      config
         home.json
    services
      service.ts
</code>```

I am trying to call the json file from config folder from service.ts like below

```<code> return this._http.get('../../resources/config/home.json')
</code>```

And I tried with couple more types. Unable to load the json file.

http://localhost:4200/resources/config/homeConfig.json 404 (Not Found) getting this error

答:
if your using angular CLI than place inside

src/assets/home.json

access like this

```<code> this.http.get('/assets/home.json')
                .subscribe(res => this.data = res.json());
</code>```

Body:
I have folder structure like below.

src
  app
    resources
      config
         home.json
    services
      service.ts

I am trying to call the json file from config folder from service.ts like below

 return this._http.get('../../resources/config/home.json')

And I tried with couple more types. Unable to load the json file.

http://localhost:4200/resources/config/homeConfig.json 404 (Not Found) getting this error

Body:
if your using angular CLI than place inside

src/assets/home.json

access like this

 this.http.get('/assets/home.json')
                .subscribe(res => this.data = res.json());


问:
vue.js: Error while using v-for
I want to render a table dynamically, based on ajax requests. The Backend is set up properly and when I execute the code the data from the response package is successfully loaded into my variables.

However, when viewing it in the browser, console logs the following error:

```<code>[Vue warn]: Failed to generate render function:

SyntaxError: Unexpected token - in

with(this){return _c('div',{attrs:{"id":"app"}},[_m(0),_v(" "),_c('table',[_c('tbody',[_c('tr',_l((header),function(head-item){return _c('th',{domProps:{"textContent":_s(head-item)}})})),_v(" "),_l((data),function(entry){return _c('tr',_l((entry),function(item){return _c('td',{domProps:{"textContent":_s(item)}})}))})],2)])])}

(found in <Root>)
</code>```

My app.js file:

```<code>new Vue({
    el: '#app',
    data: {
        header: [],
        data: [],
    },
    mounted() {
        axios.get('/contacts').then(response => this.load_response(response));
    },
    methods: {
        load_response(response) {
            this.header = response.data.header;
            this.data = response.data.data;
        }
    }
});
</code>```

And my html-file:

```<code><!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>TestProject</title>
    <body>
        <div id="app">
            <table>
                <tr>
                    <th>TestHeader/th>
                </tr>
                <tr>
                    <td>TestItem</td>
                </tr>
            </table>
            <table>
                <tr>
                    <th v-for="head-item in header" v-text="head-item"></th>
                </tr>
                <tr v-for="entry in data">
                    <td v-for="item in entry" v-text="item"></td>
                </tr>
            </table>
        </div>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.3/vue.js"></script>
        <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
        <script src="/js/app.js"></script>
    </body>
</html>
</code>```

When I try it in the browser, the first (dummy) table is shown for half a second or so, before it gets hidden. Then the page is blank.

EDIT: The json received from the server is in the form

```<code>{
header: [foo, bar, foobar...],
data:[[foo, bar, footer], [foo2, bar2, foobar2], ...]
}
</code>```

答:
You cannot use a dash in an identifier in v-for. Try

```<code><th v-for="headItem in header" v-text="headItem"></th>
</code>```

Dash isn't a valid character for any JavaScript variable.

Title: vue.js: Error while using v-for

Body:
I want to render a table dynamically, based on ajax requests. The Backend is set up properly and when I execute the code the data from the response package is successfully loaded into my variables.

However, when viewing it in the browser, console logs the following error:

[Vue warn]: Failed to generate render function:

SyntaxError: Unexpected token - in

with(this){return _c('div',{attrs:{"id":"app"}},[_m(0),_v(" "),_c('table',[_c('tbody',[_c('tr',_l((header),function(head-item){return _c('th',{domProps:{"textContent":_s(head-item)}})})),_v(" "),_l((data),function(entry){return _c('tr',_l((entry),function(item){return _c('td',{domProps:{"textContent":_s(item)}})}))})],2)])])}

(found in <Root>)

My app.js file:

new Vue({
    el: '#app',
    data: {
        header: [],
        data: [],
    },
    mounted() {
        axios.get('/contacts').then(response => this.load_response(response));
    },
    methods: {
        load_response(response) {
            this.header = response.data.header;
            this.data = response.data.data;
        }
    }
});

And my html-file:

<!doctype html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>TestProject</title>

                    TestHeader/th>

                    TestItem

When I try it in the browser, the first (dummy) table is shown for half a second or so, before it gets hidden. Then the page is blank.

EDIT: The json received from the server is in the form

{
header: [foo, bar, foobar...],
data:[[foo, bar, footer], [foo2, bar2, foobar2], ...]
}

Body:
You cannot use a dash in an identifier in v-for. Try

<th v-for="headItem in header" v-text="headItem"></th>

Dash isn't a valid character for any JavaScript variable.


问:
Capistrano deploy:assets:precompile failed on rails 5
I'm getting error on running this tasks:
Tasks: TOP => deploy:assets:precompile

```<code>Error:
The deploy has failed with an error: Exception while executing as deployer@**.**.**.***: rake exit status: 1
</code>```

Here is my Capfile:

```<code>require 'capistrano/setup'
require 'capistrano/deploy'
require 'capistrano/nginx'
require 'capistrano/puma'
require 'capistrano/puma/nginx'
require 'capistrano/rvm'
require 'capistrano/rails'
require 'capistrano/rails/db'
require 'capistrano/rails/console'
require 'capistrano/upload-config'
require 'sshkit/sudo'

Dir.glob('lib/capistrano/tasks/*.rake').each { |r| import r }
</code>```

This capfile running on Rails 4. I got the error when I migrated to rails 5.

答:
This solved my error: My capfile now looks like this

```require 'capistrano/setup'
require 'capistrano/deploy'
require 'capistrano/nginx'
require 'capistrano/puma'
require 'capistrano/puma/nginx'
require 'capistrano/rvm'
<b>require 'capistrano/rails/migrations'</b>
require 'capistrano/rails/db'
require 'capistrano/rails/console'
require 'capistrano/upload-config'
require 'sshkit/sudo'

Dir.glob('lib/capistrano/tasks/*.rake').each { |r| import r } ```

I removed this line for asset compilation

``` require 'capistrano/rails ```

And replaced to

``` require 'capistrano/rails/migrations ```

Body:
I'm getting error on running this tasks:
Tasks: TOP => deploy:assets:precompile

Error:
The deploy has failed with an error: Exception while executing as deployer@**.**.**.***: rake exit status: 1

Here is my Capfile:

require 'capistrano/setup'
require 'capistrano/deploy'
require 'capistrano/nginx'
require 'capistrano/puma'
require 'capistrano/puma/nginx'
require 'capistrano/rvm'
require 'capistrano/rails'
require 'capistrano/rails/db'
require 'capistrano/rails/console'
require 'capistrano/upload-config'
require 'sshkit/sudo'

Dir.glob('lib/capistrano/tasks/*.rake').each { |r| import r }

This capfile running on Rails 4. I got the error when I migrated to rails 5.

Body:
This solved my error: My capfile now looks like this

require 'capistrano/setup'
require 'capistrano/deploy'
require 'capistrano/nginx'
require 'capistrano/puma'
require 'capistrano/puma/nginx'
require 'capistrano/rvm'
require 'capistrano/rails/migrations'
require 'capistrano/rails/db'
require 'capistrano/rails/console'
require 'capistrano/upload-config'
require 'sshkit/sudo'

Dir.glob('lib/capistrano/tasks/*.rake').each { |r| import r }

I removed this line for asset compilation

 require 'capistrano/rails

And replaced to

 require 'capistrano/rails/migrations


问:
csrf_exclude_uri in CI version 2?
i have some problem using csrf_protection. i want to hit example.com/test/index_post from a form in mysite.com/myform using post method form but when i submit the form error page

The action you have requested is not allowed.

showed. I'm using CI version 2.
i already know some solution using csrf_exclude_uri but it didnt work in CI version 2. is there other solution similiar with csrf_exclude_uri in CI version 2?

答: according to my research and Joe's answer, the only way is to upgrade CI 2 to CI 3,because CI 2 dont have that services</p>

Title: csrf_exclude_uri in CI version 2?


问:
Python Pandas return an array instead of series
I have the following code:

```<code>for j in account_list:
 my_dict['name'] = (df[df['DESC'].str.contains(j)]['Hostname'].iloc[0])
</code>```

This one works fine and returns an array of names, but if I changed it to:

```<code> for j in account_list:
      my_dict['name'] = (df[df['DESC'].str.startswith('Account')]['Hostname'])
</code>```

It returns a series not an array, I have tried asarray() and as_matrix, none of them returns an array like the first one, could you please help me?

Sample from the excel sheet:
https://paste.pound-python.org/show/VfRmfJEWavU14luvFXQs/

EDIT: Expected result should be like this:

```<code>wordpress
wordpress
drupal
magento
</code>```

答: welcome to stack overflow. Your code doesn't really return anything, but I take it that the my_dict contains Series whilst you would like it to contain an array? Try the_pandas_serie_object.values().

Body:
I have the following code:

for j in account_list:
 my_dict['name'] = (df[df['DESC'].str.contains(j)]['Hostname'].iloc[0])

This one works fine and returns an array of names, but if I changed it to:

 for j in account_list:
      my_dict['name'] = (df[df['DESC'].str.startswith('Account')]['Hostname'])

It returns a series not an array, I have tried asarray() and as_matrix, none of them returns an array like the first one, could you please help me?

Sample from the excel sheet:
https://paste.pound-python.org/show/VfRmfJEWavU14luvFXQs/

EDIT: Expected result should be like this:

wordpress
wordpress
drupal
magento


问:
For PHP REST API, how can I define/set the database connection parameters outside the class definition?
I'm using the PHP REST API example that appears all over the web. Here's basically what it is:

```<code><?php

    require_once("Rest.inc.php");

    class API extends REST {

        const DB_SERVER     = "myhost";
        const DB_USER       = "myuser";
        const DB_PASSWORD   = "mypassword";
        const DB_NAME       = "mydb";

        public $data = "";
        private $db = NULL;

        public function __construct(){
            parent::__construct();
            $this->dbConnect();
        }

        private function dbConnect(){

            try {
                $this->db = new PDO("mysql:host=" . self::DB_SERVER . ";dbname=" . self::DB_NAME, self::DB_USER, self::DB_PASSWORD);
                $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            }
            catch(PDOException $e) {
                echo "Connection failed: " . $e->getMessage();
            }
        }

        public function processApi(){

            $func = strtolower(trim(str_replace("/","",$_REQUEST['rquest'])));

            if((int)method_exists($this,$func) > 0) {
                $this->$func();
            } else {
                $this->response('',404);
            }

        }

        private function activity(){
            ...
        }

        private function client(){
            ...
        }

        private function facility(){
            ...
        }

        etc...

        private function json($data){
            if(is_array($data)){
                return json_encode($data);
            }
        }
    }

    // Initiiate Library

    $api = new API;
    $api->processApi();

?>
</code>```

It works fine, except that I don't want to hardcode the database connection parameters in that script. What is the best way (or is there a way) to separate them from this script? I can't use an include file inside the class declaration. Can I put the whole dbConnect() function in an include file, and include that outside the class definition? Any other options? I just want it so that there is nothing tying this script to a specific server. I would prefer to have the db server defined in a separate file that could be different on each server. I'm new to PHP and just wondering how the experts handle this.

**Edit: Got it working! This is a bit of a hybrid of the supplied answers.

dbConnect.php

```<code><?php
    class DB {

        const DB_SERVER     = "myserver";
        const DB_USER       = "myuser";
        const DB_PASSWORD   = "mypassword";
        const DB_NAME       = "mydb";

        private $db = null;

        public function __construct() {
            try {
                $this->db = new PDO("mysql:host=" . self::DB_SERVER . ";dbname=" . self::DB_NAME, self::DB_USER, self::DB_PASSWORD);
                $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            }
            catch(PDOException $e) {
                echo "Connection failed: " . $e->getMessage();
            }
        }
    }
?>
</code>```

api.php

```<code><?php

    require_once("Rest.inc.php");
    require_once("dbConnect.php");

    class API extends REST {
        public $data = "";
        private $db = null;

        public function __construct(DB $mydb){
            parent::__construct();
            $this->db = mydb->db;
        }
    }

    // Initiiate Library

    $api = new API(new DB());
    $api->processApi();

?>
</code>```

答:
You can use like below:

db.php:

create connection function in separate class.

```<code>class DB {
    const DB_SERVER     = "myhost";
    const DB_USER       = "myuser";
    const DB_PASSWORD   = "mypassword";
    const DB_NAME       = "mydb";

    public $data = "";
    private $db = NULL;

    private function dbConnect(){

        try {
            $this->db = new PDO("mysql:host=" . self::DB_SERVER . ";dbname=" . self::DB_NAME, self::DB_USER, self::DB_PASSWORD);
            $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }
        catch(PDOException $e) {
            echo "Connection failed: " . $e->getMessage();
        }
    }
}
</code>```

current_file.php:

```<code>class API extends REST {

    public function __construct(){
        parent::__construct();
        //$this->dbConnect();
        //here you can implement the class and function
        $this->db = new DB();
        $this->db->dbConnect();
    }

}
</code>```

Body:
I'm using the PHP REST API example that appears all over the web. Here's basically what it is:

<?php

    require_once("Rest.inc.php");

    class API extends REST {

        const DB_SERVER     = "myhost";
        const DB_USER       = "myuser";
        const DB_PASSWORD   = "mypassword";
        const DB_NAME       = "mydb";

        public $data = "";
        private $db = NULL;

        public function __construct(){
            parent::__construct();
            $this->dbConnect();
        }

        private function dbConnect(){

            try {
                $this->db = new PDO("mysql:host=" . self::DB_SERVER . ";dbname=" . self::DB_NAME, self::DB_USER, self::DB_PASSWORD);
                $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            }
            catch(PDOException $e) {
                echo "Connection failed: " . $e->getMessage();
            }
        }

        public function processApi(){

            $func = strtolower(trim(str_replace("/","",$_REQUEST['rquest'])));

            if((int)method_exists($this,$func) > 0) {
                $this->$func();
            } else {
                $this->response('',404);
            }

        }

        private function activity(){
            ...
        }

        private function client(){
            ...
        }

        private function facility(){
            ...
        }

        etc...

        private function json($data){
            if(is_array($data)){
                return json_encode($data);
            }
        }
    }

    // Initiiate Library

    $api = new API;
    $api->processApi();

?>

It works fine, except that I don't want to hardcode the database connection parameters in that script. What is the best way (or is there a way) to separate them from this script? I can't use an include file inside the class declaration. Can I put the whole dbConnect() function in an include file, and include that outside the class definition? Any other options? I just want it so that there is nothing tying this script to a specific server. I would prefer to have the db server defined in a separate file that could be different on each server. I'm new to PHP and just wondering how the experts handle this.

**Edit: Got it working! This is a bit of a hybrid of the supplied answers.

dbConnect.php

<?php
    class DB {

        const DB_SERVER     = "myserver";
        const DB_USER       = "myuser";
        const DB_PASSWORD   = "mypassword";
        const DB_NAME       = "mydb";

        private $db = null;

        public function __construct() {
            try {
                $this->db = new PDO("mysql:host=" . self::DB_SERVER . ";dbname=" . self::DB_NAME, self::DB_USER, self::DB_PASSWORD);
                $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            }
            catch(PDOException $e) {
                echo "Connection failed: " . $e->getMessage();
            }
        }
    }
?>

api.php

<?php

    require_once("Rest.inc.php");
    require_once("dbConnect.php");

    class API extends REST {
        public $data = "";
        private $db = null;

        public function __construct(DB $mydb){
            parent::__construct();
            $this->db = mydb->db;
        }
    }

    // Initiiate Library

    $api = new API(new DB());
    $api->processApi();

?>

Body:
You can use like below:

db.php:

create connection function in separate class.

class DB {
    const DB_SERVER     = "myhost";
    const DB_USER       = "myuser";
    const DB_PASSWORD   = "mypassword";
    const DB_NAME       = "mydb";

    public $data = "";
    private $db = NULL;

    private function dbConnect(){

        try {
            $this->db = new PDO("mysql:host=" . self::DB_SERVER . ";dbname=" . self::DB_NAME, self::DB_USER, self::DB_PASSWORD);
            $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }
        catch(PDOException $e) {
            echo "Connection failed: " . $e->getMessage();
        }
    }
}

current_file.php:

class API extends REST {

    public function __construct(){
        parent::__construct();
        //$this->dbConnect();
        //here you can implement the class and function
        $this->db = new DB();
        $this->db->dbConnect();
    }

}


问:
Python - How can I find out if a specific XML node is present using Python?
Here is a sample of some XML code I have:

```<code><VAST version="2.0">
<Ad id="602678">
<InLine>
<AdSystem>Acudeo Compatible</AdSystem>
<AdTitle>NonLinear Test Campaign 1</AdTitle>
<Description>NonLinear Test Campaign 1</Description>
<Creatives>
<Creative AdID="602678-NonLinear">
</Creative>
</Creatives>
</InLine>
</Ad>
</VAST>
</code>```

This XML is served online so I hit a specific URL in order to get this data back. However, in some cases, nothing is returned so I am looking for a way to verify whether or not the "Creatives" node is present in whatever is returned at any given time. I have tried BeautifulSoup with no luck but I think that is more for HTML rather than XML. Any help is greatly appreciated, thanks.

答:
Let's suppose you retrieve the XML from an URL like this:

```<code>import requests

r = requests.get(url)
if r.status_code == 200:
    xml_tag_exists(r)
</code>```

Then you just have to build a simple function which will return True/False based on whether the required XML tag exists:

```<code>def xml_tag_exists(r):
    return '<Creatives>' in r.text
</code>```

For example, let's take the following URL:

```<code>>>> import requests
>>> url = 'http://www.w3schools.com/xml/plant_catalog.xml'
>>> r = requests.get(url)
>>> if r.status_code == 200:
...     print(r.text)
</code>```

The above will return an XML of the following form:

```<code><CATALOG>
  <PLANT>
    <COMMON>Bloodroot</COMMON>
    <BOTANICAL>Sanguinaria canadensis</BOTANICAL>
    <ZONE>4</ZONE>
    <LIGHT>Mostly Shady</LIGHT>
    <PRICE>$2.44</PRICE>
    <AVAILABILITY>031599</AVAILABILITY>
  </PLANT>
  <PLANT>
    <COMMON>Columbine</COMMON>
    <BOTANICAL>Aquilegia canadensis</BOTANICAL>
    <ZONE>3</ZONE>
    <LIGHT>Mostly Shady</LIGHT>
    <PRICE>$9.37</PRICE>
    <AVAILABILITY>030699</AVAILABILITY>
  </PLANT>
  ...
</CATALOG>
</code>```

Which if we check for some tag:

```<code>>>> if '<CATALOG>' in r.text:
...     print(True)
...
True
</code>```

So, if I were to do this, I'd write something like this:

```<code>import requests

def xml_tag_exists(r):
    return '<Creatives>' in r.text

def main():
    r = requests.get('your_url_goes_here')
    if r.status_code == 200:
        xml_tag_exists(r)

if __name__ == '__main__':
    main()
</code>```

Body:
Here is a sample of some XML code I have:

<VAST version="2.0">
<Ad id="602678">
<InLine>
<AdSystem>Acudeo Compatible</AdSystem>
<AdTitle>NonLinear Test Campaign 1</AdTitle>
<Description>NonLinear Test Campaign 1</Description>
<Creatives>
<Creative AdID="602678-NonLinear">
</Creative>
</Creatives>
</InLine>
</Ad>
</VAST>

This XML is served online so I hit a specific URL in order to get this data back. However, in some cases, nothing is returned so I am looking for a way to verify whether or not the "Creatives" node is present in whatever is returned at any given time. I have tried BeautifulSoup with no luck but I think that is more for HTML rather than XML. Any help is greatly appreciated, thanks.

Body:
Let's suppose you retrieve the XML from an URL like this:

import requests

r = requests.get(url)
if r.status_code == 200:
    xml_tag_exists(r)

Then you just have to build a simple function which will return True/False based on whether the required XML tag exists:

def xml_tag_exists(r):
    return '<Creatives>' in r.text

For example, let's take the following URL:

>>> import requests
>>> url = 'http://www.w3schools.com/xml/plant_catalog.xml'
>>> r = requests.get(url)
>>> if r.status_code == 200:
...     print(r.text)

The above will return an XML of the following form:

<CATALOG>
  <PLANT>
    <COMMON>Bloodroot</COMMON>
    <BOTANICAL>Sanguinaria canadensis</BOTANICAL>
    <ZONE>4</ZONE>
    <LIGHT>Mostly Shady</LIGHT>
    <PRICE>$2.44</PRICE>
    <AVAILABILITY>031599</AVAILABILITY>
  </PLANT>
  <PLANT>
    <COMMON>Columbine</COMMON>
    <BOTANICAL>Aquilegia canadensis</BOTANICAL>
    <ZONE>3</ZONE>
    <LIGHT>Mostly Shady</LIGHT>
    <PRICE>$9.37</PRICE>
    <AVAILABILITY>030699</AVAILABILITY>
  </PLANT>
  ...
</CATALOG>

Which if we check for some tag:

>>> if '<CATALOG>' in r.text:
...     print(True)
...
True

So, if I were to do this, I'd write something like this:

import requests

def xml_tag_exists(r):
    return '<Creatives>' in r.text

def main():
    r = requests.get('your_url_goes_here')
    if r.status_code == 200:
        xml_tag_exists(r)

if __name__ == '__main__':
    main()