问:
Create a json array
I'm writing a code where in there has to be a main array generated in json. my code is as below.

My pojos

JsonCreator.java

```<code>package com.createjson;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({ "EntityLabels", "ExampleText", "SelectedIntentName" })
public class Jsoncreator {

    @JsonProperty("EntityLabels")
    private List<EntityLabel> entityLabels = null;
    @JsonProperty("ExampleText")
    private String exampleText;
    @JsonProperty("SelectedIntentName")
    private String selectedIntentName;
    @JsonIgnore
    private Map<String, Object> additionalProperties = new HashMap<String, Object>();

    @JsonProperty("EntityLabels")
    public List<EntityLabel> getEntityLabels() {
        return entityLabels;
    }

    @JsonProperty("EntityLabels")
    public void setEntityLabels(List<EntityLabel> entityLabels) {
        this.entityLabels = entityLabels;
    }

    @JsonProperty("ExampleText")
    public String getExampleText() {
        return exampleText;
    }

    @JsonProperty("ExampleText")
    public void setExampleText(String exampleText) {
        this.exampleText = exampleText;
    }

    @JsonProperty("SelectedIntentName")
    public String getSelectedIntentName() {
        return selectedIntentName;
    }

    @JsonProperty("SelectedIntentName")
    public void setSelectedIntentName(String selectedIntentName) {
        this.selectedIntentName = selectedIntentName;
    }

    @JsonAnyGetter
    public Map<String, Object> getAdditionalProperties() {
        return this.additionalProperties;
    }

    @JsonAnySetter
    public void setAdditionalProperty(String name, Object value) {
        this.additionalProperties.put(name, value);
    }

}
</code>```

EntityLabel.java

```<code>package com.createjson;

import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({ "StartToken", "EntityType", "EndToken" })
public class EntityLabel {

    @JsonProperty("StartToken")
    private int startToken;
    @JsonProperty("EntityType")
    private String entityType;
    @JsonProperty("EndToken")
    private int endToken;
    @JsonIgnore
    private Map<String, Object> additionalProperties = new HashMap<String, Object>();

    @JsonProperty("StartToken")
    public int getStartToken() {
        return startToken;
    }

    @JsonProperty("StartToken")
    public void setStartToken(int startToken) {
        this.startToken = startToken;
    }

    @JsonProperty("EntityType")
    public String getEntityType() {
        return entityType;
    }

    @JsonProperty("EntityType")
    public void setEntityType(String entityType) {
        this.entityType = entityType;
    }

    @JsonProperty("EndToken")
    public int getEndToken() {
        return endToken;
    }

    @JsonProperty("EndToken")
    public void setEndToken(int endToken) {
        this.endToken = endToken;
    }

    @JsonAnyGetter
    public Map<String, Object> getAdditionalProperties() {
        return this.additionalProperties;
    }

    @JsonAnySetter
    public void setAdditionalProperty(String name, Object value) {
        this.additionalProperties.put(name, value);
    }

}
</code>```

Main Class

```<code>import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.config.ConfigDetails;
import com.createjson.EntityLabel;
import com.createjson.Jsoncreator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class dummy {

    public static void main(String[] args) throws JsonProcessingException {
        Jsoncreator jsoncreator = null;
        EntityLabel label;
        List<EntityLabel> entityLabelList;
        ObjectMapper objectMapper;
        List<String> matchList;
        String[] lines = { "What is (Jim)'s gift (limit)? <=> Personname <=> Amount::Spent",
                "What is (John)'s gift (limit)? <=> Personname <=> Amount::Spent" };
        // check if the text has entities
        for (String line : lines) {
            entityLabelList = new ArrayList<EntityLabel>();

            if (line.contains("<=>")) {
                String[] example_split = line.split("<=>", 2);
                // System.out.println("String is " + example_split[1]);
                if (example_split[0].length() > 1) {
                    String[] example_entity = example_split[1].split("<=>");
                    int entities_count = 0;
                    int startPosition;
                    int endPosition = 0;
                    matchList = new ArrayList<>();
                    Pattern regex = Pattern.compile("\\((.*?)\\)");
                    Matcher regexMatcher = regex.matcher(line);
                    jsoncreator = new Jsoncreator();
                    while (regexMatcher.find()) {
                        startPosition = regexMatcher.start() + 1;
                        endPosition = regexMatcher.end() - 1;

                        matchList.add(regexMatcher.group(1));
                        label = new EntityLabel();

                        label.setStartToken(startPosition);
                        label.setEntityType(example_entity[entities_count].toString());
                        label.setEndToken(endPosition);
                        entityLabelList.add(label);

                        objectMapper = new ObjectMapper();
                        TestCasesString = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(label);
                        jsoncreator.setEntityLabels(entityLabelList);

                        entities_count++;
                    }

                }
            }
            objectMapper = new ObjectMapper();
            System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsoncreator));

        }

    }
}
</code>```

when I run this program, there are two objects created, but I want a songle object created.

My Current O/P

```<code>{
  "EntityLabels" : [ {
    "StartToken" : 9,
    "EntityType" : " Personname ",
    "EndToken" : 12
  }, {
    "StartToken" : 22,
    "EntityType" : " Amount::Spent",
    "EndToken" : 27
  } ]
}
{
  "EntityLabels" : [ {
    "StartToken" : 9,
    "EntityType" : " Personname ",
    "EndToken" : 13
  }, {
    "StartToken" : 23,
    "EntityType" : " Amount::Spent",
    "EndToken" : 28
  } ]
}
</code>```

My Expected O/P

```<code>[{
  "EntityLabels" : [ {
    "StartToken" : 9,
    "EntityType" : " Personname ",
    "EndToken" : 12
  }, {
    "StartToken" : 22,
    "EntityType" : " Amount::Spent",
    "EndToken" : 27
  } ]
},
{
  "EntityLabels" : [ {
    "StartToken" : 9,
    "EntityType" : " Personname ",
    "EndToken" : 13
  }, {
    "StartToken" : 23,
    "EntityType" : " Amount::Spent",
    "EndToken" : 28
  } ]
}]
</code>```

please let me know how can I do this.

Thanks

答:
If you want an array you need to serialise a list, the same way you are already doing with entityLabels. Every jsoncreator object is going to create a json representation for that instance, just need to save them in a list and serialise it.

Something like:

```<code>public class dummy {

  public static void main(String[] args) throws JsonProcessingException {
      List<Jsoncreator> objectsToSerialise = new ArrayList<>();

      ... your code

    // check if the text has entities
    for (String line : lines) {

      ... your code

      objectsToSerialise.add(jsonCreator);
    }

    objectMapper = new ObjectMapper();
    System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(objectsToSerialise));

  }
}
</code>```

Hope you get the idea.

Jackson – Unmarshall to Collection/Array

Title: Create a json array

Body:
I'm writing a code where in there has to be a main array generated in json. my code is as below.

My pojos

JsonCreator.java

package com.createjson;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({ "EntityLabels", "ExampleText", "SelectedIntentName" })
public class Jsoncreator {

    @JsonProperty("EntityLabels")
    private List<EntityLabel> entityLabels = null;
    @JsonProperty("ExampleText")
    private String exampleText;
    @JsonProperty("SelectedIntentName")
    private String selectedIntentName;
    @JsonIgnore
    private Map<String, Object> additionalProperties = new HashMap<String, Object>();

    @JsonProperty("EntityLabels")
    public List<EntityLabel> getEntityLabels() {
        return entityLabels;
    }

    @JsonProperty("EntityLabels")
    public void setEntityLabels(List<EntityLabel> entityLabels) {
        this.entityLabels = entityLabels;
    }

    @JsonProperty("ExampleText")
    public String getExampleText() {
        return exampleText;
    }

    @JsonProperty("ExampleText")
    public void setExampleText(String exampleText) {
        this.exampleText = exampleText;
    }

    @JsonProperty("SelectedIntentName")
    public String getSelectedIntentName() {
        return selectedIntentName;
    }

    @JsonProperty("SelectedIntentName")
    public void setSelectedIntentName(String selectedIntentName) {
        this.selectedIntentName = selectedIntentName;
    }

    @JsonAnyGetter
    public Map<String, Object> getAdditionalProperties() {
        return this.additionalProperties;
    }

    @JsonAnySetter
    public void setAdditionalProperty(String name, Object value) {
        this.additionalProperties.put(name, value);
    }

}

EntityLabel.java

package com.createjson;

import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({ "StartToken", "EntityType", "EndToken" })
public class EntityLabel {

    @JsonProperty("StartToken")
    private int startToken;
    @JsonProperty("EntityType")
    private String entityType;
    @JsonProperty("EndToken")
    private int endToken;
    @JsonIgnore
    private Map<String, Object> additionalProperties = new HashMap<String, Object>();

    @JsonProperty("StartToken")
    public int getStartToken() {
        return startToken;
    }

    @JsonProperty("StartToken")
    public void setStartToken(int startToken) {
        this.startToken = startToken;
    }

    @JsonProperty("EntityType")
    public String getEntityType() {
        return entityType;
    }

    @JsonProperty("EntityType")
    public void setEntityType(String entityType) {
        this.entityType = entityType;
    }

    @JsonProperty("EndToken")
    public int getEndToken() {
        return endToken;
    }

    @JsonProperty("EndToken")
    public void setEndToken(int endToken) {
        this.endToken = endToken;
    }

    @JsonAnyGetter
    public Map<String, Object> getAdditionalProperties() {
        return this.additionalProperties;
    }

    @JsonAnySetter
    public void setAdditionalProperty(String name, Object value) {
        this.additionalProperties.put(name, value);
    }

}

Main Class

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.config.ConfigDetails;
import com.createjson.EntityLabel;
import com.createjson.Jsoncreator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class dummy {

    public static void main(String[] args) throws JsonProcessingException {
        Jsoncreator jsoncreator = null;
        EntityLabel label;
        List<EntityLabel> entityLabelList;
        ObjectMapper objectMapper;
        List<String> matchList;
        String[] lines = { "What is (Jim)'s gift (limit)? <=> Personname <=> Amount::Spent",
                "What is (John)'s gift (limit)? <=> Personname <=> Amount::Spent" };
        // check if the text has entities
        for (String line : lines) {
            entityLabelList = new ArrayList<EntityLabel>();

            if (line.contains("<=>")) {
                String[] example_split = line.split("<=>", 2);
                // System.out.println("String is " + example_split[1]);
                if (example_split[0].length() > 1) {
                    String[] example_entity = example_split[1].split("<=>");
                    int entities_count = 0;
                    int startPosition;
                    int endPosition = 0;
                    matchList = new ArrayList<>();
                    Pattern regex = Pattern.compile("\\((.*?)\\)");
                    Matcher regexMatcher = regex.matcher(line);
                    jsoncreator = new Jsoncreator();
                    while (regexMatcher.find()) {
                        startPosition = regexMatcher.start() + 1;
                        endPosition = regexMatcher.end() - 1;

                        matchList.add(regexMatcher.group(1));
                        label = new EntityLabel();

                        label.setStartToken(startPosition);
                        label.setEntityType(example_entity[entities_count].toString());
                        label.setEndToken(endPosition);
                        entityLabelList.add(label);

                        objectMapper = new ObjectMapper();
                        TestCasesString = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(label);
                        jsoncreator.setEntityLabels(entityLabelList);

                        entities_count++;
                    }

                }
            }
            objectMapper = new ObjectMapper();
            System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsoncreator));

        }

    }
}

when I run this program, there are two objects created, but I want a songle object created.

My Current O/P

{
  "EntityLabels" : [ {
    "StartToken" : 9,
    "EntityType" : " Personname ",
    "EndToken" : 12
  }, {
    "StartToken" : 22,
    "EntityType" : " Amount::Spent",
    "EndToken" : 27
  } ]
}
{
  "EntityLabels" : [ {
    "StartToken" : 9,
    "EntityType" : " Personname ",
    "EndToken" : 13
  }, {
    "StartToken" : 23,
    "EntityType" : " Amount::Spent",
    "EndToken" : 28
  } ]
}

My Expected O/P

[{
  "EntityLabels" : [ {
    "StartToken" : 9,
    "EntityType" : " Personname ",
    "EndToken" : 12
  }, {
    "StartToken" : 22,
    "EntityType" : " Amount::Spent",
    "EndToken" : 27
  } ]
},
{
  "EntityLabels" : [ {
    "StartToken" : 9,
    "EntityType" : " Personname ",
    "EndToken" : 13
  }, {
    "StartToken" : 23,
    "EntityType" : " Amount::Spent",
    "EndToken" : 28
  } ]
}]

please let me know how can I do this.

Thanks

Body:
If you want an array you need to serialise a list, the same way you are already doing with entityLabels. Every jsoncreator object is going to create a json representation for that instance, just need to save them in a list and serialise it.

Something like:

public class dummy {

  public static void main(String[] args) throws JsonProcessingException {
      List<Jsoncreator> objectsToSerialise = new ArrayList<>();

      ... your code

    // check if the text has entities
    for (String line : lines) {

      ... your code

      objectsToSerialise.add(jsonCreator);
    }

    objectMapper = new ObjectMapper();
    System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(objectsToSerialise));

  }
}

Hope you get the idea.

Jackson – Unmarshall to Collection/Array


来源: stackexchange

问:
razor - how to dynamicaly insert id into div element
In my view I have:

```<code>@foreach (var comment in Model.commentList)
{
    var id = comment.CommentId;
    <div id="@(id)" style="height:100px; width: 100px; background-color: red; display:none;"></div>
    <a id=@id onClick="ShowForm(this.id)" href="#">Comment</a>
}
</code>```

And then I have a script:

```<code>function ShowForm(clicked_id) {
    var element = "#" + clicked_id;
    $(element).fadeIn(1000);
}
</code>```

What I want to achieve is to show a certain element after clicking a link but it is not working. Where is my mistake?

答:
The first point is that IDs should be unique - ID means identity, how can you identify something if it is not unique?

This will be probably what is causing your jQuery not to work.  But as you are using jQuery, why not bind your click using jQuery?

What I would do is give your links a class, remove the link id and put it into the href (so that your code will be more accessible) and then bind your click using jquery on document ready:

$(function() {
    $('.link').on('click', function(e) {
      e.preventDefault();                 // prevent default action of link

      var link = $(this),
          targetId = link.attr('href'),  // get the href of the current link and use it as the id of the element
          targetDiv = $(targetId);

          targetDiv.fadeIn(1000);        // fade in the div
          link.hide();                   // hide the link? not sure if you want to let them click it again
    });
});
```

<pre class="lang-razor prettyprint-override"><code>@foreach (var comment in Model.commentList)
{
    var id = comment.CommentId;
    <div id="@(id)" style="height:100px; width: 100px; background-color: red; display:none;"></div>
    Comment
}
</code>```

Example:

$(function() {
  $('.link').on('click', function(e) {
    e.preventDefault(); // prevent default action of link

    var link = $(this),
      targetId = link.attr('href'), // get the href of the current link and use it as the id of the element
      targetDiv = $(targetId);

    targetDiv.fadeIn(1000); // fade in the div
    link.hide(); // hide the link? not sure if you want to let them click it again
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test" style="height:100px; width: 100px; background-color: red; display:none;"></div>
Comment</code>```

ContentLicense: CC BY-SA 3.0

Body:
In my view I have:

@foreach (var comment in Model.commentList)
{
    var id = comment.CommentId;

    Comment
}

And then I have a script:

function ShowForm(clicked_id) {
    var element = "#" + clicked_id;
    $(element).fadeIn(1000);
}

What I want to achieve is to show a certain element after clicking a link but it is not working. Where is my mistake?

Body:
The first point is that IDs should be unique - ID means identity, how can you identify something if it is not unique?

This will be probably what is causing your jQuery not to work.  But as you are using jQuery, why not bind your click using jQuery?

What I would do is give your links a class, remove the link id and put it into the href (so that your code will be more accessible) and then bind your click using jquery on document ready:

$(function() {
    $('.link').on('click', function(e) {
      e.preventDefault();                 // prevent default action of link

      var link = $(this),
          targetId = link.attr('href'),  // get the href of the current link and use it as the id of the element
          targetDiv = $(targetId);

          targetDiv.fadeIn(1000);        // fade in the div
          link.hide();                   // hide the link? not sure if you want to let them click it again
    });
});

@foreach (var comment in Model.commentList)
{
    var id = comment.CommentId;
    <div id="@(id)" style="height:100px; width: 100px; background-color: red; display:none;"></div>
    <a href="#@(id)" class="link">Comment</a>
}

Example:

$(function() {
  $('.link').on('click', function(e) {
    e.preventDefault(); // prevent default action of link

    var link = $(this),
      targetId = link.attr('href'), // get the href of the current link and use it as the id of the element
      targetDiv = $(targetId);

    targetDiv.fadeIn(1000); // fade in the div
    link.hide(); // hide the link? not sure if you want to let them click it again
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test" style="height:100px; width: 100px; background-color: red; display:none;"></div>
<a href="#test" class="link">Comment</a>


问:
FATAL EXCEPTION: main java.lang.NoClassDefFoundError: rx.plugins.RxJavaHooks
In my application after successfully login, loading data through retrofit library.
from last two days i founded one major issue in my application. below android API level 21 application getting crashes i checked in console and logs. i got "FATAL EXCEPTION" due to no class def found error. same app working above android API level 23.

in build.gradle file

```<code>android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"

    defaultConfig {
        applicationId "com.example.rsukumar.gluser"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        // Enabling multidex support.
        multiDexEnabled true
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'

    //dagger 2
    compile 'com.google.dagger:dagger:2.0.2'
    provided 'com.google.dagger:dagger-compiler:2.0'
    provided 'javax.annotation:jsr250-api:1.0'
    compile 'com.neenbedankt.gradle.plugins:android-apt:1.8'
    compile 'com.nineoldandroids:library:2.4.0'
    compile 'com.daimajia.easing:library:1.0.1@aar'
    compile 'com.daimajia.androidanimations:library:1.1.3@aar'

    //retrofit 2
    compile 'com.squareup.retrofit:adapter-rxjava:2.0.0-beta2'
    compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'
    compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'
}
</code>```

enter image description here

My main question is why i'm getting above exception and error? that too in different Android API levels.

答: this problem can be related to multidex support for your application. Android Version < 21 do not support Multidex by default. You need to enhance your application. I followed the following instructions to resovle this problem for my applications API Level < 21</p>

Body:
In my application after successfully login, loading data through retrofit library.
from last two days i founded one major issue in my application. below android API level 21 application getting crashes i checked in console and logs. i got "FATAL EXCEPTION" due to no class def found error. same app working above android API level 23.

in build.gradle file

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"

    defaultConfig {
        applicationId "com.example.rsukumar.gluser"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        // Enabling multidex support.
        multiDexEnabled true
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'

    //dagger 2
    compile 'com.google.dagger:dagger:2.0.2'
    provided 'com.google.dagger:dagger-compiler:2.0'
    provided 'javax.annotation:jsr250-api:1.0'
    compile 'com.neenbedankt.gradle.plugins:android-apt:1.8'
    compile 'com.nineoldandroids:library:2.4.0'
    compile 'com.daimajia.easing:library:1.0.1@aar'
    compile 'com.daimajia.androidanimations:library:1.1.3@aar'

    //retrofit 2
    compile 'com.squareup.retrofit:adapter-rxjava:2.0.0-beta2'
    compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'
    compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'
}

enter image description here

My main question is why i'm getting above exception and error? that too in different Android API levels.


问:
twitterbot is repeating itself
For a bit of fun I decided to put a twitter bot together using a youtube based tutorial, and while this was relatively easy to execute I am having an issue with the bot repeating the same tweet a few times before it tweets something new.

At this stage the bot is only set up to post tweets that are put together at random from three seperate arrays

```<code>Array.prototype.pick = function() {
  return this[Math.floor(Math.random()*this.length)];
};

console.log("The bot is starting");

var Twit = require('twit');
var T = new Twit(require('./config.js'));
var partOne = require('./content/partone.js');
var partTwo = require('./content/parttwo.js');
var emoji = require('./content/emojis.js');
var statusOne = partOne.pick();
var statusEmoji = emoji.pick();
var statusTwo = partTwo.pick();

function tweetIt() {

    var tweet = {
      status: statusOne + statusTwo + ' ' + statusEmoji
    };

    T.post('statuses/update', tweet, tweeted);

    function tweeted(err, data, response) {
      if (err) {
        console.log("Something went wwrong!");
      } else {
        console.log("It worked!");
      }
    }
}

//tweetIt();

setInterval(tweetIt, 60 * 1000);
</code>```

I have looked over this but cannot seem to figure out what would cause the bot to repeat itself a few times instead of creating a brand new tweet,

Any help with this would be much appreciated

答:
You're picking your tweet parts outside of your interval. Try putting this:

```<code>var statusOne = partOne.pick();
var statusEmoji = emoji.pick();
var statusTwo = partTwo.pick();
</code>```

inside your tweetIt function.

Title: twitterbot is repeating itself

Body:
For a bit of fun I decided to put a twitter bot together using a youtube based tutorial, and while this was relatively easy to execute I am having an issue with the bot repeating the same tweet a few times before it tweets something new.

At this stage the bot is only set up to post tweets that are put together at random from three seperate arrays

Array.prototype.pick = function() {
  return this[Math.floor(Math.random()*this.length)];
};

console.log("The bot is starting");

var Twit = require('twit');
var T = new Twit(require('./config.js'));
var partOne = require('./content/partone.js');
var partTwo = require('./content/parttwo.js');
var emoji = require('./content/emojis.js');
var statusOne = partOne.pick();
var statusEmoji = emoji.pick();
var statusTwo = partTwo.pick();

function tweetIt() {

    var tweet = {
      status: statusOne + statusTwo + ' ' + statusEmoji
    };

    T.post('statuses/update', tweet, tweeted);

    function tweeted(err, data, response) {
      if (err) {
        console.log("Something went wwrong!");
      } else {
        console.log("It worked!");
      }
    }
}

//tweetIt();

setInterval(tweetIt, 60 * 1000);

I have looked over this but cannot seem to figure out what would cause the bot to repeat itself a few times instead of creating a brand new tweet,

Any help with this would be much appreciated

Body:
You're picking your tweet parts outside of your interval. Try putting this:

var statusOne = partOne.pick();
var statusEmoji = emoji.pick();
var statusTwo = partTwo.pick();

inside your tweetIt function.


问:
Put a Linearlayout under the ListView
I'm facing problem to put a linearlayout under the listview like what is shown in this image link:

I want the layout with the Add icon and text:"Add New Members" to be displayed under the listview. What am I doing wrong? Pls help me to solve the problem. Thank you very much.

This is the xml file for the layout

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.thomasbrown.myapplication.MemberActivity"
android:background="@android:color/white">

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/groupID"
    android:textSize="20sp"
    android:layout_marginBottom="15dp" />

<LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1">

    <ListView
        android:id="@+id/ListView1"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:background="@android:color/white"
        android:layout_weight="1" />

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            app:srcCompat="@drawable/add"
            android:id="@+id/imageView2"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_width="80dp"
            android:layout_height="60dp"
            android:layout_weight="1" />

        <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/addMember"
                android:text="Add New Members"
                android:textSize="18sp"
                android:textColor="@android:color/holo_red_dark"
            android:layout_weight="1"
            android:layout_gravity="center_vertical" />
    </LinearLayout>

</LinearLayout>

<Button
    android:text="Leave this group"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/leaveGroupButton"
    android:background="@color/colorPrimary"
    android:layout_gravity="bottom|end" />

</LinearLayout>
</code>```

答:
```<code> <ScrollView ..

   <RelativeLayout..

      <LinearLayout // vertical orientation

          <ListView ../>

          <LinearLayout  // your linear layout
              layout_below="@+id/listviewid"
      </LinearLayout>

   </RelativeLayout>

 </ScrollView>
</code>```

<p>Try this view hierarchy. </p>

Title: Put a Linearlayout under the ListView

Body:
I'm facing problem to put a linearlayout under the listview like what is shown in this image link:

I want the layout with the Add icon and text:"Add New Members" to be displayed under the listview. What am I doing wrong? Pls help me to solve the problem. Thank you very much.

This is the xml file for the layout

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.thomasbrown.myapplication.MemberActivity"
android:background="@android:color/white">

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/groupID"
    android:textSize="20sp"
    android:layout_marginBottom="15dp" />

<LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1">

    <ListView
        android:id="@+id/ListView1"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:background="@android:color/white"
        android:layout_weight="1" />

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            app:srcCompat="@drawable/add"
            android:id="@+id/imageView2"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_width="80dp"
            android:layout_height="60dp"
            android:layout_weight="1" />

        <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/addMember"
                android:text="Add New Members"
                android:textSize="18sp"
                android:textColor="@android:color/holo_red_dark"
            android:layout_weight="1"
            android:layout_gravity="center_vertical" />
    </LinearLayout>

</LinearLayout>

<Button
    android:text="Leave this group"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/leaveGroupButton"
    android:background="@color/colorPrimary"
    android:layout_gravity="bottom|end" />

</LinearLayout>

Body:
 <ScrollView ..

   <RelativeLayout..

      <LinearLayout // vertical orientation

          <ListView ../>

          <LinearLayout  // your linear layout
              layout_below="@+id/listviewid"
      </LinearLayout>

   </RelativeLayout>

 </ScrollView>

Try this view hierarchy.


问:
SoapUI: Count Nodes Returned in JSON Array Response
I've learned so much using SoapUI, but, I'm just stuck on this one thing. I have the following payload returned:

```<code>[
      {
      "@c": ".CreditPaymentInfo",
      "supplementalInfo": null,
      "date": "06/30/2015 17:03:50",
      "posTxCode": "107535",
      "amt": 2.56,
      "transactionId": 235087,
      "id": 232163,
      "cardType": "CREDIT",
      "cardHolderName": "SMITH2/JOE",
      "expMonthYear": "0119",
      "lastFourDigits": "4444",
      "approvalCode": "315PNI",
      "creditTransactionNumber": "A71A7DB6C2F4"
   },
      {
      "@c": ".CreditPaymentInfo",
      "supplementalInfo": null,
      "date": "07/01/2015 15:53:29",
      "posTxCode": "2097158",
      "amt": 58.04,
      "transactionId": 235099,
      "id": 232176,
      "cardType": "CREDIT",
      "cardHolderName": "SMITH2/JOE",
      "expMonthYear": "0119",
      "lastFourDigits": "4444",
      "approvalCode": "",
      "creditTransactionNumber": null
   }
]
</code>```

I would like to count how many nodes are returned... so, in this case, I would expect that 2 nodes be returned whenever I run this test step in SoapUI.

I was attempting to get this done using the JsonPath Count assertion, but, I just can't see to format it correctly.

Any help would be greatly appreciated!

答:
Counted successfully with 'JsonPath count' using one of the following (assuming my top level object is an array) :

```<code>$
$.
$[*]
</code>```

If you need to be more specific on the objects you're counting, you can rely only on the 3rd syntax, specifying one of the redundant field. One of the following worked for me :

```<code>$[*].fieldName
$[*].['fieldName']
</code>```

Should return 2 in your case with one of the following :

```<code>$[*].@c
$[*].['@c']
$[*].id
$[*].['id']
</code>```

And so on

Body:
I've learned so much using SoapUI, but, I'm just stuck on this one thing. I have the following payload returned:

[
      {
      "@c": ".CreditPaymentInfo",
      "supplementalInfo": null,
      "date": "06/30/2015 17:03:50",
      "posTxCode": "107535",
      "amt": 2.56,
      "transactionId": 235087,
      "id": 232163,
      "cardType": "CREDIT",
      "cardHolderName": "SMITH2/JOE",
      "expMonthYear": "0119",
      "lastFourDigits": "4444",
      "approvalCode": "315PNI",
      "creditTransactionNumber": "A71A7DB6C2F4"
   },
      {
      "@c": ".CreditPaymentInfo",
      "supplementalInfo": null,
      "date": "07/01/2015 15:53:29",
      "posTxCode": "2097158",
      "amt": 58.04,
      "transactionId": 235099,
      "id": 232176,
      "cardType": "CREDIT",
      "cardHolderName": "SMITH2/JOE",
      "expMonthYear": "0119",
      "lastFourDigits": "4444",
      "approvalCode": "",
      "creditTransactionNumber": null
   }
]

I would like to count how many nodes are returned... so, in this case, I would expect that 2 nodes be returned whenever I run this test step in SoapUI.

I was attempting to get this done using the JsonPath Count assertion, but, I just can't see to format it correctly.

Any help would be greatly appreciated!

Body:
Counted successfully with 'JsonPath count' using one of the following (assuming my top level object is an array) :

$
$.
$[*]

If you need to be more specific on the objects you're counting, you can rely only on the 3rd syntax, specifying one of the redundant field. One of the following worked for me :

$[*].fieldName
$[*].['fieldName']

Should return 2 in your case with one of the following :

$[*].@c
$[*].['@c']
$[*].id
$[*].['id']

And so on


问:
How to use CTE recursion to get a running total of a column
I have been researching CTE recursion, but I still seem to be confused.

I have table: utb(date, b_id, v_id, b_vol)

I need to get the running total of the column: b_vol.

The catch is that I need to divide if the row_number is even, and multiply if it is odd, so essentially:

P1= b_vol1, P2 = b_vol1/b_vol2, P3= b_vol1/b_vol2*b_vol3,
  P4= b_vol1/b_vol2*b_vol3/b_vol4

So, it is basically P(n)= (P(n-1)(*OR/(b_vol(n))

I can't seem to figure out how to put that into a query.

Thanks for taking the time to read this. I hope you can help.

答:
you should try this,</p>

```<code>DECLARE @SampleData AS TABLE ( B_VOL int)
INSERT INTO @SampleData VALUES (50), (50), ( 50), (50) ,(155), (255)

;with CTE as
(
select S.B_VOL,ROW_NUMBER()over(order by ((select null)))rn
from @SampleData S
)
,CTE1 AS
(
select b_vol,cast(b_vol as float) sv,1 rn1
from cte    where rn=1

union ALL

select c.b_vol,
case when (c1.rn1+1)%2=0
THEN c1.sv/cast(c.b_vol as float)
ELSE
c1.sv*cast(c.b_vol as float)
end
,c1.rn1+1
from CTE C
inner join CTE1 c1
on c.rn=c1.rn1+1
where c1.rn1<7
)

select * from cte1
</code>```

Body:
you should try this,

DECLARE @SampleData AS TABLE ( B_VOL int)
INSERT INTO @SampleData VALUES (50), (50), ( 50), (50) ,(155), (255)

;with CTE as
(
select S.B_VOL,ROW_NUMBER()over(order by ((select null)))rn
from @SampleData S
)
,CTE1 AS
(
select b_vol,cast(b_vol as float) sv,1 rn1
from cte    where rn=1

union ALL

select c.b_vol,
case when (c1.rn1+1)%2=0
THEN c1.sv/cast(c.b_vol as float)
ELSE
c1.sv*cast(c.b_vol as float)
end
,c1.rn1+1
from CTE C
inner join CTE1 c1
on c.rn=c1.rn1+1
where c1.rn1<7
)

select * from cte1


问:
Vertically middle align text in a bootstrap column
I need tree cells in tree columns(col-4), with an image, that determines the height of the cell, and vertically middle-aligned text, like this:

This is what I get (CodePen Here):

      Some text red-yellow

      some other text long text some other long text lightgreen-gray

      this is another long long long text that should be here skyblue-violet

```

Where is the problem ?

答:
The problem is that you are closing the first  with a
 tag mate, so you close the div with the row class too early. =)

Body:
I need tree cells in tree columns(col-4), with an image, that determines the height of the cell, and vertically middle-aligned text, like this:

This is what I get (CodePen Here):

      Some text red-yellow

      some other text long text some other long text lightgreen-gray

      this is another long long long text that should be here skyblue-violet

Where is the problem ?

Body: The problem is that you are closing the first <a> with a </div> tag mate, so you close the div with the row class too early. =)


问:
Alternatives to the Turing Test
So we learned a bit about the Turing Test in my AI class.  This got me thinking about it.  I can see a few limitations with it:

It's limited to a certain context.  What if I'm not designing an AI to converse with humans?

It favors acting humanly over acting rationally.  For example, if I'm designing an AI to control nuclear missiles, do I really want it to act human?  Granted, this is an extreme example, but you get the idea.

It could be influenced by factors that don't indicate that the computer can think humanly.  For example, suppose I ask what 2334 * 321 is.  I could tell if the device is a computer because it will probably answer me fairly quickly while a human would have to figure it out.  The solution?  Make the computer pause.

Now, I'm sure that the Turing Test still has its place in determining machine intelligence.  But I see it as being fairly limited in scope.  Are there any alternatives?  For that matter, am I wrong as to what I perceive to be its limitations?

EDIT:  Let me be clear:  I'm not suggesting that the Turing Test should be abandoned.  I'm just curious if there are any other tests that overcome its limitations (probably trading them for other limitations).

答:
Tell you what: before we answer your question, define "intelligence".

The Turing Test, as originally described, had some other problems too, the most notable of them being that it's not "effective", which is to say there is no way to tell when it's over.

Now, look at your (quite reasonable) objections: on one hand, if it gives the right answer too quickly, it would make you suspicious; on the other, you're not sure it would be good if it gives wrong answers, even if it would make you think it might be "intelligent."

But, now, consider our interaction: you don't know that I'm not an intelligent computer.  How about, for a Star Trek reference, Mr Data on ST:TNG?  He's certainly distinguishable from a human and doesn't give human responses at all times, but mostly passes.

Now, let's for a moment consider a person you meet who, instead of being intelligent, is completely a mechanism: no "consciousness", no "soul."  (This kind of entity is called a "philosophical zombie" in the literature.)  Except for that missing "consciousness", this person, or simulacrum of a person, acts like a person in all other ways: expresses pain on an injury, shows pleasure when eating a good meal, shows affection to kittens and small children.  (Corrected because I want to pass this test myself.)

How could you tell that this philosophical zombie wasn't "intelligent" ?

The point here is that you've got good questions, but there aren't necessarily well-accepted answers.  My own opinion of the Turing Test is that it's a good valid test, because the point of it, as Turing himself said, is that if you can't tell the difference between an intelligent or sentient computer, and a really intelligent entity, then you have to assume there is no difference.

Some other things you could read:

Read about John Searle's "Chinese
Room"

Read Doug Hofstadter's "Gödel
Escher Bach: An Eternal Golden
Braid"

OwnerDisplayName: Jason Baker

ContentLicense: CC BY-SA 2.5

Title: Alternatives to the Turing Test

LastEditorDisplayName: Rob

OwnerDisplayName: Charlie Martin

LastEditorDisplayName: splattne


问:
OCAML function in parameter of another function
I'm trying to pass a function as parameter to another function but I get an error at compilation.

```<code>Error: This function has type 'a -> 'a -> int
       It is applied to too many arguments; maybe you forgot a `;'.
</code>```

My code is:

```<code>let sort to_do my_list =
        let rec change to_do my_list verify newlist = match my_list with
                | Empty -> if verify = newlist then newlist else
                           change to_do newlist newlist Empty
                | Item (elem, next) -> change to_do my_list verify (compare to_do elem newlist)
        in
        change to_do my_list my_list Empty
;;

let rec compare to_do elem my_list = match my_list with
        | Empty -> (elem, my_list)
        | Item (elem1, Empty) -> if to_do elem elem1 > 0 then Item (elem, elem1) else
                                  Item (elem1, elem)
        | Item (elem1, next) -> compare to_do elem next
;;
</code>```

答:
For the person interesting my final code is :</p>

```<code> let rec comp to_do elem my_list memlist = match my_list with
         | Empty -> Item (elem, memlist)
         | Item (elem1, Empty) -> if to_do elem1 elem > 0 then Item (elem, memlist) else
                                  rev (Item (elem, (rev memlist)))
         | Item (elem1, next) -> comp to_do elem next memlist
 ;;

 let sort to_do my_list =
         let rec change to_do my_list verify newlist = match my_list with
                 | Empty -> if verify = newlist then newlist else
                            change to_do newlist newlist Empty
                 | Item (elem, next) -> change to_do next verify (comp to_do elem newlist newlist)
         in
         change to_do my_list my_list Empty
 ;;
</code>```

Body:
I'm trying to pass a function as parameter to another function but I get an error at compilation.

Error: This function has type 'a -> 'a -> int
       It is applied to too many arguments; maybe you forgot a `;'.

My code is:

let sort to_do my_list =
        let rec change to_do my_list verify newlist = match my_list with
                | Empty -> if verify = newlist then newlist else
                           change to_do newlist newlist Empty
                | Item (elem, next) -> change to_do my_list verify (compare to_do elem newlist)
        in
        change to_do my_list my_list Empty
;;

let rec compare to_do elem my_list = match my_list with
        | Empty -> (elem, my_list)
        | Item (elem1, Empty) -> if to_do elem elem1 > 0 then Item (elem, elem1) else
                                  Item (elem1, elem)
        | Item (elem1, next) -> compare to_do elem next
;;

Body:
For the person interesting my final code is :

 let rec comp to_do elem my_list memlist = match my_list with
         | Empty -> Item (elem, memlist)
         | Item (elem1, Empty) -> if to_do elem1 elem > 0 then Item (elem, memlist) else
                                  rev (Item (elem, (rev memlist)))
         | Item (elem1, next) -> comp to_do elem next memlist
 ;;

 let sort to_do my_list =
         let rec change to_do my_list verify newlist = match my_list with
                 | Empty -> if verify = newlist then newlist else
                            change to_do newlist newlist Empty
                 | Item (elem, next) -> change to_do next verify (comp to_do elem newlist newlist)
         in
         change to_do my_list my_list Empty
 ;;


问:
How to use @Html.DropDownList by giving values manually?
I want to use @Html.DropDownList without any model but simply as we use select in normal html.

Please revert, Thanks!

答:
Its very simple, u may understand we the following example.      </p>

```<code>@Html.DropDownList("selectedState", new List<SelectListItem>
                                {
                                    new SelectListItem {Text = "Not verified", Value = "1"},
                                    new SelectListItem {Text = "Verified", Value = "2"},
                                    new SelectListItem {Text = "Migrated", Value = "3"}
                                    new SelectListItem {Text = "Completed", Value = "4"}
                                }, "All states", new { @onchange = "form.submit();", @class = "form-control" })
</code>```

Body:
Its very simple, u may understand we the following example.

@Html.DropDownList("selectedState", new List<SelectListItem>
                                {
                                    new SelectListItem {Text = "Not verified", Value = "1"},
                                    new SelectListItem {Text = "Verified", Value = "2"},
                                    new SelectListItem {Text = "Migrated", Value = "3"}
                                    new SelectListItem {Text = "Completed", Value = "4"}
                                }, "All states", new { @onchange = "form.submit();", @class = "form-control" })


问:
Binding routes to wrong method controller
I am using laravel 5.1 app. I
have the bellow routes:

```<code>Route::get('{thing}', 'DisplayController@showThingNewRoute');
Route::get('{about}', 'DisplayController@showAboutNewRoute');
</code>```

Also I use RouteServiceProvider like so:

```<code>    public function boot(Router $router)
    {

    parent::boot($router);

    $router->bind('thing', function($thing){
       return \App\Thing::publish()->where('seo_url', '=', $thing)->first();
   });

    $router->bind('about', function($about){
       return \App\About::publish()->where('seo_url', '=', $about)->firstOrFail();
    });

    }
</code>```

The problem is that I can't have a route to execute with a second method showAboutNewRoute

What am i doing wrong here?

答:
Your both route share the same url, whatever you are putting inside curly braces it is like a variable.

You can define your route like this

```<code>Route::get('thing/{thing}', 'DisplayController@showThingNewRoute');
Route::get('about/{about}', 'DisplayController@showAboutNewRoute');
</code>```

Otherwise whatever you will put after your domain, it will pick as first route unless you define any string as a first argument of get method.

Body:
I am using laravel 5.1 app. I
have the bellow routes:

Route::get('{thing}', 'DisplayController@showThingNewRoute');
Route::get('{about}', 'DisplayController@showAboutNewRoute');

Also I use RouteServiceProvider like so:

    public function boot(Router $router)
    {

    parent::boot($router);

    $router->bind('thing', function($thing){
       return \App\Thing::publish()->where('seo_url', '=', $thing)->first();
   });

    $router->bind('about', function($about){
       return \App\About::publish()->where('seo_url', '=', $about)->firstOrFail();
    });

    }

The problem is that I can't have a route to execute with a second method showAboutNewRoute

What am i doing wrong here?

Body:
Your both route share the same url, whatever you are putting inside curly braces it is like a variable.

You can define your route like this

Route::get('thing/{thing}', 'DisplayController@showThingNewRoute');
Route::get('about/{about}', 'DisplayController@showAboutNewRoute');

Otherwise whatever you will put after your domain, it will pick as first route unless you define any string as a first argument of get method.


问:
cant_delete_file even if I have the right scopes?
Since Slack doesn't support bulk delete, I have searched for alternatives. The search didn't took long, and I stumbled upon this Python script which use Slack's Web API to delete all files that are there for more than 30 days.

After struggling to get the token right, I got a valid token with the scopes files:read and files:write:user.

The script starts, gets the list of files, and sends the request to delete correctly, but the answer from Slack is systematic:

```<code>{"ok":false,"error":"cant_delete_file"}
</code>```

Searching for this error code reveals it is because I don't have the permissions to do erase them.

I can't find any more information, and I'm struggling to know what goes wrong. What is the reason I don't have the permissions?

答:
You need to be authenticated as an admin user to delete a file that belongs to another user.

I would agree that the error message could give more details about the situation.

Edit: this answer is outdated, see this comment.

Body:
Since Slack doesn't support bulk delete, I have searched for alternatives. The search didn't took long, and I stumbled upon this Python script which use Slack's Web API to delete all files that are there for more than 30 days.

After struggling to get the token right, I got a valid token with the scopes files:read and files:write:user.

The script starts, gets the list of files, and sends the request to delete correctly, but the answer from Slack is systematic:

{"ok":false,"error":"cant_delete_file"}

Searching for this error code reveals it is because I don't have the permissions to do erase them.

I can't find any more information, and I'm struggling to know what goes wrong. What is the reason I don't have the permissions?

ContentLicense: CC BY-SA 4.0


问:
Angular2 check if object has peoperty inside *ngIf
```<code>export interface Element {
    name: string;
}

export class Room implements Element {
name: string;
type:string
}

export class Hall implements Element {
name: string;
}
</code>```

and my varibale type is like below

```<code>selectedElement: Element;
</code>```

now in html how can I check if the object is having property 'type' or not?

```<code><div *ngIf="selectedElement?.type">
my div
</div>
</code>```

答:
I guess this should do what you want:</p>

```<code>*ngIf="hasProp(selectedElement, 'type')"
</code>```

```<code>hasProp(o, name) {
  return o.hasOwnProperty(name);
}
</code>```

Body:
export interface Element {
    name: string;
}

export class Room implements Element {
name: string;
type:string
}

export class Hall implements Element {
name: string;
}

and my varibale type is like below

selectedElement: Element;

now in html how can I check if the object is having property 'type' or not?

my div

Body:
I guess this should do what you want:

*ngIf="hasProp(selectedElement, 'type')"

hasProp(o, name) {
  return o.hasOwnProperty(name);
}


问:
How can I put an icon and an input text on the same line?
I want to put an icon on the left and an input type text on the right occupying all the remaining space.

```<code>----------------------------------------------------
| [ico]  ----------------------------------------  |
|        |   input type="text"                  |  |
|        ----------------------------------------  |
----------------------------------------------------
</code>```

If I set both with display: inline-block and set the input's width to 100% it jumps the line, because 100% is not considering the space - icosize...

I want to expand the input to the remaining available space (I don't care for vertical align). Is there a way to achieve this behavior without using tables?

An example of the problem on jsFiddle.

答: Try display: table-cell .

Body:
I want to put an icon on the left and an input type text on the right occupying all the remaining space.

----------------------------------------------------
| [ico]  ----------------------------------------  |
|        |   input type="text"                  |  |
|        ----------------------------------------  |
----------------------------------------------------

If I set both with display: inline-block and set the input's width to 100% it jumps the line, because 100% is not considering the space - icosize...

I want to expand the input to the remaining available space (I don't care for vertical align). Is there a way to achieve this behavior without using tables?

An example of the problem on jsFiddle.

Body: Try display: table-cell .


答:
You can use @Html.Dropdownlist without model
for example in controller you set the values for Dropdownlist,

```<code>var dates = new List<SelectListItem>{
new SelectListItem {Selected = false, Text = "Show offers for all dates", Value = ""},
new SelectListItem {Selected = false, Text = "Show offers for today", Value = today.ToShortDateString()},
new SelectListItem {Selected = false, Text = "Show offers for this week", Value = endOfThisWeek.ToShortDateString()},
new SelectListItem {Selected = false, Text = "Show offers for this month", Value = endOfThisMonth.ToShortDateString()},
new SelectListItem {Selected = false, Text = "Show offers for further out", Value = all.ToShortDateString()},};
ViewBag.Dropdowndata = dates;
</code>```

and you can access the values of Viewbag from View and set it to Dropdown list like

```<code>@using (Html.BeginForm())
        {
            <label>
                Select Dates</label>
            @Html.DropDownList("Dates", (IEnumerable<SelectListItem>)ViewBag.Dropdowndata, "---Select---", new { id = "dateList" ,@class = "form-control" });
        }
</code>```

Title: How to use @Html.DropDownList by giving values manually?

Body:
I want to use @Html.DropDownList without any model but simply as we use select in normal html.

Please revert, Thanks!

Body:
You can use @Html.Dropdownlist without model
for example in controller you set the values for Dropdownlist,

var dates = new List<SelectListItem>{
new SelectListItem {Selected = false, Text = "Show offers for all dates", Value = ""},
new SelectListItem {Selected = false, Text = "Show offers for today", Value = today.ToShortDateString()},
new SelectListItem {Selected = false, Text = "Show offers for this week", Value = endOfThisWeek.ToShortDateString()},
new SelectListItem {Selected = false, Text = "Show offers for this month", Value = endOfThisMonth.ToShortDateString()},
new SelectListItem {Selected = false, Text = "Show offers for further out", Value = all.ToShortDateString()},};
ViewBag.Dropdowndata = dates;

and you can access the values of Viewbag from View and set it to Dropdown list like

@using (Html.BeginForm())
        {
            <label>
                Select Dates</label>
            @Html.DropDownList("Dates", (IEnumerable<SelectListItem>)ViewBag.Dropdowndata, "---Select---", new { id = "dateList" ,@class = "form-control" });
        }


问:
Download file from Azure
Have multiple blobs, have extracted the name of each blob into a list, with its last modified date.
Have set a download path, and then run the following code, where the kvp.Key is the name of each blob. The idea being I can loop round each file name and download it:

```<code> foreach (KeyValuePair<string, DateTimeOffset?> kvp in to_be_dl)
        {
            Console.WriteLine("Downloading: " + kvp.Key);

            //Console.WriteLine(kvp.Key+" "+kvp.Value);
            foreach (CloudBlockBlob blobItem in blobs)
            {

                    try
                    {
                        blobItem.DownloadToFile(downloadpath + "\\" + kvp.Key, FileMode.Create);
                        break;
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                        break;
                    }
            }
            Console.WriteLine("Downloaded: " + kvp.Key);
        }
</code>```

Is there a way to be able to get a blob by its name and download the corresponding file?

答:
There's a flaw in your logic :).

Essentially your outer loop gets the name of the downloaded file but then your inner loop iterates over the blobs and then downloads each blob with the same name set in the outer loop.

What that does is that it saves the last blob (or the first blob) in the inner loop multiple times with different names.

That's why when you unzip the files, you get the same content even though the file name is different because the same blob gets downloaded (even though saved with a different name).

To solve this problem, what you can do is create an instance of CloudBlockBlob using the Key in your kvp and then try to download that blob. Something like below:

```<code>        foreach (KeyValuePair<string, DateTimeOffset?> kvp in to_be_dl)
        {
            Console.WriteLine("Downloading: " + kvp.Key);
            var blob = container.GetBlockBlobReference(kvp.Key);
            try
            {
                //If the blob doesn't exist, you will get an error and then your code should move to the next key
                blob.DownloadToFile(downloadpath + "\\" + kvp.Key, FileMode.Create);
                Console.WriteLine("Downloaded: " + kvp.Key);
            }
            catch (Exception e)
            {
                Console.WriteLine("Failed to download: " + kvp.Key);
                Console.WriteLine(e);
            }
        }
</code>```

Title: Download file from Azure

Body:
Have multiple blobs, have extracted the name of each blob into a list, with its last modified date.
Have set a download path, and then run the following code, where the kvp.Key is the name of each blob. The idea being I can loop round each file name and download it:

 foreach (KeyValuePair<string, DateTimeOffset?> kvp in to_be_dl)
        {
            Console.WriteLine("Downloading: " + kvp.Key);

            //Console.WriteLine(kvp.Key+" "+kvp.Value);
            foreach (CloudBlockBlob blobItem in blobs)
            {

                    try
                    {
                        blobItem.DownloadToFile(downloadpath + "\\" + kvp.Key, FileMode.Create);
                        break;
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                        break;
                    }
            }
            Console.WriteLine("Downloaded: " + kvp.Key);
        }

Is there a way to be able to get a blob by its name and download the corresponding file?

Body:
There's a flaw in your logic :).

Essentially your outer loop gets the name of the downloaded file but then your inner loop iterates over the blobs and then downloads each blob with the same name set in the outer loop.

What that does is that it saves the last blob (or the first blob) in the inner loop multiple times with different names.

That's why when you unzip the files, you get the same content even though the file name is different because the same blob gets downloaded (even though saved with a different name).

To solve this problem, what you can do is create an instance of CloudBlockBlob using the Key in your kvp and then try to download that blob. Something like below:

        foreach (KeyValuePair<string, DateTimeOffset?> kvp in to_be_dl)
        {
            Console.WriteLine("Downloading: " + kvp.Key);
            var blob = container.GetBlockBlobReference(kvp.Key);
            try
            {
                //If the blob doesn't exist, you will get an error and then your code should move to the next key
                blob.DownloadToFile(downloadpath + "\\" + kvp.Key, FileMode.Create);
                Console.WriteLine("Downloaded: " + kvp.Key);
            }
            catch (Exception e)
            {
                Console.WriteLine("Failed to download: " + kvp.Key);
                Console.WriteLine(e);
            }
        }


问:
Convert tuple elements into separate strings
I have a dictionary which contains tuples, which in turn, contain strings & integers. I want to convert them to series of strings separated by comma.

```<code>new = [('POU5F1', 13), ('BICD1', 11), ('VEGFA', 10)]
links = [', '.join([t[0] for t in new])]
print(links)
</code>```

How can I convert this to the following format:

```<code> print(links)
 ['POU5F1', 'BICD1', 'VEGFA']
</code>```

答:
Hope this code can help:</p>

```<code>new = [('POU5F1', 13), ('BICD1', 11), ('VEGFA', 10)]
links = []

for i in new:
    links.append(i[0])

print(links)
</code>```

Body:
I have a dictionary which contains tuples, which in turn, contain strings & integers. I want to convert them to series of strings separated by comma.

new = [('POU5F1', 13), ('BICD1', 11), ('VEGFA', 10)]
links = [', '.join([t[0] for t in new])]
print(links)

How can I convert this to the following format:

 print(links)
 ['POU5F1', 'BICD1', 'VEGFA']

Body:
Hope this code can help:

new = [('POU5F1', 13), ('BICD1', 11), ('VEGFA', 10)]
links = []

for i in new:
    links.append(i[0])

print(links)


问:
Deploying context.xml to webapps/[webappname]/META-INF
I'm using Tomcat 6.0.26 and am writing build.xml to deploy war file. The following code is what I have right now, and I need to pack context.xml under /META-INF/ as I wish to have this configuration like #2. I have searched the attribute for the war command, but I couldn't find anything that works like webxml for WEB-INF/web.xml.

So my questions are,

1) Is there an war attribute to place the context.xml under META-INF ?

2) If there isn't such an attribute, what would be the best way to place the context.xml under META-INF for each webapp?

```<code><target name="packwar">
   <war destfile="${appname}.war" webxml="web.xml">
        <lib file="${bin}/myapp.jar"/>
   </war>
</target>
</code>```

Thank you in advance.

答:
You should be able to use the metainf nested element of the 'war' task:

The nested metainf element specifies a
  FileSet. All files included in this
  fileset will end up in the META-INF
  directory of the war file. If this
  fileset includes a file named
  MANIFEST.MF, the file is ignored and
  you will get a warning.

Something like this:

```<code><target name="packwar">
   <war destfile="${appname}.war" webxml="web.xml">
        <lib file="${bin}/myapp.jar"/>
        <metainf file="context.xml" />
   </war>
</target>
</code>```

There is a  similar option - 'webinf' - for deploying to the WEB-INF directory.

Body:
I'm using Tomcat 6.0.26 and am writing build.xml to deploy war file. The following code is what I have right now, and I need to pack context.xml under /META-INF/ as I wish to have this configuration like #2. I have searched the attribute for the war command, but I couldn't find anything that works like webxml for WEB-INF/web.xml.

So my questions are,

1) Is there an war attribute to place the context.xml under META-INF ?

2) If there isn't such an attribute, what would be the best way to place the context.xml under META-INF for each webapp?

<target name="packwar">
   <war destfile="${appname}.war" webxml="web.xml">
        <lib file="${bin}/myapp.jar"/>
   </war>
</target>

Thank you in advance.

Body:
You should be able to use the metainf nested element of the 'war' task:

The nested metainf element specifies a
  FileSet. All files included in this
  fileset will end up in the META-INF
  directory of the war file. If this
  fileset includes a file named
  MANIFEST.MF, the file is ignored and
  you will get a warning.

Something like this:

<target name="packwar">
   <war destfile="${appname}.war" webxml="web.xml">
        <lib file="${bin}/myapp.jar"/>
        <metainf file="context.xml" />
   </war>
</target>

There is a  similar option - 'webinf' - for deploying to the WEB-INF directory.


问:
Trying to detect browser close event
I have tried many methods to detect browser close event through jQuery or JavaScript. But, unfortunately, I have not been able to detect the close. The onbeforeunload and onunload methods are also not working.

How do I detect the window close, unload, or beforeunload events?

答:
```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>

<script type="text/javascript" language="javascript">

var validNavigation = false;

function endSession() {
// Browser or broswer tab is closed
// Do sth here ...
alert("bye");
}

function wireUpEvents() {
/*
* For a list of events that triggers onbeforeunload on IE
* check http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx
*/
window.onbeforeunload = function() {
  if (!validNavigation) {

            var ref="load";
      $.ajax({
            type: 'get',
            async: false,
            url: 'logout.php',
 data:
            {
                ref:ref
            },
             success:function(data)
            {
                console.log(data);
            }
            });
     endSession();
  }
 }

// Attach the event keypress to exclude the F5 refresh
$(document).bind('keypress', function(e) {
if (e.keyCode == 116){
  validNavigation = true;
}
});

// Attach the event click for all links in the page
$("a").bind("click", function() {
validNavigation = true;
});

 // Attach the event submit for all forms in the page
 $("form").bind("submit", function() {
 validNavigation = true;
 });

 // Attach the event click for all inputs in the page
 $("input[type=submit]").bind("click", function() {
 validNavigation = true;
 });

}

// Wire up the events as soon as the DOM tree is ready
$(document).ready(function() {
wireUpEvents();
});
</script>
</code>```

This is used for when logged in user close the browser or browser tab it will automatically logout the user account...

Title: Trying to detect browser close event

Body:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>

<script type="text/javascript" language="javascript">

var validNavigation = false;

function endSession() {
// Browser or broswer tab is closed
// Do sth here ...
alert("bye");
}

function wireUpEvents() {
/*
* For a list of events that triggers onbeforeunload on IE
* check http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx
*/
window.onbeforeunload = function() {
  if (!validNavigation) {

            var ref="load";
      $.ajax({
            type: 'get',
            async: false,
            url: 'logout.php',
 data:
            {
                ref:ref
            },
             success:function(data)
            {
                console.log(data);
            }
            });
     endSession();
  }
 }

// Attach the event keypress to exclude the F5 refresh
$(document).bind('keypress', function(e) {
if (e.keyCode == 116){
  validNavigation = true;
}
});

// Attach the event click for all links in the page
$("a").bind("click", function() {
validNavigation = true;
});

 // Attach the event submit for all forms in the page
 $("form").bind("submit", function() {
 validNavigation = true;
 });

 // Attach the event click for all inputs in the page
 $("input[type=submit]").bind("click", function() {
 validNavigation = true;
 });

}

// Wire up the events as soon as the DOM tree is ready
$(document).ready(function() {
wireUpEvents();
});
</script>

This is used for when logged in user close the browser or browser tab it will automatically logout the user account...


问:
Visibility of class variables
Static variables can be updated within regular members of a class. Assuming a situation in which we have private static int counter; correspondingly public void countMore(){counter++;}. now if we have two threads of 2 different objects of the same class, and the methodcountMore() is invoked on those two objects, how can we guarantee visibility of the class-static variable counter?

Edit:

Notice:

when we have two threads

```<code> Thread thread1 = new Thread(new SomeClass())
 Thread thread2 = new Thread(new SomeClass())
 thread1.start();
 thread2.start();
</code>```

synchronizing the instance method countMore() would not help in this regard.

答:
Possible solutions with glue code</p>

```<code>//You should make the counter fiels private so noone can ignore the synchronized

//Solution 1 synchronized
private static int counter;

static synchronized void countMore(){
    counter++;
}

static synchronized int getCount(){
    return counter;
}

//Solution 2 Atomics
private static AtomicInteger acounter;

static void acountMore(){
    acounter.addAndGet(1);
}

static int getaCount(){
    return acounter.get();
}
</code>```

Title: Visibility of class variables

Body:
Static variables can be updated within regular members of a class. Assuming a situation in which we have private static int counter; correspondingly public void countMore(){counter++;}. now if we have two threads of 2 different objects of the same class, and the methodcountMore() is invoked on those two objects, how can we guarantee visibility of the class-static variable counter?

Edit:

Notice:

when we have two threads

 Thread thread1 = new Thread(new SomeClass())
 Thread thread2 = new Thread(new SomeClass())
 thread1.start();
 thread2.start();

synchronizing the instance method countMore() would not help in this regard.

Body:
Possible solutions with glue code

//You should make the counter fiels private so noone can ignore the synchronized

//Solution 1 synchronized
private static int counter;

static synchronized void countMore(){
    counter++;
}

static synchronized int getCount(){
    return counter;
}

//Solution 2 Atomics
private static AtomicInteger acounter;

static void acountMore(){
    acounter.addAndGet(1);
}

static int getaCount(){
    return acounter.get();
}


问:
Apps Script to automate Bigquery runs but doesn't do anything
I'm posting this as a new question as it's slightly different to my original questions on this matter.

I have an apps script to run a query in BigQuery. The script is running and communicating with BigQuery but the job isn't working as expected. I currently get the following error in BigQuery:

Already Exists: Table fiery-cabinet-111****:***.Test4 (error code: duplicate)

Here is the script:

```<code>function saveQueryToTable() {
  var projectId = 'fiery-cabinet-*****';
  var datasetId = '11****101';
  var tableId = 'Test4';
  var job = {
    configuration: {
      query: {
        query: 'SELECT * ' +
               'FROM [fiery-cabinet-****:*****.Test2];',
        destinationTable: {
          projectId: projectId,
          datasetId: datasetId,
          tableId: tableId
        }
      }
    }
  };

var queryResults = BigQuery.Jobs.insert(job, projectId);
  Logger.log(queryResults.status);
}
</code>```

答:
It looks like you are missing the dataset name from your select query.  Change the query to include the dataset name

```<code>query: 'SELECT *' +
       'FROM 11****101.Test2;',
</code>```

and verify syntax by viewing the execution transcript and logs

Be aware that providing you have access and the syntax (i.e. project, table and dataset name) correct, your code will just log a table insert job with BigQuery and then finish.

The script completing wont be the same as the BigQuery job completing, for that you'd have to poll the job status.  You could for example be trying to insert to a table that already exists, which would post the job successfully, but fail at execution time (depending on parameters set).

Try the following to obtain the completed query status

```<code>var queryResults = BigQuery.Jobs.insert(job, projectId);

  var jobId = queryResults.jobReference.jobId;
  var response = 'Running'

  var sleepTimeMs = 500;
  while (response != 'DONE') {
    Utilities.sleep(sleepTimeMs);
    response = BigQuery.Jobs.get(projectId, jobId).status.state;
  }

  Logger.log('Job status : ' + queryResults.status);
</code>```

Body:
I'm posting this as a new question as it's slightly different to my original questions on this matter.

I have an apps script to run a query in BigQuery. The script is running and communicating with BigQuery but the job isn't working as expected. I currently get the following error in BigQuery:

Already Exists: Table fiery-cabinet-111****:***.Test4 (error code: duplicate)

Here is the script:

function saveQueryToTable() {
  var projectId = 'fiery-cabinet-*****';
  var datasetId = '11****101';
  var tableId = 'Test4';
  var job = {
    configuration: {
      query: {
        query: 'SELECT * ' +
               'FROM [fiery-cabinet-****:*****.Test2];',
        destinationTable: {
          projectId: projectId,
          datasetId: datasetId,
          tableId: tableId
        }
      }
    }
  };

var queryResults = BigQuery.Jobs.insert(job, projectId);
  Logger.log(queryResults.status);
}

Body:
It looks like you are missing the dataset name from your select query.  Change the query to include the dataset name

query: 'SELECT *' +
       'FROM 11****101.Test2;',

and verify syntax by viewing the execution transcript and logs

Be aware that providing you have access and the syntax (i.e. project, table and dataset name) correct, your code will just log a table insert job with BigQuery and then finish.

The script completing wont be the same as the BigQuery job completing, for that you'd have to poll the job status.  You could for example be trying to insert to a table that already exists, which would post the job successfully, but fail at execution time (depending on parameters set).

Try the following to obtain the completed query status

var queryResults = BigQuery.Jobs.insert(job, projectId);

  var jobId = queryResults.jobReference.jobId;
  var response = 'Running'

  var sleepTimeMs = 500;
  while (response != 'DONE') {
    Utilities.sleep(sleepTimeMs);
    response = BigQuery.Jobs.get(projectId, jobId).status.state;
  }

  Logger.log('Job status : ' + queryResults.status);


问:
How to query multiple columns in Dynamodb with node js
I am working on a project with Dynamodb and Nodejs. I need a solution for query on multiple fields like select * from table where name=this and age=22 and active=this and area=this. I need a solution with query only scan is not allowed to me. If it is possible then please let me know with a sample nodejs script.

答:
Here is the code.

1) Change the table name

2) Change login credentials if you are using the AWS DynamoDB service. The below code uses local DynamoDB service

```<code>var AWS = require("aws-sdk");

var creds = new AWS.Credentials('akid', 'secret', 'session');

AWS.config.update({
    region : "us-west-2",
    endpoint : "http://localhost:8000",
    credentials : creds
});

var docClient = new AWS.DynamoDB.DocumentClient();

var table = "tablename";

var params = {
    TableName : table,
    KeyConditionExpression : 'personId = :personIdval',
    FilterExpression : '#name= :nameVal and age= :ageVal and active=:activeVal and area=:areaVal',
     ExpressionAttributeNames : {
        '#name' : 'name'
    },
    ExpressionAttributeValues : {
        ':personIdval' : '7',
        ':nameVal' : 'this',
        ':ageVal' : 22,
        ':activeVal' : 'this',
        ':areaVal' : 'this'
    }
};

docClient.query(params, function(err, data) {
    if (err) {
        console.error("Unable to read item. Error JSON:", JSON.stringify(err,
                null, 2));
    } else {
        console.log("GetItem succeeded:", JSON.stringify(data, null, 2));
    }
});
</code>```

Body:
Here is the code.

1) Change the table name

2) Change login credentials if you are using the AWS DynamoDB service. The below code uses local DynamoDB service

var AWS = require("aws-sdk");

var creds = new AWS.Credentials('akid', 'secret', 'session');

AWS.config.update({
    region : "us-west-2",
    endpoint : "http://localhost:8000",
    credentials : creds
});

var docClient = new AWS.DynamoDB.DocumentClient();

var table = "tablename";

var params = {
    TableName : table,
    KeyConditionExpression : 'personId = :personIdval',
    FilterExpression : '#name= :nameVal and age= :ageVal and active=:activeVal and area=:areaVal',
     ExpressionAttributeNames : {
        '#name' : 'name'
    },
    ExpressionAttributeValues : {
        ':personIdval' : '7',
        ':nameVal' : 'this',
        ':ageVal' : 22,
        ':activeVal' : 'this',
        ':areaVal' : 'this'
    }
};

docClient.query(params, function(err, data) {
    if (err) {
        console.error("Unable to read item. Error JSON:", JSON.stringify(err,
                null, 2));
    } else {
        console.log("GetItem succeeded:", JSON.stringify(data, null, 2));
    }
});


问:
can a aspx page have more than one aspx.cs class to inherit?
i want to know, can one aspx page have two or more code behind page?
like if i have page collge.aspx, by default it will inherit college.aspx.cs, i want to know can't it inherit more then one aspx.cs. If not then why?</p>

答:
A class cannot inherit two different base classes.  (.Net does not support multiple inheritance)

However, you can inherit a single base class which is split among multiple files using the partial keyword.


问:
Put a Linearlayout under the ListView
I'm facing problem to put a linearlayout under the listview like what is shown in this image link:

I want the layout with the Add icon and text:"Add New Members" to be displayed under the listview. What am I doing wrong? Pls help me to solve the problem. Thank you very much.

This is the xml file for the layout

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.thomasbrown.myapplication.MemberActivity"
android:background="@android:color/white">

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/groupID"
    android:textSize="20sp"
    android:layout_marginBottom="15dp" />

<LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1">

    <ListView
        android:id="@+id/ListView1"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:background="@android:color/white"
        android:layout_weight="1" />

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            app:srcCompat="@drawable/add"
            android:id="@+id/imageView2"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_width="80dp"
            android:layout_height="60dp"
            android:layout_weight="1" />

        <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/addMember"
                android:text="Add New Members"
                android:textSize="18sp"
                android:textColor="@android:color/holo_red_dark"
            android:layout_weight="1"
            android:layout_gravity="center_vertical" />
    </LinearLayout>

</LinearLayout>

<Button
    android:text="Leave this group"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/leaveGroupButton"
    android:background="@color/colorPrimary"
    android:layout_gravity="bottom|end" />

</LinearLayout>
</code>```

答: Problem is you have android:layout_weight="1" on your ListView which will make it expand to full and give no space to your LinearLayout

Title: Put a Linearlayout under the ListView

Body:
I'm facing problem to put a linearlayout under the listview like what is shown in this image link:

I want the layout with the Add icon and text:"Add New Members" to be displayed under the listview. What am I doing wrong? Pls help me to solve the problem. Thank you very much.

This is the xml file for the layout

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.thomasbrown.myapplication.MemberActivity"
android:background="@android:color/white">

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/groupID"
    android:textSize="20sp"
    android:layout_marginBottom="15dp" />

<LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1">

    <ListView
        android:id="@+id/ListView1"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:background="@android:color/white"
        android:layout_weight="1" />

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            app:srcCompat="@drawable/add"
            android:id="@+id/imageView2"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_width="80dp"
            android:layout_height="60dp"
            android:layout_weight="1" />

        <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/addMember"
                android:text="Add New Members"
                android:textSize="18sp"
                android:textColor="@android:color/holo_red_dark"
            android:layout_weight="1"
            android:layout_gravity="center_vertical" />
    </LinearLayout>

</LinearLayout>

<Button
    android:text="Leave this group"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/leaveGroupButton"
    android:background="@color/colorPrimary"
    android:layout_gravity="bottom|end" />

</LinearLayout>


问:
Check if column name already exists in Access/oledb
I made a simple Windows forms application which creates a table in the access file(mdb) insert, delete, update columns. (I used OLEDB connection for this.)  I wrote this code to insert column.

```<code>   con.Open();
    OleDbCommand cmd = new OleDbCommand();
    cmd.Connection = con;
    cmd.CommandText = "alter table [" +tableName + "] add [" + columnName + "] long;
    cmd.ExecuteNonQuery();
    con.Close();
</code>```

Now i want program to check if column name which user want to insert is already exists in the database. What should i do for that?

答:
For MS-Access:

Since you are doing this at application code, you can wrap it in a try .. catch block. If column exists then it will throw an exception, which you can catch and do whatever needed like

```<code>try
{
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandText = "alter table [" +tableName + "] add [" + columnName + "] long";
cmd.ExecuteNonQuery();
}
catch(Exception ex)
{
  //do your processing
}
finally
{
      con?.Close();
}
</code>```

If using SQL Server then

You can check against sys.columns system view like

```<code>SELECT 1 FROM sys.columns
        WHERE [name] = N'your_new_columnName'
        AND [object_id] = OBJECT_ID(N'Your_tableName');
</code>```

Again, yo be better you can consider wrapping this in a stored procedure and call that procedure in your application code like

```<code>create procedure usp_altertable(table_name varchar(20), column_name varchar(20))
as
begin
DECLARE @sql varchar(100);
   IF NOT EXISTS(SELECT 1 FROM sys.columns
            WHERE [name] = N'your_new_columnName'
            AND [object_id] = OBJECT_ID(N'Your_tableName'))
SET @sql = 'alter table ' +table_name +' add ' + column_name + ' long';
EXEC(@sql);
end
</code>```

Finally, if table_name and column_name are coming as user input from UI then be wary of SQL Injection and use parameterized query instead.

Body:
I made a simple Windows forms application which creates a table in the access file(mdb) insert, delete, update columns. (I used OLEDB connection for this.)  I wrote this code to insert column.

   con.Open();
    OleDbCommand cmd = new OleDbCommand();
    cmd.Connection = con;
    cmd.CommandText = "alter table [" +tableName + "] add [" + columnName + "] long;
    cmd.ExecuteNonQuery();
    con.Close();

Now i want program to check if column name which user want to insert is already exists in the database. What should i do for that?

Body:
For MS-Access:

Since you are doing this at application code, you can wrap it in a try .. catch block. If column exists then it will throw an exception, which you can catch and do whatever needed like

try
{
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandText = "alter table [" +tableName + "] add [" + columnName + "] long";
cmd.ExecuteNonQuery();
}
catch(Exception ex)
{
  //do your processing
}
finally
{
      con?.Close();
}

If using SQL Server then

You can check against sys.columns system view like

SELECT 1 FROM sys.columns
        WHERE [name] = N'your_new_columnName'
        AND [object_id] = OBJECT_ID(N'Your_tableName');

Again, yo be better you can consider wrapping this in a stored procedure and call that procedure in your application code like

create procedure usp_altertable(table_name varchar(20), column_name varchar(20))
as
begin
DECLARE @sql varchar(100);
   IF NOT EXISTS(SELECT 1 FROM sys.columns
            WHERE [name] = N'your_new_columnName'
            AND [object_id] = OBJECT_ID(N'Your_tableName'))
SET @sql = 'alter table ' +table_name +' add ' + column_name + ' long';
EXEC(@sql);
end

Finally, if table_name and column_name are coming as user input from UI then be wary of SQL Injection and use parameterized query instead.


问:
How can I get start-stop-daemon to write the child process ID to the pid file?
I'm writing an init.d script to start a program that I've written in C. The program follows a pretty standard template where it calls fork() to create a child process, and then the parent process terminates almost immediately. The trouble I'm running into is that the PID file gets the parent process ID written to it, so later when I call "stop" it fails because the parent has long since ended and only the child is running.

Currently I have this command in my startup script:

```<code>start-stop-daemon --start --background -m --oknodo --pidfile "$PIDFILE" --exec "$SCRIPT" || return 2
</code>```

I confess that I'm very new to all of this so I'm not even entirely sure what all those flags do. This was mostly a copy/paste from various articles I stumbled across. In any case, this would seem like a fairly common thing. How can I make it write the correct (i.e. child) process ID in the pid file?

答:
Daemons need to create .pid file by own self. Because of daemonizing procedure by it self, when you change your start pid.

Option --pidfile is for pid file which already created. Also start-stop-daemon has option --make-pidfile, but it's useful only for program which not daemonize own self.

-m, --make-pidfile ...
Note: This feature may not work in all cases. Most notably when the program being executed forks from its main process.

Body:
I'm writing an init.d script to start a program that I've written in C. The program follows a pretty standard template where it calls fork() to create a child process, and then the parent process terminates almost immediately. The trouble I'm running into is that the PID file gets the parent process ID written to it, so later when I call "stop" it fails because the parent has long since ended and only the child is running.

Currently I have this command in my startup script:

start-stop-daemon --start --background -m --oknodo --pidfile "$PIDFILE" --exec "$SCRIPT" || return 2

I confess that I'm very new to all of this so I'm not even entirely sure what all those flags do. This was mostly a copy/paste from various articles I stumbled across. In any case, this would seem like a fairly common thing. How can I make it write the correct (i.e. child) process ID in the pid file?