问:
OpenShift Aggregated Logging: Parse Apache access log
When using OpenShift Aggregated Logging  I get logs nicely fed into elasticsearch. However, the line as logged by apache ends up in a message field.

I'd like to create queries in Kibana where I can access the url, the status code and other fields individually. For that the special apache access log parsing needs to be done.

How can I do that?

This is an example entry as seen in kibana:

```<code>{
  "_index": "42-steinbruchsteiner-staging.3af0bedd-eebc-11e6-af4b-005056a62fa6.2017.03.29",
  "_type": "fluentd",
  "_id": "AVsY3aSK190OXhxv4GIF",
  "_score": null,
  "_source": {
    "time": "2017-03-29T07:00:25.595959397Z",
    "docker_container_id": "9f4fa85a626d2f5197f0028c05e8e42271db7a4c674cc145204b67b6578f3378",
    "kubernetes_namespace_name": "42-steinbruchsteiner-staging",
    "kubernetes_pod_id": "56c61b65-0b0e-11e7-82e9-005056a62fa6",
    "kubernetes_pod_name": "php-app-3-weice",
    "kubernetes_container_name": "php-app",
    "kubernetes_labels_deployment": "php-app-3",
    "kubernetes_labels_deploymentconfig": "php-app",
    "kubernetes_labels_name": "php-app",
    "kubernetes_host": "itsrv1564.esrv.local",
    "kubernetes_namespace_id": "3af0bedd-eebc-11e6-af4b-005056a62fa6",
    "hostname": "itsrv1564.esrv.local",
    "message": "10.1.3.1 - - [29/Mar/2017:01:59:21 +0200] "GET /kwf/status/health HTTP/1.1" 200 2 "-" "Go-http-client/1.1"\n",
    "version": "1.3.0"
  },
  "fields": {
    "time": [
      1490770825595
    ]
  },
  "sort": [
    1490770825595
  ]
}
</code>```

答:
Disclaimer: I did not test this out in openshift. I don't know which tech stack you are using for your microservice.

This is how I do this in a spring boot application (with logback) deployed in Kubernetes.

1. Use logstash encoder for logback (This will write logs in Json format which is more ELK stack friendly)

I have a gradle dependency to enable this

```<code>compile "net.logstash.logback:logstash-logback-encoder:3.5"
</code>```

Then configure LogstashEncoder as encoder in the appender, in logback-spring.groovy/logback-spring.xml (or logabck.xml)

2. Have some filters or libraries to write the access log

For 2. Either use

A. Use "net.rakugakibox.springbootext:spring-boot-ext-logback-access:1.6" library

(This is what I am using)

It gives in a nice json format, as follows

```<code>{
   "@timestamp":"2017-03-29T09:43:09.536-05:00",
   "@version":1,
   "@message":"0:0:0:0:0:0:0:1 - - [2017-03-29T09:43:09.536-05:00] \"GET /orders/v1/items/42 HTTP/1.1\" 200 991",
   "@fields.method":"GET",
   "@fields.protocol":"HTTP/1.1",
   "@fields.status_code":200,
   "@fields.requested_url":"GET /orders/v1/items/42 HTTP/1.1",
   "@fields.requested_uri":"/orders/v1/items/42",
   "@fields.remote_host":"0:0:0:0:0:0:0:1",
   "@fields.HOSTNAME":"0:0:0:0:0:0:0:1",
   "@fields.content_length":991,
   "@fields.elapsed_time":48,
   "HOSTNAME":"ABCD"
}
</code>```

OR

B. Use Logback's Tee Filter

OR

C. Spring's CommonsRequestLoggingFilter (Did not really test this out)

Add a bean definition

```<code>    @Bean
    public CommonsRequestLoggingFilter requestLoggingFilter() {
        CommonsRequestLoggingFilter crlf = new CommonsRequestLoggingFilter();
        crlf.setIncludeClientInfo(true);
        crlf.setIncludeQueryString(true);
        crlf.setIncludePayload(true);
        return crlf;
    }
</code>```

Then set org.springframework.web.filter.CommonsRequestLoggingFilter to DEBUG, this can be done using the application.properties by adding:

```<code>logging.level.org.springframework.web.filter.CommonsRequestLoggingFilter=DEBUG
</code>```

Body:
When using OpenShift Aggregated Logging  I get logs nicely fed into elasticsearch. However, the line as logged by apache ends up in a message field.

I'd like to create queries in Kibana where I can access the url, the status code and other fields individually. For that the special apache access log parsing needs to be done.

How can I do that?

This is an example entry as seen in kibana:

{
  "_index": "42-steinbruchsteiner-staging.3af0bedd-eebc-11e6-af4b-005056a62fa6.2017.03.29",
  "_type": "fluentd",
  "_id": "AVsY3aSK190OXhxv4GIF",
  "_score": null,
  "_source": {
    "time": "2017-03-29T07:00:25.595959397Z",
    "docker_container_id": "9f4fa85a626d2f5197f0028c05e8e42271db7a4c674cc145204b67b6578f3378",
    "kubernetes_namespace_name": "42-steinbruchsteiner-staging",
    "kubernetes_pod_id": "56c61b65-0b0e-11e7-82e9-005056a62fa6",
    "kubernetes_pod_name": "php-app-3-weice",
    "kubernetes_container_name": "php-app",
    "kubernetes_labels_deployment": "php-app-3",
    "kubernetes_labels_deploymentconfig": "php-app",
    "kubernetes_labels_name": "php-app",
    "kubernetes_host": "itsrv1564.esrv.local",
    "kubernetes_namespace_id": "3af0bedd-eebc-11e6-af4b-005056a62fa6",
    "hostname": "itsrv1564.esrv.local",
    "message": "10.1.3.1 - - [29/Mar/2017:01:59:21 +0200] "GET /kwf/status/health HTTP/1.1" 200 2 "-" "Go-http-client/1.1"\n",
    "version": "1.3.0"
  },
  "fields": {
    "time": [
      1490770825595
    ]
  },
  "sort": [
    1490770825595
  ]
}

Body:
Disclaimer: I did not test this out in openshift. I don't know which tech stack you are using for your microservice.

This is how I do this in a spring boot application (with logback) deployed in Kubernetes.

1. Use logstash encoder for logback (This will write logs in Json format which is more ELK stack friendly)

I have a gradle dependency to enable this

compile "net.logstash.logback:logstash-logback-encoder:3.5"

Then configure LogstashEncoder as encoder in the appender, in logback-spring.groovy/logback-spring.xml (or logabck.xml)

2. Have some filters or libraries to write the access log

For 2. Either use

A. Use "net.rakugakibox.springbootext:spring-boot-ext-logback-access:1.6" library

(This is what I am using)

It gives in a nice json format, as follows

{
   "@timestamp":"2017-03-29T09:43:09.536-05:00",
   "@version":1,
   "@message":"0:0:0:0:0:0:0:1 - - [2017-03-29T09:43:09.536-05:00] \"GET /orders/v1/items/42 HTTP/1.1\" 200 991",
   "@fields.method":"GET",
   "@fields.protocol":"HTTP/1.1",
   "@fields.status_code":200,
   "@fields.requested_url":"GET /orders/v1/items/42 HTTP/1.1",
   "@fields.requested_uri":"/orders/v1/items/42",
   "@fields.remote_host":"0:0:0:0:0:0:0:1",
   "@fields.HOSTNAME":"0:0:0:0:0:0:0:1",
   "@fields.content_length":991,
   "@fields.elapsed_time":48,
   "HOSTNAME":"ABCD"
}

OR

B. Use Logback's Tee Filter

OR

C. Spring's CommonsRequestLoggingFilter (Did not really test this out)

Add a bean definition

    @Bean
    public CommonsRequestLoggingFilter requestLoggingFilter() {
        CommonsRequestLoggingFilter crlf = new CommonsRequestLoggingFilter();
        crlf.setIncludeClientInfo(true);
        crlf.setIncludeQueryString(true);
        crlf.setIncludePayload(true);
        return crlf;
    }

Then set org.springframework.web.filter.CommonsRequestLoggingFilter to DEBUG, this can be done using the application.properties by adding:

logging.level.org.springframework.web.filter.CommonsRequestLoggingFilter=DEBUG


来源: stackexchange

问:
ajax calling php loop with form not working on first loop only
I have a page called events.php that lists past and upcoming events, using ajax to call on pastevents.php and upcomingevents.php, which both have forms that collect users' opinions on past events and whether they will attend future events; then a handle sends it to psql db.

Everything works except the first iteration of the looped form does not submit correctly. Instead of continuing onto pastevents-handle.php, it doesn't post and returns a get on events.php; so I see the user's response in the url bar, but it never gets to the db. I made a test page that didn't use ajax by copy-pasting all the code and that works, so it's definitely something to do with ajax, but neither me or my professor could find out what.

I don't know how to use jquery yet, so please answer with plain javascript.

Here's events.php:

```<code>   <script>
    //show past events
    function showPastEvents(str) {
        document.getElementById('pastevents').style.display = "block";
        document.getElementById('hideoldbutton').style.display = "block";
        var xhttp;
        if (str == "") {
            document.getElementById("pastevents").innerHTML = "";
            return;
        }
        xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById("pastevents").innerHTML = this.responseText;
            }
        };
        xhttp.open("POST", "pastevents.php?q="+str, true);
        xhttp.send();
    }

    function hidePastEvents() {
        document.getElementById('pastevents').style.display = "none";
        document.getElementById('hideoldbutton').style.display = "none";
    }

    //show upcoming events
    function showUpcomingEvents(str) {
        document.getElementById('upcomingevents').style.display = "block";
        document.getElementById('hidenewbutton').style.display = "block";
        var xhttp;
        if (str == "") {
            document.getElementById("upcomingevents").innerHTML = "";
            return;
        }
        xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById("upcomingevents").innerHTML = this.responseText;
            }
        };
        xhttp.open("POST", "upcomingevents.php?q="+str, true);
        xhttp.send();
    }

    function hideUpcomingEvents() {
        document.getElementById('upcomingevents').style.display = "none";
        document.getElementById('hidenewbutton').style.display = "none";
    }
</script>
</code>```

```<code>        <!-- page content -->
        <div class="content">

            <h6>Past events</h6>

            <form name="postpastevents" action=""/>
                <div id="pastevents"></div>
                <input type="button" onClick="hidePastEvents()" id="hideoldbutton" value="Hide" style="display:none;"/>

            </form>

            <input type="button" onClick="showPastEvents()" id="showoldbutton" value="Show past"/>

            <br>
            <br>

            <!-- ####### -->
            <h6>Upcoming events</h6>

            <form name="postupcomingevents" action=""/>
                <div id="upcomingevents"></div>
                <input type="button" onClick="hideUpcomingEvents()" id="hidenewbutton" value="Hide" style="display:none;"/>

            </form>

            <input type="button" onClick="showUpcomingEvents()" id="shownewbutton" value="Show upcoming"/>
</code>```

Here is pastevents.php (it's the same code for upcomingevents.php):

```<code>    <?php
        $conn = pg_connect ('dbname=xxxx') or die ('Connect failed ');

        $query = "SELECT eventname, eventdate, location, eventdesc FROM events WHERE eventdate < current_date ORDER BY eventdate;";
        $result = pg_query($query);

        while ( $row = pg_fetch_assoc($result) ) {
            $i = 0;
            echo "<tr>"; //table row
            foreach ($row as $key => $value) {
                if ($i == 0) {
                    $eventname = $value;
                }
                if ($i == 1) {
                    $eventdate = $value;
                }
                $eventinfo = $value;
                echo "<td>"; //1 column each loop
                    echo "$eventinfo";
                    if ($i == 1) {
                        echo date(" (l, F jS)", strtotime($eventdate));
                    }
                    echo "<br><br>";
                echo "</td>";
                $i++;
            }
            echo "<td>";//1 column while same event
                ?>
                <div>
                    <form name="pasteventsurvey" action="pastevent-handle.php" method="post">
                        What did you think of the event?
                        <select name="pasteventopinion">
                                <option value="">(Choose one)</option>
                                <option value="good">Loved it!</option>
                                <option value="okay">Liked it</option>
                                <option value="bad">Needs improvement</option>
                                <option value="time">Time conflict</option>
                                <option value="NA">NA</option>
                        </select>
                        <input type="hidden" name="eventname" value="<?php echo $eventname; ?>">
                        <input type="submit" name="enter" value="Submit"><input type="reset" name="erase" value="Clear">
                    </form>
                </div>
            <?php
            echo "</td>";

            echo "</tr>"; //-table row
        }

        pg_close($conn);
    ?>
</code>```

Here's pastevents-handle.php:

```<code>    <?php
    $conn = pg_connect ('dbname=xxxx') or die ('Connect failed ');

    pg_query_params("INSERT INTO eventsurveypast(eventname, opinion) VALUES ($1, $2)", array($name, $opinion));

    echo "email is $idkey, eventname is $name, pastopinion is $opinion";

    pg_close($conn);
?>
</code>```

(I edited a bit for space, ignore anything that isn't vital)

答:
It is illegal to have a form inside another form.

Remove the outer form and everything should work fine, except you have another problem with the code.

ContentLicense: CC BY-SA 3.0

Body:
I have a page called events.php that lists past and upcoming events, using ajax to call on pastevents.php and upcomingevents.php, which both have forms that collect users' opinions on past events and whether they will attend future events; then a handle sends it to psql db.

Everything works except the first iteration of the looped form does not submit correctly. Instead of continuing onto pastevents-handle.php, it doesn't post and returns a get on events.php; so I see the user's response in the url bar, but it never gets to the db. I made a test page that didn't use ajax by copy-pasting all the code and that works, so it's definitely something to do with ajax, but neither me or my professor could find out what.

I don't know how to use jquery yet, so please answer with plain javascript.

Here's events.php:

Past events

            <form name="postpastevents" action=""/>

                <input type="button" onClick="hidePastEvents()" id="hideoldbutton" value="Hide" style="display:none;"/>

            </form>

            <input type="button" onClick="showPastEvents()" id="showoldbutton" value="Show past"/>

Upcoming events

            <form name="postupcomingevents" action=""/>

                <input type="button" onClick="hideUpcomingEvents()" id="hidenewbutton" value="Hide" style="display:none;"/>

            </form>

            <input type="button" onClick="showUpcomingEvents()" id="shownewbutton" value="Show upcoming"/>

Here is pastevents.php (it's the same code for upcomingevents.php):

    <?php
        $conn = pg_connect ('dbname=xxxx') or die ('Connect failed ');

        $query = "SELECT eventname, eventdate, location, eventdesc FROM events WHERE eventdate < current_date ORDER BY eventdate;";
        $result = pg_query($query);

        while ( $row = pg_fetch_assoc($result) ) {
            $i = 0;
            echo "
"; //table row
            foreach ($row as $key => $value) {
                if ($i == 0) {
                    $eventname = $value;
                }
                if ($i == 1) {
                    $eventdate = $value;
                }
                $eventinfo = $value;
                echo ""; //1 column each loop
                    echo "$eventinfo";
                    if ($i == 1) {
                        echo date(" (l, F jS)", strtotime($eventdate));
                    }
                    echo "

";
                echo "	";
                $i++;
            }
            echo "";//1 column while same event
                ?>

                    <form name="pasteventsurvey" action="pastevent-handle.php" method="post">
                        What did you think of the event?
                        <select name="pasteventopinion">
                                <option value="">(Choose one)</option>
                                <option value="good">Loved it!</option>
                                <option value="okay">Liked it</option>
                                <option value="bad">Needs improvement</option>
                                <option value="time">Time conflict</option>
                                <option value="NA">NA</option>
                        </select>
                        <input type="hidden" name="eventname" value="<?php echo $eventname; ?>">
                        <input type="submit" name="enter" value="Submit"><input type="reset" name="erase" value="Clear">
                    </form>

            <?php
            echo "	";

            echo "
"; //-table row
        }

        pg_close($conn);
    ?>

Here's pastevents-handle.php:

    <?php
    $conn = pg_connect ('dbname=xxxx') or die ('Connect failed ');

    pg_query_params("INSERT INTO eventsurveypast(eventname, opinion) VALUES ($1, $2)", array($name, $opinion));

    echo "email is $idkey, eventname is $name, pastopinion is $opinion";

    pg_close($conn);
?>

(I edited a bit for space, ignore anything that isn't vital)


问:
Set list of elements in object to nil
I have a Waypoint object and want to set several of it's elements to nil:

```<code>waypoint.cep = nil
waypoint.street = nil
waypoint.number = nil
waypoint.district = nil
waypoint.city = nil
waypoint.state = nil
</code>```

There are other elements in the object that I do not want to reset. But still I am sure that there is a prettier way to do it.

Any ideas?

答:
You could use:</p>

```<code>%w[ cep street number district city state ].each do |attr|
  waypoint.send("#{attr}=", nil)
end
</code>```

Title: Set list of elements in object to nil

Body:
I have a Waypoint object and want to set several of it's elements to nil:

waypoint.cep = nil
waypoint.street = nil
waypoint.number = nil
waypoint.district = nil
waypoint.city = nil
waypoint.state = nil

There are other elements in the object that I do not want to reset. But still I am sure that there is a prettier way to do it.

Any ideas?

Body:
You could use:

%w[ cep street number district city state ].each do |attr|
  waypoint.send("#{attr}=", nil)
end


问:
Image is being displayed as white box in Django template
The images are showing up as blank boxes. I'm confused as to why this is the case.

Models.py

```<code>class Aircraft(AirlineModelBase):
    image = models.ImageField(upload_to="uploads/airline", blank=True, null=True)
</code>```

Settings.py

```<code>STATIC_URL = '/static/'
STATICFILES_DIRS = [ map_path('static'),]
</code>```

Template

```<code><div class="box"><img src="{{ aircraft.image }}" alt="{{ image.title }}"/>
</code>```

答:
Try this:

```<code><div class="box"><img src="{{ aircraft.image.url }}" alt="{{ image.title }}"/>
</code>```

You are referencing the image object instead of the actual url of the image.

Also the {{ image.title }} will not be rendered since there is no such title field in your model. Maybe you mean this {{ aircraft.title }}

Body:
The images are showing up as blank boxes. I'm confused as to why this is the case.

Models.py

class Aircraft(AirlineModelBase):
    image = models.ImageField(upload_to="uploads/airline", blank=True, null=True)

Settings.py

STATIC_URL = '/static/'
STATICFILES_DIRS = [ map_path('static'),]

Template

Body:
Try this:

<div class="box"><img src="{{ aircraft.image.url }}" alt="{{ image.title }}"/>

You are referencing the image object instead of the actual url of the image.

Also the {{ image.title }} will not be rendered since there is no such title field in your model. Maybe you mean this {{ aircraft.title }}


问:
MS (Project) Find Strings in text10 and change font color
I'm changing the color of font in MS Project based on Percentage complete and Names in text10 column.  The percentages work however can someone give me a steer on the names I would be grateful, I want to highlight in teal if for example "David" or "Darren" or both are in Text10 field.

Any help gratefully received.

```<code>Sub text()

Dim Ctr As Integer

ViewApply "Gantt Chart"
OutlineShowAllTasks
FilterApply "All Tasks"
SelectAll

For Ctr = 1 To ActiveSelection.Tasks.Count
    SelectRow Row:=Ctr, rowrelative:=False
    If Not ActiveSelection.Tasks(1) Is Nothing Then
        If ActiveSelection.Tasks(1).Text10 = ("David") & ("Darren") Then
            Font Color:=pjTeal
        Else
            If ActiveSelection.Tasks(1).PercentComplete = 100 Then
                Font Color:=pjGreen
            Else
                If ActiveSelection.Tasks(1).PercentComplete = 0 Then
                    Font Color:=pjBlack
                Else
                    If ActiveSelection.Tasks(1).PercentComplete > 0 < 100 Then
                        Font Color:=pjBlue
                    Else
                    End If
                End If
            End If
        End If
    End If
Next Ctr

End Sub
</code>```

答:
Change:

```<code>If ActiveSelection.Tasks(1).Text10 = ("David") & ("Darren") Then
</code>```

To:

```<code>If ActiveSelection.Tasks(1).Text10 = "David" Or ActiveSelection.Tasks(1).Text10 = "Darren" Then
</code>```

Edit 1: Better style of coding (untested as I don't have MS-Project installed at home - can test it tomorrow morning)

```<code>Option Explicit

Sub text()

ViewApply "Gantt Chart"
OutlineShowAllTasks
FilterApply "All Tasks"

Dim T As Task

For Each T In ActiveProject.Tasks
    If Not T Is Nothing Then
        SelectRow T.UniqueID, RowRelative:=False '<-- there's no escape, in Ms-Project you need to select the Task's row in order to modify it's Font color
        If T.Text10 = "David" Or T.Text10 = "Darren" Then
            Font Color:=pjTeal
        Else
            Select Case T.PercentComplete
                Case 100
                    Font Color:=pjGreen
                Case 0
                    Font Color:=pjBlack
                Case Else
                    Font Color:=pjBlue
            End Select
        End If
    End If
Next T

End Sub
</code>```

Edit 2: added a new logics for added information by PO.

```<code>Option Explicit

Sub ColorTasks()

ViewApply "Gantt Chart"
OutlineShowAllTasks
FilterApply "All Tasks"

Dim T As Task

For Each T In ActiveProject.Tasks
    If Not T Is Nothing Then
        SelectRow T.ID, RowRelative:=False

        Select Case T.Text10
            Case "David"
                 Font Color:=pjBlue
            Case "Mary"
                Font Color:=pjTeal
            Case "Bill"
                Font Color:=pjBlack
            Case "Sandra"
                Font Color:=pjPurple
        End Select

        ' I think you wanted this outside the case of the people in Text10
        If T.PercentComplete = 100 Then
            Font Color:=pjGreen
        Else
            If DateDiff("d", T.Finish, ActiveProject.CurrentDate) > 0 Then
                Font Color:=pjRed
            End If
        End If
    End If
Next T

End Sub
</code>```

Body:
I'm changing the color of font in MS Project based on Percentage complete and Names in text10 column.  The percentages work however can someone give me a steer on the names I would be grateful, I want to highlight in teal if for example "David" or "Darren" or both are in Text10 field.

Any help gratefully received.

Sub text()

Dim Ctr As Integer

ViewApply "Gantt Chart"
OutlineShowAllTasks
FilterApply "All Tasks"
SelectAll

For Ctr = 1 To ActiveSelection.Tasks.Count
    SelectRow Row:=Ctr, rowrelative:=False
    If Not ActiveSelection.Tasks(1) Is Nothing Then
        If ActiveSelection.Tasks(1).Text10 = ("David") & ("Darren") Then
            Font Color:=pjTeal
        Else
            If ActiveSelection.Tasks(1).PercentComplete = 100 Then
                Font Color:=pjGreen
            Else
                If ActiveSelection.Tasks(1).PercentComplete = 0 Then
                    Font Color:=pjBlack
                Else
                    If ActiveSelection.Tasks(1).PercentComplete > 0 < 100 Then
                        Font Color:=pjBlue
                    Else
                    End If
                End If
            End If
        End If
    End If
Next Ctr

End Sub

Body:
Change:

If ActiveSelection.Tasks(1).Text10 = ("David") & ("Darren") Then

To:

If ActiveSelection.Tasks(1).Text10 = "David" Or ActiveSelection.Tasks(1).Text10 = "Darren" Then

Edit 1: Better style of coding (untested as I don't have MS-Project installed at home - can test it tomorrow morning)

Option Explicit

Sub text()

ViewApply "Gantt Chart"
OutlineShowAllTasks
FilterApply "All Tasks"

Dim T As Task

For Each T In ActiveProject.Tasks
    If Not T Is Nothing Then
        SelectRow T.UniqueID, RowRelative:=False '<-- there's no escape, in Ms-Project you need to select the Task's row in order to modify it's Font color
        If T.Text10 = "David" Or T.Text10 = "Darren" Then
            Font Color:=pjTeal
        Else
            Select Case T.PercentComplete
                Case 100
                    Font Color:=pjGreen
                Case 0
                    Font Color:=pjBlack
                Case Else
                    Font Color:=pjBlue
            End Select
        End If
    End If
Next T

End Sub

Edit 2: added a new logics for added information by PO.

Option Explicit

Sub ColorTasks()

ViewApply "Gantt Chart"
OutlineShowAllTasks
FilterApply "All Tasks"

Dim T As Task

For Each T In ActiveProject.Tasks
    If Not T Is Nothing Then
        SelectRow T.ID, RowRelative:=False

        Select Case T.Text10
            Case "David"
                 Font Color:=pjBlue
            Case "Mary"
                Font Color:=pjTeal
            Case "Bill"
                Font Color:=pjBlack
            Case "Sandra"
                Font Color:=pjPurple
        End Select

        ' I think you wanted this outside the case of the people in Text10
        If T.PercentComplete = 100 Then
            Font Color:=pjGreen
        Else
            If DateDiff("d", T.Finish, ActiveProject.CurrentDate) > 0 Then
                Font Color:=pjRed
            End If
        End If
    End If
Next T

End Sub


问:
How can I prevent NAN issues?
I'm getting Mean of empty slice runtime warnings.
When I print out what my variables are (numpy arrays), several
of them contain nan values. The Runtime Warning is looking at line
58 as the issue. What can I change to make it work?

Sometimes the program will run with no issues. Most times it does
not.

This is a K-Means from scratch algorithm that is clustering
the iris data set. It first prompts the users for the amount of
centroids they want (clusters). It then randomly generates said
number of clusters in the given range from the numbers in the loaded
in text file.

I have the break value in the else statement to prevent infinite
loops.

Is it because I am having numbers go below zero when I subtract the
Centroids from the data points in the file?

Error I get when I run:

```<code>How Many Centrouds? 3
Dimensionality of Data:  (150, 4)
Starting Centroiuds:
 [[ 1.4  7.9  0.2  3.4]
 [ 7.8  0.2  4.3  1.4]
 [ 5.7  6.9  3.   6.6]]
t0 :
 [[[-3.7  4.4 -1.2  3.2]
  [ 2.7 -3.3  2.9  1.2]
  [ 0.6  3.4  1.6  6.4]]

 [[-3.5  4.9 -1.2  3.2]
  [ 2.9 -2.8  2.9  1.2]
  [ 0.8  3.9  1.6  6.4]]

 [[-3.3  4.7 -1.1  3.2]
  [ 3.1 -3.   3.   1.2]
  [ 1.   3.7  1.7  6.4]]

 ...,
 [[-5.1  4.9 -5.   1.4]
  [ 1.3 -2.8 -0.9 -0.6]
  [-0.8  3.9 -2.2  4.6]]

 [[-4.8  4.5 -5.2  1.1]
  [ 1.6 -3.2 -1.1 -0.9]
  [-0.5  3.5 -2.4  4.3]]

 [[-4.5  4.9 -4.9  1.6]
  [ 1.9 -2.8 -0.8 -0.4]
  [-0.2  3.9 -2.1  4.8]]]

Warning (from warnings module):
  File "C:\Python27\lib\site-packages\numpy\core\_methods.py", line 59
    warnings.warn("Mean of empty slice.", RuntimeWarning)
RuntimeWarning: Mean of empty slice.

Warning (from warnings module):
  File "C:\Python27\lib\site-packages\numpy\core\_methods.py", line 68
    ret, rcount, out=ret, casting='unsafe', subok=False)
RuntimeWarning: invalid value encountered in true_divide
---------------
Starting Centroids:

[[ 1.4  7.9  0.2  3.4]
 [ 7.8  0.2  4.3  1.4]
 [ 5.7  6.9  3.   6.6]]

Starting NewMeans:

[[        nan         nan         nan         nan]
 [ 5.84333333  3.054       3.75866667  1.19866667]
 [        nan         nan         nan         nan]]
Starting Centroids Now:

[[        nan         nan         nan         nan]
 [ 5.84333333  3.054       3.75866667  1.19866667]
 [        nan         nan         nan         nan]]

NewMeans now:
[[        nan         nan         nan         nan]
 [ 5.84333333  3.054       3.75866667  1.19866667]
 [        nan         nan         nan         nan]]
</code>```

Python Code:

```<code>import numpy as np
from pprint import pprint
import random
import sys
import warnings

arglist = sys.argv

#UNCOMMENT BELOW IN FINAL PROGRAM
'''
NoOfCentroids = int(arglist[2])
dataPointsFromFile = np.array(np.loadtxt(sys.argv[1], delimiter = ','))
'''

dataPointsFromFile = np.array(np.loadtxt('iris.txt', delimiter = ','))

NoOfCentroids = input('How Many Centrouds? ')

dataRange = ([])

#UNCOMMENT BELOW IN FINAL PROGRAM
'''
with open(arglist[1]) as f:
    print 'Points in data set: ',sum(1 for _ in f)
'''
dataRange.append(round(np.amin(dataPointsFromFile),1))
dataRange.append(round(np.amax(dataPointsFromFile),1))
dataRange = np.asarray(dataRange)

dataPoints = np.array(dataPointsFromFile)
print 'Dimensionality of Data: ', dataPoints.shape

randomCentroids = []
data = ([])
templist = []
i = 0

while i<NoOfCentroids:
    for j in range(len(dataPointsFromFile[1,:])):
        cat = round(random.uniform(np.amin(dataPointsFromFile),np.amax(dataPointsFromFile)),1)
        templist.append(cat)
    randomCentroids.append(templist)
    templist = []
    i = i+1

centroids = np.asarray(randomCentroids)

def kMeans(array1, array2):
    ConvergenceCounter = 1
    keepGoing = True
    StartingCentroids = np.copy(centroids)
    print 'Starting Centroiuds:\n {}'.format(StartingCentroids)
    while keepGoing:
        #--------------Find The new means---------#
        t0 = StartingCentroids[None, :, :] - dataPoints[:, None, :]
        print 't0 :\n {}'.format(t0)
        t1 = np.linalg.norm(t0, axis=-1)
        t2 = np.argmin(t1, axis=-1)
        #------Push the new means to a new array for comparison---------#
        CentroidMeans = []
        for x in range(len(StartingCentroids)):
            CentroidMeans.append(np.mean(dataPoints[t2 == [x]], axis=0))
        #--------Convert to a numpy array--------#
        NewMeans = np.asarray(CentroidMeans)
        #------Compare the New Means with the Starting Means------#
        if np.array_equal(NewMeans,StartingCentroids):
            print ('Convergence has been reached after {} moves'.format(ConvergenceCounter))
            print ('Starting Centroids:\n{}'.format(centroids))
            print ('Final Means:\n{}'.format(NewMeans))
            print ('Final Cluster assignments: {}'.format(t2))
            for x in xrange(len(StartingCentroids)):
                print ('Cluster {}:\n'.format(x)), dataPoints[t2 == [x]]
            for x in xrange(len(StartingCentroids)):
                print ('Size of Cluster {}:'.format(x)), len(dataPoints[t2 == [x]])
            keepGoing = False
        else:
            print 15*'-'
            ConvergenceCounter  = ConvergenceCounter +1
            print 'Starting Centroids:\n'
            print StartingCentroids
            print '\n'
            print 'Starting NewMeans:\n'
            print NewMeans
            StartingCentroids =np.copy(NewMeans)
            print 'Starting Centroids Now:\n'
            print StartingCentroids
            print '\n'
            print 'NewMeans now:'
            print NewMeans
            break

kMeans(centroids, dataPoints)
</code>```

答:
I assume the warning comes up in

```<code>np.mean(dataPoints[t2 == [x]], axis=0)
</code>```

If t2 == [x] is all False (no match between t2 and x, then dataPoints[...] will be an empty array, resulting in the mean warning.

I think you need to be more careful with that test.  Maybe even skip the mean if the masked array is empty.

== tests with floating values are unpredictable.  You need to use something like np.isclose or np.allclose to test equivalence with a tolerance.

The second warning comes from later in  the mean calc, presumably when trying to divide by 0, the number of elements.

The full mean code can be found in numpy.core._methods.py.

In sum, don't try to take the mean of an empty array.

Title: How can I prevent NAN issues?

Body:
I'm getting Mean of empty slice runtime warnings.
When I print out what my variables are (numpy arrays), several
of them contain nan values. The Runtime Warning is looking at line
58 as the issue. What can I change to make it work?

Sometimes the program will run with no issues. Most times it does
not.

This is a K-Means from scratch algorithm that is clustering
the iris data set. It first prompts the users for the amount of
centroids they want (clusters). It then randomly generates said
number of clusters in the given range from the numbers in the loaded
in text file.

I have the break value in the else statement to prevent infinite
loops.

Is it because I am having numbers go below zero when I subtract the
Centroids from the data points in the file?

Error I get when I run:

How Many Centrouds? 3
Dimensionality of Data:  (150, 4)
Starting Centroiuds:
 [[ 1.4  7.9  0.2  3.4]
 [ 7.8  0.2  4.3  1.4]
 [ 5.7  6.9  3.   6.6]]
t0 :
 [[[-3.7  4.4 -1.2  3.2]
  [ 2.7 -3.3  2.9  1.2]
  [ 0.6  3.4  1.6  6.4]]

 [[-3.5  4.9 -1.2  3.2]
  [ 2.9 -2.8  2.9  1.2]
  [ 0.8  3.9  1.6  6.4]]

 [[-3.3  4.7 -1.1  3.2]
  [ 3.1 -3.   3.   1.2]
  [ 1.   3.7  1.7  6.4]]

 ...,
 [[-5.1  4.9 -5.   1.4]
  [ 1.3 -2.8 -0.9 -0.6]
  [-0.8  3.9 -2.2  4.6]]

 [[-4.8  4.5 -5.2  1.1]
  [ 1.6 -3.2 -1.1 -0.9]
  [-0.5  3.5 -2.4  4.3]]

 [[-4.5  4.9 -4.9  1.6]
  [ 1.9 -2.8 -0.8 -0.4]
  [-0.2  3.9 -2.1  4.8]]]

Warning (from warnings module):
  File "C:\Python27\lib\site-packages\numpy\core\_methods.py", line 59
    warnings.warn("Mean of empty slice.", RuntimeWarning)
RuntimeWarning: Mean of empty slice.

Warning (from warnings module):
  File "C:\Python27\lib\site-packages\numpy\core\_methods.py", line 68
    ret, rcount, out=ret, casting='unsafe', subok=False)
RuntimeWarning: invalid value encountered in true_divide
---------------
Starting Centroids:

[[ 1.4  7.9  0.2  3.4]
 [ 7.8  0.2  4.3  1.4]
 [ 5.7  6.9  3.   6.6]]

Starting NewMeans:

[[        nan         nan         nan         nan]
 [ 5.84333333  3.054       3.75866667  1.19866667]
 [        nan         nan         nan         nan]]
Starting Centroids Now:

[[        nan         nan         nan         nan]
 [ 5.84333333  3.054       3.75866667  1.19866667]
 [        nan         nan         nan         nan]]

NewMeans now:
[[        nan         nan         nan         nan]
 [ 5.84333333  3.054       3.75866667  1.19866667]
 [        nan         nan         nan         nan]]

Python Code:

import numpy as np
from pprint import pprint
import random
import sys
import warnings

arglist = sys.argv

#UNCOMMENT BELOW IN FINAL PROGRAM
'''
NoOfCentroids = int(arglist[2])
dataPointsFromFile = np.array(np.loadtxt(sys.argv[1], delimiter = ','))
'''

dataPointsFromFile = np.array(np.loadtxt('iris.txt', delimiter = ','))

NoOfCentroids = input('How Many Centrouds? ')

dataRange = ([])

#UNCOMMENT BELOW IN FINAL PROGRAM
'''
with open(arglist[1]) as f:
    print 'Points in data set: ',sum(1 for _ in f)
'''
dataRange.append(round(np.amin(dataPointsFromFile),1))
dataRange.append(round(np.amax(dataPointsFromFile),1))
dataRange = np.asarray(dataRange)

dataPoints = np.array(dataPointsFromFile)
print 'Dimensionality of Data: ', dataPoints.shape

randomCentroids = []
data = ([])
templist = []
i = 0

while i<NoOfCentroids:
    for j in range(len(dataPointsFromFile[1,:])):
        cat = round(random.uniform(np.amin(dataPointsFromFile),np.amax(dataPointsFromFile)),1)
        templist.append(cat)
    randomCentroids.append(templist)
    templist = []
    i = i+1

centroids = np.asarray(randomCentroids)

def kMeans(array1, array2):
    ConvergenceCounter = 1
    keepGoing = True
    StartingCentroids = np.copy(centroids)
    print 'Starting Centroiuds:\n {}'.format(StartingCentroids)
    while keepGoing:
        #--------------Find The new means---------#
        t0 = StartingCentroids[None, :, :] - dataPoints[:, None, :]
        print 't0 :\n {}'.format(t0)
        t1 = np.linalg.norm(t0, axis=-1)
        t2 = np.argmin(t1, axis=-1)
        #------Push the new means to a new array for comparison---------#
        CentroidMeans = []
        for x in range(len(StartingCentroids)):
            CentroidMeans.append(np.mean(dataPoints[t2 == [x]], axis=0))
        #--------Convert to a numpy array--------#
        NewMeans = np.asarray(CentroidMeans)
        #------Compare the New Means with the Starting Means------#
        if np.array_equal(NewMeans,StartingCentroids):
            print ('Convergence has been reached after {} moves'.format(ConvergenceCounter))
            print ('Starting Centroids:\n{}'.format(centroids))
            print ('Final Means:\n{}'.format(NewMeans))
            print ('Final Cluster assignments: {}'.format(t2))
            for x in xrange(len(StartingCentroids)):
                print ('Cluster {}:\n'.format(x)), dataPoints[t2 == [x]]
            for x in xrange(len(StartingCentroids)):
                print ('Size of Cluster {}:'.format(x)), len(dataPoints[t2 == [x]])
            keepGoing = False
        else:
            print 15*'-'
            ConvergenceCounter  = ConvergenceCounter +1
            print 'Starting Centroids:\n'
            print StartingCentroids
            print '\n'
            print 'Starting NewMeans:\n'
            print NewMeans
            StartingCentroids =np.copy(NewMeans)
            print 'Starting Centroids Now:\n'
            print StartingCentroids
            print '\n'
            print 'NewMeans now:'
            print NewMeans
            break

kMeans(centroids, dataPoints)

Body:
I assume the warning comes up in

np.mean(dataPoints[t2 == [x]], axis=0)

If t2 == [x] is all False (no match between t2 and x, then dataPoints[...] will be an empty array, resulting in the mean warning.

I think you need to be more careful with that test.  Maybe even skip the mean if the masked array is empty.

== tests with floating values are unpredictable.  You need to use something like np.isclose or np.allclose to test equivalence with a tolerance.

The second warning comes from later in  the mean calc, presumably when trying to divide by 0, the number of elements.

The full mean code can be found in numpy.core._methods.py.

In sum, don't try to take the mean of an empty array.


问:
Slide and fade jquery
How can i slide a div in whilst it fades in using jquery.  I guess it would need to be offset slightly from the position stipulated within the style sheet.

So for example this div would slide in from the left whilst fading into 100% from 0.

```<code><div id="pageintro">We are a wholly independent</div>
</code>```

答:
Assuming the element is already hidden / opacity at 0:

```<code>$('#pageintro').animate({
    opacity: 1,
    left: '+=100'
}, 1000);
</code>```

The above example will only work on elements with the 'left:'  css attribute defined :)

Alternatively:

```<code>$('#pageintro').animate({
    opacity: 1,
    marginLeft: '+=100'
}, 1000);
</code>```

This will work on most elements :)

They will move the element 100px from the left to the right and from 0 opacity to 1 (completely visible) in 1 second.

:)

ContentLicense: CC BY-SA 2.5

Title: Slide and fade jquery

Body:
How can i slide a div in whilst it fades in using jquery.  I guess it would need to be offset slightly from the position stipulated within the style sheet.

So for example this div would slide in from the left whilst fading into 100% from 0.

We are a wholly independent

Body:
Assuming the element is already hidden / opacity at 0:

$('#pageintro').animate({
    opacity: 1,
    left: '+=100'
}, 1000);

The above example will only work on elements with the 'left:'  css attribute defined :)

Alternatively:

$('#pageintro').animate({
    opacity: 1,
    marginLeft: '+=100'
}, 1000);

This will work on most elements :)

They will move the element 100px from the left to the right and from 0 opacity to 1 (completely visible) in 1 second.

:)


问:
Ajax call is returning [object Object]
Html

```<code><div>
    <select id="method">
        <option value="get">GET</option>
        <option value="post">POST</option>
        <option value="put">PUT</option>
    </select>
    <input type="button" value="Try it" onclick="sendRequest()" />
    <span id='value1'>(Result)</span>
</div>
</code>```

Jquery

```<code>@section scripts {
    <script>
        // TODO: Replace with the URL of your WebService app
        var serviceUrl = 'http://localhost:99999/api/books';

        function sendRequest() {
            var method = $('#method').val();

            $.ajax({
                type: method,
                url: serviceUrl,
                dataType: 'json',
                success: function (data) {
                    $('#value1').text(data);
                    console.log(data);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    $('#value1').text(jqXHR.responseText || textStatus);
                }
            });
        }
    </script>
</code>```

The success function is showing up with arrays of [object, Object]. The console shows the data for each object, but it is not showing on the page.

For each book, I have to list the Id, Title, and the Author.

```<code>public IHttpActionResult Get()
        {
            IQueryable<BookDTO> books;
            books = from b in db.Books
                    select new BookDTO()
                    {
                        Id = b.Id,
                        Title = b.Title,
                        AuthorName = b.Author.Name
                    };
            return Ok(books);
</code>```

console.log Output

答:
Since you now know that data is an array, you can use Array#forEach to iterate through it.

You'd have to modify your html to give the container
 an id to target and exclude the first  element .

You could then append an HTML element at each iteration containing the data for each element in the data array:

```<code><div id="container">
  <select id="method">
    <option value="get">GET</option>
    <option value="post">POST</option>
    <option value="put">PUT</option>
  </select>
  <input type="button" value="Try it" onclick="sendRequest()" />
  <!--- <span id='value1'>(Result)</span> remove because these can be added dynamically --->
</div>
</code>```

Then your success callback would look like:

```<code>success: function (data) {
  data.forEach(function(dataObj, index){
    var id = dataObj.Id,
      title = dataObj.Title,
      author  = dataObj.AuthorName;

    // Target div.container and append a span for every element in the data array
    $('#container').append(
      '<span>' +
        '<h3>' + title + '</h3>' +
        '<p>' + author + '</p>' +
      '</span>'
    );
  });
}
</code>```

Title: Ajax call is returning [object Object]

Body:
Html

    <select id="method">
        <option value="get">GET</option>
        <option value="post">POST</option>
        <option value="put">PUT</option>
    </select>
    <input type="button" value="Try it" onclick="sendRequest()" />
    (Result)

Jquery

@section scripts {

The success function is showing up with arrays of [object, Object]. The console shows the data for each object, but it is not showing on the page.

For each book, I have to list the Id, Title, and the Author.

public IHttpActionResult Get()
        {
            IQueryable<BookDTO> books;
            books = from b in db.Books
                    select new BookDTO()
                    {
                        Id = b.Id,
                        Title = b.Title,
                        AuthorName = b.Author.Name
                    };
            return Ok(books);

console.log Output

Body:
Since you now know that data is an array, you can use Array#forEach to iterate through it.

You'd have to modify your html to give the container <div> an id to target and exclude the first <span> element .

You could then append an HTML element at each iteration containing the data for each element in the data array:

<div id="container">
  <select id="method">
    <option value="get">GET</option>
    <option value="post">POST</option>
    <option value="put">PUT</option>
  </select>
  <input type="button" value="Try it" onclick="sendRequest()" />
  <!--- <span id='value1'>(Result)</span> remove because these can be added dynamically --->
</div>

Then your success callback would look like:

success: function (data) {
  data.forEach(function(dataObj, index){
    var id = dataObj.Id,
      title = dataObj.Title,
      author  = dataObj.AuthorName;

    // Target div.container and append a span for every element in the data array
    $('#container').append(
      '<span>' +
        '<h3>' + title + '</h3>' +
        '<p>' + author + '</p>' +
      '</span>'
    );
  });
}


问:
For loop with two input files
I wish to use a for loop for a command that requires two input files. There is a single character change between the two files. Here are two example files:

```<code>Fay2_TCCGGAGA-CCTATCCT_L001_R1_001.fastq
Fay2_TCCGGAGA-CCTATCCT_L001_R2_001.fastq
</code>```

Here is my attempt of the command:

```<code>for f in /directory/*R1*.fastq
 pref=${basename "$f" _*R1*.fastq}
command input1 $f input2 ${pref}_*R2*.fastq
</code>```

The issue most likely lies in manipulating the basename so the loop uses the permutation of file1 to find file2. How do I make the basename shorter than the entire file name. I am getting the error

```<code>Fay2_TCCGGAGA-CCTATCCT_L001_R2_001.fastq_*R2.fastq does not exist
</code>```

Thanks to comments below the looping is working properly but my files are being overwritten whenever a the command loops over a new file. The following is my entire command which requires naming both output files.

```<code>for f1 in /directory/*R1*.fastq
f2="${f1/_R1_/_R2_}"
 pref=${basename "$f" _*R1*.fastq}
command output1 ${pref}_trim_R1.fastq output2 ${pref}_trim_R2.fastq input1 $f input2 $f2
</code>```

答:
You can loop through the R1 files and use brace expansion to derive R2 file names:</p>

```<code>for r1_file in /directory/*_R1_*.fastq; do
  r2_file="${r1_file/_R1_/_R2_}"
  command input1 "$r1_file" input2 "$r2_file"
done
</code>```

Title: For loop with two input files

Body:
I wish to use a for loop for a command that requires two input files. There is a single character change between the two files. Here are two example files:

Fay2_TCCGGAGA-CCTATCCT_L001_R1_001.fastq
Fay2_TCCGGAGA-CCTATCCT_L001_R2_001.fastq

Here is my attempt of the command:

for f in /directory/*R1*.fastq
 pref=${basename "$f" _*R1*.fastq}
command input1 $f input2 ${pref}_*R2*.fastq

The issue most likely lies in manipulating the basename so the loop uses the permutation of file1 to find file2. How do I make the basename shorter than the entire file name. I am getting the error

Fay2_TCCGGAGA-CCTATCCT_L001_R2_001.fastq_*R2.fastq does not exist

Thanks to comments below the looping is working properly but my files are being overwritten whenever a the command loops over a new file. The following is my entire command which requires naming both output files.

for f1 in /directory/*R1*.fastq
f2="${f1/_R1_/_R2_}"
 pref=${basename "$f" _*R1*.fastq}
command output1 ${pref}_trim_R1.fastq output2 ${pref}_trim_R2.fastq input1 $f input2 $f2

Body:
You can loop through the R1 files and use brace expansion to derive R2 file names:

for r1_file in /directory/*_R1_*.fastq; do
  r2_file="${r1_file/_R1_/_R2_}"
  command input1 "$r1_file" input2 "$r2_file"
done


问:
Why am I getting error when enum type variable is initialized in file scope?
I am unable to understand the situation when I try to initialize the enum variable as global, i.e., outside of any scope. For example if I try to compile below code:

```<code>#include <stdio.h>

enum suit {
    club = 0,
    diamonds = 10,
    hearts = 20,
    spades = 3
} card;

card = club;
int main()
{
    printf("Size of enum variable = %d bytes", sizeof(card));
    return 0;
}
</code>```

Following compilation errors happen:

```<code>prog.c:9:1: warning: data definition has no type or storage class
card = club;
^
prog.c:9:1: warning: type defaults to 'int' in declaration of 'card' [Wimplicit-int]
prog.c:9:1: error: conflicting types for 'card'
prog.c:8:3: note: previous declaration of 'card' was here
} card;
  ^
</code>```

But when I put the initialization within the main() scope , no error occurs like the code below:

```<code>#include <stdio.h>

enum suit {
    club = 0,
    diamonds = 10,
    hearts = 20,
    spades = 3
} card;

int main()
{
    card = club;
    printf("Size of enum variable = %d bytes", sizeof(card));
    return 0;
}
</code>```

Output is :

```<code>Size of enum variable = 4 bytes
</code>```

答:
This happens because

```<code>  card = club;
</code>```

is an assignment statement , which needs to be in block scope (some function body) not in file scope, not an initialization.

If you use initialization, it'll work.

Also note the extra changes

int main() should be int main(void)

sizeof yields a size_t, so you should use %zu format specifier to print the result.

Example

```<code>#include <stdio.h>

enum suit {
    club = 0,
    diamonds = 10,
    hearts = 20,
    spades = 3
} card = club;

int main(void)
{
    printf("Size of enum variable = %zu bytes", sizeof(card));
    return 0;
}
</code>```

Body:
I am unable to understand the situation when I try to initialize the enum variable as global, i.e., outside of any scope. For example if I try to compile below code:

#include <stdio.h>

enum suit {
    club = 0,
    diamonds = 10,
    hearts = 20,
    spades = 3
} card;

card = club;
int main()
{
    printf("Size of enum variable = %d bytes", sizeof(card));
    return 0;
}

Following compilation errors happen:

prog.c:9:1: warning: data definition has no type or storage class
card = club;
^
prog.c:9:1: warning: type defaults to 'int' in declaration of 'card' [Wimplicit-int]
prog.c:9:1: error: conflicting types for 'card'
prog.c:8:3: note: previous declaration of 'card' was here
} card;
  ^

But when I put the initialization within the main() scope , no error occurs like the code below:

#include <stdio.h>

enum suit {
    club = 0,
    diamonds = 10,
    hearts = 20,
    spades = 3
} card;

int main()
{
    card = club;
    printf("Size of enum variable = %d bytes", sizeof(card));
    return 0;
}

Output is :

Size of enum variable = 4 bytes

Body:
This happens because

  card = club;

is an assignment statement , which needs to be in block scope (some function body) not in file scope, not an initialization.

If you use initialization, it'll work.

Also note the extra changes

int main() should be int main(void)

sizeof yields a size_t, so you should use %zu format specifier to print the result.

Example

#include <stdio.h>

enum suit {
    club = 0,
    diamonds = 10,
    hearts = 20,
    spades = 3
} card = club;

int main(void)
{
    printf("Size of enum variable = %zu bytes", sizeof(card));
    return 0;
}


问:
Can a git repository be created where branches are clones from other repositories?
Here is the situation:
I have inherited two separate machines, one used for "development" the other is the production machine.  The problem: They are of course out of sync.  In order to bring some sanity to situation I made independent git repositories of the application directory on each machine.

I now wish to be able to compare those repos so I can find out what is different between them.  My idea was to make a third repository that contained two branches, one from the repository of the "dev" machine and one from the repository of the "prod" machine.

Is this or an equivalent solution possible with git ?

Thanks.

答:
The easiest way is to commit all the changes in dev first.  Then create a new branch in dev called production with git branch production and git checkout production.  Then drop all the production files onto dev and overwrite (minus the .git files from production).

Now you have all the changes compared to dev.  You can do a git diff and see the changes and git status to see the new files and which files have changed.  Commit it and then you can slow do the merge.

I would recommend this method instead of the whole 2 repo thing.  Its much easier when your dev and production are in the same repo.


问:
System.ObjectModel Warning Xamarin does not run on Android
We are running the 'Welcome to Xamarin` example on Visual Studio Enterprise, using the latest Xamarin, in a Windows 8.1 environment.

We are managing to build and run on both Windows and Apple, but we are facing problems with Android.

Error:
The referenced component System.ObjectModel could not be found.

The errors can be seen in the screen shot below:

See screenshot

We've already tried searching online for solutions, we found some, which we tried, but to no avail.

On the other hand, is Xamarin compatible with Windows 8.1? Perhaps some Android requirement actually needs a Windows 10 environment.

Any help would be appreciated.

答: Try moving it to desktop, then add it as ref in solution. worked for me, visual studio had access to all the other ref but for some reason dident have access to that specific ref. So i moved it, and i think it gave visual studio access. simply try to move it where access wont be a problem.</p>


问:
How to open/load asp.net downloaded projects in Visual Studio 2013 without .sln or .csproj file
I'm a beginner at asp.net. I've downloaded a few projects of asp.net but several of them don't contain the .sln file or the .csproj file to run them on MS Visual Studio 13.
Question is how can I open/load downloaded projects on Visual studio 2013 and modify to my own needs. I've tried but couldn't find anything relevant. Any youtube link/step by step guide will be appreciated. Thanks.

答:
If they don't. It's most probably means that they are web-site. To open them: In VS File->Open->Web Site (OR Shift-Alt-O)

BTW when you open as Web Site solution file will be created automatically.


问:
Update values in a pair of text fields
I have a form component:

```<code>import React from 'react'
import Relay from 'react-relay'

import { browserHistory } from 'react-router'

import MenuItem from 'material-ui/MenuItem'
import TextField from 'material-ui/TextField'

import CreateTransformationSetMutation from '../mutations/CreateTransformationSetMutation'

class CreateTransformationSetDialog extends React.Component {

  componentWillMount() {
    this.props.setOnDialog({
      onSubmit: this.onSubmit,
      title: 'Create and Apply Transformation Set'
    })
  }

  initial_state = {
    targetTableName: '',
    transformations: this.props.viewer.version.columns.edges.map(edge => edge.node).map(column => {
      return {
        targetColumnName: column.name,
        ruleExpression: '{{' + column.name + '}}'
      }
    })
  }

  state = this.initial_state

  onSubmit = () => {
    const onSuccess = (response) => {
      browserHistory.push('/table')
    }

    const onFailure = () => {}

    Relay.Store.commitUpdate(
      new CreateTransformationSetMutation(
        {
          viewer: this.props.viewer,
          version: this.props.viewer.version,
          targetTableName: this.state.targetTableName,
          transformations: JSON.stringify({transformations: this.state.transformations}),
        }
      ),
      { onSuccess: onSuccess }
    )
  }

  handleTableNameChange = (e) => {
    this.setState({
      targetTableName: e.target.value
    })
  }

  handleTransChange = (e) => {

    ////what should go here////

  }

  render() {
    return (
      <div>
        <TextField
          floatingLabelText="Table Name"
          value={this.state.targetTableName}
          onChange={this.handleTableNameChange}
        />
        <br />
        {
          this.props.viewer.version.columns.edges.map((edge) => edge.node).map((column, i) =>
            <div key={column.id}>
              <TextField
                name="targetColumnName"
                floatingLabelText="Target Column"
                value={this.state.transformations[i].targetColumnName}
                onChange={this.handleTransChange}
                style={{ margin: 12 }}
              />
              <TextField
                name="ruleExpression"
                floatingLabelText="Rule to Apply"
                value={this.state.transformations[i].ruleExpression}
                onChange={this.handleTransChange}
                style={{ margin: 12 }}
              />
            </div>
          )
        }

      </div>
    )
  }

}

export default Relay.createContainer(CreateTransformationSetDialog, {
  fragments: {
    viewer: () => Relay.QL`
      fragment on Viewer {
        ${CreateTransformationSetMutation.getFragment('viewer')}
        version(id: $modalEntityId) @include(if: $modalShow) {
          ${CreateTransformationSetMutation.getFragment('version')}
          id
          name
          columns(first: 100) {
            edges {
              node {
                id
                name
              }
            }
          }
        }
      }
    `
  },
  initialVariables: {
    modalEntityId: '',
    modalName: '',
    modalShow: true,
  },
  prepareVariables: ({ modalEntityId, modalName }) => {
    return {
      modalEntityId,
      modalName,
      modalShow: modalName === 'createTransformationSet'
    }
  }
})
</code>```

Each input is a set of two material-ui TextFields that have a default value obtained from this.state.transformations. However, I am trying to update the values in these fields and I am not having any luck.

The default state of transformations will look something like this:

```<code>transformations: [
  {targetColumnName: 'ID', ruleExpression: '{{ID}}'},
  {targetColumnName: 'First Name', ruleExpression: '{{FirstName}}'},
  {targetColumnName: 'Last Name', ruleExpression: '{{LastName}}'}
]
</code>```

And I want to be able to update it so that the state can change, for example to:

```<code>transformations: [
  {targetColumnName: 'ID', ruleExpression: '{{ID}}'},
  {targetColumnName: 'First Name', ruleExpression: '{{FirstName}}'},
  {targetColumnName: 'Percentage', ruleExpression: '{{Percentage/100}}'}
]
</code>```

The form is built using Relay but that is not relevant to this question.

Any help with this would be much appreciated.

Thanks for your time.

答:
I had a similar problem and instead I put the value in value attribute, uses defaultValue='some-value' so that it can be mutated and changed.

It seems that what you are trying to do is not possible to protect from XSS (Cross-site scripting)

Write like this:

```<code><TextField
  name="targetColumnName"
  floatingLabelText="Target Column"
  defaultValue={this.state.transformations[i].targetColumnName} {/* change from value to defaultValue */}
  onChange={this.handleTransChange}
  style={{ margin: 12 }}
/>
</code>```

Title: Update values in a pair of text fields

Body:
I have a form component:

import React from 'react'
import Relay from 'react-relay'

import { browserHistory } from 'react-router'

import MenuItem from 'material-ui/MenuItem'
import TextField from 'material-ui/TextField'

import CreateTransformationSetMutation from '../mutations/CreateTransformationSetMutation'

class CreateTransformationSetDialog extends React.Component {

  componentWillMount() {
    this.props.setOnDialog({
      onSubmit: this.onSubmit,
      title: 'Create and Apply Transformation Set'
    })
  }

  initial_state = {
    targetTableName: '',
    transformations: this.props.viewer.version.columns.edges.map(edge => edge.node).map(column => {
      return {
        targetColumnName: column.name,
        ruleExpression: '{{' + column.name + '}}'
      }
    })
  }

  state = this.initial_state

  onSubmit = () => {
    const onSuccess = (response) => {
      browserHistory.push('/table')
    }

    const onFailure = () => {}

    Relay.Store.commitUpdate(
      new CreateTransformationSetMutation(
        {
          viewer: this.props.viewer,
          version: this.props.viewer.version,
          targetTableName: this.state.targetTableName,
          transformations: JSON.stringify({transformations: this.state.transformations}),
        }
      ),
      { onSuccess: onSuccess }
    )
  }

  handleTableNameChange = (e) => {
    this.setState({
      targetTableName: e.target.value
    })
  }

  handleTransChange = (e) => {

    ////what should go here////

  }

  render() {
    return (

        <TextField
          floatingLabelText="Table Name"
          value={this.state.targetTableName}
          onChange={this.handleTableNameChange}
        />

        {
          this.props.viewer.version.columns.edges.map((edge) => edge.node).map((column, i) =>

              <TextField
                name="targetColumnName"
                floatingLabelText="Target Column"
                value={this.state.transformations[i].targetColumnName}
                onChange={this.handleTransChange}
                style={{ margin: 12 }}
              />
              <TextField
                name="ruleExpression"
                floatingLabelText="Rule to Apply"
                value={this.state.transformations[i].ruleExpression}
                onChange={this.handleTransChange}
                style={{ margin: 12 }}
              />

          )
        }

    )
  }

}

export default Relay.createContainer(CreateTransformationSetDialog, {
  fragments: {
    viewer: () => Relay.QL`
      fragment on Viewer {
        ${CreateTransformationSetMutation.getFragment('viewer')}
        version(id: $modalEntityId) @include(if: $modalShow) {
          ${CreateTransformationSetMutation.getFragment('version')}
          id
          name
          columns(first: 100) {
            edges {
              node {
                id
                name
              }
            }
          }
        }
      }
    `
  },
  initialVariables: {
    modalEntityId: '',
    modalName: '',
    modalShow: true,
  },
  prepareVariables: ({ modalEntityId, modalName }) => {
    return {
      modalEntityId,
      modalName,
      modalShow: modalName === 'createTransformationSet'
    }
  }
})

Each input is a set of two material-ui TextFields that have a default value obtained from this.state.transformations. However, I am trying to update the values in these fields and I am not having any luck.

The default state of transformations will look something like this:

transformations: [
  {targetColumnName: 'ID', ruleExpression: '{{ID}}'},
  {targetColumnName: 'First Name', ruleExpression: '{{FirstName}}'},
  {targetColumnName: 'Last Name', ruleExpression: '{{LastName}}'}
]

And I want to be able to update it so that the state can change, for example to:

transformations: [
  {targetColumnName: 'ID', ruleExpression: '{{ID}}'},
  {targetColumnName: 'First Name', ruleExpression: '{{FirstName}}'},
  {targetColumnName: 'Percentage', ruleExpression: '{{Percentage/100}}'}
]

The form is built using Relay but that is not relevant to this question.

Any help with this would be much appreciated.

Thanks for your time.

Body:
I had a similar problem and instead I put the value in value attribute, uses defaultValue='some-value' so that it can be mutated and changed.

It seems that what you are trying to do is not possible to protect from XSS (Cross-site scripting)

Write like this:

<TextField
  name="targetColumnName"
  floatingLabelText="Target Column"
  defaultValue={this.state.transformations[i].targetColumnName} {/* change from value to defaultValue */}
  onChange={this.handleTransChange}
  style={{ margin: 12 }}
/>


问:
UIImage to UIColor array of pixel colors
I'm sorry to ask this, but I can't figure out how to represent a UIImage as an array of UIColor for each pixel. I've tried my best with converting UIImagePNG/JPEGRepresentation but couldn't get the desired result.

答:
Here's a Swiftier version (Swift 3):</p>

```<code>extension UIImage {
    var colors: [UIColor]? {

        var colors = [UIColor]()

        let colorSpace = CGColorSpaceCreateDeviceRGB()

        guard let cgImage = cgImage else {
            return nil
        }

        let width = Int(size.width)
        let height = Int(size.height)

        var rawData = [UInt8](repeating: 0, count: width * height * 4)
        let bytesPerPixel = 4
        let bytesPerRow = bytesPerPixel * width
        let bytesPerComponent = 8

        let bitmapInfo = CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Big.rawValue

        let context = CGContext(data: &rawData,
                                width: width,
                                height: height,
                                bitsPerComponent: bytesPerComponent,
                                bytesPerRow: bytesPerRow,
                                space: colorSpace,
                                bitmapInfo: bitmapInfo)

        let drawingRect = CGRect(origin: .zero, size: CGSize(width: width, height: height))
        context?.draw(cgImage, in: drawingRect)

        for x in 0..<width {
            for y in 0..<height {
                let byteIndex = (bytesPerRow * x) + y * bytesPerPixel

                let red = CGFloat(rawData[byteIndex]) / 255.0
                let green = CGFloat(rawData[byteIndex + 1]) / 255.0
                let blue = CGFloat(rawData[byteIndex + 2]) / 255.0
                let alpha = CGFloat(rawData[byteIndex + 3]) / 255.0

                let color = UIColor(red: red, green: green, blue: blue, alpha: alpha)
                colors.append(color)
            }
        }

        return colors
    }
}
</code>```

Body:
Here's a Swiftier version (Swift 3):

extension UIImage {
    var colors: [UIColor]? {

        var colors = [UIColor]()

        let colorSpace = CGColorSpaceCreateDeviceRGB()

        guard let cgImage = cgImage else {
            return nil
        }

        let width = Int(size.width)
        let height = Int(size.height)

        var rawData = [UInt8](repeating: 0, count: width * height * 4)
        let bytesPerPixel = 4
        let bytesPerRow = bytesPerPixel * width
        let bytesPerComponent = 8

        let bitmapInfo = CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Big.rawValue

        let context = CGContext(data: &rawData,
                                width: width,
                                height: height,
                                bitsPerComponent: bytesPerComponent,
                                bytesPerRow: bytesPerRow,
                                space: colorSpace,
                                bitmapInfo: bitmapInfo)

        let drawingRect = CGRect(origin: .zero, size: CGSize(width: width, height: height))
        context?.draw(cgImage, in: drawingRect)

        for x in 0..<width {
            for y in 0..<height {
                let byteIndex = (bytesPerRow * x) + y * bytesPerPixel

                let red = CGFloat(rawData[byteIndex]) / 255.0
                let green = CGFloat(rawData[byteIndex + 1]) / 255.0
                let blue = CGFloat(rawData[byteIndex + 2]) / 255.0
                let alpha = CGFloat(rawData[byteIndex + 3]) / 255.0

                let color = UIColor(red: red, green: green, blue: blue, alpha: alpha)
                colors.append(color)
            }
        }

        return colors
    }
}


问:
RecyclerView - control item count by boolean
I'm using a RecyclerView where there is a boolean involved in getItemCount(). This boolean value controls the visibility of the last item in the RecyclerView, kinda like a load more view, but slightly different. From time to time, the value of this boolean changes, so the RecyclerView will know whether to include the last item.

The code looks something like this

```<code>@Override
public int getItemCount() {
    return mItemArray.size() + (shouldShow ? 1 : 0);
}
</code>```

When the value of shouldShow gets updated, I'm not calling notifyDataSetChanged() or notifyItemChanged(), but the RecyclerView still gets updated properly. But I worry it will eventually cause the RecyclerView to crash because of inconsistency. My questions are,

Is using a dynamic boolean value in getItemCount() a proper way to control RecyclerView size?

Should I call notify...() when the value of this boolean changes?

Would my RecyclerView crashes for inconsistency because of this?

答:
1.not a problem untill you are passing int in it
2.there is no need to call notifydatasetchanged(we should call them when their is change in adapter data)
3.there will not be any consistency</p>

Body:
I'm using a RecyclerView where there is a boolean involved in getItemCount(). This boolean value controls the visibility of the last item in the RecyclerView, kinda like a load more view, but slightly different. From time to time, the value of this boolean changes, so the RecyclerView will know whether to include the last item.

The code looks something like this

@Override
public int getItemCount() {
    return mItemArray.size() + (shouldShow ? 1 : 0);
}

When the value of shouldShow gets updated, I'm not calling notifyDataSetChanged() or notifyItemChanged(), but the RecyclerView still gets updated properly. But I worry it will eventually cause the RecyclerView to crash because of inconsistency. My questions are,

Is using a dynamic boolean value in getItemCount() a proper way to control RecyclerView size?

Should I call notify...() when the value of this boolean changes?

Would my RecyclerView crashes for inconsistency because of this?


问:
org.hibernate.HibernateException: The database returned no natively generated identity value
I'm getting this exception from Hibernate

building session factory

  13:32:09,937  INFO SessionFactoryObjectFactory:105 - Not binding factory to JNDI, no JNDI name configured

  Exception in thread "main" org.hibernate.HibernateException: The database returned no natively generated identity value

What does this mean and how can I solve it? Thanks!

答:
While creating Table in Database you may have forgot to give Autoincrement to that particular column.

Or

You forgot to annotate in Java class as "Generated Value"

This will work fine


问:
void* will have the same representation and memory alignment as a pointer to char
I am reading a book on pointers named "understanding and using c pointers"

When it comes to void * it says

It has two interesting properties:

A pointer to void will have the same representation and memory alignment as a pointer to char.

What am confused about is isn't the memory of all the pointers same? They why instead of writing void* is same as normal pointer it explicitly mentioned char pointers? Will really appreciate any help

答:
On most common architectures, pointer to any data type has the same representation, while pointer to function may differ. However, it's not a requirement, so it's possible to create valid C implementation, which uses different pointers for different data types. The reason behind this is that C standard tends to describe only crucial requirements, leaving a lot of freedom for possible implementations. Here is what standard says:

A pointer to void shall have the same representation and alignment requirements as a
  pointer to a character type.
  Similarly, pointers to qualified or unqualified versions of
  compatible types shall have the same representation and alignment requirements. All
  pointers to structure types shall have the same representation and alignment requirements
  as each other. All pointers to union types shall have the same representation and
  alignment requirements as each other. Pointers to other types need not have the same
  representation or alignment requirements.

If you're curious to see examples of systems with different sizes for different data types, this question mentions these wonderful examples


问:
unable to update textview immideately
i'm making a translation app in which i want to update a textview but it is not doing as i want.

```<code>final audioTranslate at[] = new audioTranslate[1];
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_audio_translate);
    tv = (TextView) findViewById(R.id.textView11);
    spokentext = (TextView) findViewById(R.id.textView12);
    translatedtext = (TextView) findViewById(R.id.textView13);
    at[0] = this;
    start = (Button) findViewById(R.id.Start);
    start.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Button b = (Button) v;
            if (b.getText().toString().equals("Start")) {
                //code
            }
            else{
                tv.setText("");  //these all 3 operations are happening after transfer method is finished.
                b.setText("Wait");
                b.setEnabled(false);
                transfer();
            }
        }
    });
}

void transfer() {
    Thread t = new Thread() {
        public void run() {
            //socket connection
            //it is giving exception on below line too.
            //Only the original thread that created a view hierarchy can touch its views.
            //java.lang.RuntimeException
            at[0].spokentext.setText(spoken);
        }
    };
t.start();
}
</code>```

this is my layout file for reference:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_audio_translate"
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="diverse.technologies.transcriber.audioTranslate">

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TableLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true">

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center_horizontal">

            <Button
                android:text="Start"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/Start" />
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="20dp"
            android:gravity="center_horizontal">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/textView11"
                android:textColor="@color/colorAccent"
                android:textSize="24sp" />
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/textView12"
                android:textSize="26sp"
                android:fontFamily="serif-monospace"
                android:textStyle="normal|bold" />
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="5px">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/textView13"
                android:textSize="24sp"/>
        </TableRow>

    </TableLayout>
</ScrollView>

</RelativeLayout>
</code>```

I'm not getting what is wrong with above exception i'm getting. i'm using the object of the view that is having the textview. please help.

答:
use this for your transfer method:</p>

```<code>void transfer() {
Thread t = new Thread() {
    public void run() {
        //socket connection
        //it is giving exception on below line too.
        //Only the original thread that created a view hierarchy can touch its views.
        //java.lang.RuntimeException
        spokentext.post(new Runnable() {
        @Override
        public void run() {
            at[0].spokentext.setText(spoken);
        }
    });

    }
};
t.start();
}
</code>```

Title: unable to update textview immideately

Body:
i'm making a translation app in which i want to update a textview but it is not doing as i want.

final audioTranslate at[] = new audioTranslate[1];
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_audio_translate);
    tv = (TextView) findViewById(R.id.textView11);
    spokentext = (TextView) findViewById(R.id.textView12);
    translatedtext = (TextView) findViewById(R.id.textView13);
    at[0] = this;
    start = (Button) findViewById(R.id.Start);
    start.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Button b = (Button) v;
            if (b.getText().toString().equals("Start")) {
                //code
            }
            else{
                tv.setText("");  //these all 3 operations are happening after transfer method is finished.
                b.setText("Wait");
                b.setEnabled(false);
                transfer();
            }
        }
    });
}

void transfer() {
    Thread t = new Thread() {
        public void run() {
            //socket connection
            //it is giving exception on below line too.
            //Only the original thread that created a view hierarchy can touch its views.
            //java.lang.RuntimeException
            at[0].spokentext.setText(spoken);
        }
    };
t.start();
}

this is my layout file for reference:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_audio_translate"
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="diverse.technologies.transcriber.audioTranslate">

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TableLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true">

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center_horizontal">

            <Button
                android:text="Start"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/Start" />
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="20dp"
            android:gravity="center_horizontal">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/textView11"
                android:textColor="@color/colorAccent"
                android:textSize="24sp" />
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/textView12"
                android:textSize="26sp"
                android:fontFamily="serif-monospace"
                android:textStyle="normal|bold" />
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="5px">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/textView13"
                android:textSize="24sp"/>
        </TableRow>

    </TableLayout>
</ScrollView>

</RelativeLayout>

I'm not getting what is wrong with above exception i'm getting. i'm using the object of the view that is having the textview. please help.

Body:
use this for your transfer method:

void transfer() {
Thread t = new Thread() {
    public void run() {
        //socket connection
        //it is giving exception on below line too.
        //Only the original thread that created a view hierarchy can touch its views.
        //java.lang.RuntimeException
        spokentext.post(new Runnable() {
        @Override
        public void run() {
            at[0].spokentext.setText(spoken);
        }
    });

    }
};
t.start();
}