问:
Redux Form Checkbox Validation
I have the following code. The checkbox is for confirming that the user has read Terms and Conditions. Im not sure how to add validation for this on the front end. i.e. If the user clicks submit without checking this box, I want to highlight this text in some way that lets the user know to agree to Terms.</p>

```<code><Field
    label='Terms'
    name="terms-and-conditions"
    type="checkbox"
    component={this.renderField}
    submissionErrors={this.state.submissionErrors}
/>
</code>```

答:
You can create a custom component for the Field component. In the custom component you will receive error prop so you can process with additional styling, error messages, etc. If you want to validate on submit, pass onSubmit prop to the decorated component.

Live example: https://codesandbox.io/s/207mj8k3py

Create a custom component with the error logic:

```<code>const Checkbox = ({ input, meta: { touched, error } }) => (
  <div style={{ border: touched && error ? "1px solid red" : "none" }}>
    <input type="checkbox" {...input} />
    <label>Terms and conditions</label>
  </div>
)
</code>```

Set Field's component prop to Checkbox:

```<code>const SimpleForm = ({ handleSubmit, onSubmit }) => (
  <form onSubmit={handleSubmit(onSubmit)}>
    <Field
      name="termsAndConditions"
      component={Checkbox}
    />
    <div>
      <button type="submit">Submit</button>
    </div>
  </form>
)
</code>```

In onSubmit function, check if the checkbox is checked, if not - throw SubmissionError with the name of the Field:

```<code>const onSubmit = values => {
  if (!values.termsAndConditions) {
    throw new SubmissionError({
      termsAndConditions: 'Field required'
    })
  }

  console.log('Form submitted')
}
</code>```

Decorate the form:

```<code>export default reduxForm({
  form: "simple",
  onSubmit
})(SimpleForm)
</code>```

Title: Redux Form Checkbox Validation

Body:
I have the following code. The checkbox is for confirming that the user has read Terms and Conditions. Im not sure how to add validation for this on the front end. i.e. If the user clicks submit without checking this box, I want to highlight this text in some way that lets the user know to agree to Terms.

<Field
    label='Terms'
    name="terms-and-conditions"
    type="checkbox"
    component={this.renderField}
    submissionErrors={this.state.submissionErrors}
/>

Body:
You can create a custom component for the Field component. In the custom component you will receive error prop so you can process with additional styling, error messages, etc. If you want to validate on submit, pass onSubmit prop to the decorated component.

Live example: https://codesandbox.io/s/207mj8k3py

Create a custom component with the error logic:

const Checkbox = ({ input, meta: { touched, error } }) => (
  <div style={{ border: touched && error ? "1px solid red" : "none" }}>
    <input type="checkbox" {...input} />
    <label>Terms and conditions</label>
  </div>
)

Set Field's component prop to Checkbox:

const SimpleForm = ({ handleSubmit, onSubmit }) => (
  <form onSubmit={handleSubmit(onSubmit)}>
    <Field
      name="termsAndConditions"
      component={Checkbox}
    />
    <div>
      <button type="submit">Submit</button>
    </div>
  </form>
)

In onSubmit function, check if the checkbox is checked, if not - throw SubmissionError with the name of the Field:

const onSubmit = values => {
  if (!values.termsAndConditions) {
    throw new SubmissionError({
      termsAndConditions: 'Field required'
    })
  }

  console.log('Form submitted')
}

Decorate the form:

export default reduxForm({
  form: "simple",
  onSubmit
})(SimpleForm)


来源: stackexchange

问:
Nested If, Else If, Else
I've just got onto nested if statements in Scala and I've seen examples on here which suggest this syntax is correctly however the { under else if and second to last } are giving me "( expected" and invalid start of expression.</p>

```<code>object NestedIf2 {
  def main(args: Array[String]): Unit = {
    var x = 30
    var y = 10

    if ( x == 30 ) {
      if ( y == 10 ) {
        println("X = 30 and Y = 10")
      }
    } else if {
      if ( y == 20 ) {
        println("X = 30 and Y = 20")
      }
    } else {
      if ( y == 30 ) {
        println("X = 30 and Y = 30")
      }
    }
  }
}
</code>```

答:
Make sure you follow these rules:

Every if keyword should be followed by a condition

An else clause can only follow an if clause

Applied to your code:

```<code>if (x == 30) {
  if (y == 10) {
    println("X = 30 and Y = 10")
  } else if (y == 20) {
    println("X = 30 and Y = 20")
  } else if (y == 30) {
    println("X = 30 and Y = 30")
  }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Nested If, Else If, Else

Body:
I've just got onto nested if statements in Scala and I've seen examples on here which suggest this syntax is correctly however the { under else if and second to last } are giving me "( expected" and invalid start of expression.

object NestedIf2 {
  def main(args: Array[String]): Unit = {
    var x = 30
    var y = 10

    if ( x == 30 ) {
      if ( y == 10 ) {
        println("X = 30 and Y = 10")
      }
    } else if {
      if ( y == 20 ) {
        println("X = 30 and Y = 20")
      }
    } else {
      if ( y == 30 ) {
        println("X = 30 and Y = 30")
      }
    }
  }
}

Body:
Make sure you follow these rules:

Every if keyword should be followed by a condition

An else clause can only follow an if clause

Applied to your code:

if (x == 30) {
  if (y == 10) {
    println("X = 30 and Y = 10")
  } else if (y == 20) {
    println("X = 30 and Y = 20")
  } else if (y == 30) {
    println("X = 30 and Y = 30")
  }
}


问:
Set default header value for sample requests in generated documentation
I'm trying to set up sample requests for my api docs. It works fine but i need manyally set header values for every request

Is there a way to define default value for header that will be sent with every sample request?

I've tried to set default value for headers like:

```<code>/**
 * @apiHeader {String} Authorization=someToken
 * @apiHeader {String} Content-Type=application/json
 */
</code>```

Also I was thinking about including custom js in generated html that will fill these fields (I'm not sure if it's possible) but I hope there is a simplier solution.

答:
The owner of the apidoc/apidoc writes here:

You can set default values. But the send sample request module did not
  use the default value at the moment (you can modify the template for
  this).

Body:
I'm trying to set up sample requests for my api docs. It works fine but i need manyally set header values for every request

Is there a way to define default value for header that will be sent with every sample request?

I've tried to set default value for headers like:

/**
 * @apiHeader {String} Authorization=someToken
 * @apiHeader {String} Content-Type=application/json
 */

Also I was thinking about including custom js in generated html that will fill these fields (I'm not sure if it's possible) but I hope there is a simplier solution.


问:
How to make, in one SPARQL query, three independent queries on three different SPARQL endpoints?
is there a way that I can do three independent queries on on three different SPARQL endpoints, in one SPARQL query? For example, I have three SPARQL endpoints (i.e., url1, url2 and url3) and three independent queries I want to make, i.e., query1 on url1, query2 on url2 and query3 on url3. Is it possible that I can conduct the three queries once in one SPARQL query?

I tried the pattern like

```<code>SELECT * WHERE {

 SERVICE <url1> {query1}

 SERVICE <url2> {query2}

 SERVICE <url3> {query3}
}
</code>```

It seems that the query tries to connect results from three queries, because the three queries are independent, the final result is empty. If I do three times query one endpoint by one endpoint, each query has returned results.

Thank you very much for your help!

答:
You can use UNION to make 3 separate calls: it is roughly the same as making 3 queries.

```<code>SELECT * WHERE {
 { SERVICE <url1> {query1} }
 UNION
 { SERVICE <url2> {query2} }
  UNION
 { SERVICE <url3> {query3} }
}
</code>```

The app may need to know which rows come from which call, so labelling the results can be useful:

```<code>SELECT * WHERE {
 { SERVICE <url1> { query1 } BIND (<url1> AS ?serviceLabel) }
 UNION
 { SERVICE <url2> { query2 } BIND (<url2> AS ?serviceLabel) }
  UNION
 { SERVICE <url3> { query3 } BIND (<url2> AS ?serviceLabel) }
}
</code>```

Body:
is there a way that I can do three independent queries on on three different SPARQL endpoints, in one SPARQL query? For example, I have three SPARQL endpoints (i.e., url1, url2 and url3) and three independent queries I want to make, i.e., query1 on url1, query2 on url2 and query3 on url3. Is it possible that I can conduct the three queries once in one SPARQL query?

I tried the pattern like

SELECT * WHERE {

 SERVICE <url1> {query1}

 SERVICE <url2> {query2}

 SERVICE <url3> {query3}
}

It seems that the query tries to connect results from three queries, because the three queries are independent, the final result is empty. If I do three times query one endpoint by one endpoint, each query has returned results.

Thank you very much for your help!

Body:
You can use UNION to make 3 separate calls: it is roughly the same as making 3 queries.

SELECT * WHERE {
 { SERVICE <url1> {query1} }
 UNION
 { SERVICE <url2> {query2} }
  UNION
 { SERVICE <url3> {query3} }
}

The app may need to know which rows come from which call, so labelling the results can be useful:

SELECT * WHERE {
 { SERVICE <url1> { query1 } BIND (<url1> AS ?serviceLabel) }
 UNION
 { SERVICE <url2> { query2 } BIND (<url2> AS ?serviceLabel) }
  UNION
 { SERVICE <url3> { query3 } BIND (<url2> AS ?serviceLabel) }
}


问:
MYSQL database transfer using knex
```<code>const exec_string = 'mysqldump --user=abc--password=abc--host=localhost test | mysql --user=xyz--password=xyz --host=localhost new_test';
knex.raw(exec_string)
.then((res) => {
    console.log("res >>",res);
})
.catch((err)=>{
    console.log("err >>",err);
})
</code>```

Here i have test database. i want transfer that database in new_test database using knex npm.
If any other solution please suggest me.

答: Knex is not the right tool for this. Using exec or shelljs sounds like a good way to do this.

Title: MYSQL database transfer using knex

Body:
const exec_string = 'mysqldump --user=abc--password=abc--host=localhost test | mysql --user=xyz--password=xyz --host=localhost new_test';
knex.raw(exec_string)
.then((res) => {
    console.log("res >>",res);
})
.catch((err)=>{
    console.log("err >>",err);
})

Here i have test database. i want transfer that database in new_test database using knex npm.
If any other solution please suggest me.


问:
Access Configuration from a View in ASP.NET Core
How can I access IConfiguration in an MVC View in ASP.NET Core 1.1?

Ex. _Layout.cshtml

```<code><link href="@Configuration["MyConfigEntry"]/css/site.min.css>
</code>```

答:
In asp.net core , you can inject IConfiguration implementation to your views and use that :)

```<code>@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration
<link rel="stylesheet" href="@Configuration["MyConfigEntry"]/css/site.min.css">
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How can I access IConfiguration in an MVC View in ASP.NET Core 1.1?

Ex. _Layout.cshtml

<link href="@Configuration["MyConfigEntry"]/css/site.min.css>

Body:
In asp.net core , you can inject IConfiguration implementation to your views and use that :)

@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration
<link rel="stylesheet" href="@Configuration["MyConfigEntry"]/css/site.min.css">


问:
Node js, Express and handlebars rendering fullcalendar plugin not working
I have been unable to implement fullcalendar into my application and cannot find any information detailing exactly how to implement it using node, express and handlebars. I've tried multiple ways of adding fullcalendar without any luck. Other web pages in my application are working and render their information so I don't know why fullcalendar won't work after following the instructions on the website.

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M"
    crossorigin="anonymous">
  <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">

  <link href="vendor/datatables/dataTables.bootstrap4.css" rel="stylesheet">

  <link href="css/sb-admin.css" rel="stylesheet">
  <link href="css/style.css" rel="stylesheet">

  <link rel='stylesheet' href='../../node_modules/fullcalendar/dist/fullcalendar.css' />

  <title>Workmate</title>

  {{#if user}}
    {{> _appNavbar}}
  {{else}}
    {{> _navbar}}
  {{/if}}

    {{> _msg}}
    {{> _errors}}
    {{{body}}}

```
</div>
</div>
</p>

<p>After the main.handlebars I have the schedule.handlebars which should load the empty calendar. </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id='calendar'></div></code>```

I've followed the instructions on the fullcalendar website and it doesn't render the calendar on the schedule.handlebars page.

// webapp.js

//App schedules route
router.get('/schedules', ensureAuthenticated, (req, res) =>{
  res.render('webapp/schedules');
});```

This is all the code I have to implement the application. Any help will be greatly appreciated as this is for my final year project in college.

Thanking you all in advance.

答:
I can see two potential issues. You are including some local scripts like that:

```<code><!-- Link and script for calendar -->
<link rel='stylesheet' href='../../node_modules/fullcalendar/dist/fullcalendar.css' />
<script src='../../node_modules/jquery/dist/jquery.min.js'></script>
<script src='../../node_modules/moment/min/moment.min.js'></script>
<script src='../../node_modules/fullcalendar/dist/fullcalendar.js'></script>
</code>```

Do you expose the node_modules directory through express in order to be able to serve those files? Have a look here:
https://expressjs.com/en/starter/static-files.html

It is not good practice though to expose the node_modules directory though, it is better if you have a building step of your application that will copy over all your libraries into a dedicated dist directory and ideally will minify and uglify them as well.

The second thing that can be problematic is the place that you include your script. It is good practice to move all the js imports inside the body just before the body closing tag (). You already defined some there. The document ready function will run but the div with the id calendar will not be there. More details here: Where should I put
<script src='/modules/moment/min/moment.min.js'></script>
<script src='/modules/fullcalendar/dist/fullcalendar.js'></script>
```

Body:
I have been unable to implement fullcalendar into my application and cannot find any information detailing exactly how to implement it using node, express and handlebars. I've tried multiple ways of adding fullcalendar without any luck. Other web pages in my application are working and render their information so I don't know why fullcalendar won't work after following the instructions on the website.

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M"
    crossorigin="anonymous">
  <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">

  <link href="vendor/datatables/dataTables.bootstrap4.css" rel="stylesheet">

  <link href="css/sb-admin.css" rel="stylesheet">
  <link href="css/style.css" rel="stylesheet">

  <link rel='stylesheet' href='../../node_modules/fullcalendar/dist/fullcalendar.css' />

  <title>Workmate</title>

  {{#if user}}
    {{> _appNavbar}}
  {{else}}
    {{> _navbar}}
  {{/if}}

    {{> _msg}}
    {{> _errors}}
    {{{body}}}

After the main.handlebars I have the schedule.handlebars which should load the empty calendar.

I've followed the instructions on the fullcalendar website and it doesn't render the calendar on the schedule.handlebars page.

// webapp.js

//App schedules route
router.get('/schedules', ensureAuthenticated, (req, res) =>{
  res.render('webapp/schedules');
});

This is all the code I have to implement the application. Any help will be greatly appreciated as this is for my final year project in college.

Thanking you all in advance.

Body:
I can see two potential issues. You are including some local scripts like that:

<!-- Link and script for calendar -->
<link rel='stylesheet' href='../../node_modules/fullcalendar/dist/fullcalendar.css' />
<script src='../../node_modules/jquery/dist/jquery.min.js'></script>
<script src='../../node_modules/moment/min/moment.min.js'></script>
<script src='../../node_modules/fullcalendar/dist/fullcalendar.js'></script>

Do you expose the node_modules directory through express in order to be able to serve those files? Have a look here:
https://expressjs.com/en/starter/static-files.html

It is not good practice though to expose the node_modules directory though, it is better if you have a building step of your application that will copy over all your libraries into a dedicated dist directory and ideally will minify and uglify them as well.

The second thing that can be problematic is the place that you include your script. It is good practice to move all the js imports inside the body just before the body closing tag (). You already defined some there. The document ready function will run but the div with the id calendar will not be there. More details here: Where should I put <script> tags in HTML markup?

Update 1

You need to be able to server the files in the node_modules (it is not a good practice though) like that:

app.use('/modules', express.static(path.join(__dirname, 'node_modules')))

And then include your script paths like that:

<link rel='stylesheet' href='/modules/fullcalendar/dist/fullcalendar.css' />
<script src='/modules/jquery/dist/jquery.min.js'></script>
<script src='/modules/moment/min/moment.min.js'></script>
<script src='/modules/fullcalendar/dist/fullcalendar.js'></script>


问:
Adding a Table of values to a google sheet (python)
```<code>#Write to sheet
subjects = ['Maths', 'Physics', 'Geography', 'Biology',
            'Chemistry', 'ICT', 'Travel and Tourism', 'Computer Science',
            'History', 'LINC', 'Design and Technology', 'Art',
            'English Literature', 'Welsh', 'MFL', 'Music',
            'Business','Applied Science', 'Medical Science', 'Media']
values =[]
import random
random.shuffle(subjects)

chunks = [subjects[x:x+5] for x in range(0, len(subjects), 5)]
I = chunks[0]
c = 0
for element in I:
    temp = str(element)
    print(temp)
    values.append(temp)
    print(values)
body = {
    'values': values,
    'majorDimension':'COLUMNS'

}
result = service.spreadsheets().values().update(
    spreadsheetId=spreadsheetId, range="Data!A1:D5",
    valueInputOption='USER_ENTERED',body=body).execute()
</code>```

Running this it will basically move some list elements about randomly, then split them into smaller lists so I can add them column by column, my range is currently A1:D5 on the google sheet however I have tried using just A1 and a single list element and I get the same error, for example only having "Geography" appended to the list

My error is as follows:

googleapiclient.errors.HttpError: <HttpError 400 when requesting https://sheets.googleapis.com/v4/spreadsheets/1DIP0UqEuS8mcEgAiKnFXaSsyqiUq2LXkGa7VmAJS4S8/values/Data%21A1?valueInputOption=USER_ENTERED&alt=json returned "Invalid value at 'data.values[0]' (type.googleapis.com/google.protobuf.ListValue), "English Literature"">

答:
```<code>subjects = ['Maths', 'Physics', 'Geography', 'Biology',
            'Chemistry', 'ICT', 'Travel and Tourism', 'Computer Science',
            'History', 'LINC', 'Design and Technology', 'Art',
            'English Literature', 'Welsh', 'MFL', 'Music',
            'Business','Applied Science', 'Medical Science', 'Media']
t = ['Maths','Chemistry']
E = 0
Alphabet = ['A','B','C','D','E']
tempList = []
import random
random.shuffle(subjects)

chunks = [subjects[x:x+5] for x in range(0, len(subjects), 5)]
I = chunks[0]
c = 0
#print(chunks[0])
for chunk in chunks:
    R = Alphabet[E]
    print(chunk)
    c = c+1
    values = [[chunk[0]],[chunk[1]],[chunk[2]],[chunk[3]],[chunk[4]],]
    body = {
    'values': values,
    'majorDimension':'ROWS'

    }
    result = service.spreadsheets().values().update(
        spreadsheetId=spreadsheetId, range="Data!"+R+"2:Z",
        valueInputOption='RAW',body=body).execute()
    E = E+1
</code>```

Body:
#Write to sheet
subjects = ['Maths', 'Physics', 'Geography', 'Biology',
            'Chemistry', 'ICT', 'Travel and Tourism', 'Computer Science',
            'History', 'LINC', 'Design and Technology', 'Art',
            'English Literature', 'Welsh', 'MFL', 'Music',
            'Business','Applied Science', 'Medical Science', 'Media']
values =[]
import random
random.shuffle(subjects)

chunks = [subjects[x:x+5] for x in range(0, len(subjects), 5)]
I = chunks[0]
c = 0
for element in I:
    temp = str(element)
    print(temp)
    values.append(temp)
    print(values)
body = {
    'values': values,
    'majorDimension':'COLUMNS'

}
result = service.spreadsheets().values().update(
    spreadsheetId=spreadsheetId, range="Data!A1:D5",
    valueInputOption='USER_ENTERED',body=body).execute()

Running this it will basically move some list elements about randomly, then split them into smaller lists so I can add them column by column, my range is currently A1:D5 on the google sheet however I have tried using just A1 and a single list element and I get the same error, for example only having "Geography" appended to the list

My error is as follows:

googleapiclient.errors.HttpError: <HttpError 400 when requesting https://sheets.googleapis.com/v4/spreadsheets/1DIP0UqEuS8mcEgAiKnFXaSsyqiUq2LXkGa7VmAJS4S8/values/Data%21A1?valueInputOption=USER_ENTERED&alt=json returned "Invalid value at 'data.values[0]' (type.googleapis.com/google.protobuf.ListValue), "English Literature"">


问:
Strange MySQL/PHP issue: mysql query does not execute and there is no error
I ran into a strange bug in my PHP web app that I'm unable to sort out. The php script fetches a row from the database, it processes it and serializes a new query and writes back the row to the database.

I copied the code that does this:

```<code>foreach($a as $key => $value)
{
    $a[$key]="'".mysql_real_escape_string($value)."'";
}
$a['lastUpdate']="$when";
//assembling request
$assignments=array();
foreach($a as $key => $value)
{
    $assignments[]="$key=$value";
}

$q="UPDATE wtfb2_villages SET ".implode(',',$assignments)." WHERE (id=${a['id']})";
logText($q);
logText(mysql_error());
$r=mysql_query($q) or die(__FILE__.':'.__LINE__.':'.mysql_error().':'.$q);
logText(mysql_affected_rows());
logText('Mysql error in query is: '.mysql_error()."\n");
</code>```

That UPDATE seemingly executes. mysql_error() gives an empty string. mysql_affected_rows says 1 just like when everything is done. But if I look into the table using phpmyadmin I saw that nothing is changed.

I logged the query itself its:

```<code>UPDATE wtfb2_villages SET id='22',ownerId='56',villageName='Új falu',x='0',y='1',buildPoints='7.2226273148149',barracksLevel='0',archeryRangeLevel='0',stablesLevel='0',workshopLevel='0',townHallLevel='0',blacksmithLevel='0',goldmineLevel='1',wallLevel='0',spearmen='0',archers='0',knights='0',catapults='0',diplomats='0',spearmanLevel='0',archerLevel='0',knightLevel='0',catapultLevel='0',spearmenTraining='0',archersTraining='0',knightsTraining='0',catapultsTraining='0',diplomatsTraining='0',lastUpdate='2011-01-18 21:56:10' WHERE (id='22')
</code>```

If I just copy-paste this query directly into the phpmyadmin it executes it and I see the result in the table.

The table is using myIsam engine. So no transactions or anythin such.

I got stuck at this problem more than 2 hours and I'm unable to find out what's going on.

This is the only one query that does this. queries before and after this one executing properly.

Any ideas?

答:
I found it out... The bug was elsewhere...

When a village is attacked by an army the event processor script first checks whether the village exists. If exists it fetches the row too. Reads the owner's id from the row, and updates the owner's all villages to determine how much loot can be got from that village. After that the event procesor simulates the battle, calculates the casualties and... ...writes back the row with the old update date... pfff That was it...

My advice: if you got stuck with a completely absurd bug... Have a shower, eat your dinner, feed the dog or run a round around the block etc... Just stop thinking... After you sit back in front of the computer you can almost find any kind of bug immediately...

ps: And only when everything fails start a SO post...

ContentLicense: CC BY-SA 2.5

Body:
I ran into a strange bug in my PHP web app that I'm unable to sort out. The php script fetches a row from the database, it processes it and serializes a new query and writes back the row to the database.

I copied the code that does this:

foreach($a as $key => $value)
{
    $a[$key]="'".mysql_real_escape_string($value)."'";
}
$a['lastUpdate']="$when";
//assembling request
$assignments=array();
foreach($a as $key => $value)
{
    $assignments[]="$key=$value";
}

$q="UPDATE wtfb2_villages SET ".implode(',',$assignments)." WHERE (id=${a['id']})";
logText($q);
logText(mysql_error());
$r=mysql_query($q) or die(__FILE__.':'.__LINE__.':'.mysql_error().':'.$q);
logText(mysql_affected_rows());
logText('Mysql error in query is: '.mysql_error()."\n");

That UPDATE seemingly executes. mysql_error() gives an empty string. mysql_affected_rows says 1 just like when everything is done. But if I look into the table using phpmyadmin I saw that nothing is changed.

I logged the query itself its:

UPDATE wtfb2_villages SET id='22',ownerId='56',villageName='Új falu',x='0',y='1',buildPoints='7.2226273148149',barracksLevel='0',archeryRangeLevel='0',stablesLevel='0',workshopLevel='0',townHallLevel='0',blacksmithLevel='0',goldmineLevel='1',wallLevel='0',spearmen='0',archers='0',knights='0',catapults='0',diplomats='0',spearmanLevel='0',archerLevel='0',knightLevel='0',catapultLevel='0',spearmenTraining='0',archersTraining='0',knightsTraining='0',catapultsTraining='0',diplomatsTraining='0',lastUpdate='2011-01-18 21:56:10' WHERE (id='22')

If I just copy-paste this query directly into the phpmyadmin it executes it and I see the result in the table.

The table is using myIsam engine. So no transactions or anythin such.

I got stuck at this problem more than 2 hours and I'm unable to find out what's going on.

This is the only one query that does this. queries before and after this one executing properly.

Any ideas?


问:
Vertical alignment of nodes in graphviz
I am trying to make a graph where {C1;C2} are aligned vertically. Same with {A;B;C} and {E1;E2;E3}

Here is my code so far:

```<code>digraph G{
    rankdir="LR";
    S -> C1 [label="150"];
    S -> C2 [label="130"];
    C1 -> A [label="70"];
    C1 -> B [label="80"];
    C2 -> B [label="60"];
    C2 -> C [label="70"];
    C -> B [label="10"];
    A -> E1 [label="70"];
    B -> E1 [label="80"];
    B -> D [label="70"];
    C -> E3 [label="60"];
    D -> E1 [label="40"];
    D -> E2 [label="0"];
    D -> E3 [label="30"];
    E1 -> t [label="190"];
    E2 -> t [label="0"];
    E3 -> t [label="90"];
}
</code>```

Here is the result so far:

答:
{ rank = same; } is your friend. I have added invisible edges between A, B and C to keep them tighter together, and reversed one of your connections in orde to keep A over B over C etc.

```<code>digraph G
{
    rankdir="LR";
    { rank = same; C1 C2 }
    { rank = same; A -> B -> C[ style = invis ] }
    { rank = same; E1 E2 E3 }
    S -> C1 [label="150"];
    S -> C2 [label="130"];
    C1 -> A [label="70"];
    C1 -> B [label="80"];
    C2 -> B [label="60"];
    C2 -> C [label="70"];
    B -> C [dir = back, label="10"];   // to keep B above C
    A -> E1 [label="70"];
    B -> E1 [label="80"];
    B -> D [label="70"];
    C -> E3 [label="60"];
    D -> E1 [label="40"];
    D -> E2 [label="0"];
    D -> E3 [label="30"];
    E1 -> t [label="190"];
    E2 -> t [label="0"];
    E3 -> t [label="90"];
}
</code>```

yields

Title: Vertical alignment of nodes in graphviz

Body:
I am trying to make a graph where {C1;C2} are aligned vertically. Same with {A;B;C} and {E1;E2;E3}

Here is my code so far:

digraph G{
    rankdir="LR";
    S -> C1 [label="150"];
    S -> C2 [label="130"];
    C1 -> A [label="70"];
    C1 -> B [label="80"];
    C2 -> B [label="60"];
    C2 -> C [label="70"];
    C -> B [label="10"];
    A -> E1 [label="70"];
    B -> E1 [label="80"];
    B -> D [label="70"];
    C -> E3 [label="60"];
    D -> E1 [label="40"];
    D -> E2 [label="0"];
    D -> E3 [label="30"];
    E1 -> t [label="190"];
    E2 -> t [label="0"];
    E3 -> t [label="90"];
}

Here is the result so far:

Body:
{ rank = same; } is your friend. I have added invisible edges between A, B and C to keep them tighter together, and reversed one of your connections in orde to keep A over B over C etc.

digraph G
{
    rankdir="LR";
    { rank = same; C1 C2 }
    { rank = same; A -> B -> C[ style = invis ] }
    { rank = same; E1 E2 E3 }
    S -> C1 [label="150"];
    S -> C2 [label="130"];
    C1 -> A [label="70"];
    C1 -> B [label="80"];
    C2 -> B [label="60"];
    C2 -> C [label="70"];
    B -> C [dir = back, label="10"];   // to keep B above C
    A -> E1 [label="70"];
    B -> E1 [label="80"];
    B -> D [label="70"];
    C -> E3 [label="60"];
    D -> E1 [label="40"];
    D -> E2 [label="0"];
    D -> E3 [label="30"];
    E1 -> t [label="190"];
    E2 -> t [label="0"];
    E3 -> t [label="90"];
}

yields


问:
How to check if an Array of strings is sorted in alphabetical order or not using Kotlin?
I am given a list of strings and I need to see if they are in alphabetical order.

I know I need to use a for loop and check the first character of each string but I don't know how to progress from there.

```<code>for (item in array)
     println(item[0])
</code>```

For example ["adam", "ben", "chloe"] should return true.

And likewise for ["ben", "adam", "chloe"] should return false.

答:
Yet another solution :)</p>

```<code>data class Result(val isInOrder: Boolean, val lastString: String) {
    val toString = when {
        isInOrder -> "Strings are in alphabetical order."
        else -> "Strings are not in alphabetical order."
    }
}

fun Array<String>.isInAlphabeticalOrder() =
    this.fold(Result(true, ""), { acc, word -> Result(acc.isInOrder && acc.lastString < word, word) })

fun main(args: Array<String>) {
    val test1 = arrayOf("adam", "ben", "chloe")
    val test2 = arrayOf("ben", "adam", "chloe")
    println(test1.isInAlphabeticalOrder().toString)
    println(test2.isInAlphabeticalOrder().toString)
}
</code>```

Body:
I am given a list of strings and I need to see if they are in alphabetical order.

I know I need to use a for loop and check the first character of each string but I don't know how to progress from there.

for (item in array)
     println(item[0])

For example ["adam", "ben", "chloe"] should return true.

And likewise for ["ben", "adam", "chloe"] should return false.

Body:
Yet another solution :)

data class Result(val isInOrder: Boolean, val lastString: String) {
    val toString = when {
        isInOrder -> "Strings are in alphabetical order."
        else -> "Strings are not in alphabetical order."
    }
}

fun Array<String>.isInAlphabeticalOrder() =
    this.fold(Result(true, ""), { acc, word -> Result(acc.isInOrder && acc.lastString < word, word) })

fun main(args: Array<String>) {
    val test1 = arrayOf("adam", "ben", "chloe")
    val test2 = arrayOf("ben", "adam", "chloe")
    println(test1.isInAlphabeticalOrder().toString)
    println(test2.isInAlphabeticalOrder().toString)
}


问:
extremely slow table operations on a table with few rows but large column contents
I have a table with only 9 rows and 10 columns. Three of these columns are VarBinary and contain about 12-30 MB of data in each column for each row. Now even simple updating of one row takes more than 20 minutes and Sql times out. Even a select statement takes about 40 seconds unless I excluded the Varbinary columns from the query

Any suggestions. Thanks

答: 20 minutes to update sure sounds like either a network or IO bottleneck.  Have you looked at your wait stats for things like PAGEIOLATCH_* waits?  This article is a good reference for running a performance monitor to see if your subsystem is having issues: https://blogs.msdn.microsoft.com/sqljourney/2013/06/03/how-to-troubleshooting-sql-server-io-bottlenecks/</p>


问:
What version of sqlite does iOS provide?
What version of Sqlite does iOS include?</p>

答:
Use following to printout the version in your code. You may define following as a separate debug only function and call it from didFinishLaunchingWithOptions in your appDelegate.

```<code>#if DEBUG
// Int representing version; e.g. "3016000" for macOS 10.12.4
int sqliteVersion = sqlite3_libversion_number();
NSLog(@"Sqlite Version: %d", sqliteVersion);

// String representing version; e.g. "3.19.3" for iOS 11
const char *sqliteLibVersion = sqlite3_libversion();
NSString *sqliteLibVersionStr = [NSString stringWithUTF8String:sqliteLibVersion];
NSLog(@"Sqlite Lib Version: %@", sqliteLibVersionStr);

// String representing sourceId; e.g. "2017-06-27 16:48:08 2b09...2e2377b" on iOS11
const char *sqliteSourceid = sqlite3_sourceid();
NSString *sqliteSourceidStr = [NSString stringWithUTF8String:sqliteSourceid];
NSLog(@"Sqlite SourceID: %@", sqliteSourceidStr);
#endif
</code>```

Alternatively, look at sqlite3.h directly in Xcode. For iOS 11:

```<code>#define SQLITE_VERSION        "3.19.3"
#define SQLITE_VERSION_NUMBER 3019003
#define SQLITE_SOURCE_ID      "2017-06-27 16:48:08 2b09...2e2377b"
</code>```

sqlite3.h also has other methods that can be used for debugging purposes.

Body:
Use following to printout the version in your code. You may define following as a separate debug only function and call it from didFinishLaunchingWithOptions in your appDelegate.

#if DEBUG
// Int representing version; e.g. "3016000" for macOS 10.12.4
int sqliteVersion = sqlite3_libversion_number();
NSLog(@"Sqlite Version: %d", sqliteVersion);

// String representing version; e.g. "3.19.3" for iOS 11
const char *sqliteLibVersion = sqlite3_libversion();
NSString *sqliteLibVersionStr = [NSString stringWithUTF8String:sqliteLibVersion];
NSLog(@"Sqlite Lib Version: %@", sqliteLibVersionStr);

// String representing sourceId; e.g. "2017-06-27 16:48:08 2b09...2e2377b" on iOS11
const char *sqliteSourceid = sqlite3_sourceid();
NSString *sqliteSourceidStr = [NSString stringWithUTF8String:sqliteSourceid];
NSLog(@"Sqlite SourceID: %@", sqliteSourceidStr);
#endif

Alternatively, look at sqlite3.h directly in Xcode. For iOS 11:

#define SQLITE_VERSION        "3.19.3"
#define SQLITE_VERSION_NUMBER 3019003
#define SQLITE_SOURCE_ID      "2017-06-27 16:48:08 2b09...2e2377b"

sqlite3.h also has other methods that can be used for debugging purposes.


问:
add asteriks to correct answers, 2D arrays
So this program is supposed to read and count correct answers for each student as well as put up a table of all the questions answered. My issue is there is supposed to be an asteriks next to a correct answer on the 2nd table. It's the only part I'm getting wrong.

```<code>#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>

using namespace std;

void main()
{
char ch;

string answers, id, responses;
int numstudents = 0, i, j, numcorrect, chart[20][5] = { 0 };

ifstream ftests, fans;
ofstream fout;

ftests.open("Tests.dat");
fans.open("answers.dat");
fout.open("table.out");

fans >> answers;

fout << setw(11) << "student-id" << setw(19) << "number correct" << endl << endl;

ftests >> id >> responses;

while (!ftests.eof())
{
    numstudents++;
    numcorrect = 0;

    for (i = 0; i < 20; i++)
    {
        if (responses[i] == answers[i])
        {
            numcorrect++;
        }
        for (j = 0; j < 5; j++)
        {

            if (responses[i] == (char)('A' + j))
            {
                chart[i][j]++;

            }

        }

    }

    fout << setw(11) << id << setw(19) << numcorrect << endl;

    ftests >> id >> responses;

}

fout << endl << endl << endl;

fout << "number of students taking exam = " << numstudents << endl << endl;

fout << setw(8) << "question" << setw(5) << "A" << setw(5) << "B" << setw(5) << "C" << setw(5) << "D" << setw(5) << "E" << endl;

for (i = 0; i < 20; i++)
{
    fout << setw(2) << i + 1  << " " << setw(10);
    for (j = 0; j < 5; j++)
    {
        fout << chart[i][j];

        if (responses[i] == i)//I BELIEVE THE PROBLEM LIES HERE!!!
        {
            fout << "*" << setw(4);
        }
        else
        {
            fout << " " << setw(4);

        }
    }
    fout << endl;
}

}
</code>```

The tables looks like this:

```<code> student-id     number correct

430-52-6192                 13
112-81-5225                 19
120-49-5322                 12
456-65-3211                  2
990-45-0978                  4
324-98-5445                  6
112-34-3443                 12
435-56-8790                 18
452-23-5675                  6
776-45-5454                  7
567-71-9909                  6
345-54-7834                  9
555-12-2341                 18
568-09-0096                 20
664-61-0987                 10
612-45-7687                  5
567-23-1125                  3
561-43-6781                  6
498-12-4321                  3
479-01-4867                  4
489-90-0999                 17
456-09-1111                 19
561-66-6657                  3

number of students taking exam = 23

question    A    B    C    D    E
 1          5    1   13    3    1
 2          4    7    1    7    4
 3          2    3    2    2   14
 4          2    1    3   13    4
 5          2    8    1    4    8
 6          5    1    3    3   11
 7          5    7    0    4    7
 8         11    4    0    3    5
 9          3    2    1    2   15
10          0    1   12    3    7
11          6    2    4   10    1
12          2    2    4    9    6
13          9    4    0    6    4
14          4    2    2    2   13
15          3    3    1    1   15
16          1    8    4    3    7
17          6    3    1    7    6
18          4    1    2    5   11
19          0    1    1   10   11
20          2    0    1    1   19
</code>```

Where as table 2 should look like this:

```<code>question    A    B    C    D    E
 1          5    1   13*   3    1
 2          4    7*   1    7    4
 3          2    3    2    2   14*
 4          2    1    3   13*   4
 5          2    8*   1    4    8
 6          5    1    3    3   11*
 7          5    7*   0    4    7
 8         11*   4    0    3    5
 9          3    2    1    2   15*
10          0    1   12*   3    7
11          6    2    4   10*   1
12          2    2    4    9*   6
13          9*   4    0    6    4
14          4    2    2    2   13*
15          3    3    1    1   15*
16          1    8*   4    3    7
17          6    3    1    7*   6
18          4    1    2    5   11*
19          0    1    1   10*  11
20          2    0    1    1   19*
</code>```

I hope I am being clear enough and any help is appreciated!

答: I would think the line "if (responses[i] == i)" would cause a compile error.  This is comparing a string data type to an int.  Based on your earlier lines of code I would think "if (responses[i] == answers[i])" is a better choice.  I am interpreting the meaning of each variable based on context and I may be wrong.  But it seems that answers[] is a list of the correct answers and this comparison is used to count the number of correct answers.  If my interpretation of the variables is wrong then I would suggest defining a variable that allows for this comparison.</p>

Body:
So this program is supposed to read and count correct answers for each student as well as put up a table of all the questions answered. My issue is there is supposed to be an asteriks next to a correct answer on the 2nd table. It's the only part I'm getting wrong.

#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>

using namespace std;

void main()
{
char ch;

string answers, id, responses;
int numstudents = 0, i, j, numcorrect, chart[20][5] = { 0 };

ifstream ftests, fans;
ofstream fout;

ftests.open("Tests.dat");
fans.open("answers.dat");
fout.open("table.out");

fans >> answers;

fout << setw(11) << "student-id" << setw(19) << "number correct" << endl << endl;

ftests >> id >> responses;

while (!ftests.eof())
{
    numstudents++;
    numcorrect = 0;

    for (i = 0; i < 20; i++)
    {
        if (responses[i] == answers[i])
        {
            numcorrect++;
        }
        for (j = 0; j < 5; j++)
        {

            if (responses[i] == (char)('A' + j))
            {
                chart[i][j]++;

            }

        }

    }

    fout << setw(11) << id << setw(19) << numcorrect << endl;

    ftests >> id >> responses;

}

fout << endl << endl << endl;

fout << "number of students taking exam = " << numstudents << endl << endl;

fout << setw(8) << "question" << setw(5) << "A" << setw(5) << "B" << setw(5) << "C" << setw(5) << "D" << setw(5) << "E" << endl;

for (i = 0; i < 20; i++)
{
    fout << setw(2) << i + 1  << " " << setw(10);
    for (j = 0; j < 5; j++)
    {
        fout << chart[i][j];

        if (responses[i] == i)//I BELIEVE THE PROBLEM LIES HERE!!!
        {
            fout << "*" << setw(4);
        }
        else
        {
            fout << " " << setw(4);

        }
    }
    fout << endl;
}

}

The tables looks like this:

 student-id     number correct

430-52-6192                 13
112-81-5225                 19
120-49-5322                 12
456-65-3211                  2
990-45-0978                  4
324-98-5445                  6
112-34-3443                 12
435-56-8790                 18
452-23-5675                  6
776-45-5454                  7
567-71-9909                  6
345-54-7834                  9
555-12-2341                 18
568-09-0096                 20
664-61-0987                 10
612-45-7687                  5
567-23-1125                  3
561-43-6781                  6
498-12-4321                  3
479-01-4867                  4
489-90-0999                 17
456-09-1111                 19
561-66-6657                  3

number of students taking exam = 23

question    A    B    C    D    E
 1          5    1   13    3    1
 2          4    7    1    7    4
 3          2    3    2    2   14
 4          2    1    3   13    4
 5          2    8    1    4    8
 6          5    1    3    3   11
 7          5    7    0    4    7
 8         11    4    0    3    5
 9          3    2    1    2   15
10          0    1   12    3    7
11          6    2    4   10    1
12          2    2    4    9    6
13          9    4    0    6    4
14          4    2    2    2   13
15          3    3    1    1   15
16          1    8    4    3    7
17          6    3    1    7    6
18          4    1    2    5   11
19          0    1    1   10   11
20          2    0    1    1   19

Where as table 2 should look like this:

question    A    B    C    D    E
 1          5    1   13*   3    1
 2          4    7*   1    7    4
 3          2    3    2    2   14*
 4          2    1    3   13*   4
 5          2    8*   1    4    8
 6          5    1    3    3   11*
 7          5    7*   0    4    7
 8         11*   4    0    3    5
 9          3    2    1    2   15*
10          0    1   12*   3    7
11          6    2    4   10*   1
12          2    2    4    9*   6
13          9*   4    0    6    4
14          4    2    2    2   13*
15          3    3    1    1   15*
16          1    8*   4    3    7
17          6    3    1    7*   6
18          4    1    2    5   11*
19          0    1    1   10*  11
20          2    0    1    1   19*

I hope I am being clear enough and any help is appreciated!


问:
Prolog: searching if 2 elements in a list occur equally
I am new to Prolog and not a native speaker, so if you do not understand me,  I am sorry.

My question is how can I find if a and b from a list appears equally?

For example, [a,a,b,b] should give me true but if either one appears more than the other it should give false. ex: [a,a,a,b,b].

Can anyone help me please? This is what I have so far and I know it is wrong but I am trying.

```<code>count(N,[],0).
count(N,[N|T],U) :-
   !,
   count(N,T,U1),
   U is U1+1.
count(N,[H|T],U) :-
   count(N,T,U).

occurrences([],[]).
occurrences([H|T],[[H,X]|Y]) :-
   count(H,[H|T],X),
   occurrences(T1,Y).
</code>```

答:
You could write a predicate occurrences/5 that is true if the second and third arguments occur equally often in the list that is the first argument. The 4th and 5th arguments are the corresponding counters. Then the predicate occurrences/1 is the calling predicate:

```<code>occurrences(List) :-
   occurrences(List,a,b,0,0).

occurrences([],_A,_B,N,N).
occurrences([A|Xs],A,B,N0,M) :-
   N1 is N0+1,
   occurrences(Xs,A,B,N1,M).
occurrences([B|Xs],A,B,N,M0) :-
   M1 is M0+1,
   occurrences(Xs,A,B,N,M1).
occurrences([X|Xs],A,B,N,M) :-
   dif(A,X),
   dif(B,X),
   occurrences(Xs,A,B,N,M).
</code>```

You start with the counters at 0 and depending on the head of the list being equal to A or B the corresponding counter is incremented or no counter is incremented if the head differs from both. Now let's see the results for your given examples:

```<code>?- occurrences([a,a,b,b]).
true ;
false.

?- occurrences([a,a,a,b,b]).
false.
</code>```

However, I think a predicate occurrences/3 that lets you specify the two elements would be more useful:

```<code>occurrences(List,A,B) :-
   dif(A,B),
   occurrences(List,A,B,0,0).
</code>```

Then your example queries would look like this:

```<code>?- occurrences([a,a,b,b],a,b).
true ;
false.

?- occurrences([a,a,a,b,b],a,b).
false.
</code>```

You could also ask which elements occur equally often:

```<code>?- occurrences([a,a,b,b,c,c,d],X,Y).
X = a,
Y = b ;
X = a,
Y = c ;
X = b,
Y = a ;
X = c,
Y = a ;
X = b,
Y = c ;
X = c,
Y = b ;
dif(X, d),
dif(X, c),
dif(X, c),
dif(X, b),
dif(X, b),
dif(X, a),
dif(X, a),
dif(X, Y),
dif(Y, d),
dif(Y, c),
dif(Y, c),
dif(Y, b),
dif(Y, b),
dif(Y, a),
dif(Y, a).
</code>```

The last solution corresponds to two elements that do not appear in the list at all, since they both appear equally often, namely 0 times. If you want to use the predicate in the other direction, that is, to ask which lists there are such that two given elements appear equally often, you have to prefix a goal that is limiting the length of the list at the time of the predicate call, e.g.:

```<code>?- length(L,_),occurrences(L,a,b).
L = [] ;
L = [_G150],
dif(_G150, b),
dif(_G150, a) ;
L = [a, b] ;
L = [b, a] ;
L = [_G116, _G119],
dif(_G116, b),
dif(_G116, a),
dif(_G119, b),
dif(_G119, a) ;
L = [a, b, _G162],
dif(_G162, b),
dif(_G162, a) ;
L = [a, _G159, b],
dif(_G159, b),
dif(_G159, a) ;
L = [b, a, _G162],
dif(_G162, b),
dif(_G162, a) ;
.
.
.
</code>```

Body:
I am new to Prolog and not a native speaker, so if you do not understand me,  I am sorry.

My question is how can I find if a and b from a list appears equally?

For example, [a,a,b,b] should give me true but if either one appears more than the other it should give false. ex: [a,a,a,b,b].

Can anyone help me please? This is what I have so far and I know it is wrong but I am trying.

count(N,[],0).
count(N,[N|T],U) :-
   !,
   count(N,T,U1),
   U is U1+1.
count(N,[H|T],U) :-
   count(N,T,U).

occurrences([],[]).
occurrences([H|T],[[H,X]|Y]) :-
   count(H,[H|T],X),
   occurrences(T1,Y).

Body:
You could write a predicate occurrences/5 that is true if the second and third arguments occur equally often in the list that is the first argument. The 4th and 5th arguments are the corresponding counters. Then the predicate occurrences/1 is the calling predicate:

occurrences(List) :-
   occurrences(List,a,b,0,0).

occurrences([],_A,_B,N,N).
occurrences([A|Xs],A,B,N0,M) :-
   N1 is N0+1,
   occurrences(Xs,A,B,N1,M).
occurrences([B|Xs],A,B,N,M0) :-
   M1 is M0+1,
   occurrences(Xs,A,B,N,M1).
occurrences([X|Xs],A,B,N,M) :-
   dif(A,X),
   dif(B,X),
   occurrences(Xs,A,B,N,M).

You start with the counters at 0 and depending on the head of the list being equal to A or B the corresponding counter is incremented or no counter is incremented if the head differs from both. Now let's see the results for your given examples:

?- occurrences([a,a,b,b]).
true ;
false.

?- occurrences([a,a,a,b,b]).
false.

However, I think a predicate occurrences/3 that lets you specify the two elements would be more useful:

occurrences(List,A,B) :-
   dif(A,B),
   occurrences(List,A,B,0,0).

Then your example queries would look like this:

?- occurrences([a,a,b,b],a,b).
true ;
false.

?- occurrences([a,a,a,b,b],a,b).
false.

You could also ask which elements occur equally often:

?- occurrences([a,a,b,b,c,c,d],X,Y).
X = a,
Y = b ;
X = a,
Y = c ;
X = b,
Y = a ;
X = c,
Y = a ;
X = b,
Y = c ;
X = c,
Y = b ;
dif(X, d),
dif(X, c),
dif(X, c),
dif(X, b),
dif(X, b),
dif(X, a),
dif(X, a),
dif(X, Y),
dif(Y, d),
dif(Y, c),
dif(Y, c),
dif(Y, b),
dif(Y, b),
dif(Y, a),
dif(Y, a).

The last solution corresponds to two elements that do not appear in the list at all, since they both appear equally often, namely 0 times. If you want to use the predicate in the other direction, that is, to ask which lists there are such that two given elements appear equally often, you have to prefix a goal that is limiting the length of the list at the time of the predicate call, e.g.:

?- length(L,_),occurrences(L,a,b).
L = [] ;
L = [_G150],
dif(_G150, b),
dif(_G150, a) ;
L = [a, b] ;
L = [b, a] ;
L = [_G116, _G119],
dif(_G116, b),
dif(_G116, a),
dif(_G119, b),
dif(_G119, a) ;
L = [a, b, _G162],
dif(_G162, b),
dif(_G162, a) ;
L = [a, _G159, b],
dif(_G159, b),
dif(_G159, a) ;
L = [b, a, _G162],
dif(_G162, b),
dif(_G162, a) ;
.
.
.


问:
Unittest project Azure Functions could not load file or assembly 'Newtonsoft.Json'
I created a test project for a Function App as mentioned here. The Http triggered Azure Function I wrote, uses dependency injection (AzureFunctions.AutoFac) and looks like this:

```<code>[DependencyInjectionConfig(typeof(DependencyConfig))]
public static class CreateDeclarationsFunction
{
    [FunctionName("CreateDeclarationsFunction")]
    public static HttpResponseMessage Run(
        [HttpTrigger(AuthorizationLevel.Function, "post", Route = "CreateDeclarations")]HttpRequestMessage req,
        TraceWriter log,
        [Inject]IDeclarationDataService declarationDataService,
        [Inject]IClientDataService clientDataService)
    {
        log.Info("Http triggered function: CreateDeclarationsFunction  processed a request.");

        try
        {
            var clients = clientDataService.GetAll().ToList();

            foreach (var client in clients)
            {
                // Create and save new declaration for each client
                declarationDataService.CreateAndSaveNew(client.Id);
            }
        }
        catch (Exception ex)
        {
            return req.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
        }

        return req.CreateResponse(HttpStatusCode.OK);
    }
}
</code>```

And the unittest class (with Moq, Shouldly and NBuilder):

```<code>[TestClass]
public class CreateDeclarationsFunctionTest
{
    private Mock<IDeclarationDataService> _declarationDataService;
    private Mock<IClientDataService> _clientDataService;

    [TestInitialize]
    public void Initialize()
    {
        _declarationDataService = new Mock<IDeclarationDataService>();
        _clientDataService = new Mock<IClientDataService>();
    }

    [TestMethod]
    public void CreateDeclarations_ReturnsOk()
    {
        // Arrange
        var clients = Builder<Client>.CreateListOfSize(10).Build();

        _declarationDataService.Setup(x => x.CreateAndSaveNew(It.IsAny<int>()))
            .Returns(Builder<Declaration>.CreateNew().Build);

        // Act > Exception by calling the Run method
        var result = CreateDeclarationsFunction.Run(CreateRequest(""), new TraceWriterStub(TraceLevel.Info),
            _declarationDataService.Object, _clientDataService.Object);

        // Assert
        // TODO
    }

    private static HttpRequestMessage CreateRequest(string json)
    {
        // Just a mocked request
        var request = new HttpRequestMessage
        {
            Method = HttpMethod.Post,
            RequestUri = new Uri("https://localhost"),
            Content = new StringContent(json, Encoding.UTF8, "application/json")
        };

        return request;
    }
}
</code>```

When I run this unittest, it gives an exception.

```<code>Result StackTrace:
at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter..ctor()
   at System.Net.Http.Formatting.JsonMediaTypeFormatter..ctor()
   at System.Net.Http.Formatting.MediaTypeFormatterCollection.CreateDefaultFormatters()
   at System.Web.Http.HttpConfiguration.DefaultFormatters(HttpConfiguration config)
   at System.Web.Http.HttpConfiguration..ctor(HttpRouteCollection routes)
   at System.Net.Http.HttpRequestMessageExtensions.CreateErrorResponse(HttpRequestMessage request, HttpStatusCode statusCode, Func`2 errorCreator)
   at System.Net.Http.HttpRequestMessageExtensions.CreateErrorResponse(HttpRequestMessage request, HttpStatusCode statusCode, Exception exception)
   at FunctionApp.CreateDeclarationsFunction.Run(HttpRequestMessage req, TraceWriter log, IDeclarationDataService declarationDataService, IClientDataService clientDataService)
   at FunctionApp.Tests.CreateDeclarationsFunctionTest.CreateDeclarations_ReturnsOk() in C:\TFS\...\FunctionApp.Tests\CreateDeclarationsFunctionTest.cs:line 63
Result Message:
Test method FunctionApp.Tests.CreateDeclarationsFunctionTest.CreateDeclarations_ReturnsOk threw exception:
System.IO.FileLoadException: Could not load file or assembly 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
</code>```

The FunctionApp has 2 nested references to Newtonsoft.Json (9.0.1), but none to version 6.0.0.0.

Dependencies > Nuget > Microsoft.NET``.Sdk.Functions (1.0.6) > Newtonsoft.Json (9.0.1)

Dependencies > Nuget > AzureFunctions.Autofac (2.0.0) > Microsoft.Azure.Webjobs (2.1.0-beta4) > Newtonsoft.Json (9.0.1)

The test project has a reference to the FunctionApp project. The exception is only shown when unit testing and not when its running (and being invoked from the browser).
Does anybody have a solution for upper exception? Thanks.

UPDATE

I found out that the System.IO.FileLoadException occurs when returning req.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);

When returning req.CreateResponse(HttpStatusCode.OK); instead, it does not give the mentioned exception.

答:
I think because of the way I setup the test project (initially .NET standard and then converted the target framework manually to .NET Framework 4.6.1 as mentioned here), no app.config file is generated in the test project. Furthermore, I think that such a test project setup does not automatically generate binding redirects for nuget packages when updating the version of a nuget package partly in the solution.

As @FabioCavalcante mentioned, I manually had to add an app.config file to the test project and put a binding redirect for Newtonsoft.Json.

```<code><?xml version="1.0" encoding="utf-8" ?>
<configuration>
<runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-9.0.0.0" newVersion="9.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>
</code>```

Body:
I created a test project for a Function App as mentioned here. The Http triggered Azure Function I wrote, uses dependency injection (AzureFunctions.AutoFac) and looks like this:

[DependencyInjectionConfig(typeof(DependencyConfig))]
public static class CreateDeclarationsFunction
{
    [FunctionName("CreateDeclarationsFunction")]
    public static HttpResponseMessage Run(
        [HttpTrigger(AuthorizationLevel.Function, "post", Route = "CreateDeclarations")]HttpRequestMessage req,
        TraceWriter log,
        [Inject]IDeclarationDataService declarationDataService,
        [Inject]IClientDataService clientDataService)
    {
        log.Info("Http triggered function: CreateDeclarationsFunction  processed a request.");

        try
        {
            var clients = clientDataService.GetAll().ToList();

            foreach (var client in clients)
            {
                // Create and save new declaration for each client
                declarationDataService.CreateAndSaveNew(client.Id);
            }
        }
        catch (Exception ex)
        {
            return req.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
        }

        return req.CreateResponse(HttpStatusCode.OK);
    }
}

And the unittest class (with Moq, Shouldly and NBuilder):

[TestClass]
public class CreateDeclarationsFunctionTest
{
    private Mock<IDeclarationDataService> _declarationDataService;
    private Mock<IClientDataService> _clientDataService;

    [TestInitialize]
    public void Initialize()
    {
        _declarationDataService = new Mock<IDeclarationDataService>();
        _clientDataService = new Mock<IClientDataService>();
    }

    [TestMethod]
    public void CreateDeclarations_ReturnsOk()
    {
        // Arrange
        var clients = Builder<Client>.CreateListOfSize(10).Build();

        _declarationDataService.Setup(x => x.CreateAndSaveNew(It.IsAny<int>()))
            .Returns(Builder<Declaration>.CreateNew().Build);

        // Act > Exception by calling the Run method
        var result = CreateDeclarationsFunction.Run(CreateRequest(""), new TraceWriterStub(TraceLevel.Info),
            _declarationDataService.Object, _clientDataService.Object);

        // Assert
        // TODO
    }

    private static HttpRequestMessage CreateRequest(string json)
    {
        // Just a mocked request
        var request = new HttpRequestMessage
        {
            Method = HttpMethod.Post,
            RequestUri = new Uri("https://localhost"),
            Content = new StringContent(json, Encoding.UTF8, "application/json")
        };

        return request;
    }
}

When I run this unittest, it gives an exception.

Result StackTrace:
at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter..ctor()
   at System.Net.Http.Formatting.JsonMediaTypeFormatter..ctor()
   at System.Net.Http.Formatting.MediaTypeFormatterCollection.CreateDefaultFormatters()
   at System.Web.Http.HttpConfiguration.DefaultFormatters(HttpConfiguration config)
   at System.Web.Http.HttpConfiguration..ctor(HttpRouteCollection routes)
   at System.Net.Http.HttpRequestMessageExtensions.CreateErrorResponse(HttpRequestMessage request, HttpStatusCode statusCode, Func`2 errorCreator)
   at System.Net.Http.HttpRequestMessageExtensions.CreateErrorResponse(HttpRequestMessage request, HttpStatusCode statusCode, Exception exception)
   at FunctionApp.CreateDeclarationsFunction.Run(HttpRequestMessage req, TraceWriter log, IDeclarationDataService declarationDataService, IClientDataService clientDataService)
   at FunctionApp.Tests.CreateDeclarationsFunctionTest.CreateDeclarations_ReturnsOk() in C:\TFS\...\FunctionApp.Tests\CreateDeclarationsFunctionTest.cs:line 63
Result Message:
Test method FunctionApp.Tests.CreateDeclarationsFunctionTest.CreateDeclarations_ReturnsOk threw exception:
System.IO.FileLoadException: Could not load file or assembly 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

The FunctionApp has 2 nested references to Newtonsoft.Json (9.0.1), but none to version 6.0.0.0.

Dependencies > Nuget > Microsoft.NET``.Sdk.Functions (1.0.6) > Newtonsoft.Json (9.0.1)

Dependencies > Nuget > AzureFunctions.Autofac (2.0.0) > Microsoft.Azure.Webjobs (2.1.0-beta4) > Newtonsoft.Json (9.0.1)

The test project has a reference to the FunctionApp project. The exception is only shown when unit testing and not when its running (and being invoked from the browser).
Does anybody have a solution for upper exception? Thanks.

UPDATE

I found out that the System.IO.FileLoadException occurs when returning req.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);

When returning req.CreateResponse(HttpStatusCode.OK); instead, it does not give the mentioned exception.

Body:
I think because of the way I setup the test project (initially .NET standard and then converted the target framework manually to .NET Framework 4.6.1 as mentioned here), no app.config file is generated in the test project. Furthermore, I think that such a test project setup does not automatically generate binding redirects for nuget packages when updating the version of a nuget package partly in the solution.

As @FabioCavalcante mentioned, I manually had to add an app.config file to the test project and put a binding redirect for Newtonsoft.Json.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-9.0.0.0" newVersion="9.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>


问:
Does await new Task(async () => Actually halt execution until finished?
I guess I'm not really understanding the await command in c#. I thought that using await would allow a method to continue processing and would would work in a separate thread and return a value once it completed however, I have the following code:

```<code>public async Task<DatabaseActionResult> BackupToAzureAsync(DatabaseSchedule schedule)
{
    try
    {
        foreach (var o in myObjects)
        {
                await new Task(async () =>
                {
                    try
                    {
                        //Do some stuff.
                    }
                    catch (Exception e)
                    {
                        throw; //Should this throw the exception to the functions Try/Catch block so it can log it to the event viewer?
                    }
                }
            }
        }
    catch (Exception e)
    {
        //Log exception to event viewer and return a DatabaseActionResult object
    }
}
</code>```

However, the foreach() executes, waits for the task to complete, and then only after completion, continues to the next. If I remove the await statement, then it runs the task for every loop iteration simultaneously but the Try/Catch block doesn't throw the exception up the stack. Instead it just stop the service entirely as if it were a service unhandled exception.

How can I either get the new task to run once for each for/each loop without waiting for the previous one to complete, or how can I get the try/catch block to throw the exception up the stack so it can get caught and processed in the method's try/catch block?

Thanks!

FOLLOW-UP:

Would this work and still maintain the Try/Catch stack?

```<code>foreach (var t in tables)
{
    try
    {
        var tableTasks = new List<Task>
        {
            new Task(async () =>
                {
                    try
                    {
                        //Do stuff
                    }
                    catch (DataError e)
                    {
                        throw e;
                    }
                    catch (Exception e)
                    {
                        throw e;
                    }
                }
            )
        };
    }
    catch (Exception e)
    {
        return new DatabaseActionResult();
    }
}
</code>```

答:
I know some of these concepts took me a while to to get my head around as well.

Here is a complete example (C# 7.1) that I hope illustrates answers to the questions given in the original post:

How can I either get the new task to run once for each for/each loop without waiting for the previous one to complete, or how can I get the try/catch block to throw the exception up the stack so it can get caught and processed in the method's try/catch block?

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace AsyncTest
{
    class Program
    {
        static async Task Main(string[] args)
        {
            var data = new List<object>()
            {
                1, 2, "three", 4, 5
            };

            // Transform the data into a sequence of Tasks. Note that this does not start these tasks running.
            IEnumerable<Task> tasks = data.Select(async (o) =>
            {
                Console.WriteLine($"Processing: {o}");
                await Task.Delay(1000);
                if (o is string s) throw new InvalidOperationException($"Cannot perform operation on string '{s}'");
            });

            try
            {
                Console.WriteLine("Starting asynchronous processing");
                // This call starts all the Tasks in the sequence running. If any of those tasks raises an exception
                // the use of the await operator will rethrow that exception here, so we can catch it
                await Task.WhenAll(tasks);
                Console.WriteLine("All tasks processed successfully");
            }
            catch (InvalidOperationException e)
            {
                Console.WriteLine($"Error performing asynchronous work: {e.Message}");
                Console.WriteLine("Not all tasks processed successfully");
            }

            Console.WriteLine("Asynchronous processing finished. Exiting.");
        }
    }
}
</code>```

Body:
I guess I'm not really understanding the await command in c#. I thought that using await would allow a method to continue processing and would would work in a separate thread and return a value once it completed however, I have the following code:

public async Task<DatabaseActionResult> BackupToAzureAsync(DatabaseSchedule schedule)
{
    try
    {
        foreach (var o in myObjects)
        {
                await new Task(async () =>
                {
                    try
                    {
                        //Do some stuff.
                    }
                    catch (Exception e)
                    {
                        throw; //Should this throw the exception to the functions Try/Catch block so it can log it to the event viewer?
                    }
                }
            }
        }
    catch (Exception e)
    {
        //Log exception to event viewer and return a DatabaseActionResult object
    }
}

However, the foreach() executes, waits for the task to complete, and then only after completion, continues to the next. If I remove the await statement, then it runs the task for every loop iteration simultaneously but the Try/Catch block doesn't throw the exception up the stack. Instead it just stop the service entirely as if it were a service unhandled exception.

How can I either get the new task to run once for each for/each loop without waiting for the previous one to complete, or how can I get the try/catch block to throw the exception up the stack so it can get caught and processed in the method's try/catch block?

Thanks!

FOLLOW-UP:

Would this work and still maintain the Try/Catch stack?

foreach (var t in tables)
{
    try
    {
        var tableTasks = new List<Task>
        {
            new Task(async () =>
                {
                    try
                    {
                        //Do stuff
                    }
                    catch (DataError e)
                    {
                        throw e;
                    }
                    catch (Exception e)
                    {
                        throw e;
                    }
                }
            )
        };
    }
    catch (Exception e)
    {
        return new DatabaseActionResult();
    }
}

Body:
I know some of these concepts took me a while to to get my head around as well.

Here is a complete example (C# 7.1) that I hope illustrates answers to the questions given in the original post:

How can I either get the new task to run once for each for/each loop without waiting for the previous one to complete, or how can I get the try/catch block to throw the exception up the stack so it can get caught and processed in the method's try/catch block?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace AsyncTest
{
    class Program
    {
        static async Task Main(string[] args)
        {
            var data = new List<object>()
            {
                1, 2, "three", 4, 5
            };

            // Transform the data into a sequence of Tasks. Note that this does not start these tasks running.
            IEnumerable<Task> tasks = data.Select(async (o) =>
            {
                Console.WriteLine($"Processing: {o}");
                await Task.Delay(1000);
                if (o is string s) throw new InvalidOperationException($"Cannot perform operation on string '{s}'");
            });

            try
            {
                Console.WriteLine("Starting asynchronous processing");
                // This call starts all the Tasks in the sequence running. If any of those tasks raises an exception
                // the use of the await operator will rethrow that exception here, so we can catch it
                await Task.WhenAll(tasks);
                Console.WriteLine("All tasks processed successfully");
            }
            catch (InvalidOperationException e)
            {
                Console.WriteLine($"Error performing asynchronous work: {e.Message}");
                Console.WriteLine("Not all tasks processed successfully");
            }

            Console.WriteLine("Asynchronous processing finished. Exiting.");
        }
    }
}


问:
Force Android canvas to be on top of bitmap used for Google Maps markers
I'm drawing a circle with some text on top of a bitmap, and then using the bitmap as the icon for a Google Maps marker/pin.

Most of the time, it works perfectly, but sometimes the circle+text will show up BEHIND the bitmap - not good. It seems to consistently happen if i navigate to a new activity, and then go back.

Code:

```<code>// Make room for the circle
Bitmap myBitmap = Bitmap.createBitmap(dstWidth, dstHeight, Bitmap.Config.ARGB_8888);

Canvas canvas = new Canvas(myBitmap);
Matrix matrix = new Matrix();
int xMatrix = xPadding / 2;
matrix.setRectToRect(new RectF(0, 0, bitmap.getWidth(), bitmap.getHeight()), new RectF(xMatrix,yPadding, dstWidth - xMatrix, dstHeight), Matrix.ScaleToFit.CENTER);
canvas.drawBitmap(bitmap, matrix, null);
canvas.drawCircle(xPos, yPos, 30, backgroundPaint);
if(_badge != null && _badge.equalsIgnoreCase("") == false) {
    canvas.drawText(_badge, xPos, yPos+10, textPaint);
}
return myBitmap;
</code>```

Is there a way i can force my circle+text to be on top? Perhaps i should try to make my bitmap immutable (how do i do this?)

答:
Identifying the issue:
It's seems that you "don't clean after finishing your work".

What is that mean?: You are correctly showing circle and text on the top.

But after close activity/fragment and reopen the map you get weird result because of  drawing new canvas above last one. And you're doing that every time you open the map so it will be more weird of you navigated from map fragment much times.

Why that happened?:

Having multiple views (old canvas + old text and circle plus news of them) do that.

Solution:

Clear what you have made!.

One of the easiest ways is to clear your map in onStop() or onDestroy() : mMap.clear().

Other way: Is to draw canvas and objects only if needed.

Body:
I'm drawing a circle with some text on top of a bitmap, and then using the bitmap as the icon for a Google Maps marker/pin.

Most of the time, it works perfectly, but sometimes the circle+text will show up BEHIND the bitmap - not good. It seems to consistently happen if i navigate to a new activity, and then go back.

Code:

// Make room for the circle
Bitmap myBitmap = Bitmap.createBitmap(dstWidth, dstHeight, Bitmap.Config.ARGB_8888);

Canvas canvas = new Canvas(myBitmap);
Matrix matrix = new Matrix();
int xMatrix = xPadding / 2;
matrix.setRectToRect(new RectF(0, 0, bitmap.getWidth(), bitmap.getHeight()), new RectF(xMatrix,yPadding, dstWidth - xMatrix, dstHeight), Matrix.ScaleToFit.CENTER);
canvas.drawBitmap(bitmap, matrix, null);
canvas.drawCircle(xPos, yPos, 30, backgroundPaint);
if(_badge != null && _badge.equalsIgnoreCase("") == false) {
    canvas.drawText(_badge, xPos, yPos+10, textPaint);
}
return myBitmap;

Is there a way i can force my circle+text to be on top? Perhaps i should try to make my bitmap immutable (how do i do this?)


问:
WebRequest MVC HttpPost DateTime Format
I have an MVC Action.....

```<code>[HttpPost]
public ActionResult DoStuff(string myString, DateTime myDateTime)
</code>```

...and I'm calling the action from a compact framework application like so.....

```<code> WebRequest request = WebRequest.Create(url);

        // Set the Method property of the request to POST.
        request.Method = "POST";
        request.Proxy = null;

        // Create POST data and convert it to a byte array.
        string postData = "myString=Bonjour&myDateTime=" + DateTime.Now.ToString();

        byte[] byteArray = Encoding.UTF8.GetBytes(jsonPostData);

        // Set the ContentType property of the WebRequest.
        request.ContentType = "application/x-www-form-urlencoded";

        // Set the ContentLength property of the WebRequest.
        request.ContentLength = byteArray.Length;

        // Get the request stream.
        using (Stream dataStream = request.GetRequestStream())
        {
            dataStream.Write(byteArray, 0, byteArray.Length);
        }

        // Get the response.
        using (WebResponse response = request.GetResponse())
        {
            // Display the status.
            // Console.WriteLine(((HttpWebResponse)response).StatusDescription);

            // Get the stream containing content returned by the server.
            using (Stream responseStream = response.GetResponseStream())
            {
                // Read the response...
                using (StreamReader reader = new StreamReader(responseStream))
                {
                    Console.WriteLine(reader.ReadToEnd());
                }
            }
        }
</code>```

Problem is the "myDateTime" parameter is always null?   What format should the postData string be in for this to work (i've tried quite a few!)?

Many thanks,

ETFairfax

答:
I think your postData string is wrong. It should be:

```<code>string postData = "myString=Bonjour&myDateTime=" + DateTime.Now.ToString();
</code>```

More Info: ASP.NET MVC's parameter binding to arguments in a controller action will match on the name of the values posted or in the query string.

Title: WebRequest MVC HttpPost DateTime Format

Body:
I have an MVC Action.....

[HttpPost]
public ActionResult DoStuff(string myString, DateTime myDateTime)

...and I'm calling the action from a compact framework application like so.....

 WebRequest request = WebRequest.Create(url);

        // Set the Method property of the request to POST.
        request.Method = "POST";
        request.Proxy = null;

        // Create POST data and convert it to a byte array.
        string postData = "myString=Bonjour&myDateTime=" + DateTime.Now.ToString();

        byte[] byteArray = Encoding.UTF8.GetBytes(jsonPostData);

        // Set the ContentType property of the WebRequest.
        request.ContentType = "application/x-www-form-urlencoded";

        // Set the ContentLength property of the WebRequest.
        request.ContentLength = byteArray.Length;

        // Get the request stream.
        using (Stream dataStream = request.GetRequestStream())
        {
            dataStream.Write(byteArray, 0, byteArray.Length);
        }

        // Get the response.
        using (WebResponse response = request.GetResponse())
        {
            // Display the status.
            // Console.WriteLine(((HttpWebResponse)response).StatusDescription);

            // Get the stream containing content returned by the server.
            using (Stream responseStream = response.GetResponseStream())
            {
                // Read the response...
                using (StreamReader reader = new StreamReader(responseStream))
                {
                    Console.WriteLine(reader.ReadToEnd());
                }
            }
        }

Problem is the "myDateTime" parameter is always null?   What format should the postData string be in for this to work (i've tried quite a few!)?

Many thanks,

ETFairfax

Body:
I think your postData string is wrong. It should be:

string postData = "myString=Bonjour&myDateTime=" + DateTime.Now.ToString();

More Info: ASP.NET MVC's parameter binding to arguments in a controller action will match on the name of the values posted or in the query string.


问:
TypeError: an integer is required (got type str) in Tkinter
So I'm programming an app, which lets you store the info you provide to a listbox, which can be also used to print the data somewhere. (Create a txt with it stored.) I also tried all the advice from previous users posts, but couldn't find my case. Any help appreciated.

For some reason im getting the error you see in the title.

Here's my code:

```<code>from tkinter import*
from os import open

def addData():
    dataInsert = dataEntry.get()
    itemList.insert(END, dataInsert.upper())
    dataEntry.delete(0, END)

def deleteData():
    dataSelect = itemList.curselection()
    itemList.delete(dataSelect)

def clearData():
    itemList.delete(0, END)

def printData():
    dataDirectory = filedialog.askdirectory()
    f = open('items.txt', dataDirectory, 'ab+')
    f.write(bytes('', itemList.get(), 'UTF-8'))
    f.close()

def rootExit():
    root.destroy()

root = Tk()
root.config(bg='gray79')
root.title('Inventory Recording Systems')
root.geometry('1300x800')
root.resizable(width=False, height=False)

mainLabel = Label(text='Inventory Recording Systems',
                  font=('comic sans ms', 20, 'bold'),
                  bg='gray79',
                  fg='black')

mainLabel.place(x=360, y=10)

f1 = Frame(root,
           bg='black',
           width=300,
           height=40)

f1.place(x=40, y=22)

f2 = Frame(root,
           bg='black',
           width=300,
           height=40)

f2.place(x=950, y=22)

dataLabel = Label(root,
                  text='Enter Data:',
                  font=('comic sans ms', 20, 'bold'),
                  bg='gray79')

dataLabel.place(x=10, y=130)

dataEntry = Entry(root,
                  font=('arial', 16, 'bold'))

dataEntry.place(x=250, y=142)

itemList = Listbox(root,
                    font=('arial', 15, 'bold'),
                    width=47,
                    height=16)

itemList.place(x=10, y=200)

addButton = Button(root,
                   text='Add Data',
                   font=('arial', 20, 'bold'),
                   bg='gray89',
                   fg='black',
                   relief=GROOVE,
                   width=15,
                   height=1,
                   bd=5,
                   command=addData)

addButton.place(x=865, y=215)

deleteButton = Button(root,
                   text='Delete Data',
                   font=('arial', 20, 'bold'),
                   bg='gray89',
                   fg='black',
                   relief=GROOVE,
                   width=15,
                   height=1,
                   bd=5,
                   command=deleteData)

deleteButton.place(x=865, y=345)

clearButton = Button(root,
                   text='Clear Data',
                   font=('arial', 20, 'bold'),
                   bg='gray89',
                   fg='black',
                   relief=GROOVE,
                   width=15,
                   height=1,
                   bd=5,
                   command=clearData)

clearButton.place(x=865, y=470)

printButton = Button(root,
                   text='Print Data',
                   font=('arial', 20, 'bold'),
                   bg='gray89',
                   fg='black',
                   relief=GROOVE,
                   width=15,
                   height=1,
                   bd=5,
                   command=printData)

printButton.place(x=865, y=595)

exitButton = Button(root,
                   text='Exit',
                   font=('arial', 10, 'bold'),
                   bg='gray89',
                   fg='black',
                   relief=GROOVE,
                   width=6,
                   height=1,
                   bd=5,
                   command=rootExit)

exitButton.place(x=1212, y=752)

root.mainloop()
</code>```

答:
The parameter encoding  has to be passed like this

This code need to be re-written as

```<code>f.write(bytes('', itemList.get(), 'UTF-8'))
</code>```

as

```<code>f.write(bytes('', itemList.get(), encoding='UTF-8'))
</code>```

Body:
So I'm programming an app, which lets you store the info you provide to a listbox, which can be also used to print the data somewhere. (Create a txt with it stored.) I also tried all the advice from previous users posts, but couldn't find my case. Any help appreciated.

For some reason im getting the error you see in the title.

Here's my code:

from tkinter import*
from os import open

def addData():
    dataInsert = dataEntry.get()
    itemList.insert(END, dataInsert.upper())
    dataEntry.delete(0, END)

def deleteData():
    dataSelect = itemList.curselection()
    itemList.delete(dataSelect)

def clearData():
    itemList.delete(0, END)

def printData():
    dataDirectory = filedialog.askdirectory()
    f = open('items.txt', dataDirectory, 'ab+')
    f.write(bytes('', itemList.get(), 'UTF-8'))
    f.close()

def rootExit():
    root.destroy()

root = Tk()
root.config(bg='gray79')
root.title('Inventory Recording Systems')
root.geometry('1300x800')
root.resizable(width=False, height=False)

mainLabel = Label(text='Inventory Recording Systems',
                  font=('comic sans ms', 20, 'bold'),
                  bg='gray79',
                  fg='black')

mainLabel.place(x=360, y=10)

f1 = Frame(root,
           bg='black',
           width=300,
           height=40)

f1.place(x=40, y=22)

f2 = Frame(root,
           bg='black',
           width=300,
           height=40)

f2.place(x=950, y=22)

dataLabel = Label(root,
                  text='Enter Data:',
                  font=('comic sans ms', 20, 'bold'),
                  bg='gray79')

dataLabel.place(x=10, y=130)

dataEntry = Entry(root,
                  font=('arial', 16, 'bold'))

dataEntry.place(x=250, y=142)

itemList = Listbox(root,
                    font=('arial', 15, 'bold'),
                    width=47,
                    height=16)

itemList.place(x=10, y=200)

addButton = Button(root,
                   text='Add Data',
                   font=('arial', 20, 'bold'),
                   bg='gray89',
                   fg='black',
                   relief=GROOVE,
                   width=15,
                   height=1,
                   bd=5,
                   command=addData)

addButton.place(x=865, y=215)

deleteButton = Button(root,
                   text='Delete Data',
                   font=('arial', 20, 'bold'),
                   bg='gray89',
                   fg='black',
                   relief=GROOVE,
                   width=15,
                   height=1,
                   bd=5,
                   command=deleteData)

deleteButton.place(x=865, y=345)

clearButton = Button(root,
                   text='Clear Data',
                   font=('arial', 20, 'bold'),
                   bg='gray89',
                   fg='black',
                   relief=GROOVE,
                   width=15,
                   height=1,
                   bd=5,
                   command=clearData)

clearButton.place(x=865, y=470)

printButton = Button(root,
                   text='Print Data',
                   font=('arial', 20, 'bold'),
                   bg='gray89',
                   fg='black',
                   relief=GROOVE,
                   width=15,
                   height=1,
                   bd=5,
                   command=printData)

printButton.place(x=865, y=595)

exitButton = Button(root,
                   text='Exit',
                   font=('arial', 10, 'bold'),
                   bg='gray89',
                   fg='black',
                   relief=GROOVE,
                   width=6,
                   height=1,
                   bd=5,
                   command=rootExit)

exitButton.place(x=1212, y=752)

root.mainloop()

Body:
The parameter encoding  has to be passed like this

This code need to be re-written as

f.write(bytes('', itemList.get(), 'UTF-8'))

as

f.write(bytes('', itemList.get(), encoding='UTF-8'))


问:
Can I place Function definition in one script and function call in another script
Can I place Function definition in one script
and function call in another script in shell?</p>

答:
Yes, here's an example:</p>

```<code>$ cat library.sh
function func() {
  echo "hello"
}

$ cat main.sh
source library.sh
func

$ ./main.sh
</code>```

Body:
Yes, here's an example:

$ cat library.sh
function func() {
  echo "hello"
}

$ cat main.sh
source library.sh
func

$ ./main.sh


问:
How is it possible that kill -9 for a process on Linux has no effect?
I'm writing a plugin to highlight text strings automatically as you visit a web site. It's like the highlight search results but automatic and for many words; it could be used for people with allergies to make words really stand out, for example, when they browse a food site.

But I have problem. When I try to close an empty, fresh FF window, it somehow blocks the whole process. When I kill the process, all the windows vanish, but the Firefox process stays alive (parent PID is 1, doesn't listen to any signals, has lots of resources open, still eats CPU, but won't budge).

So two questions:

How is it even possible for a process not to listen to kill -9 (neither as user nor as root)?

Is there anything I can do but a reboot?

[EDIT] This is the offending process:

```<code>USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
digulla  16688  4.3  4.2 784476 345464 pts/14  D    Mar28  75:02 /opt/firefox-3.0/firefox-bin
</code>```

Same with ps -ef | grep firefox

```<code>UID        PID  PPID  C STIME TTY          TIME CMD
digulla  16688     1  4 Mar28 pts/14   01:15:02 /opt/firefox-3.0/firefox-bin
</code>```

It's the only process left. As you can see, it's not a zombie, it's running! It doesn't listen to kill -9, no matter if I kill by PID or name! If I try to connect with strace, then the strace also hangs and can't be killed. There is no output, either. My guess is that FF hangs in some kernel routine but which?

[EDIT2] Based on feedback by sigjuice:

```<code>ps axopid,comm,wchan
</code>```

can show you in which kernel routine a process hangs. In my case, the offending plugin was the Beagle Indexer (openSUSE 11.1). After disabling the plugin, FF was a quick and happy fox again.

答:
I lately get trapped into a pitfall of Double Fork and had landed to this page before finally finding my answer. The symptoms are identical even if the problem is not the same:

WYKINWYT :What You Kill Is Not What You Thought

The minimal test code is shown below based on an example for an SNMP Daemon

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>

int main(int argc, char* argv[])
{
    //We omit the -f option (do not Fork) to reproduce the problem
    char * options[]={"/usr/local/sbin/snmpd",/*"-f","*/-d","--master=agentx", "-Dagentx","--agentXSocket=tcp:localhost:1706",  "udp:10161", (char*) NULL};

    pid_t pid = fork();
    if ( 0 > pid ) return -1;

    switch(pid)
    {
        case 0:
        {   //Child launches SNMP daemon
            execv(options[0],options);
            exit(-2);
            break;
        }
        default:
        {
            sleep(10); //Simulate "long" activity

            kill(pid,SIGTERM);//kill what should be child,
                              //i.e the SNMP daemon I assume
            printf("Signal sent to %d\n",pid);

            sleep(10); //Simulate "long" operation before closing
            waitpid(pid);
            printf("SNMP should be now down\n");

            getchar();//Blocking (for observation only)
            break;
        }
    }
    printf("Bye!\n");
}
```

<p>During the first phase the main process (7699) launches the SNMP daemon (7700) but we can see that this one is now <em>Defunct/Zombie</em>. Beside we can see another process (7702) with the options we specified</p>

```[nils@localhost ~]$ ps -ef | tail
root       7439      2  0 23:00 ?        00:00:00 [kworker/1:0]
root       7494      2  0 23:03 ?        00:00:00 [kworker/0:1]
root       7544      2  0 23:08 ?        00:00:00 [kworker/0:2]
root       7605      2  0 23:10 ?        00:00:00 [kworker/1:2]
root       7698    729  0 23:11 ?        00:00:00 sleep 60
nils       7699   2832  0 23:11 pts/0    00:00:00 ./main
nils       7700   7699  0 23:11 pts/0    00:00:00 [snmpd] <defunct>
nils       7702      1  0 23:11 ?        00:00:00 /usr/local/sbin/snmpd -Lo -d --master=agentx -Dagentx --agentXSocket=tcp:localhost:1706 udp:10161
nils       7727   3706  0 23:11 pts/1    00:00:00 ps -ef
nils       7728   3706  0 23:11 pts/1    00:00:00 tail
```

<p>After the 10 sec simulated we will try to kill the only process we know (7700). What we succeed at last with <em>waitpid()</em>. But Process 7702 is still here</p>

```[nils@localhost ~]$ ps -ef | tail
root       7431      2  0 23:00 ?        00:00:00 [kworker/u256:1]
root       7439      2  0 23:00 ?        00:00:00 [kworker/1:0]
root       7494      2  0 23:03 ?        00:00:00 [kworker/0:1]
root       7544      2  0 23:08 ?        00:00:00 [kworker/0:2]
root       7605      2  0 23:10 ?        00:00:00 [kworker/1:2]
root       7698    729  0 23:11 ?        00:00:00 sleep 60
nils       7699   2832  0 23:11 pts/0    00:00:00 ./main
nils       7702      1  0 23:11 ?        00:00:00 /usr/local/sbin/snmpd -Lo -d --master=agentx -Dagentx --agentXSocket=tcp:localhost:1706 udp:10161
nils       7751   3706  0 23:12 pts/1    00:00:00 ps -ef
nils       7752   3706  0 23:12 pts/1    00:00:00 tail
```

<p>After giving a character to the getchar() function our main process terminates but the SNMP daemon with the pid 7002 is still here</p>

```[nils@localhost ~]$ ps -ef | tail
postfix    7399   1511  0 22:58 ?        00:00:00 pickup -l -t unix -u
root       7431      2  0 23:00 ?        00:00:00 [kworker/u256:1]
root       7439      2  0 23:00 ?        00:00:00 [kworker/1:0]
root       7494      2  0 23:03 ?        00:00:00 [kworker/0:1]
root       7544      2  0 23:08 ?        00:00:00 [kworker/0:2]
root       7605      2  0 23:10 ?        00:00:00 [kworker/1:2]
root       7698    729  0 23:11 ?        00:00:00 sleep 60
nils       7702      1  0 23:11 ?        00:00:00 /usr/local/sbin/snmpd -Lo -d --master=agentx -Dagentx --agentXSocket=tcp:localhost:1706 udp:10161
nils       7765   3706  0 23:12 pts/1    00:00:00 ps -ef
nils       7766   3706  0 23:12 pts/1    00:00:00 tail
```

Conclusion

The fact that we ignored the double fork mechanism made us think that the kill action did not succeed. But in fact we simply killed the wrong process !!

By adding the -f option ( Do Not (Double) Fork ) all go as expected

OwnerDisplayName: Aaron Digulla

Body:
I'm writing a plugin to highlight text strings automatically as you visit a web site. It's like the highlight search results but automatic and for many words; it could be used for people with allergies to make words really stand out, for example, when they browse a food site.

But I have problem. When I try to close an empty, fresh FF window, it somehow blocks the whole process. When I kill the process, all the windows vanish, but the Firefox process stays alive (parent PID is 1, doesn't listen to any signals, has lots of resources open, still eats CPU, but won't budge).

So two questions:

How is it even possible for a process not to listen to kill -9 (neither as user nor as root)?

Is there anything I can do but a reboot?

[EDIT] This is the offending process:

USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
digulla  16688  4.3  4.2 784476 345464 pts/14  D    Mar28  75:02 /opt/firefox-3.0/firefox-bin

Same with ps -ef | grep firefox

UID        PID  PPID  C STIME TTY          TIME CMD
digulla  16688     1  4 Mar28 pts/14   01:15:02 /opt/firefox-3.0/firefox-bin

It's the only process left. As you can see, it's not a zombie, it's running! It doesn't listen to kill -9, no matter if I kill by PID or name! If I try to connect with strace, then the strace also hangs and can't be killed. There is no output, either. My guess is that FF hangs in some kernel routine but which?

[EDIT2] Based on feedback by sigjuice:

ps axopid,comm,wchan

can show you in which kernel routine a process hangs. In my case, the offending plugin was the Beagle Indexer (openSUSE 11.1). After disabling the plugin, FF was a quick and happy fox again.

LastEditorDisplayName: Dave Sherohman

Body:
I lately get trapped into a pitfall of Double Fork and had landed to this page before finally finding my answer. The symptoms are identical even if the problem is not the same:

WYKINWYT :What You Kill Is Not What You Thought

The minimal test code is shown below based on an example for an SNMP Daemon

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>

int main(int argc, char* argv[])
{
    //We omit the -f option (do not Fork) to reproduce the problem
    char * options[]={"/usr/local/sbin/snmpd",/*"-f","*/-d","--master=agentx", "-Dagentx","--agentXSocket=tcp:localhost:1706",  "udp:10161", (char*) NULL};

    pid_t pid = fork();
    if ( 0 > pid ) return -1;

    switch(pid)
    {
        case 0:
        {   //Child launches SNMP daemon
            execv(options[0],options);
            exit(-2);
            break;
        }
        default:
        {
            sleep(10); //Simulate "long" activity

            kill(pid,SIGTERM);//kill what should be child,
                              //i.e the SNMP daemon I assume
            printf("Signal sent to %d\n",pid);

            sleep(10); //Simulate "long" operation before closing
            waitpid(pid);
            printf("SNMP should be now down\n");

            getchar();//Blocking (for observation only)
            break;
        }
    }
    printf("Bye!\n");
}

During the first phase the main process (7699) launches the SNMP daemon (7700) but we can see that this one is now Defunct/Zombie. Beside we can see another process (7702) with the options we specified

[nils@localhost ~]$ ps -ef | tail
root       7439      2  0 23:00 ?        00:00:00 [kworker/1:0]
root       7494      2  0 23:03 ?        00:00:00 [kworker/0:1]
root       7544      2  0 23:08 ?        00:00:00 [kworker/0:2]
root       7605      2  0 23:10 ?        00:00:00 [kworker/1:2]
root       7698    729  0 23:11 ?        00:00:00 sleep 60
nils       7699   2832  0 23:11 pts/0    00:00:00 ./main
nils       7700   7699  0 23:11 pts/0    00:00:00 [snmpd] <defunct>
nils       7702      1  0 23:11 ?        00:00:00 /usr/local/sbin/snmpd -Lo -d --master=agentx -Dagentx --agentXSocket=tcp:localhost:1706 udp:10161
nils       7727   3706  0 23:11 pts/1    00:00:00 ps -ef
nils       7728   3706  0 23:11 pts/1    00:00:00 tail

After the 10 sec simulated we will try to kill the only process we know (7700). What we succeed at last with waitpid(). But Process 7702 is still here

[nils@localhost ~]$ ps -ef | tail
root       7431      2  0 23:00 ?        00:00:00 [kworker/u256:1]
root       7439      2  0 23:00 ?        00:00:00 [kworker/1:0]
root       7494      2  0 23:03 ?        00:00:00 [kworker/0:1]
root       7544      2  0 23:08 ?        00:00:00 [kworker/0:2]
root       7605      2  0 23:10 ?        00:00:00 [kworker/1:2]
root       7698    729  0 23:11 ?        00:00:00 sleep 60
nils       7699   2832  0 23:11 pts/0    00:00:00 ./main
nils       7702      1  0 23:11 ?        00:00:00 /usr/local/sbin/snmpd -Lo -d --master=agentx -Dagentx --agentXSocket=tcp:localhost:1706 udp:10161
nils       7751   3706  0 23:12 pts/1    00:00:00 ps -ef
nils       7752   3706  0 23:12 pts/1    00:00:00 tail

After giving a character to the getchar() function our main process terminates but the SNMP daemon with the pid 7002 is still here

[nils@localhost ~]$ ps -ef | tail
postfix    7399   1511  0 22:58 ?        00:00:00 pickup -l -t unix -u
root       7431      2  0 23:00 ?        00:00:00 [kworker/u256:1]
root       7439      2  0 23:00 ?        00:00:00 [kworker/1:0]
root       7494      2  0 23:03 ?        00:00:00 [kworker/0:1]
root       7544      2  0 23:08 ?        00:00:00 [kworker/0:2]
root       7605      2  0 23:10 ?        00:00:00 [kworker/1:2]
root       7698    729  0 23:11 ?        00:00:00 sleep 60
nils       7702      1  0 23:11 ?        00:00:00 /usr/local/sbin/snmpd -Lo -d --master=agentx -Dagentx --agentXSocket=tcp:localhost:1706 udp:10161
nils       7765   3706  0 23:12 pts/1    00:00:00 ps -ef
nils       7766   3706  0 23:12 pts/1    00:00:00 tail

Conclusion

The fact that we ignored the double fork mechanism made us think that the kill action did not succeed. But in fact we simply killed the wrong process !!

By adding the -f option ( Do Not (Double) Fork ) all go as expected