问:
How to transform this xml using xslt
I have an XML in the following format:

```<code><?xml version="1.0" encoding="utf-8"?>
<dataset  xmlns="http://developer.cognos.com/schemas/xmldata/1/"  xmlns:xs="http://www.w3.org/2001/XMLSchema-instance">
    <metadata>
          <item name="Col1" type="xs:string" length="14"/>
          <item name="Col2" type="xs:string" length="92"/>
          <item name="Col3" type="xs:string" length="66"/>
          <item name="Col4 With Space" type="xs:string" length="32"/>
    </metadata>
    <data>
        <row>
            <value>SomeVal1</value>
            <value>SomeVal2</value>
            <value>SomeVal3</value>
            <value>SomeVal4</value>
        </row>
        <row>
            <value>SomeVal11</value>
            <value>SomeVal22</value>
            <value>SomeVal33</value>
            <value>SomeVal44</value>
        </row>
    </data>
</dataset>
</code>```

I want to transform it to this format:

```<code><?xml version="1.0" encoding="utf-8"?>
<dataset>
    <data>
        <row>
            <Col1 type="xs:string" length="14">SomeVal1</Col1>
            <Col2 type="xs:string" length="92">SomeVal2</Col2>
            <Col3 type="xs:string" length="66">SomeVal3</Col3>
            <Col4_With_Space type="xs:string" length="32">SomeVal4</Col4_With_Space>
        </row>
        <row>
            <Col1 type="xs:string" length="14">SomeVal11</Col1>
            <Col2 type="xs:string" length="92">SomeVal22</Col2>
            <Col3 type="xs:string" length="66">SomeVal33</Col3>
            <Col4_With_Space type="xs:string" length="32">SomeVal44</Col4_With_Space>
        </row>
    </data>
</dataset>
</code>```

I've never used xslt before and I am out of my depth. I tried something like this (which doesn't work) but I'm stuck.

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.w3.org/1999/xhtml" version="1.0">
<xsl:output encoding="UTF-8" indent="yes" method="xml" standalone="no" omit-xml-declaration="no"/>
    <xsl:template match="dataset">
        <xsl:for-each select="data/row">
            <Col1 select="1"/>
            <Col2 select="2"/>
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>
</code>```

The reason for wanting to transform is SSIS "Data Flow" "XML Source" doesn't recognise the first format. I'm trying to import data from an XML into a DB table. "XML Source" works with the 2nd format but not the first.

I think I should add, there is no guarantee XML metadata will always be the same, so transform needs to take the column names and types from the metadata, instead of hard-coding.

答:
I've never used xslt before and I am out of my depth.

This is certainly not a task suitable for a beginner.

As I mentioned in the comment to your question, your first problem is that your source XML places all its elements in a namespace. You need to declare the same namespace in your stylesheet, assign it a prefix and use that prefix to address the elements in the source XML.

The other issue with your attempt is that you're not actually getting any data from the source XML.

```<code><Col1 select="1"/>
</code>```

will output the same static element for each row in your XML.

Now, the real complication here is getting the columns names and attributes from the metadata section and pairing them with the corresponding cell value from the current row. This could be accomplished as follows:

XSLT 1.0

```<code><xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:cog="http://developer.cognos.com/schemas/xmldata/1/"
exclude-result-prefixes="cog">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="/cog:dataset">
    <xsl:variable name="cols" select="cog:metadata/cog:item" />
    <dataset>
        <data>
            <xsl:for-each select="cog:data/cog:row">
                <xsl:variable name="curr-row-cells" select="cog:value" />
                <row>
                    <xsl:for-each select="$cols">
                        <xsl:variable name="i" select="position()" />
                        <xsl:element name="{translate(@name, ' ', '_')}">
                            <xsl:copy-of select="@type | @length"/>
                            <xsl:value-of select="$curr-row-cells[$i]" />
                        </xsl:element>
                    </xsl:for-each>
                </row>
            </xsl:for-each>
        </data>
    </dataset>
</xsl:template>

</xsl:stylesheet>
</code>```

Result

```<code><?xml version="1.0" encoding="UTF-8"?>
<dataset>
  <data>
    <row>
      <Col1 type="xs:string" length="14">SomeVal1</Col1>
      <Col2 type="xs:string" length="92">SomeVal2</Col2>
      <Col3 type="xs:string" length="66">SomeVal3</Col3>
      <Col4_With_Space type="xs:string" length="32">SomeVal4</Col4_With_Space>
    </row>
    <row>
      <Col1 type="xs:string" length="14">SomeVal11</Col1>
      <Col2 type="xs:string" length="92">SomeVal22</Col2>
      <Col3 type="xs:string" length="66">SomeVal33</Col3>
      <Col4_With_Space type="xs:string" length="32">SomeVal44</Col4_With_Space>
    </row>
  </data>
</dataset>
</code>```

Important:

The supplied column names are not necessarily valid XML element names. In this example, "Col4 With Space" contains spaces which I have translated to underscores - but there are many other potential pitfalls that may cause a name to be unusable and generate a fatal error.

Title: How to transform this xml using xslt

Body:
I have an XML in the following format:

<?xml version="1.0" encoding="utf-8"?>
<dataset  xmlns="http://developer.cognos.com/schemas/xmldata/1/"  xmlns:xs="http://www.w3.org/2001/XMLSchema-instance">
    <metadata>
          <item name="Col1" type="xs:string" length="14"/>
          <item name="Col2" type="xs:string" length="92"/>
          <item name="Col3" type="xs:string" length="66"/>
          <item name="Col4 With Space" type="xs:string" length="32"/>
    </metadata>
    <data>
        <row>
            <value>SomeVal1</value>
            <value>SomeVal2</value>
            <value>SomeVal3</value>
            <value>SomeVal4</value>
        </row>
        <row>
            <value>SomeVal11</value>
            <value>SomeVal22</value>
            <value>SomeVal33</value>
            <value>SomeVal44</value>
        </row>
    </data>
</dataset>

I want to transform it to this format:

<?xml version="1.0" encoding="utf-8"?>
<dataset>
    <data>
        <row>
            <Col1 type="xs:string" length="14">SomeVal1</Col1>
            <Col2 type="xs:string" length="92">SomeVal2</Col2>
            <Col3 type="xs:string" length="66">SomeVal3</Col3>
            <Col4_With_Space type="xs:string" length="32">SomeVal4</Col4_With_Space>
        </row>
        <row>
            <Col1 type="xs:string" length="14">SomeVal11</Col1>
            <Col2 type="xs:string" length="92">SomeVal22</Col2>
            <Col3 type="xs:string" length="66">SomeVal33</Col3>
            <Col4_With_Space type="xs:string" length="32">SomeVal44</Col4_With_Space>
        </row>
    </data>
</dataset>

I've never used xslt before and I am out of my depth. I tried something like this (which doesn't work) but I'm stuck.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.w3.org/1999/xhtml" version="1.0">
<xsl:output encoding="UTF-8" indent="yes" method="xml" standalone="no" omit-xml-declaration="no"/>
    <xsl:template match="dataset">
        <xsl:for-each select="data/row">
            <Col1 select="1"/>
            <Col2 select="2"/>
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>

The reason for wanting to transform is SSIS "Data Flow" "XML Source" doesn't recognise the first format. I'm trying to import data from an XML into a DB table. "XML Source" works with the 2nd format but not the first.

I think I should add, there is no guarantee XML metadata will always be the same, so transform needs to take the column names and types from the metadata, instead of hard-coding.

Body:
I've never used xslt before and I am out of my depth.

This is certainly not a task suitable for a beginner.

As I mentioned in the comment to your question, your first problem is that your source XML places all its elements in a namespace. You need to declare the same namespace in your stylesheet, assign it a prefix and use that prefix to address the elements in the source XML.

The other issue with your attempt is that you're not actually getting any data from the source XML.

<Col1 select="1"/>

will output the same static element for each row in your XML.

Now, the real complication here is getting the columns names and attributes from the metadata section and pairing them with the corresponding cell value from the current row. This could be accomplished as follows:

XSLT 1.0

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:cog="http://developer.cognos.com/schemas/xmldata/1/"
exclude-result-prefixes="cog">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="/cog:dataset">
    <xsl:variable name="cols" select="cog:metadata/cog:item" />
    <dataset>
        <data>
            <xsl:for-each select="cog:data/cog:row">
                <xsl:variable name="curr-row-cells" select="cog:value" />
                <row>
                    <xsl:for-each select="$cols">
                        <xsl:variable name="i" select="position()" />
                        <xsl:element name="{translate(@name, ' ', '_')}">
                            <xsl:copy-of select="@type | @length"/>
                            <xsl:value-of select="$curr-row-cells[$i]" />
                        </xsl:element>
                    </xsl:for-each>
                </row>
            </xsl:for-each>
        </data>
    </dataset>
</xsl:template>

</xsl:stylesheet>

Result

<?xml version="1.0" encoding="UTF-8"?>
<dataset>
  <data>
    <row>
      <Col1 type="xs:string" length="14">SomeVal1</Col1>
      <Col2 type="xs:string" length="92">SomeVal2</Col2>
      <Col3 type="xs:string" length="66">SomeVal3</Col3>
      <Col4_With_Space type="xs:string" length="32">SomeVal4</Col4_With_Space>
    </row>
    <row>
      <Col1 type="xs:string" length="14">SomeVal11</Col1>
      <Col2 type="xs:string" length="92">SomeVal22</Col2>
      <Col3 type="xs:string" length="66">SomeVal33</Col3>
      <Col4_With_Space type="xs:string" length="32">SomeVal44</Col4_With_Space>
    </row>
  </data>
</dataset>

Important:

The supplied column names are not necessarily valid XML element names. In this example, "Col4 With Space" contains spaces which I have translated to underscores - but there are many other potential pitfalls that may cause a name to be unusable and generate a fatal error.


来源: stackexchange

问:
Extracting date from filename in AWS S3
I have a  file named F1_2017_01_23.txt in Aws S3. From S3 i have to load the data into redshift.

Requirement: S3 is having 10 columns and redshift is having 11 columns (basically 1 column extra). As per the name of the file (mentioned above) i have to extract the date from the file and load into redshift 11th column.

Can you please help me how to extract the file name from S3, so that I can populate the last field in redshift.?

答:
You cannot do this directly with Redshift.

You'll need to either edit the file before loading it into Redshift, or perform an UPDATE operation to modify this field after loading. For example, UPDATE any row where that field is currently empty. This would need to be run as a subsequent command after the COPY command.

There's a vague chance you could use NULLAS to insert a value that is specified with the COPY command.

ContentLicense: CC BY-SA 3.0

Title: Extracting date from filename in AWS S3


问:
Rerendering component to already rendered container doesnt work as expected?
Can you explain it to me why rerendered element doesnt apply change to the element state.status property?Is using ReactDOM.unmountComponentAtNode proper way to do this?I know that the element should not delete itself but this is for presentation.

class CustomModal extends React.Component {

  constructor(props){
    super(props)
    this.state = {

      status:this.props.status

    }
    this.onClick = this.onClick.bind(this);
  }

  render(){
   return
Click Me!

  }

  onClick(){

    console.log('May i log to console?:' + this.state.status)

    this.setState({status:false});

    // this is somewhat cumbersome?
    {/* ReactDOM.unmountComponentAtNode(document.getElementById('container')) */}

    // supposed to rerender the element?
    // And the state.status element should be true?
        ReactDOM.render(<CustomModal status={true} />,document.getElementById('container'))
  }

}

      ReactDOM.render(<CustomModal status={true} />,document.getElementById('container'))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="container">

</div></code>```

答:
The primary API for rendering into the DOM looks like this:

```<code>ReactDOM.render(reactElement, domContainerNode)
</code>```

To update the properties of an existing component, you call render
  again with a new element.

If you are rendering React components within a single-page app, you
  may need to plug into the app's view lifecycle to ensure your app will
  invoke unmountComponentAtNode at the appropriate time. React will not
  automatically clean up a tree. You need to manually call:

```<code>ReactDOM.unmountComponentAtNode(domContainerNode)
</code>```

This is important and often forgotten. Forgetting to call
  unmountComponentAtNode will cause your app to leak memory. There is no
  way for us to automatically detect when it is appropriate to do this
  work. Every system is different.

It is not unique to the DOM. If you want to insert a React Native view
  in the middle of an existing iOS app you will hit similar issues.

Source: https://facebook.github.io/react/blog/2015/10/01/react-render-and-top-level-api.html

Body:
The primary API for rendering into the DOM looks like this:

ReactDOM.render(reactElement, domContainerNode)

To update the properties of an existing component, you call render
  again with a new element.

If you are rendering React components within a single-page app, you
  may need to plug into the app's view lifecycle to ensure your app will
  invoke unmountComponentAtNode at the appropriate time. React will not
  automatically clean up a tree. You need to manually call:

ReactDOM.unmountComponentAtNode(domContainerNode)

This is important and often forgotten. Forgetting to call
  unmountComponentAtNode will cause your app to leak memory. There is no
  way for us to automatically detect when it is appropriate to do this
  work. Every system is different.

It is not unique to the DOM. If you want to insert a React Native view
  in the middle of an existing iOS app you will hit similar issues.

Source: https://facebook.github.io/react/blog/2015/10/01/react-render-and-top-level-api.html


问:
Fluid Floating Elements Wrapped in Container
I have the following test code to play around with:

http://jsfiddle.net/b6QFY/1/

I want the "left" element to be fixed and the "right" element to be fluid within the parent container so that it will grow and shrink as the browser width changes, and not wrap.  Seems so simple, but have issues getting something to work.

答:
you can use display:inline-block;

this article has will help http://www.tjkdesign.com/articles/liquid/3.asp

ContentLicense: CC BY-SA 2.5


问:
How to display post like a forum on wordpress site
When we take any action(Comment/Update) on any forum sites old post that post come on top . Have any way to use this function on WordPress site ? Something like, when anyone comment any post this post come on top or when we update any post that come on top . </p>

答:
If you like to forums and post commenting reply like VBulletin you can use  pluigns

https://wordpress.org/plugins/cm-answers/

for more check the tutorials

http://www.wpbeginner.com/plugins/5-best-forum-plugins-for-wordpress/

Thanks


问:
Merge and broadcast, building a (simple) Akka graph
The Akka documentation is vast and there are a lot of tutorials. But either they are outdated or they only cover the basics (or, maybe I simply can't find the right ones).

What I want to create is a websocket application with multiple clients and multiple sources on the server side. As I don't want to get over my head from the start, I want to make baby steps and incrementally increase the complexity of the software I am building.

After toying around with some simple flows I wanted to start with a more sophisticated graph now.

What I want is:

Two sources, one that pushes "keepAlive" messages from the server to the client (currently only one) and a second one that actually pushes useful data.

Now for the first one I have this:

```<code>val tickingSource: Source[Array[Byte], Cancellable] =
  Source.tick(initialDelay = 1 second, interval = 10 seconds, tick = NotUsed)
        .zipWithIndex
        .map{ case (_, counter) => SomeMessage().toByteArray}
</code>```

Where SomeMessage is a protobuf type.

Because I can't find an up-to-date way to add an actor as a source, I tried the following for my second source:

```<code>val secondSource = Source(1 to 1000)
val secondSourceConverter = Flow[Int].map(x => BigInteger.valueOf(x).toByteArray)
</code>```

My attempt at the graph:

```<code>val g: RunnableGraph[NotUsed] = RunnableGraph.fromGraph(GraphDSL.create()
{
  implicit builder =>
  import GraphDSL.Implicits._

  val sourceMerge = builder.add(Merge[Array[Byte]](2).named("sourceMerge"))

  val x = Source(1 to 1000)

  val y = Flow[Int].map(x => BigInteger.valueOf(x).toByteArray)

  val out = Sink.ignore
  tickingSource ~> sourceMerge ~> out
  x ~> y ~> sourceMerge

  ClosedShape
})
</code>```

Now g is of type RunnableGraph[NotUsed] while it should be RunnableGraph[Array[Byte]] for my websocket. And I wonder here: am I already doing something completely wrong?

答:
You need to pass the secondSourceConverter into the GraphDSL.create, like the following example taken from their docs. Here they import 2 sinks, but it's the same technique.

```<code>RunnableGraph.fromGraph(GraphDSL.create(topHeadSink, bottomHeadSink)((_, _)) { implicit builder =>
  (topHS, bottomHS) =>
  import GraphDSL.Implicits._
  val broadcast = builder.add(Broadcast[Int](2))
  Source.single(1) ~> broadcast.in

  broadcast.out(0) ~> sharedDoubler ~> topHS.in
  broadcast.out(1) ~> sharedDoubler ~> bottomHS.in
  ClosedShape
})
</code>```

Body:
The Akka documentation is vast and there are a lot of tutorials. But either they are outdated or they only cover the basics (or, maybe I simply can't find the right ones).

What I want to create is a websocket application with multiple clients and multiple sources on the server side. As I don't want to get over my head from the start, I want to make baby steps and incrementally increase the complexity of the software I am building.

After toying around with some simple flows I wanted to start with a more sophisticated graph now.

What I want is:

Two sources, one that pushes "keepAlive" messages from the server to the client (currently only one) and a second one that actually pushes useful data.

Now for the first one I have this:

val tickingSource: Source[Array[Byte], Cancellable] =
  Source.tick(initialDelay = 1 second, interval = 10 seconds, tick = NotUsed)
        .zipWithIndex
        .map{ case (_, counter) => SomeMessage().toByteArray}

Where SomeMessage is a protobuf type.

Because I can't find an up-to-date way to add an actor as a source, I tried the following for my second source:

val secondSource = Source(1 to 1000)
val secondSourceConverter = Flow[Int].map(x => BigInteger.valueOf(x).toByteArray)

My attempt at the graph:

val g: RunnableGraph[NotUsed] = RunnableGraph.fromGraph(GraphDSL.create()
{
  implicit builder =>
  import GraphDSL.Implicits._

  val sourceMerge = builder.add(Merge[Array[Byte]](2).named("sourceMerge"))

  val x = Source(1 to 1000)

  val y = Flow[Int].map(x => BigInteger.valueOf(x).toByteArray)

  val out = Sink.ignore
  tickingSource ~> sourceMerge ~> out
  x ~> y ~> sourceMerge

  ClosedShape
})

Now g is of type RunnableGraph[NotUsed] while it should be RunnableGraph[Array[Byte]] for my websocket. And I wonder here: am I already doing something completely wrong?

Body:
You need to pass the secondSourceConverter into the GraphDSL.create, like the following example taken from their docs. Here they import 2 sinks, but it's the same technique.

RunnableGraph.fromGraph(GraphDSL.create(topHeadSink, bottomHeadSink)((_, _)) { implicit builder =>
  (topHS, bottomHS) =>
  import GraphDSL.Implicits._
  val broadcast = builder.add(Broadcast[Int](2))
  Source.single(1) ~> broadcast.in

  broadcast.out(0) ~> sharedDoubler ~> topHS.in
  broadcast.out(1) ~> sharedDoubler ~> bottomHS.in
  ClosedShape
})


问:
jQuery add attribute to span and alert when added
I have html table like below:

```<code><table id="list" style="width:100%">
  <tr>
    <th>Firstname</th>
    <th>Lastname</th>
    <th>Age</th>
  </tr>
  <tr class='thread selected'>
    <td class='subject'>Jill</td>
    <td>Smith</td>
    <td class='flags'>
    <span class='attach'></span>
    <span class='flag'>
    <span class='flag'></span>
    </span>
    </td>
  </tr>
  <tr class='thread'>
    <td class='subject'>Eve</td>
    <td>Jackson</td>
    <td class='flags'>
    <span class='attach'></span>
    <span class='flag'>
    </span>
  </td>
  </tr>
</table>
</code>```

If a user select a row I want to add dynamically title='With flag'in last span like

```<code><span class='flag' title='With flag'></span>
</span>
</code>```

and want to alert('title added'); using if statement.

How can I achive this using jQuery

答:
You can try it:</p>

```<code>$('#list').on("click", '.thread tr', function(){
    $(".flag").attr("title","With flag");
   alert("title added");
});
</code>```

Body:
I have html table like below:

    Firstname
    Lastname
    Age

    Jill
    Smith

    Eve
    Jackson

If a user select a row I want to add dynamically title='With flag'in last span like

and want to alert('title added'); using if statement.

How can I achive this using jQuery

Body:
You can try it:

$('#list').on("click", '.thread tr', function(){
    $(".flag").attr("title","With flag");
   alert("title added");
});


问:
Rails: How to pass value from textfield to a partial
How can I easily pass the value I get from the auto_complete textfield to a partial.

```<code><%= text_field_with_auto_complete :participant, :name, {}, {:url => {:controller => "contentcom/discussions", :action => :get_users_for_auto_complete}, :method => :get, :param_name => 'search'} %>
        <%= button_to_function(:OK) do |page|
                page.insert_html :top, :participants, :partial => 'participant', :locals =>  end %>
</code>```

Bye,

Nico

答:
First of all you need to know that the helpers text_field_with_auto_complete and button_to_function not really handle user actions, but only generate HTML and javascript code. Only generated javascript code can interact with the user. In this case text_field_with_auto_complete generates the following (approximately):

```<code><input type="text" id="participant_name" name="participant[name]" size="15" />
<div id="participant_name_auto_complete" class="auto_complete"> </div>

<script type="text/javascript">
  var participant_auto_completer = new Ajax.Autocompleter (
    'Participant',
    'Name',
    '/contentcom/discussions/get_users_for_auto_complete',
    {method: 'GET', param_name: 'search'}
  );
</script>
</code>```

The above code is that the user gets in his browser.
If you read the documentation for text_field_with_auto_complete, then you will see that we can use the option :after_update_element. This option allows us to specify the name of the JavaScript function that will be called when the user selects one of the proposed values.

What we need to do:

write a JavaScript function that
will display anywhere user-selected
value from autocomplete field.

call text_field_with_auto_complete
with :after_update_element

That's how the template will look like:

```<code><ul id="selected_participant_container"></ul>

<%= text_field_with_auto_complete :participant, :name, {}, {
  :url => {:controller => "contentcom/discussions", :action => :get_users_for_auto_complete},
  :method => :get,
  :param_name => 'search',
  :after_update_element => 'afterParticipantSelected'
}%>

<script type="text/javascript">
  function afterParticipantSelected (el, value) {
    var container = document.getElementById ('selected_participant_container');

    container.innerHTML = value;
  }
</ Script>
</code>```

Now, when a user selects a value in the autocomplete field, it will be displayed in the element with id = selected_participant_container

Of course, you can use methods that are proposed by tokland.

But I would Recommend you first learn the basics of HTML and Javascript.

Body:
How can I easily pass the value I get from the auto_complete textfield to a partial.

<%= text_field_with_auto_complete :participant, :name, {}, {:url => {:controller => "contentcom/discussions", :action => :get_users_for_auto_complete}, :method => :get, :param_name => 'search'} %>
        <%= button_to_function(:OK) do |page|
                page.insert_html :top, :participants, :partial => 'participant', :locals =>  end %>

Bye,

Nico

Body:
First of all you need to know that the helpers text_field_with_auto_complete and button_to_function not really handle user actions, but only generate HTML and javascript code. Only generated javascript code can interact with the user. In this case text_field_with_auto_complete generates the following (approximately):

<input type="text" id="participant_name" name="participant[name]" size="15" />
<div id="participant_name_auto_complete" class="auto_complete"> </div>

<script type="text/javascript">
  var participant_auto_completer = new Ajax.Autocompleter (
    'Participant',
    'Name',
    '/contentcom/discussions/get_users_for_auto_complete',
    {method: 'GET', param_name: 'search'}
  );
</script>

The above code is that the user gets in his browser.
If you read the documentation for text_field_with_auto_complete, then you will see that we can use the option :after_update_element. This option allows us to specify the name of the JavaScript function that will be called when the user selects one of the proposed values.

What we need to do:

write a JavaScript function that
will display anywhere user-selected
value from autocomplete field.

call text_field_with_auto_complete
with :after_update_element

That's how the template will look like:

<ul id="selected_participant_container"></ul>

<%= text_field_with_auto_complete :participant, :name, {}, {
  :url => {:controller => "contentcom/discussions", :action => :get_users_for_auto_complete},
  :method => :get,
  :param_name => 'search',
  :after_update_element => 'afterParticipantSelected'
}%>

<script type="text/javascript">
  function afterParticipantSelected (el, value) {
    var container = document.getElementById ('selected_participant_container');

    container.innerHTML = value;
  }
</ Script>

Now, when a user selects a value in the autocomplete field, it will be displayed in the element with id = selected_participant_container

Of course, you can use methods that are proposed by tokland.

But I would Recommend you first learn the basics of HTML and Javascript.


问:
Confused with Type conversions in golang
I recently tried to learn golang. But I got confused with this code from https://tour.golang.org/basics/13.

```<code>package main

import (
    "fmt"
    "math"
)

func main() {
    var x, y int = 3, 4
    var f float64 = math.Sqrt(float64(x*x + y*y))
    var z uint = uint(f)
    fmt.Println(x, y, z)
}
</code>```

That one works well. Then I tried

var f = math.Sqrt(9 + 16)

which also works. But when I change it to var f = math.Sqrt(x*x + y*y) why is it not working? It says cannot use x * x + y * y (type int) as type float64 in argument to math.Sqrt

I have javascript background, and I somehow can't understand the code above.

答:
But when we pass a number directly, it automatically converted?

No, not really *). Your "direct numbers" are called "constants" in Go and constants are often "untyped" and (almost) of arbitrary precision. There are special rules for constants: A constant 5 and the integer a defined by a := 5 behave differently because 5 is a constant with special rules and not an int.

Constant expressions like 9 + 16 are evaluated at compile time like if you had typed 25. This 25 is still a (constant.

While Go does not have automatic type conversions for types it does have automatic conversions from constants to several types. The constant 25 can be converted to float64 or int, uint8 or even complex128 automatically.

Please read the blog post https://blog.golang.org/constants and the official language spec for a full explanation and all details: https://golang.org/ref/spec#Constants . This explains the strange notion of
"untyped integer" better than I could.

*) "not really" because it is not helpful to think about it that way. The distinction of constants is special in Go: Most other languages tread 3+5 as a sum of two ints resulting in an int while Go sees two untyped integer constants and evaluates this expression into a new arbitrary precision, untyped constant. Only later are constants converted to actual integers.

Body:
I recently tried to learn golang. But I got confused with this code from https://tour.golang.org/basics/13.

package main

import (
    "fmt"
    "math"
)

func main() {
    var x, y int = 3, 4
    var f float64 = math.Sqrt(float64(x*x + y*y))
    var z uint = uint(f)
    fmt.Println(x, y, z)
}

That one works well. Then I tried

var f = math.Sqrt(9 + 16)

which also works. But when I change it to var f = math.Sqrt(x*x + y*y) why is it not working? It says cannot use x * x + y * y (type int) as type float64 in argument to math.Sqrt

I have javascript background, and I somehow can't understand the code above.


问:
Replace content in first set of quotes found in string c#
I am working on a project that involves having to manipulate a bat file based on certain user produced parameters. The bat files themselves are created manually, with a static format. A basic example of a bat file would be:

```<code>cd \some\predefined\bat
start run_some_script "user_generated_argument" [other pre-defined arguments]
</code>```

The "user_generated_argument" bit of the bat file is manipulated in C# by the following code:

```<code>string bat_text = File.ReadAllText(bat_path);
Regex regex = new Regex("(.*?)\".*\"(.*)");
string new_argument = "A new argument";
string new_bat = regex.Replace(bat_text , "$1\"" + new_argument + "\"$2", 1);
</code>```

And that would produce the following:

```<code>cd \some\predefined\bat
start run_some_script "A new argument" [other pre-defined arguments]
</code>```

which is the expected output.

However, the problem lies when one of the other pre-defined arguments after the first quoted argument is also in quotes when that is the case, it seems that the second quoted argument disappears. For example, if the bat file looks like:

```<code>cd \some\predefined\bat
start run_some_script "user_generated_argument" "a_predefined_quoted_argument" [other pre-defined arguments]
</code>```

Running the same C# code from above would produce the following:

```<code>cd \some\predefined\bat
start run_some_script "A new argument" [other pre-defined arguments]
</code>```

The "a_predefined_quoted_argument" would no longer be in the string.

I may be doing this completely wrong. How would I make the predefined quoted argument not disappear?

答:
Instead of using Regex you could also read the lines with File.ReadAllLines(), take the desired line and split it with string.Split() and replace them in that way.

Something like:

```<code>string[] lines = File.ReadAllLines(fileName);
string commandLine = lines.Where(d => d.StartsWith("start")).Single();
string[] arguments = commandLine.Split(' ');

foreach (var argument in arguments)
{
    if (argument.StartsWith("\""))
    {
        // do your stuff and reassemble
    }
}
</code>```

Body:
I am working on a project that involves having to manipulate a bat file based on certain user produced parameters. The bat files themselves are created manually, with a static format. A basic example of a bat file would be:

cd \some\predefined\bat
start run_some_script "user_generated_argument" [other pre-defined arguments]

The "user_generated_argument" bit of the bat file is manipulated in C# by the following code:

string bat_text = File.ReadAllText(bat_path);
Regex regex = new Regex("(.*?)\".*\"(.*)");
string new_argument = "A new argument";
string new_bat = regex.Replace(bat_text , "$1\"" + new_argument + "\"$2", 1);

And that would produce the following:

cd \some\predefined\bat
start run_some_script "A new argument" [other pre-defined arguments]

which is the expected output.

However, the problem lies when one of the other pre-defined arguments after the first quoted argument is also in quotes when that is the case, it seems that the second quoted argument disappears. For example, if the bat file looks like:

cd \some\predefined\bat
start run_some_script "user_generated_argument" "a_predefined_quoted_argument" [other pre-defined arguments]

Running the same C# code from above would produce the following:

cd \some\predefined\bat
start run_some_script "A new argument" [other pre-defined arguments]

The "a_predefined_quoted_argument" would no longer be in the string.

I may be doing this completely wrong. How would I make the predefined quoted argument not disappear?

Body:
Instead of using Regex you could also read the lines with File.ReadAllLines(), take the desired line and split it with string.Split() and replace them in that way.

Something like:

string[] lines = File.ReadAllLines(fileName);
string commandLine = lines.Where(d => d.StartsWith("start")).Single();
string[] arguments = commandLine.Split(' ');

foreach (var argument in arguments)
{
    if (argument.StartsWith("\""))
    {
        // do your stuff and reassemble
    }
}


问:
Compiling/Linking multiple c++ libraries in linux
I have 3 separate libraries with no dependencies, exclusive to themselves, individually compiled using g++ -c and then individually added to separate archives using ar rvs *.o.

I now have 3 separate archives.

I now have another 4th library that depends on all 3 of the previous libraries. How can I compile my 4th library to include the 3 other exclusive libraries, to use all 4(referencing only the 4th library) in a main.cpp program?

I am a g++/linux/makefile COMPLETE BEGINNER.

答:
Is the fourth library a static library or a dynamic library?

The three first libraries are static libraries, they are nothing more than archives of object files. If the fourth library is that, then there's nothing you do with it, just create the archive.

The problem is when linking with the fourth library. Since static libraries are nothing more than archives of object files, you nee to link with all four libraries. You also need to put the libraries correct on the command line for the linker: If library A depends on library B, then A needs to come before B on the linker command line.

On the other hand if the fourth library is a shared library, then it is linked much like an executable program, and when doing that you link with all libraries needed as usual. Then when creating a program using the shared library, you don't need to link with the dependencies.

As for actual command line, the simplest way is to just add the libraries when linking:

```<code>$ g++ main.o -o my_program lib4.a lib3.a lib2.a lib1.a
</code>```

The above command is for linking with static libraries, and after creating an object file of the main.cpp source.

Body:
Is the fourth library a static library or a dynamic library?

The three first libraries are static libraries, they are nothing more than archives of object files. If the fourth library is that, then there's nothing you do with it, just create the archive.

The problem is when linking with the fourth library. Since static libraries are nothing more than archives of object files, you nee to link with all four libraries. You also need to put the libraries correct on the command line for the linker: If library A depends on library B, then A needs to come before B on the linker command line.

On the other hand if the fourth library is a shared library, then it is linked much like an executable program, and when doing that you link with all libraries needed as usual. Then when creating a program using the shared library, you don't need to link with the dependencies.

As for actual command line, the simplest way is to just add the libraries when linking:

$ g++ main.o -o my_program lib4.a lib3.a lib2.a lib1.a

The above command is for linking with static libraries, and after creating an object file of the main.cpp source.


问:
why can we use variable name to get data stored in it?
When using Python, I am confronted with a problem confusing me for a long time. Say, I use numpy to define an array x = np.array([1, 2]).

This, I think, means that x is an instance of class array. Moreover, the tutorial also says that [1,2] is actually stored in x.data. But I get data [1,2] through the instance name x instead of x.data in Python.

How does this happen? There is a link between the instance name x and x.data?

答:
x and x.data are different types though they are interpreting data from the same location in memory

```<code>In [1]: import numpy as np

In [2]: x = np.array([1,2])

In [3]: type(x)
Out[3]: numpy.ndarray

In [4]: type(x.data)
Out[4]: buffer
</code>```

x.data is a pointer to the underlying buffer of bytes that composes the array object in memory, referenced here in the numpy docs.

When we check the underlying datatype (dtype) the array is storing the data as we see the following:

```<code>In [5]: x.dtype
Out[5]: dtype('int64')
</code>```

An int64 is composed of 64 bits or 8 bytes (8 bits in a byte). This means the underlying buffer of x, x.data should be a buffer of length 16. We confirm that here:

```<code>In [6]: len(x.data)
Out[6]: 16
</code>```

Lastly, we can peek into the actual values of the buffer to see how Python is storing the values in memory:

```<code>In [7]: for i in range(len(x.data)): print ord(x.data[i])
1
0
0
0
0
0
0
0
# first 8 bytes above, second 8 below
2
0
0
0
0
0
0
0
</code>```

We use ord to return the value of the byte since numpy is storing the value as an 8 bit (1 byte) string.

Since, each of these bytes only stores 8 bits of information, none of the above values printed by the loop will never exceed 255, the maximum value of a byte.

The link between x and x.data is that x.data points to the location in memory of the values you see when you inspect x. numpy uses the ndarray type as an abstraction on top of this lower level storage in memory to make it easy to deal with arrays at a high level, like getting the value of x at index one:

```<code>In [8]: x[1]
Out[8]: 2
</code>```

instead of needing to implement the correct offsetting and binary to integer conversion yourself.

Body:
x and x.data are different types though they are interpreting data from the same location in memory

In [1]: import numpy as np

In [2]: x = np.array([1,2])

In [3]: type(x)
Out[3]: numpy.ndarray

In [4]: type(x.data)
Out[4]: buffer

x.data is a pointer to the underlying buffer of bytes that composes the array object in memory, referenced here in the numpy docs.

When we check the underlying datatype (dtype) the array is storing the data as we see the following:

In [5]: x.dtype
Out[5]: dtype('int64')

An int64 is composed of 64 bits or 8 bytes (8 bits in a byte). This means the underlying buffer of x, x.data should be a buffer of length 16. We confirm that here:

In [6]: len(x.data)
Out[6]: 16

Lastly, we can peek into the actual values of the buffer to see how Python is storing the values in memory:

In [7]: for i in range(len(x.data)): print ord(x.data[i])
1
0
0
0
0
0
0
0
# first 8 bytes above, second 8 below
2
0
0
0
0
0
0
0

We use ord to return the value of the byte since numpy is storing the value as an 8 bit (1 byte) string.

Since, each of these bytes only stores 8 bits of information, none of the above values printed by the loop will never exceed 255, the maximum value of a byte.

The link between x and x.data is that x.data points to the location in memory of the values you see when you inspect x. numpy uses the ndarray type as an abstraction on top of this lower level storage in memory to make it easy to deal with arrays at a high level, like getting the value of x at index one:

In [8]: x[1]
Out[8]: 2

instead of needing to implement the correct offsetting and binary to integer conversion yourself.


问:
How to automatically handle DialogBoxShowing event in Python(Revit Dynamo)?
How do I subscribe to Revit events in Python (Dynamo)?

Specifically DialogBoxShowing so I can see if it is "Export with Temporary Hide/Isolate" warning and select "Leave the Temporary Isolate Mode on and Export"?

It is done in C# here:

http://thebuildingcoder.typepad.com/blog/2013/03/export-wall-parts-individually-to-dxf.html

See sub-heading: Handling and Dismissing a Warning Message

Thanks!

答:
To answer your first question. Try to read this tutorial from Pierre Moureu : https://github.com/PMoureu/samples-Python-RPS/tree/master/Tutorial-IUpdater.
He his subscribing to a IUpdater.</p>


问:
JSON parsing swift 3
```<code>if statusCode == 200 {
    let json = response.result.value as? NSDictionary
    print("JSON FILE")
    //print(json)
    let companies = json?["companies"] as? [AnyObject]
    print(companies)
    for value in companies! {
        let address = value["address"] as? String
        print(address)
        let schedule = companies?["schedule"] as? [AnyObject]// as? NSDictionary
        print(schedule)
            for sch in schedule! {
        }
    }
}
</code>```

Here json file

```<code>  {
      "code": "200",
      "message": "OK",
      "companies": [
        {
          "id": "1",
          "img": "doxsun.jpg",
          "schedule": [
            {
              "id": "1",
              "company_id": "1",
              "day": "0",
              "time_from": "06:00:00",
              "time_to": "23:00:00"
            }
          ]
        },
        {
          "id": "2",
          "img": "zalypa.jpg",
          "schedule": []
        }
      ]
 }
</code>```

I have a problem with json file parsing how correctly parse it? I can't parse schedule. How to convert all this types?               words to pass quality. words to pass quality.words to pass quality.words to pass quality.words to pass quality.words to pass quality.words to pass quality.words to pass quality.words to pass quality.words to pass quality.

答:
```<code>    Alamofire.request(url, method: .get, headers: nil).responseJSON{response in

        switch response.result{

        case.success:

            print("sucess")

            if let JSON = response.result.value
            {

                self.hk = JSON as! NSDictionary

                print(self.hk)

                print(((self.hk.value(forKey: "contacts")as! NSArray).object(at: 4        )as! NSDictionary).value(forKey: "name")as! NSString)

                self.flag = 1
                self.tbl1.reloadData()

            }
        case.failure(let Error):

            print("error\(Error)")

        }

    }

}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if flag == 0
    {
        return 0
    }
    else
    {
        return (self.hk.value(forKey: "contacts")as! NSArray).count

    }
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tbl1.dequeueReusableCell(withIdentifier: "cell", for: indexPath)as! TableViewCell1

    cell.lbl1.text = (((self.hk.value(forKey: "contacts")as! NSArray).object(at: indexPath.row)as! NSDictionary).value(forKey: "name")as!String)

    return cell

}
</code>```

Title: JSON parsing swift 3

Body:
if statusCode == 200 {
    let json = response.result.value as? NSDictionary
    print("JSON FILE")
    //print(json)
    let companies = json?["companies"] as? [AnyObject]
    print(companies)
    for value in companies! {
        let address = value["address"] as? String
        print(address)
        let schedule = companies?["schedule"] as? [AnyObject]// as? NSDictionary
        print(schedule)
            for sch in schedule! {
        }
    }
}

Here json file

  {
      "code": "200",
      "message": "OK",
      "companies": [
        {
          "id": "1",
          "img": "doxsun.jpg",
          "schedule": [
            {
              "id": "1",
              "company_id": "1",
              "day": "0",
              "time_from": "06:00:00",
              "time_to": "23:00:00"
            }
          ]
        },
        {
          "id": "2",
          "img": "zalypa.jpg",
          "schedule": []
        }
      ]
 }

I have a problem with json file parsing how correctly parse it? I can't parse schedule. How to convert all this types?               words to pass quality. words to pass quality.words to pass quality.words to pass quality.words to pass quality.words to pass quality.words to pass quality.words to pass quality.words to pass quality.words to pass quality.


问:
GridControl display values in new line
I have a  class wherein I am storing all the values of FileALine and FileBLine properties into a list called Changes
The code for the properties is as shown below.

```<code>public class Result
{
    public Result()
    {
        this.Changes = new List<Difference>();
    }

    public IList<Difference> Changes { get; set; }
}

public class Differences
{
    public int LineNumber { get; set; }

    public string FileALine { get; set; }

    public string FileBLine { get; set; }
}
</code>```

I am calling the Changes list from a form to populate a Synfusion GridControl. It has two Columns DataRow and Details. Right now I am only able to fill in either FileAline values or FileBLine values into the second column.

I am unable to figure out how to display both FileAline values on one line and FileBLine values in the next line as shown in the image below.

```<code>public partial class Form: Form
{
    private void DisplayValues(Result result)
    {
        if (result != null && result.Changes.Count > 0)
        {
            var differences = result.Changes;
            this.detailsGridControl.RowCount = differences.Count;
            this.detailsGridControl.ColCount = 2;

            for (var i = 0; i < differences.Count; i++)
            {
                var detailsA = differences[i];
                var row = i + 1;
                this.detailsGridControl[row, (int)FormColumns.DataRow].Text = detailsA.LineNumber.ToString();
                this.detailsGridControl[row, (int)FormColumns.Details].Text = detailsA.FileALine;
                this.detailsGridControl[row, (int)FormColumns.Details].Text = detailsA.FileBLine;
            }
        }
    }
}
</code>```

So the output must be something like this.

Any suggestions on how to achieve this?

Thanks in advance!

答:
Actually figured out the solution.</p>

```<code>for (var i = 0; i < differences.Count; i++)
{
     var detailsA = differences[i];
     var row = i + 1;
     this.detailsGridControl[row, (int)FormColumns.DataRow].Text = detailsA.LineNumber.ToString();
     this.detailsGridControl[row, (int)FormColumns.Details].Text = detailsA.FileALine + Environment.NewLine + detailsA.FileBLine;
}
</code>```

Title: GridControl display values in new line

Body:
I have a  class wherein I am storing all the values of FileALine and FileBLine properties into a list called Changes
The code for the properties is as shown below.

public class Result
{
    public Result()
    {
        this.Changes = new List<Difference>();
    }

    public IList<Difference> Changes { get; set; }
}

public class Differences
{
    public int LineNumber { get; set; }

    public string FileALine { get; set; }

    public string FileBLine { get; set; }
}

I am calling the Changes list from a form to populate a Synfusion GridControl. It has two Columns DataRow and Details. Right now I am only able to fill in either FileAline values or FileBLine values into the second column.

I am unable to figure out how to display both FileAline values on one line and FileBLine values in the next line as shown in the image below.

public partial class Form: Form
{
    private void DisplayValues(Result result)
    {
        if (result != null && result.Changes.Count > 0)
        {
            var differences = result.Changes;
            this.detailsGridControl.RowCount = differences.Count;
            this.detailsGridControl.ColCount = 2;

            for (var i = 0; i < differences.Count; i++)
            {
                var detailsA = differences[i];
                var row = i + 1;
                this.detailsGridControl[row, (int)FormColumns.DataRow].Text = detailsA.LineNumber.ToString();
                this.detailsGridControl[row, (int)FormColumns.Details].Text = detailsA.FileALine;
                this.detailsGridControl[row, (int)FormColumns.Details].Text = detailsA.FileBLine;
            }
        }
    }
}

So the output must be something like this.

Any suggestions on how to achieve this?

Thanks in advance!

Body:
Actually figured out the solution.

for (var i = 0; i < differences.Count; i++)
{
     var detailsA = differences[i];
     var row = i + 1;
     this.detailsGridControl[row, (int)FormColumns.DataRow].Text = detailsA.LineNumber.ToString();
     this.detailsGridControl[row, (int)FormColumns.Details].Text = detailsA.FileALine + Environment.NewLine + detailsA.FileBLine;
}


问:
extracting the word from the string ignoring symbols and numbers
I want to extract the word from a string but it should ignore all the symbols and numbers in between if any.

```<code>string = C#%3HA#*$03IR
</code>```

I want to extract the word CHAIR from the above string. Ignore all symbols and numbers.

答:
Strings in C# are like arrays, so you can loop through all the characters of a string and check if they are letters or not using:

```<code>Regex reg = new Regex("^[a-zA-Z]+$");
</code>```

and accordingly you can keep or remove them from array(string).

Body:
I want to extract the word from a string but it should ignore all the symbols and numbers in between if any.

string = C#%3HA#*$03IR

I want to extract the word CHAIR from the above string. Ignore all symbols and numbers.

Body:
Strings in C# are like arrays, so you can loop through all the characters of a string and check if they are letters or not using:

Regex reg = new Regex("^[a-zA-Z]+$");

and accordingly you can keep or remove them from array(string).


答:
A string is a collection of char so by using linq's Where you can query all those that are char.IsLetter:

```<code>string str = "C#%3HA#*$03IR";
string result = new string(str.Where(c => char.IsLetter(c)).ToArray());
</code>```

You can do it this way too:

```<code>string result = String.Concat(str.Where(c => char.IsLetter(c)));
</code>```

Title: extracting the word from the string ignoring symbols and numbers

Body:
A string is a collection of char so by using linq's Where you can query all those that are char.IsLetter:

string str = "C#%3HA#*$03IR";
string result = new string(str.Where(c => char.IsLetter(c)).ToArray());

You can do it this way too:

string result = String.Concat(str.Where(c => char.IsLetter(c)));


问:
Silent installation of SQL Server service pack not working with parameters
iam installing service pack on SQL Server through silent installation.
code is working without parameters but with parameters ts not working

code without parameters

```<code>param([string]$servername)
param([string]$instance)

$path1="D:\sysdba\SQLServer2008R2SP2-KB2630458-x64-ENU.exe"

Try
{

$SqlQuery = "SELECT * from dbo.BlockingInfoOutput;"
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection

$SqlConnection.ConnectionString = "Server = $Servername; Database = master; Integrated Security = SSPI;"
write-host $SqlConnection.ConnectionString
$command=$path1

write-host $servername
write-host $instance

$arg1="/instancename=" + $instance
$arg2= "/quiet"
$arg3= "/IACCEPTSQLSERVERLICENSETERMS=TRUE"

write-host $arg1
write-host $instance
# D:\sysdba\SQLServer2008R2SP2-KB2630458-x64-ENU.exe  /instancename=SQLINST /quiet  /IACCEPTSQLSERVERLICENSETERMS=”TRUE” | Out-File d:\sysdba\test.txt

write-host $path1 $arg1 $arg2 $arg3

          Write-Host "Success."

}

Catch
</code>```

{
    Write-Host -BackgroundColor Red -ForegroundColor White "Fail"

```<code>    $errText =  $Error[0].ToString()

        if ($errText.Contains("network-related"))

    {Write-Host "Connection Error. Check server name, port, firewall."}

    Write-Host $errText

    continue
</code>```

}

code with parameters

```<code>& $path1 $arg1 $arg2 $arg3
</code>```

this is i am using as concatenation but not working?

any help please

答:
I didn't test the command with your exe and parametrs. But try this:</p>

```<code>Start-Process -FilePath $PathToExe-ArgumentList "/quiet" -Wait
</code>```

Body:
iam installing service pack on SQL Server through silent installation.
code is working without parameters but with parameters ts not working

code without parameters

param([string]$servername)
param([string]$instance)

$path1="D:\sysdba\SQLServer2008R2SP2-KB2630458-x64-ENU.exe"

Try
{

$SqlQuery = "SELECT * from dbo.BlockingInfoOutput;"
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection

$SqlConnection.ConnectionString = "Server = $Servername; Database = master; Integrated Security = SSPI;"
write-host $SqlConnection.ConnectionString
$command=$path1

write-host $servername
write-host $instance

$arg1="/instancename=" + $instance
$arg2= "/quiet"
$arg3= "/IACCEPTSQLSERVERLICENSETERMS=TRUE"

write-host $arg1
write-host $instance
# D:\sysdba\SQLServer2008R2SP2-KB2630458-x64-ENU.exe  /instancename=SQLINST /quiet  /IACCEPTSQLSERVERLICENSETERMS=”TRUE” | Out-File d:\sysdba\test.txt

write-host $path1 $arg1 $arg2 $arg3

          Write-Host "Success."

}

Catch

{
    Write-Host -BackgroundColor Red -ForegroundColor White "Fail"

    $errText =  $Error[0].ToString()

        if ($errText.Contains("network-related"))

    {Write-Host "Connection Error. Check server name, port, firewall."}

    Write-Host $errText

    continue

}

code with parameters

& $path1 $arg1 $arg2 $arg3

this is i am using as concatenation but not working?

any help please

Body:
I didn't test the command with your exe and parametrs. But try this:

Start-Process -FilePath $PathToExe-ArgumentList "/quiet" -Wait


问:
Javascript lossless image compression
I am looking for a way to encoding a bmp image as a tiff or some other standard, compressed but lossless format in a browser (javascript). I guess if worst comes to worst I can write a library myself (getting the data from a canvas element) but I was hoping either: there's a better way to do it or someone else has already written something similar (I can't find a library).

I have users wanting to upload ~ 4mb (8-bit monochrome) bmp files, which I can losslessly compress to ~700kb tiff files with LZW (or even better ~300kb lossless JPEG-2000). I'd like to do this before the files are uploaded to save transfer costs/time.

Before you ask, I'm not being anal about the lossless encoding instead of just using high bitrate JPEG. These are astronomy photos that are used for analysis so they can't handle any compression artifacts being introduced.

Thanks,
Jonny

答:
If you are willing to experiment something new, you could try a new lossless compression algorithm I created; through a Java applet it is possible to visualize the compressed images in a browser. You could use Javascript to trigger the loading of the applet, or manipulate directly the Java code (the program is open source). For many images, the compression ratio will be better than lossless Jpeg 2000. The address of the website is http://www.researchandtechnology.net/bcif/ .

If instead you want to use some well-known standard, then I'd agree with amphetamachine: using PNG would be the best choice.

So long,
Stefano

Title: Javascript lossless image compression


问:
Can you use the GPU QR factorization algorithm from cuSOLVER in tensorflow?
I can see it's referenced in https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/kernels/cuda_solvers.h (Geqrf), but the tensorflow QR op at https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/kernels/qr_op_float.cc isn't registered for GPU usage. Can I somehow make my own op using Geqrf, or is there maybe another way?</p>

答:
This line in the source code you linked gives a hint about the current situation.

TODO(rmlarsen, volunteers): Implement the kernels below.


问:
How can I use tensorboard with tf.estimator.Estimator
I am considering to move my code base to tf.estimator.Estimator, but I cannot find an example on how to use it in combination with tensorboard summaries.

MWE:

```<code>import numpy as np
import tensorflow as tf

tf.logging.set_verbosity(tf.logging.INFO)

# Declare list of features, we only have one real-valued feature
def model(features, labels, mode):
    # Build a linear model and predict values
    W = tf.get_variable("W", [1], dtype=tf.float64)
    b = tf.get_variable("b", [1], dtype=tf.float64)
    y = W*features['x'] + b
    loss = tf.reduce_sum(tf.square(y - labels))

    # Summaries to display for TRAINING and TESTING
    tf.summary.scalar("loss", loss)
    tf.summary.image("X", tf.reshape(tf.random_normal([10, 10]), [-1, 10, 10, 1])) # dummy, my inputs are images

    # Training sub-graph
    global_step = tf.train.get_global_step()
    optimizer = tf.train.GradientDescentOptimizer(0.01)
    train = tf.group(optimizer.minimize(loss), tf.assign_add(global_step, 1))

    return tf.estimator.EstimatorSpec(mode=mode, predictions=y,loss= loss,train_op=train)

estimator = tf.estimator.Estimator(model_fn=model, model_dir='/tmp/tf')
# define our data set
x=np.array([1., 2., 3., 4.])
y=np.array([0., -1., -2., -3.])
input_fn = tf.contrib.learn.io.numpy_input_fn({"x": x}, y, 4, num_epochs=1000)

for epoch in range(10):
    # train
    estimator.train(input_fn=input_fn, steps=100)
    # evaluate our model
    estimator.evaluate(input_fn=input_fn, steps=10)
</code>```

How can I display my two summaries in tensorboard? Do I have to register a hook in which I use a tf.summary.FileWriter or something else?

答:
EDIT:
Upon testing (in v1.1.0, and probably in later versions as well), it is apparent that tf.estimator.Estimator will automatically write summaries for you. I confirmed this using OP's code and tensorboard.

(Some poking around r1.4 leads me to conclude that this automatic summary writing occurs due to tf.train.MonitoredTrainingSession.)

Ultimately, the automatic summarizing is accomplished with the use of hooks, so if you wanted to customize the Estimator's default summarizing, you could do so using hooks. Below are the (edited) details from the original answer.

You'll want to use hooks, formerly known as monitors. (Linked is a conceptual/quickstart guide; the short of it is that the notion of hooking into / monitoring training is built into the Estimator API. A bit confusingly, though, it doesn't seem like the deprecation of monitors for hooks is really documented except in a deprecation annotation in the actual source code...)

Based on your usage, it looks like r1.2's SummarySaverHook fits your bill.

```<code>summary_hook = tf.train.SummarySaverHook(
    SAVE_EVERY_N_STEPS,
    output_dir='/tmp/tf',
    summary_op=tf.summary.merge_all())
</code>```

You may want to customize the hook's initialization parameters, as by providing an explicity SummaryWriter or writing every N seconds instead of N steps.

If you pass this into the EstimatorSpec, you'll get your customized Summary behavior:

return tf.estimator.EstimatorSpec(mode=mode, predictions=y,loss=loss,
                                  train_op=train,
                                  training_hooks=[summary_hook])
```

EDIT NOTE:
A previous version of this answer suggested passing the summary_hook into estimator.train(input_fn=input_fn, steps=5, hooks=[summary_hook]). This does not work because tf.summary.merge_all() has to be called in the same context as your model graph.

Body:
I am considering to move my code base to tf.estimator.Estimator, but I cannot find an example on how to use it in combination with tensorboard summaries.

MWE:

import numpy as np
import tensorflow as tf

tf.logging.set_verbosity(tf.logging.INFO)

# Declare list of features, we only have one real-valued feature
def model(features, labels, mode):
    # Build a linear model and predict values
    W = tf.get_variable("W", [1], dtype=tf.float64)
    b = tf.get_variable("b", [1], dtype=tf.float64)
    y = W*features['x'] + b
    loss = tf.reduce_sum(tf.square(y - labels))

    # Summaries to display for TRAINING and TESTING
    tf.summary.scalar("loss", loss)
    tf.summary.image("X", tf.reshape(tf.random_normal([10, 10]), [-1, 10, 10, 1])) # dummy, my inputs are images

    # Training sub-graph
    global_step = tf.train.get_global_step()
    optimizer = tf.train.GradientDescentOptimizer(0.01)
    train = tf.group(optimizer.minimize(loss), tf.assign_add(global_step, 1))

    return tf.estimator.EstimatorSpec(mode=mode, predictions=y,loss= loss,train_op=train)

estimator = tf.estimator.Estimator(model_fn=model, model_dir='/tmp/tf')
# define our data set
x=np.array([1., 2., 3., 4.])
y=np.array([0., -1., -2., -3.])
input_fn = tf.contrib.learn.io.numpy_input_fn({"x": x}, y, 4, num_epochs=1000)

for epoch in range(10):
    # train
    estimator.train(input_fn=input_fn, steps=100)
    # evaluate our model
    estimator.evaluate(input_fn=input_fn, steps=10)

How can I display my two summaries in tensorboard? Do I have to register a hook in which I use a tf.summary.FileWriter or something else?

Body:
EDIT:
Upon testing (in v1.1.0, and probably in later versions as well), it is apparent that tf.estimator.Estimator will automatically write summaries for you. I confirmed this using OP's code and tensorboard.

(Some poking around r1.4 leads me to conclude that this automatic summary writing occurs due to tf.train.MonitoredTrainingSession.)

Ultimately, the automatic summarizing is accomplished with the use of hooks, so if you wanted to customize the Estimator's default summarizing, you could do so using hooks. Below are the (edited) details from the original answer.

You'll want to use hooks, formerly known as monitors. (Linked is a conceptual/quickstart guide; the short of it is that the notion of hooking into / monitoring training is built into the Estimator API. A bit confusingly, though, it doesn't seem like the deprecation of monitors for hooks is really documented except in a deprecation annotation in the actual source code...)

Based on your usage, it looks like r1.2's SummarySaverHook fits your bill.

summary_hook = tf.train.SummarySaverHook(
    SAVE_EVERY_N_STEPS,
    output_dir='/tmp/tf',
    summary_op=tf.summary.merge_all())

You may want to customize the hook's initialization parameters, as by providing an explicity SummaryWriter or writing every N seconds instead of N steps.

If you pass this into the EstimatorSpec, you'll get your customized Summary behavior:

return tf.estimator.EstimatorSpec(mode=mode, predictions=y,loss=loss,
                                  train_op=train,
                                  training_hooks=[summary_hook])

EDIT NOTE:
A previous version of this answer suggested passing the summary_hook into estimator.train(input_fn=input_fn, steps=5, hooks=[summary_hook]). This does not work because tf.summary.merge_all() has to be called in the same context as your model graph.


答:
Try

```<code>$(".thread").click(function() {
    $(".flag").attr("title","With flag");
    alert("title added");
});
</code>```

Hope this helps

Title: jQuery add attribute to span and alert when added

Body:
I have html table like below:

    Firstname
    Lastname
    Age

    Jill
    Smith

    Eve
    Jackson

If a user select a row I want to add dynamically title='With flag'in last span like

and want to alert('title added'); using if statement.

How can I achive this using jQuery

Body:
Try

$(".thread").click(function() {
    $(".flag").attr("title","With flag");
    alert("title added");
});

Hope this helps


问:
Showing two of the four choices as the same country
```<code>Partial Class Default2
    Inherits System.Web.UI.Page

    Private Sub form1_Load(sender As Object, e As EventArgs) Handles form1.Load

        Dim Flagimageurl(6) As String ' creating the flag image url array'
        Flagimageurl(0) = "https://www.cia.gov/library/publications/the-world-factbook/graphics/flags/large/uk-lgflag.gif"
        Flagimageurl(1) = "https://upload.wikimedia.org/wikipedia/en/thumb/c/c3/Flag_of_France.svg/800px-Flag_of_France.svg.png"
        Flagimageurl(2) = "https://upload.wikimedia.org/wikipedia/en/thumb/0/05/Flag_of_Brazil.svg/720px-Flag_of_Brazil.svg.png"
        Flagimageurl(3) = "https://upload.wikimedia.org/wikipedia/en/thumb/9/9a/Flag_of_Spain.svg/750px-Flag_of_Spain.svg.png"
        Flagimageurl(4) = "https://upload.wikimedia.org/wikipedia/en/thumb/a/a4/Flag_of_the_United_States.svg/1235px-Flag_of_the_United_States.svg.png"
        Flagimageurl(5) = "https://upload.wikimedia.org/wikipedia/commons/thumb/a/a2/Flag_of_Russia_%28Kremlin.ru%29.svg/1024px-Flag_of_Russia_%28Kremlin.ru%29.svg.png"

        Dim CountryNames(6) As String 'creating the country names array'
        CountryNames(0) = "United Kingdom"
        CountryNames(1) = "France"
        CountryNames(2) = "Brazil"
        CountryNames(3) = "Spain"
        CountryNames(4) = "United States of America (USA)"
        CountryNames(5) = "Russia"

        flag.ImageUrl = Flagimageurl(6 * Rnd()) 'Choosing a random flag'
        RadioButton1.Text = CountryNames(5 * Rnd()) 'Randomly picks the country according to the CountryNames array'
        RadioButton2.Text = CountryNames(5 * Rnd())  ' with random * 6 you get blanks so you need to use random * 5'
        RadioButton3.Text = CountryNames(5 * Rnd())
        RadioButton4.Text = CountryNames(5 * Rnd())

        If RadioButton1.Text = RadioButton2.Text Then 'Makes sure that the radiobuttons don't show duplicate answers'
            RadioButton2.Text = CountryNames(5 * Rnd())
        End If

        If RadioButton2.Text = RadioButton1.Text Then
            RadioButton1.Text = CountryNames(5 * Rnd())
        End If

        If RadioButton3.Text = RadioButton1.Text Or RadioButton3.Text = RadioButton2.Text Then
            RadioButton3.Text = CountryNames(5 * Rnd())
        End If

        If RadioButton4.Text = RadioButton1.Text Or RadioButton2.Text = RadioButton3.Text Then
            RadioButton4.Text = CountryNames(5 * Rnd())
        End If

    End Sub
End Class
</code>```

The problem is that when I run the code two of the four answers are the same. Or the other thing that it does is it does not always have the correct answer for that flag.

How can I fix this issue?

答:
One way of doing it is to replace all your If statements with the 3 loops below - not the best way of doing it, but for the purposes of your program, it won't impact performance much.

The code checks that buttons 2,3 and 4 are not the same as any other. You dont need to check button 1 because the loops will check that all of the subsequent buttons aren't the same as it.

Each loop will choose a new random text string from your array. If it is the same as any of the other buttons, it will choose another one until it is different to all of them.

```<code>    Do While RadioButton2.Text = RadioButton1.Text Or RadioButton2.Text = RadioButton3.Text Or RadioButton2.Text = RadioButton4.Text  'Makes sure that the radiobuttons don't show duplicate answers'
        RadioButton1.Text = CountryNames(5 * Rnd())
    Loop
    Do While RadioButton3.Text = RadioButton2.Text Or RadioButton3.Text = RadioButton1.Text Or RadioButton3.Text = RadioButton4.Text  'Makes sure that the radiobuttons don't show duplicate answers'
        RadioButton1.Text = CountryNames(5 * Rnd())
    Loop
    Do While RadioButton4.Text = RadioButton2.Text Or RadioButton4.Text = RadioButton3.Text Or RadioButton4.Text = RadioButton1.Text  'Makes sure that the radiobuttons don't show duplicate answers'
        RadioButton1.Text = CountryNames(5 * Rnd())
    Loop
</code>```

However, your choice of using Rnd() will be very unlikely to generate the number 5. You would be better changing the above code to this

```<code>    Dim randomNumber As New Random

    flag.ImageUrl = Flagimageurl(randomNumber.Next(0, 5)) 'Choosing a random flag'
    RadioButton1.Text = CountryNames(randomNumber.Next(0, 5)) 'Randomly picks the country according to the CountryNames array'
    RadioButton2.Text = CountryNames(randomNumber.Next(0, 5))
    RadioButton3.Text = CountryNames(randomNumber.Next(0, 5))
    RadioButton4.Text = CountryNames(randomNumber.Next(0, 5))

    Do While RadioButton2.Text = RadioButton1.Text Or RadioButton2.Text = RadioButton3.Text Or RadioButton2.Text = RadioButton4.Text  'Makes sure that the radiobuttons don't show duplicate answers'
        RadioButton1.Text = CountryNames(randomNumber.Next(0, 5))
    Loop
    Do While RadioButton3.Text = RadioButton2.Text Or RadioButton3.Text = RadioButton1.Text Or RadioButton3.Text = RadioButton4.Text  'Makes sure that the radiobuttons don't show duplicate answers'
        RadioButton1.Text = CountryNames(randomNumber.Next(0, 5))
    Loop
    Do While RadioButton4.Text = RadioButton2.Text Or RadioButton4.Text = RadioButton3.Text Or RadioButton4.Text = RadioButton1.Text  'Makes sure that the radiobuttons don't show duplicate answers'
        RadioButton1.Text = CountryNames(randomNumber.Next(0, 5))
    Loop
</code>```

This code will be equally likely to generate all of the numbers.

Body:
Partial Class Default2
    Inherits System.Web.UI.Page

    Private Sub form1_Load(sender As Object, e As EventArgs) Handles form1.Load

        Dim Flagimageurl(6) As String ' creating the flag image url array'
        Flagimageurl(0) = "https://www.cia.gov/library/publications/the-world-factbook/graphics/flags/large/uk-lgflag.gif"
        Flagimageurl(1) = "https://upload.wikimedia.org/wikipedia/en/thumb/c/c3/Flag_of_France.svg/800px-Flag_of_France.svg.png"
        Flagimageurl(2) = "https://upload.wikimedia.org/wikipedia/en/thumb/0/05/Flag_of_Brazil.svg/720px-Flag_of_Brazil.svg.png"
        Flagimageurl(3) = "https://upload.wikimedia.org/wikipedia/en/thumb/9/9a/Flag_of_Spain.svg/750px-Flag_of_Spain.svg.png"
        Flagimageurl(4) = "https://upload.wikimedia.org/wikipedia/en/thumb/a/a4/Flag_of_the_United_States.svg/1235px-Flag_of_the_United_States.svg.png"
        Flagimageurl(5) = "https://upload.wikimedia.org/wikipedia/commons/thumb/a/a2/Flag_of_Russia_%28Kremlin.ru%29.svg/1024px-Flag_of_Russia_%28Kremlin.ru%29.svg.png"

        Dim CountryNames(6) As String 'creating the country names array'
        CountryNames(0) = "United Kingdom"
        CountryNames(1) = "France"
        CountryNames(2) = "Brazil"
        CountryNames(3) = "Spain"
        CountryNames(4) = "United States of America (USA)"
        CountryNames(5) = "Russia"

        flag.ImageUrl = Flagimageurl(6 * Rnd()) 'Choosing a random flag'
        RadioButton1.Text = CountryNames(5 * Rnd()) 'Randomly picks the country according to the CountryNames array'
        RadioButton2.Text = CountryNames(5 * Rnd())  ' with random * 6 you get blanks so you need to use random * 5'
        RadioButton3.Text = CountryNames(5 * Rnd())
        RadioButton4.Text = CountryNames(5 * Rnd())

        If RadioButton1.Text = RadioButton2.Text Then 'Makes sure that the radiobuttons don't show duplicate answers'
            RadioButton2.Text = CountryNames(5 * Rnd())
        End If

        If RadioButton2.Text = RadioButton1.Text Then
            RadioButton1.Text = CountryNames(5 * Rnd())
        End If

        If RadioButton3.Text = RadioButton1.Text Or RadioButton3.Text = RadioButton2.Text Then
            RadioButton3.Text = CountryNames(5 * Rnd())
        End If

        If RadioButton4.Text = RadioButton1.Text Or RadioButton2.Text = RadioButton3.Text Then
            RadioButton4.Text = CountryNames(5 * Rnd())
        End If

    End Sub
End Class

The problem is that when I run the code two of the four answers are the same. Or the other thing that it does is it does not always have the correct answer for that flag.

How can I fix this issue?

Body:
One way of doing it is to replace all your If statements with the 3 loops below - not the best way of doing it, but for the purposes of your program, it won't impact performance much.

The code checks that buttons 2,3 and 4 are not the same as any other. You dont need to check button 1 because the loops will check that all of the subsequent buttons aren't the same as it.

Each loop will choose a new random text string from your array. If it is the same as any of the other buttons, it will choose another one until it is different to all of them.

    Do While RadioButton2.Text = RadioButton1.Text Or RadioButton2.Text = RadioButton3.Text Or RadioButton2.Text = RadioButton4.Text  'Makes sure that the radiobuttons don't show duplicate answers'
        RadioButton1.Text = CountryNames(5 * Rnd())
    Loop
    Do While RadioButton3.Text = RadioButton2.Text Or RadioButton3.Text = RadioButton1.Text Or RadioButton3.Text = RadioButton4.Text  'Makes sure that the radiobuttons don't show duplicate answers'
        RadioButton1.Text = CountryNames(5 * Rnd())
    Loop
    Do While RadioButton4.Text = RadioButton2.Text Or RadioButton4.Text = RadioButton3.Text Or RadioButton4.Text = RadioButton1.Text  'Makes sure that the radiobuttons don't show duplicate answers'
        RadioButton1.Text = CountryNames(5 * Rnd())
    Loop

However, your choice of using Rnd() will be very unlikely to generate the number 5. You would be better changing the above code to this

    Dim randomNumber As New Random

    flag.ImageUrl = Flagimageurl(randomNumber.Next(0, 5)) 'Choosing a random flag'
    RadioButton1.Text = CountryNames(randomNumber.Next(0, 5)) 'Randomly picks the country according to the CountryNames array'
    RadioButton2.Text = CountryNames(randomNumber.Next(0, 5))
    RadioButton3.Text = CountryNames(randomNumber.Next(0, 5))
    RadioButton4.Text = CountryNames(randomNumber.Next(0, 5))

    Do While RadioButton2.Text = RadioButton1.Text Or RadioButton2.Text = RadioButton3.Text Or RadioButton2.Text = RadioButton4.Text  'Makes sure that the radiobuttons don't show duplicate answers'
        RadioButton1.Text = CountryNames(randomNumber.Next(0, 5))
    Loop
    Do While RadioButton3.Text = RadioButton2.Text Or RadioButton3.Text = RadioButton1.Text Or RadioButton3.Text = RadioButton4.Text  'Makes sure that the radiobuttons don't show duplicate answers'
        RadioButton1.Text = CountryNames(randomNumber.Next(0, 5))
    Loop
    Do While RadioButton4.Text = RadioButton2.Text Or RadioButton4.Text = RadioButton3.Text Or RadioButton4.Text = RadioButton1.Text  'Makes sure that the radiobuttons don't show duplicate answers'
        RadioButton1.Text = CountryNames(randomNumber.Next(0, 5))
    Loop

This code will be equally likely to generate all of the numbers.


答:
You can simply make it using Regex class available inside System.Text.RegularExpressions namespace.

```<code>using System;
using System.Text.RegularExpressions;

namespace RemoveSpecialCharactersConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string line = "C#%3HA#*$03IR";
            line = RemoveSpecialCharacters(line);
            Console.WriteLine(line);
            Console.Read();
        }

        public static string RemoveSpecialCharacters(string input)
        {
            Regex r = new Regex("(?:[^a-z]|(?<=['\"])s)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled);
            return r.Replace(input, string.Empty);
        }
    }
}
</code>```

Output

Body:
You can simply make it using Regex class available inside System.Text.RegularExpressions namespace.

using System;
using System.Text.RegularExpressions;

namespace RemoveSpecialCharactersConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string line = "C#%3HA#*$03IR";
            line = RemoveSpecialCharacters(line);
            Console.WriteLine(line);
            Console.Read();
        }

        public static string RemoveSpecialCharacters(string input)
        {
            Regex r = new Regex("(?:[^a-z]|(?<=['\"])s)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled);
            return r.Replace(input, string.Empty);
        }
    }
}

Output


答:
```<code>Regex rgx = new Regex("[^a-zA-Z -]");
str = rgx.Replace(str, "");
</code>```


问:
What does `BNE #+-20` ARM instruction do?
I came across the following instruction when looking at output from a disassembler, running on an OS binary:

```<code>BNE #+-20
</code>```

I know what the BNE instruction does, but I have not been able to find any reference to +-.

When Z is non-zero, where will the program counter jump?

Or maybe my disassembler is buggy?

答:
I must admit that I've never seen the notation #+ before; disassemblers I used replaced the argument of relative jump instructions by the destination address.

However I think that #+X means: The address of this instruction (or the following one - depending on the architecture) plus X bytes (or words).

So #+-20 means: "The destination address is the address of this instruction minus 20 bytes". (*)

(*) You have to find out if -20 is relative to the address of the BNE instruction itself or to the address of the next instruction and you have to find out if -20 is the number of bytes or the number of 16- or 32-bit words.

Body:
I came across the following instruction when looking at output from a disassembler, running on an OS binary:

BNE #+-20

I know what the BNE instruction does, but I have not been able to find any reference to +-.

When Z is non-zero, where will the program counter jump?

Or maybe my disassembler is buggy?


问:
Function Not Working In My Program
My compiler says "too few arguments in the function". I can not figure out what is wrong. Does anyone have any idea on what I am doing wrong?</p>

```<code>#include<stdio.h>
#include<math.h>
int show(int a, int b, int c);

main( ){
int a, b = 10, c = 24;
printf("Enter a number\n");
scanf("%d\n", &a);
show(int a, int b, int c);
system("pause");
}

int show(int a, int b, int c){
if(a>c){
    printf("a is the largest number\n");
} else if(a>b){
    printf("a is smaller than c\n");
} else if(a<b){
    printf("a is bigger than b\n");
} else{
    printf("a is the smallest number \n");
}
return;
}
</code>```

答: You defined your function as: int show(int a, int b, int c) but called it with improper arguments: show(int a, int b, int c). What you should have done is call it with show(a,  b,  c) as a,b,c are already declared and defined

Title: Function Not Working In My Program

Body:
My compiler says "too few arguments in the function". I can not figure out what is wrong. Does anyone have any idea on what I am doing wrong?

#include<stdio.h>
#include<math.h>
int show(int a, int b, int c);

main( ){
int a, b = 10, c = 24;
printf("Enter a number\n");
scanf("%d\n", &a);
show(int a, int b, int c);
system("pause");
}

int show(int a, int b, int c){
if(a>c){
    printf("a is the largest number\n");
} else if(a>b){
    printf("a is smaller than c\n");
} else if(a<b){
    printf("a is bigger than b\n");
} else{
    printf("a is the smallest number \n");
}
return;
}


问:
UTC time not getting converted to local for bootgrid?
i have a table to display the timestamp inside bootgrid. This timestamp is created using NOW() and is in UTC.I want to display this to local time while displaying inside bootgrid.The table head is as shown below.

```<code><th data-column-id="ts" data-header-align="center" data-align="center" data-order="desc" data-converter="datetime">Upload Date</th>
</code>```

I have written a converter for datetime to convert to local time using momnet

```<code>converters: {
        datetime: {
            from: function (value) { return moment(value); },
            to: function (value) { return moment(value).local().format("lll"); }
        }
    }
</code>```

But the problem is that it is still displaying in UTC and not in local time.How to fix this?

答:
```<code>var now = new Date();
var now_utc = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(),  now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
</code>```

Body:
i have a table to display the timestamp inside bootgrid. This timestamp is created using NOW() and is in UTC.I want to display this to local time while displaying inside bootgrid.The table head is as shown below.

Upload Date

I have written a converter for datetime to convert to local time using momnet

converters: {
        datetime: {
            from: function (value) { return moment(value); },
            to: function (value) { return moment(value).local().format("lll"); }
        }
    }

But the problem is that it is still displaying in UTC and not in local time.How to fix this?


问:
Selenium: Automate Vertical Scrolling in Java
I need to automate scrolling down using the scroll bar. This is what the scroll bar looks like.
This is the html code of the scroll bar:

```<code><div class="z-biglistbox-wscroll-vertical">
    <div class="z-biglistbox-wscroll-drag" style="top: 132.253px;">
        <div class="z-biglistbox-wscroll-home" title="Home"></div>
        <div class="z-biglistbox-wscroll-up" title="Previous"></div>
        <div class="z-biglistbox-wscroll-down" title="Next"></div>
        <div class="z-biglistbox-wscroll-end" title="End"></div>
    </div>
</div>
</code>```

I think of maybe clicking the "Next" button of the scroll bar but my code's not working. I did something like the following:

```<code>((JavascriptExecutor)driver).executeScript("arguments[0].click();", scroll_down);
</code>```

.

```<code>WebElement scroll_down = driver.findElement(By.cssSelector(".z-biglistbox-wscroll-down"));
scroll_down.click();
</code>```

Neither of the two worked. Can anyone give me an idea how to do it?

UPDATE:
This problem was already solved. Refer to alecxe's answer in this link for the solution that worked for me.

答:
```<code>WebElement element = driver.findElement(By.className("z-biglistbox-wscroll-down"));
element.click();
</code>```

You can use this but it will click only once in the scroll down element.

Body:
I need to automate scrolling down using the scroll bar. This is what the scroll bar looks like.
This is the html code of the scroll bar:

I think of maybe clicking the "Next" button of the scroll bar but my code's not working. I did something like the following:

((JavascriptExecutor)driver).executeScript("arguments[0].click();", scroll_down);

.

WebElement scroll_down = driver.findElement(By.cssSelector(".z-biglistbox-wscroll-down"));
scroll_down.click();

Neither of the two worked. Can anyone give me an idea how to do it?

UPDATE:
This problem was already solved. Refer to alecxe's answer in this link for the solution that worked for me.

Body:
WebElement element = driver.findElement(By.className("z-biglistbox-wscroll-down"));
element.click();

You can use this but it will click only once in the scroll down element.


问:
How to force chrome and Firefox to resize in bluestack
I installed Bluestack on my PC and I also success resized the inner window of the Bluestack which makes all apps resized to a normal android phone. But the issue is the Chrome and Firefox browsers refuse to be resized, they display in a tablet form.

Please do anyone know how I can fix this?

答:
If you are using Bluestacks 2 you have a single button on left hand side, press that after you have opened an app to toggle the orientation.

for Bluestacks 3  you have to goto Settings > Manage applications  here you can select in between tablet or default


问:
Learning C# prior to learning ASP.NET MVC?
With only mild programming experience in the past, I was wondering about C# and ASP.NET MVC..

Do you guys think it's a better idea to learn C# before learning ASP.NET MVC?  I've already delved a little into both of these already, but I still need some help deciding.

I think I would be a much stronger MVC user if I had more knowledge of the C# language itself.

What do you guys think?

Thanks!

答: Knowing C# before jumping into anything .NET related is very recommended if not required. MVC is only a way of making webpages with the tools of ASP.NET which uses C# and VB as its backend languages. MVC is actually called ASP.NET MVC. Think of C# as the equivalent to PHP or Ruby in "Ruby on Rails". </p>


问:
SSRS returned data type not valid for the aggregate function
I am making a SSRS, when executing the query

```<code>SELECT Brand.[KeyOffer],
   COALESCE(SUM([Key Offer].Revenue),0) as Revenue
FROM [Brand Key Offer] Brand
LEFT JOIN [Key Offer] ON Brand.Keyoffer = [Key Offer].[Key Offer] AND [Key Offer].[Date] = '7/05/2017'
WHERE Brand.[Brand] = 'SMART'
GROUP BY [Brand].[KeyOffer]
ORDER BY [Revenue] DESC
</code>```

But when I preview the reprot, I get this warning message.

```<code>Warning     [rsAggregateOfInvalidExpressionDataType] The Value expression for the textrun ‘Textbox21.Paragraphs[0].TextRuns[0]’ uses an aggregate function with an expression that returned a data type not valid for the aggregate function.       c:\users\t-aordiz\documents\visual studio 2015\Projects\TelemarketingRS\TelemarketingRS\Telemarketing Revenue.rdl   0
</code>```

Ive been to a lot of topics but cant seem to find a way to solve this problem.

答:
You can use conversion in your expression to the appopriate type like below

```<code>= CDec(Fields!Revenue.value)
</code>```

Also try the following SQL alternatives

```<code>COALESCE(SUM([Key Offer].Revenue),0.00)
</code>```

or

```<code>CAST(COALESCE(SUM([Key Offer].Revenue),0) AS DECIMAL(10, 2))
</code>```

(it's a little different from what Tim suggested)

Body:
I am making a SSRS, when executing the query

SELECT Brand.[KeyOffer],
   COALESCE(SUM([Key Offer].Revenue),0) as Revenue
FROM [Brand Key Offer] Brand
LEFT JOIN [Key Offer] ON Brand.Keyoffer = [Key Offer].[Key Offer] AND [Key Offer].[Date] = '7/05/2017'
WHERE Brand.[Brand] = 'SMART'
GROUP BY [Brand].[KeyOffer]
ORDER BY [Revenue] DESC

But when I preview the reprot, I get this warning message.

Warning     [rsAggregateOfInvalidExpressionDataType] The Value expression for the textrun ‘Textbox21.Paragraphs[0].TextRuns[0]’ uses an aggregate function with an expression that returned a data type not valid for the aggregate function.       c:\users\t-aordiz\documents\visual studio 2015\Projects\TelemarketingRS\TelemarketingRS\Telemarketing Revenue.rdl   0

Ive been to a lot of topics but cant seem to find a way to solve this problem.

Body:
You can use conversion in your expression to the appopriate type like below

= CDec(Fields!Revenue.value)

Also try the following SQL alternatives

COALESCE(SUM([Key Offer].Revenue),0.00)

or

CAST(COALESCE(SUM([Key Offer].Revenue),0) AS DECIMAL(10, 2))

(it's a little different from what Tim suggested)


问:
Applescript rename file in current folder
I want to change a filename in the folder which is not always the same, it depends on where the applescript is stored (same folder as the file to change).

I made this script with a dialog to check the path, that works fine but after but I get an error (-1700, Can't change "test" into an integer. Why, and how do I fix this?

```<code>tell application "Finder"
    set thePath to POSIX path of ((path to me as string) & "::")
    display dialog thePath buttons {"Clipboard", "OK"} default button 2
    if the button returned of the result is "Clipboard" then
        set the clipboard to thePath
    end if
    set name of document file "test" of thePath to "test_OLD"
end tell
</code>```

答:
Could this be an easier way syntax wise?</p>

```<code> tell application "System Events"
        set name of file "/Users/Firebird/Documents/test2.jpg" to "/Users/Firebird/Documents/11.jpg"
    end tell
</code>```

Body:
I want to change a filename in the folder which is not always the same, it depends on where the applescript is stored (same folder as the file to change).

I made this script with a dialog to check the path, that works fine but after but I get an error (-1700, Can't change "test" into an integer. Why, and how do I fix this?

tell application "Finder"
    set thePath to POSIX path of ((path to me as string) & "::")
    display dialog thePath buttons {"Clipboard", "OK"} default button 2
    if the button returned of the result is "Clipboard" then
        set the clipboard to thePath
    end if
    set name of document file "test" of thePath to "test_OLD"
end tell

Body:
Could this be an easier way syntax wise?

 tell application "System Events"
        set name of file "/Users/Firebird/Documents/test2.jpg" to "/Users/Firebird/Documents/11.jpg"
    end tell


答:
You have declared variables in a function call. It is not valid in C.

So, Use this:

```<code>show(a, b, c);
</code>```

instead of

```<code>show(int a, int b, int c);
</code>```

Title: Function Not Working In My Program

Body:
You have declared variables in a function call. It is not valid in C.

So, Use this:

show(a, b, c);

instead of

show(int a, int b, int c);


问:
Jenkins - Publish HTML report to custom URL
One of my jobs in Jenkins generates an html report and uses the HTML Publisher Plugin to link to it from respective build. In such case, if I want to get to this HTML page directly (assume no security enabled so no log in required), I need to follow a link that has the following form:

http://hostname:port/job/Some%20Job%20Name/buildNumber/Functional_Test_Report/

And for each subsequent build, the URL is going to change based on buildNumber. I would like to have a "pretty" URL that will just display the last report all the time. Say something like this:

http://hostname:port/testReport

The actual report HTML will then be automatically pushed into this location every time the build is finished and will eliminate the need of going through Jenkins each time to see the report.

Is there a way to accomplish this?

Body:
You should be able to expose the BUILD_NUMBER via environment variables and from there generate the URL where the HTML report will be. How you wanna do it is up to you but you could make it so the Jenkins job either deploys a file that has the build number hard coded in an index.html file with a <script> that redirects to the URL pattern you posted above. It really depends on how you have your hostname:port set up. Since you only need the latest report, you can simply make it so the latest job always overwrites the old file.

We do something similar although we just expose the build number to a PHP, JSP, etc file so QA knows what build they are looking at. We then have a fixed URL they can always go to (hostname:port/status). We could make it redirect if we really wanted though.


问:
SQL transaction log shipping after differential backup
I'm facing a scenario:

Full backup of production database is created

Full backup is restored to DR database

A differential backup of production database is created, BUT accidentally deleted

Start transaction log backup on production database

The question is, will the first generated transaction log would be able to be restored into DR database, or the deleted differential database backup must be restored to DR database first?

答:
The short answer is no, you need a/the differential backup or a new full backup. So either take a new full backup to restart the backup chain, or a new differential backup to replace the lost/deleted one.

Simplified, a Transaction Log backup will maintain a chronological list of changes made to your database since the last backup (Any backup; either full, differential or another transaction log backup). A differential backup will save a list of all extents that changed since the last Full Backup (so including whatever any transaction log backup already backed up in the mean time). This also means that if you create a full backup, followed by a differential backup, followed by a differential backup, the second differential backup contains everything the first one contains.

A typical scenario is where a full backup is taken, followed by a few transaction log backups. The next step then is a differential backup, and probably more transaction log backups and differential backups until a new full backup is created.

This ensures the time to recovery is reduced by ensuring that in case of disaster, you can take a backup of the tail of the transaction log. You can then restore the full backup, followed by the latest differential backup, followed by any transaction log backups (in chronological order).


问:
decrypting pdf protected by aes-256bit using the right password
Is there any way to decrypting a pdf protected by an aes-256 bit key?

I have the correct password and I need a command-line tool (or library - perhaps in python :P ) for decrypting the file and then doing some operation over it.

The best thing could be if the file could be saved decrypted, then I elaborate it and then I can remove it...

Does anyone know something about it?

答:
```<code>import pyPdf
pdf = pyPdf.PdfFileReader(open("file.pdf"))
pdf.decrypt("password")
</code>```

You can then do whatever you want with the contents.  This will work with either the user or owner passwords.

OwnerDisplayName: GIANCARLO

Body:
import pyPdf
pdf = pyPdf.PdfFileReader(open("file.pdf"))
pdf.decrypt("password")

You can then do whatever you want with the contents.  This will work with either the user or owner passwords.

OwnerDisplayName: Tony Meyer


问:
Django populate choice from ForeignKey
In the following code I am trying to have the Owner form with a drop-down menu that has car brands from the Car model as choices. I do get the drop-down menu but the elements listed as "Car object" each, instead of the brands. How do I get the brands from the Car model into the menu? Thanks.

models.py

```<code>from django.db import models

class Car(models.Model):
    brand = models.CharField(max_length=20)

class Owner(models.Model):
    name = models.CharField(max_length=20)
    car_brand = models.ForeignKey(Car)
</code>```

forms.py

```<code>from django.forms import ModelForm, ModelChoiceField
from app.models import Owner

class OwnerForm(ModelForm):
    car_brand = ModelChoiceField(queryset=Car.objects.all())

class Meta():
    model = Owner
</code>```

答:
Thanks so much for sharing this, it helped me! In Django 1.8, try:
brand = models.ForeignKey(Car)

Dont put car_ in front of the foreign key

Title: Django populate choice from ForeignKey

Body:
In the following code I am trying to have the Owner form with a drop-down menu that has car brands from the Car model as choices. I do get the drop-down menu but the elements listed as "Car object" each, instead of the brands. How do I get the brands from the Car model into the menu? Thanks.

models.py

from django.db import models

class Car(models.Model):
    brand = models.CharField(max_length=20)

class Owner(models.Model):
    name = models.CharField(max_length=20)
    car_brand = models.ForeignKey(Car)

forms.py

from django.forms import ModelForm, ModelChoiceField
from app.models import Owner

class OwnerForm(ModelForm):
    car_brand = ModelChoiceField(queryset=Car.objects.all())

class Meta():
    model = Owner


问:
How to allow only numbers (even when copy-pasted) in input text field using jQuery?
I am using this jQuery code to allow only numbers to be entered in input text field.

```<code>jQuery(document).ready(function() {
    jQuery( '.only_numbers' ).keydown(function (e) {
        // Allow: backspace, delete, tab, escape, enter and .
        if (jQuery.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
             // Allow: Ctrl+A, Command+A
            ((e.keyCode === 65) && (e.ctrlKey === true || e.metaKey === true)) ||
             // Allow: home, end, left, right, down, up
            (e.keyCode >= 35 && e.keyCode <= 40)) {
                 // let it happen, don't do anything
                 return;
        }
        // Ensure that it is a number and stop the keypress
        if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
            e.preventDefault();
        }
    });
});
</code>```

This works fine, except one small problem. It does not allow anything to be pasted in the field. How can I allow user to paste a string in the field, only if the string contains all numeric characters?

Also, it will be awesome if I could do the same for input text fields allowing only alphabets.

答:
Restrict other keys using keyboard event</p>

```<code>//numbers, delete, backspace, arrows
var validKeyCodes = [8, 9, 37, 38, 39, 40, 46, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57];
        $("Selectors").on("keydown", function (e) {
            if (!($.inarray(e.keycode, validkeycodes) >= 0))
                e.preventDefault();
        });
</code>```

Body:
I am using this jQuery code to allow only numbers to be entered in input text field.

jQuery(document).ready(function() {
    jQuery( '.only_numbers' ).keydown(function (e) {
        // Allow: backspace, delete, tab, escape, enter and .
        if (jQuery.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
             // Allow: Ctrl+A, Command+A
            ((e.keyCode === 65) && (e.ctrlKey === true || e.metaKey === true)) ||
             // Allow: home, end, left, right, down, up
            (e.keyCode >= 35 && e.keyCode <= 40)) {
                 // let it happen, don't do anything
                 return;
        }
        // Ensure that it is a number and stop the keypress
        if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
            e.preventDefault();
        }
    });
});

This works fine, except one small problem. It does not allow anything to be pasted in the field. How can I allow user to paste a string in the field, only if the string contains all numeric characters?

Also, it will be awesome if I could do the same for input text fields allowing only alphabets.

Body:
Restrict other keys using keyboard event

//numbers, delete, backspace, arrows
var validKeyCodes = [8, 9, 37, 38, 39, 40, 46, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57];
        $("Selectors").on("keydown", function (e) {
            if (!($.inarray(e.keycode, validkeycodes) >= 0))
                e.preventDefault();
        });