问:
I need to loop through TextBox to get the text values in asp.net c# using code behind?
```<code><asp:Panel runat="server" ID="pnlDocUpload">
<div class="row">
    <div class="col-md-4">
    <div class="column-pad-bottom column-pad-top">Document Title:</div>
        <div class="column-pad-bottom2"><asp:TextBox runat="server" ID="fuTitle1" CssClass="form-control"/></div>
        <div class="column-pad-bottom2"><asp:TextBox runat="server" ID="fuTitle2" CssClass="form-control"/></div>
        <div class="column-pad-bottom2"><asp:TextBox runat="server" ID="fuTitle3" CssClass="form-control"/></div>
        <div class="column-pad-bottom2"><asp:TextBox runat="server" ID="fuTitle4" CssClass="form-control"/></div>
        <div class="column-pad-bottom2"><asp:TextBox runat="server" ID="fuTitle5" CssClass="form-control"/></div>
        <div class="column-pad-bottom2"><asp:TextBox runat="server" ID="fuTitle6" CssClass="form-control"/></div>
        <div class="column-pad-bottom2"><asp:TextBox runat="server" ID="fuTitle7" CssClass="form-control"/></div>
        <div class="column-pad-bottom2"><asp:TextBox runat="server" ID="fuTitle8" CssClass="form-control"/></div>
        <div class="column-pad-bottom2"><asp:TextBox runat="server" ID="fuTitle9" CssClass="form-control"/></div>
        <div class="column-pad-bottom2"><asp:TextBox runat="server" ID="fuTitle10" CssClass="form-control"/></div>
        <div class="column-pad-bottom2"><asp:TextBox runat="server" ID="fuTitle11" CssClass="form-control"/></div>
        <div class="column-pad-bottom2"><asp:TextBox runat="server" ID="fuTitle12" CssClass="form-control"/></div>
    </div>

<H3> I tried using find controls it is always returning null </H3>

protected void btAddSection_Click(object sender, EventArgs e)
{
    string path = "C:/Users/emahou1/Desktop/testfolder";
    if (cbIsLink.Checked == true)
    {
        if (fuTitleLink.HasFile)
        {
            // it is other section has nothing to do with the 12 input tags
        }
        else
        {
            // get the link path from the text box and save it ??
        }
    }
    else
    {
        for (int i = 0; i < Request.Files.Count; i++  )
        {
            string text = "";
            for (int t = 1; t <= 5; t++)
            {
                TextBox tb = FindControl("fuTitle" + t.ToString()) as TextBox;
                if (tb != null) text += tb.Text;
            }
            if (Request.Files[i].FileName.ToString() != "")
            {

               // here i will collect the files and the textbox values to submit them to database
            }
        }
    }
}
</code>```

 I have 12 input tabs that I will use to upload files to the server, I am already looping throgh the input controls to get the files, but these text boxes i want to loop through them so I can capture the text entered by the user and use that text to rename each file being uploaded ....

答:
How about using FindControl inside the panel. Something like this

```<code>for (int t = 1; t <= 5; t++)
{
    TextBox tb = pnlDocUpload.FindControl("fuTitle" + t.ToString()) as TextBox;
    if (tb != null) text += tb.Text + "<br>";
}
</code>```

Body:
<asp:Panel runat="server" ID="pnlDocUpload">

Document Title:

<asp:TextBox runat="server" ID="fuTitle1" CssClass="form-control"/>

<asp:TextBox runat="server" ID="fuTitle2" CssClass="form-control"/>

<asp:TextBox runat="server" ID="fuTitle3" CssClass="form-control"/>

<asp:TextBox runat="server" ID="fuTitle4" CssClass="form-control"/>

<asp:TextBox runat="server" ID="fuTitle5" CssClass="form-control"/>

<asp:TextBox runat="server" ID="fuTitle6" CssClass="form-control"/>

<asp:TextBox runat="server" ID="fuTitle7" CssClass="form-control"/>

<asp:TextBox runat="server" ID="fuTitle8" CssClass="form-control"/>

<asp:TextBox runat="server" ID="fuTitle9" CssClass="form-control"/>

<asp:TextBox runat="server" ID="fuTitle10" CssClass="form-control"/>

<asp:TextBox runat="server" ID="fuTitle11" CssClass="form-control"/>

<asp:TextBox runat="server" ID="fuTitle12" CssClass="form-control"/>

 I tried using find controls it is always returning null

protected void btAddSection_Click(object sender, EventArgs e)
{
    string path = "C:/Users/emahou1/Desktop/testfolder";
    if (cbIsLink.Checked == true)
    {
        if (fuTitleLink.HasFile)
        {
            // it is other section has nothing to do with the 12 input tags
        }
        else
        {
            // get the link path from the text box and save it ??
        }
    }
    else
    {
        for (int i = 0; i < Request.Files.Count; i++  )
        {
            string text = "";
            for (int t = 1; t <= 5; t++)
            {
                TextBox tb = FindControl("fuTitle" + t.ToString()) as TextBox;
                if (tb != null) text += tb.Text;
            }
            if (Request.Files[i].FileName.ToString() != "")
            {

               // here i will collect the files and the textbox values to submit them to database
            }
        }
    }
}

 I have 12 input tabs that I will use to upload files to the server, I am already looping throgh the input controls to get the files, but these text boxes i want to loop through them so I can capture the text entered by the user and use that text to rename each file being uploaded ....

Body:
How about using FindControl inside the panel. Something like this

for (int t = 1; t <= 5; t++)
{
    TextBox tb = pnlDocUpload.FindControl("fuTitle" + t.ToString()) as TextBox;
    if (tb != null) text += tb.Text + "<br>";
}


来源: stackexchange

问:
How to write a POST method result into a file put contents content?
I would like to have the the result of an HTML form POST call into the content of another PHP file.
The goal is to have a redirection page generated dynamically  based on the HTML form values.

```<code>$redirectionLink = $_POST["redirectionLink"];
$redirectionFileContent =
`
<?php
header("Location:.".'$redirectionLink ');
?>
`;

$otherFileLocation= 'c:\xampp\htdocs\li\something.php';
file_put_contents($otherFileLocation,$redirectionFileContent);
</code>```

I receive the following output when I run the code above:

```<code>Notice: Array to string conversion in C:\xampp\htdocs\shortlink\process.php on line 25
</code>```

I don't know how it would be better. Maybe store it in a variable or write into it as a post call

I'm open to suggestions.

Thank you for your help in advance.

答:
If what you are trying to do is to simply make a new file that will redirect to the URL received from the POST request, this should do:</p>

```<code>$longlink = $_POST["longlink"];
$redirection = <<<EOT
<?php
header('Location:{$longlink}');
?>
EOT;
file_put_contents($fileplace, $redirection);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I would like to have the the result of an HTML form POST call into the content of another PHP file.
The goal is to have a redirection page generated dynamically  based on the HTML form values.

$redirectionLink = $_POST["redirectionLink"];
$redirectionFileContent =
`
<?php
header("Location:.".'$redirectionLink ');
?>
`;

$otherFileLocation= 'c:\xampp\htdocs\li\something.php';
file_put_contents($otherFileLocation,$redirectionFileContent);

I receive the following output when I run the code above:

Notice: Array to string conversion in C:\xampp\htdocs\shortlink\process.php on line 25

I don't know how it would be better. Maybe store it in a variable or write into it as a post call

I'm open to suggestions.

Thank you for your help in advance.

Body:
If what you are trying to do is to simply make a new file that will redirect to the URL received from the POST request, this should do:

$longlink = $_POST["longlink"];
$redirection = <<<EOT
<?php
header('Location:{$longlink}');
?>
EOT;
file_put_contents($fileplace, $redirection);


问:
Escape special character in CSS
I am getting image URL dynamically using PHP. I want to set that image into a div background.

All is good but the image URL (it's a blob) when I insert into css it changes & into & that resulting 404.

Please have a look in commented code for output.

Can anyone help me keep the URL as it is?

```<code><?php
$content = @$this->content[ 'q_view' ][ 'content' ];
preg_match_all( '/<img[^>]+src=[\'"]([^\'"]+)[\'"][^>]*>/i', $content, $matches );
if ( ! empty( $matches[ 0 ] ) ) {
    $this->_q_header_image = $matches[ 1 ][ 0 ];
} else {
    $this->_q_header_image = $this->rooturl . '/images/q-header-default.jpg';
}
var_dump($this->_q_header_image) // http://localhost/lion/?qa=blob&qa_blobid=17313457200794318190
echo '<style>.qa-q-feature-image { background-image: url("' . $this->_q_header_image . '")}</style>';

// http://localhost/lion/?qa=blob&qa_blobid=17313457200794318190
</code>```

答:
You just need to decode it before assigning it to $this->_q_header_image . Use the below code :-

```<code><?php
$content = @$this->content[ 'q_view' ][ 'content' ];
preg_match_all( '/<img[^>]+src=[\'"]([^\'"]+)[\'"][^>]*>/i', $content, $matches );
if ( ! empty( $matches[ 0 ] ) ) {
    $this->_q_header_image = html_entity_decode($matches[ 1 ][ 0 ]);
} else {
    $this->_q_header_image = $this->rooturl . '/images/q-header-default.jpg';
}
var_dump($this->_q_header_image) // http://localhost/lion/?qa=blob&qa_blobid=17313457200794318190
echo '<style>.qa-q-feature-image { background-image: url("' . $this->_q_header_image . '")}</style>';
</code>```

I hope this helps

Title: Escape special character in CSS

Body:
I am getting image URL dynamically using PHP. I want to set that image into a div background.

All is good but the image URL (it's a blob) when I insert into css it changes & into & that resulting 404.

Please have a look in commented code for output.

Can anyone help me keep the URL as it is?

<?php
$content = @$this->content[ 'q_view' ][ 'content' ];
preg_match_all( '/]+src=[\'"]([^\'"]+)[\'"][^>]*>/i', $content, $matches );
if ( ! empty( $matches[ 0 ] ) ) {
    $this->_q_header_image = $matches[ 1 ][ 0 ];
} else {
    $this->_q_header_image = $this->rooturl . '/images/q-header-default.jpg';
}
var_dump($this->_q_header_image) // http://localhost/lion/?qa=blob&qa_blobid=17313457200794318190
echo '';

// http://localhost/lion/?qa=blob&qa_blobid=17313457200794318190

Body:
You just need to decode it before assigning it to $this->_q_header_image . Use the below code :-

<?php
$content = @$this->content[ 'q_view' ][ 'content' ];
preg_match_all( '/<img[^>]+src=[\'"]([^\'"]+)[\'"][^>]*>/i', $content, $matches );
if ( ! empty( $matches[ 0 ] ) ) {
    $this->_q_header_image = html_entity_decode($matches[ 1 ][ 0 ]);
} else {
    $this->_q_header_image = $this->rooturl . '/images/q-header-default.jpg';
}
var_dump($this->_q_header_image) // http://localhost/lion/?qa=blob&qa_blobid=17313457200794318190
echo '<style>.qa-q-feature-image { background-image: url("' . $this->_q_header_image . '")}</style>';

I hope this helps


问:
Handle Entity Framework On Create POCO
I'd like to see if there's a way to hook into the Entity Framework context so I know as soon as it has finished creating a POCO object.

Are there any attributes I can use, such as with [OnDeserializing]? The purpose is to set a few values on the object as soon as the context is done creating it from a database fetch.

Thanks very much.

答:
Hook into the ObjectMaterialized event fired by ObjectContext.  In CTP5, you need to cast your DbContext like so in the constructor for your DbContext:

```<code>((IObjectContextAdapter)this).ObjectContext.ObjectMaterialized +=
    this.ObjectContext_OnObjectMaterialized;
</code>```

If you are not using Code First, you don't need to cast.  Then implement your function ObjectContext_OnObjectMaterialized(object sender, ObjectMaterializedEventArgs e).  Via the EventArgs, you will be able to access your object, which has just been materialized.

ContentLicense: CC BY-SA 2.5

Title: Handle Entity Framework On Create POCO

Body:
Hook into the ObjectMaterialized event fired by ObjectContext.  In CTP5, you need to cast your DbContext like so in the constructor for your DbContext:

((IObjectContextAdapter)this).ObjectContext.ObjectMaterialized +=
    this.ObjectContext_OnObjectMaterialized;

If you are not using Code First, you don't need to cast.  Then implement your function ObjectContext_OnObjectMaterialized(object sender, ObjectMaterializedEventArgs e).  Via the EventArgs, you will be able to access your object, which has just been materialized.


问:
iOS: Hide UIStackView SubViews
I have a small issue in mu UIStackView.
I created a project similar in this guide:

https://medium.com/@nrewik/easy-animation-with-uistackview-8878b2856ae2

and it works perfectly.
Anyway if in the stackView there is only a subView it disappears on the top-left corner instead to disappear completely from the bottom side.
Do you have any idea?
Thanks.

答: I found a solution to this problem, it's important to add a leading and trailing constraint to every single subview.</p>

Title: iOS: Hide UIStackView SubViews


问:
why does it only add 2 when passed by reference?
How come only when its passed by reference does the value of age change? why doesn't it work when passed by value?

```<code>    #include<stdio.h>
struct employee{
char name[20];
int age;
};
void modify_byVal(struct employee v){
    v.age=v.age+2;
    }
    void modify_byRef(struct employee *p){
 p ->age=p->age+2;
 }
 void main(){
     struct employee Sam = {"Sam", 35};
     struct employee Mary = {"Mary", 25};
     modify_byVal(Sam);
     modify_byRef(&Mary);
     printf("%s %d", Sam.name, Sam.age);
     printf(" ");
     printf("%s %d", Mary.name, Mary.age);
     }
</code>```

Output of code

答:
Pass by value : The copy of variable will be passed, change occurs on that copy not in actual variable

pass by address : The address is passed inside function so the change will occur on variable stored at that address

Body:
How come only when its passed by reference does the value of age change? why doesn't it work when passed by value?

    #include<stdio.h>
struct employee{
char name[20];
int age;
};
void modify_byVal(struct employee v){
    v.age=v.age+2;
    }
    void modify_byRef(struct employee *p){
 p ->age=p->age+2;
 }
 void main(){
     struct employee Sam = {"Sam", 35};
     struct employee Mary = {"Mary", 25};
     modify_byVal(Sam);
     modify_byRef(&Mary);
     printf("%s %d", Sam.name, Sam.age);
     printf(" ");
     printf("%s %d", Mary.name, Mary.age);
     }

Output of code


问:
How can I test what my readme.md file will look like before committing to github?
I am writing a readme for my github project in the .md format. Is there a way can I test what my readme.md file will look like before committing to github?   </p>

答: For those who wish to develop on their iPads, I like Textastic.  You can edit and preview the README.md files without an internet connection, once you have downloaded the document from the cloud.</p>


问:
PHP preg_replace shortening a string
So I've got this php code:

```<code>$text = preg_replace("/(\s)http:\/\/([\S]+?)(\s)/i" ,
"$1[url=\"http://$2\"]http://$2[/url]$3" , " $text ");
</code>```

I guess it's replacing http://xyz.xyz.xyz kind of strings into [url=http://xyz.xyz.xyz]http://xyz.xyz.xyz[/url] inside of a given text (in my case it's a postparser for my forum) right?

now what I'm trying to do is, to limit the stringlength of the http://xyz.xyz.xyz-string that comes inside the [url=http://xyz.xyz.xyz] http://xyz.xyz.xyz <-- this string [/url]
because sometimes users post very long links and those are messing up my forum design and look very ugly anyway.

is there a way I could realize that in php, while keeping the 1. http link like it is so it still links correct?

big thanks in advance! :)

答:
You could maybe just split the process in a couple of lines of code instead of one do-it-all preg_replace.

preg_match

check strlen for match

shorten url between [url][/url] if need

build replacement string

str_replace match with replacement string

Title: PHP preg_replace shortening a string

Body:
So I've got this php code:

$text = preg_replace("/(\s)http:\/\/([\S]+?)(\s)/i" ,
"$1[url=\"http://$2\"]http://$2[/url]$3" , " $text ");

I guess it's replacing http://xyz.xyz.xyz kind of strings into [url=http://xyz.xyz.xyz]http://xyz.xyz.xyz[/url] inside of a given text (in my case it's a postparser for my forum) right?

now what I'm trying to do is, to limit the stringlength of the http://xyz.xyz.xyz-string that comes inside the [url=http://xyz.xyz.xyz] http://xyz.xyz.xyz <-- this string [/url]
because sometimes users post very long links and those are messing up my forum design and look very ugly anyway.

is there a way I could realize that in php, while keeping the 1. http link like it is so it still links correct?

big thanks in advance! :)


问:
JHipster in 12 minutes -- problems
First time using JHipster.  Looks pretty awesome, but have a problem with Matt Raible's 12 minute video: Get Started with JHipster 4 (showcased on the web site front page)

I am running JHipster on the latest version of openSUSE (linux) with IntelliJ IDEA for the IDE.  I followed carefully his instructions, and broadly speaking everything works, but I have a problem.

The blog application fails to create a datepicker UI element for the entry edit page.  A date field is created in the database, but it is rendered on screen as a text string (appears to be ISO format e.g.2017-11-30T08:09:00) which can be edited as such, but is not very friendly.  Matt Raible's video shows a datepicker, but I don't get one.  Anyone know why?

Cheers!

PS: FireFox v52.5.0; Node v3.10.10; Yarn v1.3.2; using gradle, and compiling/launching by clicking the 'Run' button within IntelliJ  (which pops the browser open at localhost:8080).  No obvious errors appear in the console.

After I rebuild/run, my IntelliJ run window ends with:

```<code>Application 'blog' is running! Access URLs:
Local:      http://localhost:8080
External:   http://127.0.0.1:8080
Profile(s):     [swagger, dev]
</code>```

Also,
IntelliJ IDEA 2017.3
JRE: 1.8.0_152-release-915-b12 amd64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Linux 4.4.92-31-default

After that, I run 'yarn start' from the command line and open the browser at localhost:9000

Happy to add whatever additional information necessary to help get things moving...

PPS: Repeated steps on a Windows 10 64-bit machine, and exactly the same thing happens.

No datepicker.  Any ideas, anyone...?

答:
Ok! Wow!

Out of curiosity (and after thinking about Mr. Marziou's set of questions in his comment), I tried using a different browser (Opera v48.0.2685.52), and... I get a datepicker!

It seems the datepicker that comes "out-of-the-box" with JHipster doesn't work with Firefox (including the latest version: 57.0.1 64-bit).  Would have been nice if that was documented somewhere up front.

Thanks for your comments, Mr. Marziou!

Title: JHipster in 12 minutes -- problems

Body:
First time using JHipster.  Looks pretty awesome, but have a problem with Matt Raible's 12 minute video: Get Started with JHipster 4 (showcased on the web site front page)

I am running JHipster on the latest version of openSUSE (linux) with IntelliJ IDEA for the IDE.  I followed carefully his instructions, and broadly speaking everything works, but I have a problem.

The blog application fails to create a datepicker UI element for the entry edit page.  A date field is created in the database, but it is rendered on screen as a text string (appears to be ISO format e.g.2017-11-30T08:09:00) which can be edited as such, but is not very friendly.  Matt Raible's video shows a datepicker, but I don't get one.  Anyone know why?

Cheers!

PS: FireFox v52.5.0; Node v3.10.10; Yarn v1.3.2; using gradle, and compiling/launching by clicking the 'Run' button within IntelliJ  (which pops the browser open at localhost:8080).  No obvious errors appear in the console.

After I rebuild/run, my IntelliJ run window ends with:

Application 'blog' is running! Access URLs:
Local:      http://localhost:8080
External:   http://127.0.0.1:8080
Profile(s):     [swagger, dev]

Also,
IntelliJ IDEA 2017.3
JRE: 1.8.0_152-release-915-b12 amd64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Linux 4.4.92-31-default

After that, I run 'yarn start' from the command line and open the browser at localhost:9000

Happy to add whatever additional information necessary to help get things moving...

PPS: Repeated steps on a Windows 10 64-bit machine, and exactly the same thing happens.

No datepicker.  Any ideas, anyone...?


问:
Postcss-loader Autoprefixer not working with Webpack 3
I'm attempting to use a series of loaders to extract all the SCSS files into one file with ExtractTextPlugin. Within the series of loaders I have, I'm using the autoprefixer plugin that is used within postcss-loader. However, nothing seems to be getting prefixed!

My webpack config is as follows:

webpack.config.js

```<code>const path = require('path');
const autoprefixer = require('autoprefixer');
const ExtractTextPlugin = require('extract-text-webpack-plugin');

const config = {
  context: __dirname,
  entry: {
    app: [
      path.resolve(entrypath),
    ],
  },
  module: {
    rules: [
      {
        test: /\.scss$/,
        use: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: [
            'css-loader',
            'sass-loader',
            {
              loader: 'postcss-loader',
              options: {
                plugins: () => [autoprefixer()]
              }
            }
          ]
        }),
      },
    ],
  },
  output: {
    path: path.join(__dirname, '../app/assets/javascripts/generated/'),
  },
  plugins: [
    new ExtractTextPlugin({
      filename: 'compiled-draft-document-scss.css',
      allChunks: true
    }),
  ],
};

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

My output seems all good with the exception that none of the prefixes are added. Below are the relevant versions of packages I am using:

```<code>"extract-text-webpack-plugin": "3.0.1",
"webpack": "^3.1.0",
"style-loader": "^0.19.0",
"css-loader": "^0.23.1",
"moment": "^2.11.1",
"postcss-loader": "^0.10.1",
"sass-loader": "^6.0.6",
</code>```

答:
From postcss-loader README:

Use it after css-loader and style-loader, but before other preprocessor loaders like e.g. sass|less|stylus-loader.

So your loader chain should be:

```<code>[
  'css-loader',
  {
    loader: 'postcss-loader',
    options: {
      plugins: () => [autoprefixer()]
    }
  },
  'sass-loader'
]
</code>```

Body:
I'm attempting to use a series of loaders to extract all the SCSS files into one file with ExtractTextPlugin. Within the series of loaders I have, I'm using the autoprefixer plugin that is used within postcss-loader. However, nothing seems to be getting prefixed!

My webpack config is as follows:

webpack.config.js

const path = require('path');
const autoprefixer = require('autoprefixer');
const ExtractTextPlugin = require('extract-text-webpack-plugin');

const config = {
  context: __dirname,
  entry: {
    app: [
      path.resolve(entrypath),
    ],
  },
  module: {
    rules: [
      {
        test: /\.scss$/,
        use: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: [
            'css-loader',
            'sass-loader',
            {
              loader: 'postcss-loader',
              options: {
                plugins: () => [autoprefixer()]
              }
            }
          ]
        }),
      },
    ],
  },
  output: {
    path: path.join(__dirname, '../app/assets/javascripts/generated/'),
  },
  plugins: [
    new ExtractTextPlugin({
      filename: 'compiled-draft-document-scss.css',
      allChunks: true
    }),
  ],
};

module.exports = config;

My output seems all good with the exception that none of the prefixes are added. Below are the relevant versions of packages I am using:

"extract-text-webpack-plugin": "3.0.1",
"webpack": "^3.1.0",
"style-loader": "^0.19.0",
"css-loader": "^0.23.1",
"moment": "^2.11.1",
"postcss-loader": "^0.10.1",
"sass-loader": "^6.0.6",

Body:
From postcss-loader README:

Use it after css-loader and style-loader, but before other preprocessor loaders like e.g. sass|less|stylus-loader.

So your loader chain should be:

[
  'css-loader',
  {
    loader: 'postcss-loader',
    options: {
      plugins: () => [autoprefixer()]
    }
  },
  'sass-loader'
]


问:
How to set alignment of text in cell of a dynamically generated table in ASP?
I have the following table that I am working on. It is a dynamically generated table, </p>

```<code>TableRow durationTableRow = new TableRow();
TableDuration.Rows.Add(durationTableRow);
for (durationCellCounter = 1; durationCellCounter <= durationCellCount; durationCellCounter++)
{
    if (durationCellCounter == 1)
    {
        TableCell durationTableCell = new TableCell();
        durationTableCell.Text = "Duration: ";
        durationTableRow.Cells.Add(durationTableCell);
    }
    else if (durationCellCounter == 2)
    {
        TableCell durationTableCell = new TableCell();
        string duration = years + "Y. " + months + "M. " + days + "D.";
        durationTableCell.Text = duration;
        durationTableRow.Cells.Add(durationTableCell);
    }
}
</code>```

<p>I want to right-align the value of duration string in the table. </p>

答:
You can add an align attribute to the cell.

```<code>durationTableCell.Attributes.Add("align", "right");
</code>```

Or with css

```<code><asp:Table ID="TableDuration" CssClass="rightAlign"></asp:Table>

<style>
    .rightAlign td {
        text-align: right;
    }
</style>
</code>```

Body:
I have the following table that I am working on. It is a dynamically generated table,

TableRow durationTableRow = new TableRow();
TableDuration.Rows.Add(durationTableRow);
for (durationCellCounter = 1; durationCellCounter <= durationCellCount; durationCellCounter++)
{
    if (durationCellCounter == 1)
    {
        TableCell durationTableCell = new TableCell();
        durationTableCell.Text = "Duration: ";
        durationTableRow.Cells.Add(durationTableCell);
    }
    else if (durationCellCounter == 2)
    {
        TableCell durationTableCell = new TableCell();
        string duration = years + "Y. " + months + "M. " + days + "D.";
        durationTableCell.Text = duration;
        durationTableRow.Cells.Add(durationTableCell);
    }
}

I want to right-align the value of duration string in the table.

Body:
You can add an align attribute to the cell.

durationTableCell.Attributes.Add("align", "right");

Or with css

<asp:Table ID="TableDuration" CssClass="rightAlign"></asp:Table>

<style>
    .rightAlign td {
        text-align: right;
    }
</style>


问:
Why aren't variables being recognized even when i properly set them
I am relatively new to Xcode and Swift and i was following this guide: https://codewithchris.com/iphone-app-connect-to-mysql-database/#app but three of the variables aren't being recognized even though they were properly recognized earlier:

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

        // Retrieve cell
        let cellIdentifier: String = "BasicCell"
        let myCell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)!
        // Get the location to be shown
        let item: InputModel = feedItems[indexPath.row] as! InputModel
        // Get references to labels of cell
        myCell.textLabel!.text = item.Street

        return myCell
    }

}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    // Set selected location to var
    selectedLocation = feedItems[indexPath.row] as! InputModel
    // Manually call segue to detail view controller
    self.performSegue(withIdentifier: "detailSegue", sender: self)

}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    // Get reference to the destination view controller
    let detailVC  = segue.destination as! DetailViewController
    // Set the property to the selected location so when the view for
    // detail view controller loads, it can access that property to get the feeditem obj
    detailVC.selectedLocation = selectedLocation
}
</code>```

the result i got back was "use of unresolved identifier selectedLocation" twice and "use of unresolved identifier feedItems". i should also say that i changed the title of locationModel() to InputModel, and address to street. i can explain more and add source files if need be.

Edit: sorry, the variables were set earlier, here:

```<code>  class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, HomeModelProtocol  {

        //Properties
        var feedItems: NSArray = NSArray()
        var selectedLocation : InputModel = InputModel()
        @IBOutlet weak var listTableView: UITableView!

        override func viewDidLoad() {
            super.viewDidLoad()

            //set delegates and initialize homeModel

            self.listTableView.delegate = self
            self.listTableView.dataSource = self

            let homeModel = HomeModel()
            homeModel.delegate = self
            homeModel.downloadItems()

        }

        func itemsDownloaded(items: NSArray) {

            feedItems = items
            self.listTableView.reloadData()
        }

        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            // Return the number of feed items
            return feedItems.count

        }
</code>```

答:
I think that the culprit is the extra closing bracket "}". </p>

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

        // Retrieve cell
        let cellIdentifier: String = "BasicCell"
        let myCell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)!
        // Get the location to be shown
        let item: InputModel = feedItems[indexPath.row] as! InputModel
        // Get references to labels of cell
        myCell.textLabel!.text = item.Street

        return myCell
    }

}  <================ Delete this bracket because it is redundant here and move to the end  ======

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    ....
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // Return the number of feed items
            return feedItems.count

    }
} <======== MOVE IT HERE
</code>```

Body:
I am relatively new to Xcode and Swift and i was following this guide: https://codewithchris.com/iphone-app-connect-to-mysql-database/#app but three of the variables aren't being recognized even though they were properly recognized earlier:

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

        // Retrieve cell
        let cellIdentifier: String = "BasicCell"
        let myCell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)!
        // Get the location to be shown
        let item: InputModel = feedItems[indexPath.row] as! InputModel
        // Get references to labels of cell
        myCell.textLabel!.text = item.Street

        return myCell
    }

}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    // Set selected location to var
    selectedLocation = feedItems[indexPath.row] as! InputModel
    // Manually call segue to detail view controller
    self.performSegue(withIdentifier: "detailSegue", sender: self)

}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    // Get reference to the destination view controller
    let detailVC  = segue.destination as! DetailViewController
    // Set the property to the selected location so when the view for
    // detail view controller loads, it can access that property to get the feeditem obj
    detailVC.selectedLocation = selectedLocation
}

the result i got back was "use of unresolved identifier selectedLocation" twice and "use of unresolved identifier feedItems". i should also say that i changed the title of locationModel() to InputModel, and address to street. i can explain more and add source files if need be.

Edit: sorry, the variables were set earlier, here:

  class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, HomeModelProtocol  {

        //Properties
        var feedItems: NSArray = NSArray()
        var selectedLocation : InputModel = InputModel()
        @IBOutlet weak var listTableView: UITableView!

        override func viewDidLoad() {
            super.viewDidLoad()

            //set delegates and initialize homeModel

            self.listTableView.delegate = self
            self.listTableView.dataSource = self

            let homeModel = HomeModel()
            homeModel.delegate = self
            homeModel.downloadItems()

        }

        func itemsDownloaded(items: NSArray) {

            feedItems = items
            self.listTableView.reloadData()
        }

        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            // Return the number of feed items
            return feedItems.count

        }

Body:
I think that the culprit is the extra closing bracket "}".

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

        // Retrieve cell
        let cellIdentifier: String = "BasicCell"
        let myCell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)!
        // Get the location to be shown
        let item: InputModel = feedItems[indexPath.row] as! InputModel
        // Get references to labels of cell
        myCell.textLabel!.text = item.Street

        return myCell
    }

}  <================ Delete this bracket because it is redundant here and move to the end  ======

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    ....
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // Return the number of feed items
            return feedItems.count

    }
} <======== MOVE IT HERE


问:
Laravel delete all belongsToMany relations in belongsToMany relation
I have a Tournament model which contains a belongsToMany relationship with a Session model:

```<code>class Tournament extends Model{

    public function sessions(){
        return $this->belongsToMany(Session::class, 'tournament_has_sessions');
    }
}
</code>```

Then my sessions model contains a belongsToMany relationship with the User model:

```<code>class Session extends Model{

    public function users(){
        return $this->belongsToMany(User::class, 'session_has_users');
    }

}
</code>```

Now when I delete a Tournament, I want to delete all sessions and all information in the session_has_users table with it.

I have tried:

```<code>$tournament->sessions()->with('users')->delete(); -- < This
$tournament->sessions()->delete();
$tournament->users()->detach();
$tournament->delete();
</code>```

But it does't work. The data in the session_has_users table persists

I realize i could do something like this:

```<code>DB::table('session_has_users')->whereIn('session_id', $this->sessions()->pluck('id'))->delete();
</code>```

But is there a more efficient/handy (or even alternative if not more efficient) way to accomplish this?

答:
In the table 'tournament_has_sessions' you can set onDelete('cascade') like this

```<code>$table->integer('tournament_id')->unsigned()->nullable();
$table->foreign('tournament_id')->references('id')->on('tournaments')->onDelete('cascade');
$table->integer('session_id')->unsigned()->nullable();
$table->foreign('session_id')->references('id')->on('sessions')->onDelete('cascade');
</code>```

And when delete tournaments automaticly deleted all records in this table

Body:
I have a Tournament model which contains a belongsToMany relationship with a Session model:

class Tournament extends Model{

    public function sessions(){
        return $this->belongsToMany(Session::class, 'tournament_has_sessions');
    }
}

Then my sessions model contains a belongsToMany relationship with the User model:

class Session extends Model{

    public function users(){
        return $this->belongsToMany(User::class, 'session_has_users');
    }

}

Now when I delete a Tournament, I want to delete all sessions and all information in the session_has_users table with it.

I have tried:

$tournament->sessions()->with('users')->delete(); -- < This
$tournament->sessions()->delete();
$tournament->users()->detach();
$tournament->delete();

But it does't work. The data in the session_has_users table persists

I realize i could do something like this:

DB::table('session_has_users')->whereIn('session_id', $this->sessions()->pluck('id'))->delete();

But is there a more efficient/handy (or even alternative if not more efficient) way to accomplish this?

Body:
In the table 'tournament_has_sessions' you can set onDelete('cascade') like this

$table->integer('tournament_id')->unsigned()->nullable();
$table->foreign('tournament_id')->references('id')->on('tournaments')->onDelete('cascade');
$table->integer('session_id')->unsigned()->nullable();
$table->foreign('session_id')->references('id')->on('sessions')->onDelete('cascade');

And when delete tournaments automaticly deleted all records in this table


问:
Jquery .submit with function() does not work
I am using Jquery and I want to automatically update my form on the page if I click on a link or perform some action. If I use .submit() it works fine, if I use .submit(function(e){}) the form will not submit. I need to get the response from the form submission, thats why i need the .submit(function(e){}) to work over the .submit(). Thanks.

I have a form:

```<code>  <form action="action.html" id="form1">
  </form>
</code>```

I have a link:

```<code> <a href="" data-id="1" class="myLink">Link</a>
</code>```

When I click on the link I do the following:

```<code> $(document).on('click', '.myLink', function(e) {
      // this will call a function to submit my form...
      var response = saveEmailDraft($(this).data('id'));
      e.preventDefault();
 });

 function saveEmailDraft(id){
      $('#form' + id).submit(); // this works fine...
      $('#form' + id).submit(function(e){
          // this DOES NOT work...
          alert('my form submitted!');
      });

      // I've also tried;
      $(document).ready(function() {
           $('#form' + id).submit(); // this works fine...
           $('#form' + id).submit(function(e){
               // this DOES NOT work...
               alert('my form submitted!');
           });
      });

 }
</code>```

答:
You need to bind the event handler before you submit the form.

```<code>function saveEmailDraft(id){
    $('#form' + id).submit(function(e){
        alert('my form submitted!');
    });
    $('#form' + id).submit();
}
</code>```

But this won't let you get the response from the form submission. The event handler is executed before the form data is sent to the server. When the form is submitted, the page reloads and all current scripts stop running.

If you want to get the response, you need to use $.ajax (or a shortcut like $.get or $.post) instead of .submit().

Body:
I am using Jquery and I want to automatically update my form on the page if I click on a link or perform some action. If I use .submit() it works fine, if I use .submit(function(e){}) the form will not submit. I need to get the response from the form submission, thats why i need the .submit(function(e){}) to work over the .submit(). Thanks.

I have a form:

  <form action="action.html" id="form1">
  </form>

I have a link:

 Link

When I click on the link I do the following:

 $(document).on('click', '.myLink', function(e) {
      // this will call a function to submit my form...
      var response = saveEmailDraft($(this).data('id'));
      e.preventDefault();
 });

 function saveEmailDraft(id){
      $('#form' + id).submit(); // this works fine...
      $('#form' + id).submit(function(e){
          // this DOES NOT work...
          alert('my form submitted!');
      });

      // I've also tried;
      $(document).ready(function() {
           $('#form' + id).submit(); // this works fine...
           $('#form' + id).submit(function(e){
               // this DOES NOT work...
               alert('my form submitted!');
           });
      });

 }

Body:
You need to bind the event handler before you submit the form.

function saveEmailDraft(id){
    $('#form' + id).submit(function(e){
        alert('my form submitted!');
    });
    $('#form' + id).submit();
}

But this won't let you get the response from the form submission. The event handler is executed before the form data is sent to the server. When the form is submitted, the page reloads and all current scripts stop running.

If you want to get the response, you need to use $.ajax (or a shortcut like $.get or $.post) instead of .submit().


问:
Using JSON result from Zippopotam.us for Google maps coordinate
The code that I made will ask the user to enter an input (any Malaysian Zip code), and the input will fetch a JSON result from Zippopotam.us. Below is my full codes :

```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Assignment  Lab 3</title>
    <style>
input[type=text], select {
    width: 100%;
    padding: 12px 20px;
    margin: 8px 0;
    display: inline-block;
    border: 1px solid #ccc;
    border-radius: 4px;
    box-sizing: border-box;
}

button {
    width: 100%;
    background-color: #4CAF50;
    color: white;
    padding: 14px 20px;
    margin: 8px 0;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

button:hover {
    background-color: #45a049;
}

div #zipdiv, #citydiv, #statediv, #longitudediv, #latitudediv
{
    border-radius: 5px;
    background-color: #f2f2f2;
    padding: 20px;
}

</style>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<script>
$(function() {

  $(document).ready( function()
  {
    $("#citydiv").hide();
    $("#statediv").hide();
    $("#longitudediv").hide();
    $("#latitudediv").hide();
    $("#mapdiv").hide();

  });

  // OnKeyDown Function
  $("#zcode").keyup(function() {
    var zip_in = $(this);
    var zip_box = $('#zipdiv');

    if (zip_in.val().length<5)
    {
      zip_box.removeClass('error success');
    }
    else if ( zip_in.val().length>5)
    {
      zip_box.addClass('error').removeClass('success');
    }
    else if ((zip_in.val().length == 5) )
    {

      // Make HTTP Request
      $.ajax({
        url: "http://api.zippopotam.us/MY/" + zip_in.val(),
        cache: false,
        dataType: "json",
        type: "GET",
        success: function(result, success) {
          // Make the city and state boxes visible
          $('#citydiv').slideDown(200);
          $('#statediv').slideDown(200);
          $('#longitudediv').slideDown(200);
          $('#latitudediv').slideDown(200);

          // Zip Code Records Officially Map to only 1 Primary Location
          places = result['places'][0];
          $("#city").val(places['place name']);
          $("#state").val(places['state']);
          $("#long").val(places['longitude']);
          $("#lat").val(places['latitude']);
          zip_box.addClass('success').removeClass('error');
        },
        error: function(result, success) {
          zip_box.removeClass('success').addClass('error');
        }
      });
    }
});

});
function mapFunction() {

var mapOptions =
{
   // Set up the map options
  center: new google.maps.LatLng(),//coordinate should be from JSON results
  mapTypeId: google.maps.MapTypeId.ROADMAP,
  zoom: 13,
};
var venueMap;                                      // Map() draws a map
venueMap = new google.maps.Map(document.getElementById('map'), mapOptions);
}

function loadScript()
{
var script = document.createElement('script');     // Create <script> element
script.src = 'http://maps.googleapis.com/maps/api/js?sensor=false&callback=mapFunction';
document.body.appendChild(script);                 // Add element to page
}

window.onload = loadScript;                          // on load call loadScript()

$(document).ready(function()
{
  $(".button").click(function()
  {
    $("#mapdiv").show(200);
  });
});

</script>

  </head>
  <body>
    <h3>Enter Malaysian Zip Code</h3>

<div>
  <form action="#" method="post" class="form fancy-form">
    <div id="zipdiv">
      <label for="zip">Zip Code</label>
      <input type="text" id="zcode" name="Zip code" placeholder="E.g : 48050">
    </div>

    <div id="citydiv">
      <label id="city_lbl" for="city">City</label>
      <input type="text" id="city" name="city">
  </div>

    <div id="statediv">
      <label id="state_lbl" for="state">State</label>
      <input type="text" id="state" name="state">
    </div>

    <div id="longitudediv">
      <label id="lgtd_lbl" for="longitude">Longitude</label>
      <input type="text" id="long" name="longitude">
    </div>

    <div id="latitudediv">
      <label id="lttd_lbl" for="latitude">Latitude</label>
      <input type="text" id="lat" name="latitude">
    </div>

    <button id="button" class="button" type="button" name="button">Submit</button>
    <div id="mapdiv">Map here: <div id="map" style="width:400px;height:400px;"></div></div>

</form>

</div>
  </body>
</html>
</code>```

Below is one of the many example of the JSON Result user can get from Zippopotam.us :

{"post code": "01000",
     "country": "Malaysia",
     "country abbreviation": "MY",
     "places": [{"place name": "Kangar", "longitude": "100.2056", "state": "Perlis",
    "state abbreviation": "PLS", "latitude": "6.4312"}]}

Another example :

{"post code": "48050", "country": "Malaysia", "country abbreviation": "MY", "places": [{"place name": "Rawang", "longitude": "101.5642", "state": "Selangor", "state abbreviation": "SGR", "latitude": "3.2559"}]}

My programme should take the value of latitude and longitude from these results to be inserted to

```<code>center: new google.maps.LatLng(latitude here, longitude here),
//coordinate should be from JSON results the user get
</code>```

The problem is, I've tried many ways, but it seems that I can't put the latitude and longitude from the JSON result to the above code (except from writing the numbers manually, but that's not how this programme supposed to work).

The programme should take the latitude and longitude value, and insert it automatically to the above code, so that when the user click the Submit button, a Google map is generated from that coordinates.

How do I solve this? Thank you in advance~

答:
```<code>myLatLng = new google.maps.LatLng(places['latitude'], places['longitude']); //from your response
venueMap.setCenter(myLatLng);
</code>```

If you want to animate transition, use

```<code>venueMap.panTo(myLatLng);
</code>```

Consider checking Google Maps JavaScript API Reference.

Body:
The code that I made will ask the user to enter an input (any Malaysian Zip code), and the input will fetch a JSON result from Zippopotam.us. Below is my full codes :

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Assignment  Lab 3</title>

Enter Malaysian Zip Code

  <form action="#" method="post" class="form fancy-form">

      Zip Code
      <input type="text" id="zcode" name="Zip code" placeholder="E.g : 48050">

      City
      <input type="text" id="city" name="city">

      State
      <input type="text" id="state" name="state">

      Longitude
      <input type="text" id="long" name="longitude">

      Latitude
      <input type="text" id="lat" name="latitude">

    <button id="button" class="button" type="button" name="button">Submit</button>

Map here:

</form>

Below is one of the many example of the JSON Result user can get from Zippopotam.us :

{"post code": "01000",
     "country": "Malaysia",
     "country abbreviation": "MY",
     "places": [{"place name": "Kangar", "longitude": "100.2056", "state": "Perlis",
    "state abbreviation": "PLS", "latitude": "6.4312"}]}

Another example :

{"post code": "48050", "country": "Malaysia", "country abbreviation": "MY", "places": [{"place name": "Rawang", "longitude": "101.5642", "state": "Selangor", "state abbreviation": "SGR", "latitude": "3.2559"}]}

My programme should take the value of latitude and longitude from these results to be inserted to

center: new google.maps.LatLng(latitude here, longitude here),
//coordinate should be from JSON results the user get

The problem is, I've tried many ways, but it seems that I can't put the latitude and longitude from the JSON result to the above code (except from writing the numbers manually, but that's not how this programme supposed to work).

The programme should take the latitude and longitude value, and insert it automatically to the above code, so that when the user click the Submit button, a Google map is generated from that coordinates.

How do I solve this? Thank you in advance~

Body:
myLatLng = new google.maps.LatLng(places['latitude'], places['longitude']); //from your response
venueMap.setCenter(myLatLng);

If you want to animate transition, use

venueMap.panTo(myLatLng);

Consider checking Google Maps JavaScript API Reference.


问:
Why doesn't AudioKit's AKMicrophoneTracker work on a physical iOS device?
When I use AudioKit's AKMicrophoneTracker on a physical device, the the frequency and amplitude are always both 0. But in the playground and in the iOS simulator, it works perfectly.

Here's a rough example:

```<code>class AppDelegate: UIResponder, UIApplicationDelegate {

    let tracker = AKMicrophoneTracker()

    func application(_ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        // start the tracker and show frequency information
        tracker.start()
        Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true, block: { _ in
            print(tracker.frequency)
            print(tracker.amplitude)
        })
    }

}
</code>```

I've reset my physical device's privacy permissions, and iOS is correctly prompting me to allow microphone access. It still doesn't work even though I'm allowing microphone access.

How can I get AKMicrophoneTracker to actually read these values?

I'm using AudioKit 4.0.3. It works as expected when using:

the AudioKit playground on my Mac

a simulator iPhone 7 Plus running iOS 11.1

It does not work when using:

A physical iPhone 7 Plus running iOS 11.1.1 (and also occurs on iOS 11.1)

I originally posted this as a bug on AudioKit's GitHub issue tracker. However, Aure (the project maintainer) encouraged me to post here instead.

答:
Ercell0's answer is correct--his code works perfectly. My specific problem appears to have been caused by some other AudioKit functionality which I thought I had disabled during testing. It was equivalent to running:

```<code>AudioKit.output = AKMixer()
AudioKit.start()
</code>```

after the AKMicrophoneTracker initialization. This caused the AKMicrophoneTracker problem I was experiencing.

It looks like this might be a bug in AudioKit. I've opened issue #1142 on Github.

Body:
When I use AudioKit's AKMicrophoneTracker on a physical device, the the frequency and amplitude are always both 0. But in the playground and in the iOS simulator, it works perfectly.

Here's a rough example:

class AppDelegate: UIResponder, UIApplicationDelegate {

    let tracker = AKMicrophoneTracker()

    func application(_ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        // start the tracker and show frequency information
        tracker.start()
        Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true, block: { _ in
            print(tracker.frequency)
            print(tracker.amplitude)
        })
    }

}

I've reset my physical device's privacy permissions, and iOS is correctly prompting me to allow microphone access. It still doesn't work even though I'm allowing microphone access.

How can I get AKMicrophoneTracker to actually read these values?

I'm using AudioKit 4.0.3. It works as expected when using:

the AudioKit playground on my Mac

a simulator iPhone 7 Plus running iOS 11.1

It does not work when using:

A physical iPhone 7 Plus running iOS 11.1.1 (and also occurs on iOS 11.1)

I originally posted this as a bug on AudioKit's GitHub issue tracker. However, Aure (the project maintainer) encouraged me to post here instead.

Body:
Ercell0's answer is correct--his code works perfectly. My specific problem appears to have been caused by some other AudioKit functionality which I thought I had disabled during testing. It was equivalent to running:

AudioKit.output = AKMixer()
AudioKit.start()

after the AKMicrophoneTracker initialization. This caused the AKMicrophoneTracker problem I was experiencing.

It looks like this might be a bug in AudioKit. I've opened issue #1142 on Github.


问:
install curl on ubuntu to use hirak/prestissimo with composer
I try to installhirak/prestissimo packages because my composer is very very very slow.
I use

```<code>composer global require hirak/prestissimo
</code>```

But I got this error. I found another solution on StackOverflow but I still can't fix that.

```<code>  Problem 1
    - Installation request for hirak/prestissimo ^0.3.6 -> satisfiable by hirak/prestissimo[0.3.6].
    - hirak/prestissimo 0.3.6 requires ext-curl * -> the requested PHP extension curl is missing from your system.

  To enable extensions, verify that they are enabled in your .ini files:
    - /etc/php/5.6/cli/php.ini
    - /etc/php/5.6/cli/conf.d/10-mysqlnd.ini
    - /etc/php/5.6/cli/conf.d/10-opcache.ini
    - /etc/php/5.6/cli/conf.d/10-pdo.ini
    - /etc/php/5.6/cli/conf.d/15-xml.ini
    - /etc/php/5.6/cli/conf.d/20-calendar.ini
    - /etc/php/5.6/cli/conf.d/20-ctype.ini
    - /etc/php/5.6/cli/conf.d/20-dom.ini
    - /etc/php/5.6/cli/conf.d/20-exif.ini
    - /etc/php/5.6/cli/conf.d/20-fileinfo.ini
    - /etc/php/5.6/cli/conf.d/20-ftp.ini
    - /etc/php/5.6/cli/conf.d/20-gd.ini
    - /etc/php/5.6/cli/conf.d/20-gettext.ini
    - /etc/php/5.6/cli/conf.d/20-iconv.ini
    - /etc/php/5.6/cli/conf.d/20-json.ini
    - /etc/php/5.6/cli/conf.d/20-mbstring.ini
    - /etc/php/5.6/cli/conf.d/20-mcrypt.ini
    - /etc/php/5.6/cli/conf.d/20-mysql.ini
    - /etc/php/5.6/cli/conf.d/20-mysqli.ini
    - /etc/php/5.6/cli/conf.d/20-pdo_mysql.ini
    - /etc/php/5.6/cli/conf.d/20-phar.ini
    - /etc/php/5.6/cli/conf.d/20-posix.ini
    - /etc/php/5.6/cli/conf.d/20-readline.ini
    - /etc/php/5.6/cli/conf.d/20-shmop.ini
    - /etc/php/5.6/cli/conf.d/20-simplexml.ini
    - /etc/php/5.6/cli/conf.d/20-sockets.ini
    - /etc/php/5.6/cli/conf.d/20-sysvmsg.ini
    - /etc/php/5.6/cli/conf.d/20-sysvsem.ini
    - /etc/php/5.6/cli/conf.d/20-sysvshm.ini
    - /etc/php/5.6/cli/conf.d/20-tokenizer.ini
    - /etc/php/5.6/cli/conf.d/20-wddx.ini
    - /etc/php/5.6/cli/conf.d/20-xmlreader.ini
    - /etc/php/5.6/cli/conf.d/20-xmlwriter.ini
    - /etc/php/5.6/cli/conf.d/20-xsl.ini
</code>```

Thanks you all !!

答:
Try it</p>

```<code>sudo apt-get install php5.6-bcmath
</code>```

Body:
I try to installhirak/prestissimo packages because my composer is very very very slow.
I use

composer global require hirak/prestissimo

But I got this error. I found another solution on StackOverflow but I still can't fix that.

  Problem 1
    - Installation request for hirak/prestissimo ^0.3.6 -> satisfiable by hirak/prestissimo[0.3.6].
    - hirak/prestissimo 0.3.6 requires ext-curl * -> the requested PHP extension curl is missing from your system.

  To enable extensions, verify that they are enabled in your .ini files:
    - /etc/php/5.6/cli/php.ini
    - /etc/php/5.6/cli/conf.d/10-mysqlnd.ini
    - /etc/php/5.6/cli/conf.d/10-opcache.ini
    - /etc/php/5.6/cli/conf.d/10-pdo.ini
    - /etc/php/5.6/cli/conf.d/15-xml.ini
    - /etc/php/5.6/cli/conf.d/20-calendar.ini
    - /etc/php/5.6/cli/conf.d/20-ctype.ini
    - /etc/php/5.6/cli/conf.d/20-dom.ini
    - /etc/php/5.6/cli/conf.d/20-exif.ini
    - /etc/php/5.6/cli/conf.d/20-fileinfo.ini
    - /etc/php/5.6/cli/conf.d/20-ftp.ini
    - /etc/php/5.6/cli/conf.d/20-gd.ini
    - /etc/php/5.6/cli/conf.d/20-gettext.ini
    - /etc/php/5.6/cli/conf.d/20-iconv.ini
    - /etc/php/5.6/cli/conf.d/20-json.ini
    - /etc/php/5.6/cli/conf.d/20-mbstring.ini
    - /etc/php/5.6/cli/conf.d/20-mcrypt.ini
    - /etc/php/5.6/cli/conf.d/20-mysql.ini
    - /etc/php/5.6/cli/conf.d/20-mysqli.ini
    - /etc/php/5.6/cli/conf.d/20-pdo_mysql.ini
    - /etc/php/5.6/cli/conf.d/20-phar.ini
    - /etc/php/5.6/cli/conf.d/20-posix.ini
    - /etc/php/5.6/cli/conf.d/20-readline.ini
    - /etc/php/5.6/cli/conf.d/20-shmop.ini
    - /etc/php/5.6/cli/conf.d/20-simplexml.ini
    - /etc/php/5.6/cli/conf.d/20-sockets.ini
    - /etc/php/5.6/cli/conf.d/20-sysvmsg.ini
    - /etc/php/5.6/cli/conf.d/20-sysvsem.ini
    - /etc/php/5.6/cli/conf.d/20-sysvshm.ini
    - /etc/php/5.6/cli/conf.d/20-tokenizer.ini
    - /etc/php/5.6/cli/conf.d/20-wddx.ini
    - /etc/php/5.6/cli/conf.d/20-xmlreader.ini
    - /etc/php/5.6/cli/conf.d/20-xmlwriter.ini
    - /etc/php/5.6/cli/conf.d/20-xsl.ini

Thanks you all !!

Body:
Try it

sudo apt-get install php5.6-bcmath


问:
The driver executable does not exist: C:\geckodriver.exe issue in Eclipse IDE
Please help me with this issue that is recurring every time I run my code.
I have extracted Geckodriver files in C Drive but when I run my code, the error that comes up is 'Exception in thread "main" java.lang.IllegalStateException: The driver executable does not exist: C:\geckodriver.exe'.

My code is given below:

```<code> package Basics;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Browserinvocation {
public static void main(String[] args) {
    // TODO Auto-generated method stub

System.setProperty("webdriver.gecko.driver","C:\\geckodriver.exe");

WebDriver driver = new FirefoxDriver();//FirefoxDriver class is used to implement methods present in Webdriver-Invocation of browser
driver.get("https://www.amazon.in/");// Get method to hit the url in browser

}

}
</code>```

Error in console :

Exception in thread "main" java.lang.IllegalStateException: The driver
  executable does not exist: C:\geckodriver.exe     at
  com.google.common.base.Preconditions.checkState(Preconditions.java:534)
    at
  org.openqa.selenium.remote.service.DriverService.checkExecutable(DriverService.java:136)
    at
  org.openqa.selenium.remote.service.DriverService.findExecutable(DriverService.java:131)
    at
  org.openqa.selenium.firefox.GeckoDriverService.access$100(GeckoDriverService.java:41)
    at
  org.openqa.selenium.firefox.GeckoDriverService$Builder.findDefaultExecutable(GeckoDriverService.java:141)
    at
  org.openqa.selenium.remote.service.DriverService$Builder.build(DriverService.java:339)
    at
  org.openqa.selenium.firefox.FirefoxDriver.toExecutor(FirefoxDriver.java:158)
    at
  org.openqa.selenium.firefox.FirefoxDriver.(FirefoxDriver.java:120)
    at
  org.openqa.selenium.firefox.FirefoxDriver.(FirefoxDriver.java:98)
    at Basics.Browserinvocation.main(Browserinvocation.java:13)

答:
You should add the path to geckodriver.exe using / rather than \\. Change your line

```<code>System.setProperty("webdriver.gecko.driver","C:\\geckodriver.exe");
</code>```

to the following

```<code>System.setProperty("webdriver.gecko.driver","C:/geckodriver.exe");
</code>```

Body:
Please help me with this issue that is recurring every time I run my code.
I have extracted Geckodriver files in C Drive but when I run my code, the error that comes up is 'Exception in thread "main" java.lang.IllegalStateException: The driver executable does not exist: C:\geckodriver.exe'.

My code is given below:

 package Basics;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Browserinvocation {
public static void main(String[] args) {
    // TODO Auto-generated method stub

System.setProperty("webdriver.gecko.driver","C:\\geckodriver.exe");

WebDriver driver = new FirefoxDriver();//FirefoxDriver class is used to implement methods present in Webdriver-Invocation of browser
driver.get("https://www.amazon.in/");// Get method to hit the url in browser

}

}

Error in console :

Exception in thread "main" java.lang.IllegalStateException: The driver
  executable does not exist: C:\geckodriver.exe     at
  com.google.common.base.Preconditions.checkState(Preconditions.java:534)
    at
  org.openqa.selenium.remote.service.DriverService.checkExecutable(DriverService.java:136)
    at
  org.openqa.selenium.remote.service.DriverService.findExecutable(DriverService.java:131)
    at
  org.openqa.selenium.firefox.GeckoDriverService.access$100(GeckoDriverService.java:41)
    at
  org.openqa.selenium.firefox.GeckoDriverService$Builder.findDefaultExecutable(GeckoDriverService.java:141)
    at
  org.openqa.selenium.remote.service.DriverService$Builder.build(DriverService.java:339)
    at
  org.openqa.selenium.firefox.FirefoxDriver.toExecutor(FirefoxDriver.java:158)
    at
  org.openqa.selenium.firefox.FirefoxDriver.(FirefoxDriver.java:120)
    at
  org.openqa.selenium.firefox.FirefoxDriver.(FirefoxDriver.java:98)
    at Basics.Browserinvocation.main(Browserinvocation.java:13)

Body:
You should add the path to geckodriver.exe using / rather than \\. Change your line

System.setProperty("webdriver.gecko.driver","C:\\geckodriver.exe");

to the following

System.setProperty("webdriver.gecko.driver","C:/geckodriver.exe");


问:
Phonegap how to save permanent data on android
I'm looking for a method to save data permanently using PhoneGap.

LocalStorage

File I/O

?

I heard LocalStorage is not 100% permanent, but is somewhere in the alley.

I wouldn't really like to begin with File I/O, because what I need is to create a database with recipes, and they need to stay.

"Number 3" is what I'm asking about. Any suggestions?

Thanks in advance :)

答: In AppStore, when you release new version of your app, all of stored datas on your users will be reset. Before you update your app, you need to find better way to store your data.</p>


问:
Is it possible to use WSDL with a REST webservice?
I am new to the area of web-services. Is it possible to use WSDL with REST bindings? Or should I use WADL?</p>

答:
It's possible to use a WSDL with REST bindings, but it's really not necessary.  The simplistic nature of REST make writing code to use that service very easy.  Using a WSDL just adds extra complexity that is just not necessary.

If you're still interested, you can find more information here:
http://www.ibm.com/developerworks/webservices/library/ws-restwsdl/

Also, this question may help you:
WSDL vs REST Pros and Cons


问:
InDesign Applescript: "override master page items" glitch?
Here's a very simple script that overrides all master page items on page 1:

```<code>tell application id "com.adobe.InDesign"
    tell active document
        override every item of master page items of page 1 destination page page 1
    end tell
end tell
</code>```

For some reason, this results in the page items shifting up and to the left of their original location. I cannot figure out why this is happening. Overriding page items should NEVER move the items. In fact, when I manually override in InDesign, nothing shifts. It appears to be affecting a specific layout. When I do a test document, the problem goes away. This particular document has many levels of master pages applied to each other, then applied to a layout.

Anyone else encountered this issue?

答:
This works for me in CC 2018 (13.0.1) and Sierra 10.12.6: </p>

```<code>tell application id "com.adobe.indesign"
    tell document 1
        repeat with i from 1 to count of pages
            try
                override (every item of master page items of page i whose allow overrides is true) destination page page i
            on error
                --
            end try
        end repeat
    end tell
end tell
</code>```

Body:
Here's a very simple script that overrides all master page items on page 1:

tell application id "com.adobe.InDesign"
    tell active document
        override every item of master page items of page 1 destination page page 1
    end tell
end tell

For some reason, this results in the page items shifting up and to the left of their original location. I cannot figure out why this is happening. Overriding page items should NEVER move the items. In fact, when I manually override in InDesign, nothing shifts. It appears to be affecting a specific layout. When I do a test document, the problem goes away. This particular document has many levels of master pages applied to each other, then applied to a layout.

Anyone else encountered this issue?

Body:
This works for me in CC 2018 (13.0.1) and Sierra 10.12.6:

tell application id "com.adobe.indesign"
    tell document 1
        repeat with i from 1 to count of pages
            try
                override (every item of master page items of page i whose allow overrides is true) destination page page i
            on error
                --
            end try
        end repeat
    end tell
end tell


问:
Function parameters out of range in function
For a class project I have to make a hangman game. Following it's guidelines I have gotten this code:

```<code>def hangman(guessed, secret):
  word = ""
  wrongLetters = 0
  checkLetter = 0
  compareLetter = 0
  for i in range(len(secret)):
      if secret[checkLetter] == guessed[compareLetter]:
            word += guessed[compareLetter]
          compareLetter = 0
          checkLetter += 1
      elif secret[checkLetter] != guessed[compareLetter]:
          compareLetter += 1
          for i in range(len(secret) - 1):
              if secret[checkLetter] == guessed[compareLetter]:
                  word += guessed[checkLetter]
                  break
              elif secret[checkLetter] != guessed[compareLetter]:
                  compareLetter += 1
                  wrongLetters += 1
              elif wrongLetters == len(secret):
                  word += "-"
                  wrongLetters = 0
                  checkLetter += 1
                  compareLetter = 0
  print(word)
</code>```

My issue is that it tells me that if secret[checkLetter] == guessed[compareLetter]: under the second for statement is out of range of the string index. I believe it is because my function parameters are local. Any idea how to fix?

答:
I tried executing your code with various inputs, what I found out is that the error occurs when value of variable compareLetter exceeds length of guessed.
Looks like there is some problem in the logic!!

I tried with hangman('banana', 'apple')
Here is the how the value of checkLetter and compareLetter is changing:

```<code>0 1
1 1
1 2
1 3
1 4
1 6
</code>```

Hope you understand the issue.

Body:
For a class project I have to make a hangman game. Following it's guidelines I have gotten this code:

def hangman(guessed, secret):
  word = ""
  wrongLetters = 0
  checkLetter = 0
  compareLetter = 0
  for i in range(len(secret)):
      if secret[checkLetter] == guessed[compareLetter]:
            word += guessed[compareLetter]
          compareLetter = 0
          checkLetter += 1
      elif secret[checkLetter] != guessed[compareLetter]:
          compareLetter += 1
          for i in range(len(secret) - 1):
              if secret[checkLetter] == guessed[compareLetter]:
                  word += guessed[checkLetter]
                  break
              elif secret[checkLetter] != guessed[compareLetter]:
                  compareLetter += 1
                  wrongLetters += 1
              elif wrongLetters == len(secret):
                  word += "-"
                  wrongLetters = 0
                  checkLetter += 1
                  compareLetter = 0
  print(word)

My issue is that it tells me that if secret[checkLetter] == guessed[compareLetter]: under the second for statement is out of range of the string index. I believe it is because my function parameters are local. Any idea how to fix?

Body:
I tried executing your code with various inputs, what I found out is that the error occurs when value of variable compareLetter exceeds length of guessed.
Looks like there is some problem in the logic!!

I tried with hangman('banana', 'apple')
Here is the how the value of checkLetter and compareLetter is changing:

0 1
1 1
1 2
1 3
1 4
1 6

Hope you understand the issue.


问:
Not able to import speech_recognition using python 2.6
I am not able to import speech_recognition module using python 2.6 on Centos 6.5. I have installed SpeechRecognition using pip and it installed successfully without any errors.

```<code>pip install SpeechRecognition

Downloading SpeechRecognition-3.6.5-py2.py3-none-any.whl (31.8MB)
100% |████████████████████████████████| 31.8MB 14kB/s
Installing collected packages: SpeechRecognition
Successfully installed SpeechRecognition-3.6.5
</code>```

But Somehow I am not able to import it.

```<code>>>> import speech_recognition
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.6/site-packages/speech_recognition/__init__.py", line 1070
if system == "Windows" and machine in {"i686", "i786", "x86", "x86_64", "AMD64"}:
                                             ^
SyntaxError: invalid syntax
>>>
</code>```

答:
```<code>pip install SpeechRecognition
pip install pyaudio
</code>```

Body:
I am not able to import speech_recognition module using python 2.6 on Centos 6.5. I have installed SpeechRecognition using pip and it installed successfully without any errors.

pip install SpeechRecognition

Downloading SpeechRecognition-3.6.5-py2.py3-none-any.whl (31.8MB)
100% |████████████████████████████████| 31.8MB 14kB/s
Installing collected packages: SpeechRecognition
Successfully installed SpeechRecognition-3.6.5

But Somehow I am not able to import it.

>>> import speech_recognition
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.6/site-packages/speech_recognition/__init__.py", line 1070
if system == "Windows" and machine in {"i686", "i786", "x86", "x86_64", "AMD64"}:
                                             ^
SyntaxError: invalid syntax
>>>


问:
Joining two strings together then converting to an integer. Python
I have to write a program so that a user can increase $100 by a percentage they input.I need to do 100 * 1.n, but I keep getting an error as I am converting a string into an integer, please help;

```<code>percent = input("Enter the % you want to increase by: ")
n = "1." + percent
k = int(n)
print(k)
</code>```

I keep getting the error message:

```<code>Traceback (most recent call last):
 File "C:\Users\T Pad\Downloads\dlee.py", line 3, in <module>
 k = int(n)
 ValueError: invalid literal for int() with base 10: '1.50'
</code>```

thanks for any help.

答:
You can't convert it to int, you need float.

```<code>percent = '2837' #input("Enter the % you want to increase by: ")
n = "1." + percent
k = float(n)
print(k)
</code>```

Body:
I have to write a program so that a user can increase $100 by a percentage they input.I need to do 100 * 1.n, but I keep getting an error as I am converting a string into an integer, please help;

percent = input("Enter the % you want to increase by: ")
n = "1." + percent
k = int(n)
print(k)

I keep getting the error message:

Traceback (most recent call last):
 File "C:\Users\T Pad\Downloads\dlee.py", line 3, in <module>
 k = int(n)
 ValueError: invalid literal for int() with base 10: '1.50'

thanks for any help.

Body:
You can't convert it to int, you need float.

percent = '2837' #input("Enter the % you want to increase by: ")
n = "1." + percent
k = float(n)
print(k)


问:
Python threading.join() hangs
My problem is as follows:
I have a class that inherits from threading.Thread that I want to be able to stop gracefully. This class also has a Queue it get's its work from.

Since there are quite some classes in my project that should have this behaviour, I've created some superclasses to reduce duplicate code like this:

Thread related behaviour:

```<code>class StoppableThread(Thread):
def __init__(self):
    Thread.__init__(self)
    self._stop = Event()

def stop(self):
    self._stop.set()

def stopped(self):
    return self._stop.isSet()
</code>```

Queue related behaviour:

```<code>class Queueable():
    def __init__(self):
        self._queue = Queue()

    def append_to_job_queue(self, job):
        self._queue.put(job)
</code>```

Combining the two above and adding queue.join() to the stop() call

```<code>class StoppableQueueThread(StoppableThread, Queueable):
    def __init__(self):
        StoppableThread.__init__(self)
        Queueable.__init__(self)

    def stop(self):
        super(StoppableQueueThread, self).stop()
        self._queue.join()
</code>```

A base class for a datasource:

```<code>class DataSource(StoppableThread, ABC):

    def __init__(self, data_parser):
        StoppableThread.__init__(self)
        self.setName("DataSource")
        ABC.__init__(self)
        self._data_parser = data_parser

    def run(self):
        while not self.stopped():
            record = self._fetch_data()
            self._data_parser.append_to_job_queue(record)

    @abstractmethod
    def _fetch_data(self):
        """implement logic here for obtaining a data piece
            should return the fetched data"""
</code>```

An implementation for a datasource:

```<code>class CSVDataSource(DataSource):
    def __init__(self, data_parser, file_path):
        DataSource.__init__(self, data_parser)
        self.file_path = file_path
        self.csv_data = Queue()
        print('loading csv')
        self.load_csv()
        print('done loading csv')

    def load_csv(self):
        """Loops through csv and adds data to a queue"""
        with open(self.file_path, 'r') as f:

            self.reader = reader(f)
            next(self.reader, None)  # skip header
            for row in self.reader:
                self.csv_data.put(row)

    def _fetch_data(self):
        """Returns next item of the queue"""
        item = self.csv_data.get()
        self.csv_data.task_done()
        print(self.csv_data.qsize())
        return item
</code>```

Suppose there is a CSVDataSource instance called ds, if I want to stop the thread I call:

```<code>ds.stop()
ds.join()
</code>```

The ds.join() call however, never returns. I'm not sure why this is, because the run() method does check if the stop event is set.

Any Ideas?

Update

A little more clarity as requested: the applications is build up out of several threads. The RealStrategy thread (below) is the owner of all the other threads and is responsible for starting and terminating them. I haven't set the daemon flag for any of the threads, so they should be non-daemonic by default.

The main thread looks like this:

```<code>if __name__ == '__main__':
    def exit_handler(signal, frame):
        rs.stop_engine()
        rs.join()
        sys.exit(0)

    signal.signal(signal.SIGINT, exit_handler)

    rs = RealStrategy()
    rs.run_engine()
</code>```

And here are the rs.run_engine() and rs.stop_engine() methods that are called in main:

```<code>class RealStrategy(Thread):
.....
.....
    def run_engine(self):
        self.on_start()
        self._order_handler.start()
        self._data_parser.start()
        self._data_source.start()
        self.start()

    def stop_engine(self):
        self._data_source.stop()
        self._data_parser.stop()
        self._order_handler.stop()

        self._data_source.join()
        self._data_parser.join()
        self._order_handler.join()

        self.stop()
</code>```

答:
If you want to use queue.Queue.join, then you must also use queue.Queue.task_done. You can read the linked documentation or see the following copied from information available online:

Queue.task_done()

Indicate that a formerly enqueued task is complete.
  Used by queue consumer threads. For each get() used to fetch a task, a
  subsequent call to task_done() tells the queue that the processing on
  the task is complete.

If a join() is currently blocking, it will resume when all items have
  been processed (meaning that a task_done() call was received for every
  item that had been put() into the queue).

Raises a ValueError if called more times than there were items placed
  in the queue.

Queue.join()

Blocks until all items in the queue have been gotten and processed.

The count of unfinished tasks goes up whenever an item is added to the
  queue. The count goes down whenever a consumer thread calls
  task_done() to indicate that the item was retrieved and all work on it
  is complete. When the count of unfinished tasks drops to zero, join()
  unblocks.

To test your problem, an example implementation was created to find out what was going on. It is slightly different from how your program works but demonstrates a method to solving your problem:

```<code>#! /usr/bin/env python3
import abc
import csv
import pathlib
import queue
import sys
import threading
import time

def main():
    source_path = pathlib.Path(r'C:\path\to\file.csv')
    data_source = CSVDataSource(source_path)
    data_source.start()
    processor = StoppableThread(target=consumer, args=[data_source])
    processor.start()
    time.sleep(0.1)
    data_source.stop()

def consumer(data_source):
    while data_source.empty:
        time.sleep(0.001)
    while not data_source.empty:
        task = data_source.get_from_queue(True, 0.1)
        print(*task.data, sep=', ', flush=True)
        task.done()

class StopThread(StopIteration):
    pass

threading.SystemExit = SystemExit, StopThread

class StoppableThread(threading.Thread):
    def _bootstrap(self, stop=False):
        # noinspection PyProtectedMember
        if threading._trace_hook:
            raise RuntimeError('cannot run thread with tracing')

        def terminate():
            nonlocal stop
            stop = True

        self.__terminate = terminate

        # noinspection PyUnusedLocal
        def trace(frame, event, arg):
            if stop:
                raise StopThread

        sys.settrace(trace)
        super()._bootstrap()

    def terminate(self):
        try:
            self.__terminate()
        except AttributeError:
            raise RuntimeError('cannot terminate thread '
                               'before it is started') from None

class Queryable:
    def __init__(self, maxsize=1 << 10):
        self.__queue = queue.Queue(maxsize)

    def add_to_queue(self, item):
        self.__queue.put(item)

    def get_from_queue(self, block=True, timeout=None):
        return self.__queue.get(block, timeout)

    @property
    def empty(self):
        return self.__queue.empty()

    @property
    def full(self):
        return self.__queue.full()

    def task_done(self):
        self.__queue.task_done()

    def join_queue(self):
        self.__queue.join()

class StoppableQueryThread(StoppableThread, Queryable):
    def __init__(self, target=None, name=None, args=(), kwargs=None,
                 *, daemon=None, maxsize=1 << 10):
        super().__init__(None, target, name, args, kwargs, daemon=daemon)
        Queryable.__init__(self, maxsize)

    def stop(self):
        self.terminate()
        self.join_queue()

class DataSource(StoppableQueryThread, abc.ABC):
    @abc.abstractmethod
    def __init__(self, maxsize=1 << 10):
        super().__init__(None, 'DataSource', maxsize=maxsize)

    def run(self):
        while True:
            record = self._fetch_data()
            self.add_to_queue(record)

    @abc.abstractmethod
    def _fetch_data(self):
        pass

class CSVDataSource(DataSource):
    def __init__(self, source_path):
        super().__init__()
        self.__data_parser = self.__build_data_parser(source_path)

    @staticmethod
    def __build_data_parser(source_path):
        with source_path.open(newline='') as source:
            parser = csv.reader(source)
            next(parser, None)
            yield from parser

    def _fetch_data(self):
        try:
            return Task(next(self.__data_parser), self.task_done)
        except StopIteration:
            raise StopThread from None

class Task:
    def __init__(self, data, callback):
        self.__data = data
        self.__callback = callback

    @property
    def data(self):
        return self.__data

    def done(self):
        self.__callback()

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

Title: Python threading.join() hangs

Body:
My problem is as follows:
I have a class that inherits from threading.Thread that I want to be able to stop gracefully. This class also has a Queue it get's its work from.

Since there are quite some classes in my project that should have this behaviour, I've created some superclasses to reduce duplicate code like this:

Thread related behaviour:

class StoppableThread(Thread):
def __init__(self):
    Thread.__init__(self)
    self._stop = Event()

def stop(self):
    self._stop.set()

def stopped(self):
    return self._stop.isSet()

Queue related behaviour:

class Queueable():
    def __init__(self):
        self._queue = Queue()

    def append_to_job_queue(self, job):
        self._queue.put(job)

Combining the two above and adding queue.join() to the stop() call

class StoppableQueueThread(StoppableThread, Queueable):
    def __init__(self):
        StoppableThread.__init__(self)
        Queueable.__init__(self)

    def stop(self):
        super(StoppableQueueThread, self).stop()
        self._queue.join()

A base class for a datasource:

class DataSource(StoppableThread, ABC):

    def __init__(self, data_parser):
        StoppableThread.__init__(self)
        self.setName("DataSource")
        ABC.__init__(self)
        self._data_parser = data_parser

    def run(self):
        while not self.stopped():
            record = self._fetch_data()
            self._data_parser.append_to_job_queue(record)

    @abstractmethod
    def _fetch_data(self):
        """implement logic here for obtaining a data piece
            should return the fetched data"""

An implementation for a datasource:

class CSVDataSource(DataSource):
    def __init__(self, data_parser, file_path):
        DataSource.__init__(self, data_parser)
        self.file_path = file_path
        self.csv_data = Queue()
        print('loading csv')
        self.load_csv()
        print('done loading csv')

    def load_csv(self):
        """Loops through csv and adds data to a queue"""
        with open(self.file_path, 'r') as f:

            self.reader = reader(f)
            next(self.reader, None)  # skip header
            for row in self.reader:
                self.csv_data.put(row)

    def _fetch_data(self):
        """Returns next item of the queue"""
        item = self.csv_data.get()
        self.csv_data.task_done()
        print(self.csv_data.qsize())
        return item

Suppose there is a CSVDataSource instance called ds, if I want to stop the thread I call:

ds.stop()
ds.join()

The ds.join() call however, never returns. I'm not sure why this is, because the run() method does check if the stop event is set.

Any Ideas?

Update

A little more clarity as requested: the applications is build up out of several threads. The RealStrategy thread (below) is the owner of all the other threads and is responsible for starting and terminating them. I haven't set the daemon flag for any of the threads, so they should be non-daemonic by default.

The main thread looks like this:

if __name__ == '__main__':
    def exit_handler(signal, frame):
        rs.stop_engine()
        rs.join()
        sys.exit(0)

    signal.signal(signal.SIGINT, exit_handler)

    rs = RealStrategy()
    rs.run_engine()

And here are the rs.run_engine() and rs.stop_engine() methods that are called in main:

class RealStrategy(Thread):
.....
.....
    def run_engine(self):
        self.on_start()
        self._order_handler.start()
        self._data_parser.start()
        self._data_source.start()
        self.start()

    def stop_engine(self):
        self._data_source.stop()
        self._data_parser.stop()
        self._order_handler.stop()

        self._data_source.join()
        self._data_parser.join()
        self._order_handler.join()

        self.stop()

Body:
If you want to use queue.Queue.join, then you must also use queue.Queue.task_done. You can read the linked documentation or see the following copied from information available online:

Queue.task_done()

Indicate that a formerly enqueued task is complete.
  Used by queue consumer threads. For each get() used to fetch a task, a
  subsequent call to task_done() tells the queue that the processing on
  the task is complete.

If a join() is currently blocking, it will resume when all items have
  been processed (meaning that a task_done() call was received for every
  item that had been put() into the queue).

Raises a ValueError if called more times than there were items placed
  in the queue.

Queue.join()

Blocks until all items in the queue have been gotten and processed.

The count of unfinished tasks goes up whenever an item is added to the
  queue. The count goes down whenever a consumer thread calls
  task_done() to indicate that the item was retrieved and all work on it
  is complete. When the count of unfinished tasks drops to zero, join()
  unblocks.

To test your problem, an example implementation was created to find out what was going on. It is slightly different from how your program works but demonstrates a method to solving your problem:

#! /usr/bin/env python3
import abc
import csv
import pathlib
import queue
import sys
import threading
import time

def main():
    source_path = pathlib.Path(r'C:\path\to\file.csv')
    data_source = CSVDataSource(source_path)
    data_source.start()
    processor = StoppableThread(target=consumer, args=[data_source])
    processor.start()
    time.sleep(0.1)
    data_source.stop()

def consumer(data_source):
    while data_source.empty:
        time.sleep(0.001)
    while not data_source.empty:
        task = data_source.get_from_queue(True, 0.1)
        print(*task.data, sep=', ', flush=True)
        task.done()

class StopThread(StopIteration):
    pass

threading.SystemExit = SystemExit, StopThread

class StoppableThread(threading.Thread):
    def _bootstrap(self, stop=False):
        # noinspection PyProtectedMember
        if threading._trace_hook:
            raise RuntimeError('cannot run thread with tracing')

        def terminate():
            nonlocal stop
            stop = True

        self.__terminate = terminate

        # noinspection PyUnusedLocal
        def trace(frame, event, arg):
            if stop:
                raise StopThread

        sys.settrace(trace)
        super()._bootstrap()

    def terminate(self):
        try:
            self.__terminate()
        except AttributeError:
            raise RuntimeError('cannot terminate thread '
                               'before it is started') from None

class Queryable:
    def __init__(self, maxsize=1 << 10):
        self.__queue = queue.Queue(maxsize)

    def add_to_queue(self, item):
        self.__queue.put(item)

    def get_from_queue(self, block=True, timeout=None):
        return self.__queue.get(block, timeout)

    @property
    def empty(self):
        return self.__queue.empty()

    @property
    def full(self):
        return self.__queue.full()

    def task_done(self):
        self.__queue.task_done()

    def join_queue(self):
        self.__queue.join()

class StoppableQueryThread(StoppableThread, Queryable):
    def __init__(self, target=None, name=None, args=(), kwargs=None,
                 *, daemon=None, maxsize=1 << 10):
        super().__init__(None, target, name, args, kwargs, daemon=daemon)
        Queryable.__init__(self, maxsize)

    def stop(self):
        self.terminate()
        self.join_queue()

class DataSource(StoppableQueryThread, abc.ABC):
    @abc.abstractmethod
    def __init__(self, maxsize=1 << 10):
        super().__init__(None, 'DataSource', maxsize=maxsize)

    def run(self):
        while True:
            record = self._fetch_data()
            self.add_to_queue(record)

    @abc.abstractmethod
    def _fetch_data(self):
        pass

class CSVDataSource(DataSource):
    def __init__(self, source_path):
        super().__init__()
        self.__data_parser = self.__build_data_parser(source_path)

    @staticmethod
    def __build_data_parser(source_path):
        with source_path.open(newline='') as source:
            parser = csv.reader(source)
            next(parser, None)
            yield from parser

    def _fetch_data(self):
        try:
            return Task(next(self.__data_parser), self.task_done)
        except StopIteration:
            raise StopThread from None

class Task:
    def __init__(self, data, callback):
        self.__data = data
        self.__callback = callback

    @property
    def data(self):
        return self.__data

    def done(self):
        self.__callback()

if __name__ == '__main__':
    main()


问:
ASP.net HTTP 404 - File not found instead of MaxRequestLength exception
I have a file upload control on my webpage. The maximum request length is set to 8 MB (maxRequestLength = 8192). I also have server validation that throws an error if the file is more than 4MB. The reason that its 8MB in the config is the leverage that's given to the user and also so that the application can be tested.

If I upload a file that's 9MB, I get thrown an exception Maximum request length exceeded., which is fine and working as expected. But when I try to upload a file that's 1GB, it shows me a HTTP 404 - File not found. Can someone please explain why this is happening and how can I get it to throw me a maxRequestLength exception?

I'm using IIS6.

答: You could configure the default error page in IIS itself.</p>


问:
Convert rows into columns in sub-query
I'm trying to convert rows into columns when using this in a subquery query like:

```<code>select distinct
    bqtID, bqtName, bqtCity, bqtStatus, bqtManagerName,
    (select
         max(case when serName = 'Capacity' then serStatus end) Capacity,
         max(case when serName = 'Parking' then serStatus end) Parking
     from
         tblService
     where
         serBqtID = bqtID),
from
    View_BanquetList
where
    bqtID = 1
</code>```

I get this error:

Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.

While when I used it separately then it works:

```<code>select
     max(case when serName = 'Capacity' then serStatus end) Capacity,
     max(case when serName = 'Parking' then serStatus end) Parking
from
    tblService
where
    serBqtID = 1
</code>```

Results:

```<code>Capacity    Parking
--------    -------
101-200     51-100
</code>```

Why is it not converting multiple rows into columns in sub-query?

答:
You are trying to return two columns as one in the select list. That doesn't work. I'm not an expert on SQL Server, but with Oracle there would be at least three options.

Move the subselect to a with-clause and then join with it.

Use two sub-selects, one for capacity and one for parking.

Move the sub-select to the from clause and use a subselect that becomes a table, which is then joined.

I think all should work with SQL Server as well. Option 3 is closest to what you have now.

EDIT: try this:

```<code>select distinct
    v.bqtID, v.bqtName, v.bqtCity, v.bqtStatus, v.bqtManagerName,
    t.Capacity, t.Parking
from
    (select
         serBqtID,
         max(case when serName = 'Capacity' then serStatus end) Capacity,
         max(case when serName = 'Parking' then serStatus end) Parking
     from
         tblService
     group by
         serBqtID) t
inner join
    View_BanquetList v on t.serBqtID = v.bqtID
where
    v.bqtID = 1
</code>```

Title: Convert rows into columns in sub-query

Body:
I'm trying to convert rows into columns when using this in a subquery query like:

select distinct
    bqtID, bqtName, bqtCity, bqtStatus, bqtManagerName,
    (select
         max(case when serName = 'Capacity' then serStatus end) Capacity,
         max(case when serName = 'Parking' then serStatus end) Parking
     from
         tblService
     where
         serBqtID = bqtID),
from
    View_BanquetList
where
    bqtID = 1

I get this error:

Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.

While when I used it separately then it works:

select
     max(case when serName = 'Capacity' then serStatus end) Capacity,
     max(case when serName = 'Parking' then serStatus end) Parking
from
    tblService
where
    serBqtID = 1

Results:

Capacity    Parking
--------    -------
101-200     51-100

Why is it not converting multiple rows into columns in sub-query?

Body:
You are trying to return two columns as one in the select list. That doesn't work. I'm not an expert on SQL Server, but with Oracle there would be at least three options.

Move the subselect to a with-clause and then join with it.

Use two sub-selects, one for capacity and one for parking.

Move the sub-select to the from clause and use a subselect that becomes a table, which is then joined.

I think all should work with SQL Server as well. Option 3 is closest to what you have now.

EDIT: try this:

select distinct
    v.bqtID, v.bqtName, v.bqtCity, v.bqtStatus, v.bqtManagerName,
    t.Capacity, t.Parking
from
    (select
         serBqtID,
         max(case when serName = 'Capacity' then serStatus end) Capacity,
         max(case when serName = 'Parking' then serStatus end) Parking
     from
         tblService
     group by
         serBqtID) t
inner join
    View_BanquetList v on t.serBqtID = v.bqtID
where
    v.bqtID = 1


问:
Autolisp list manipulation
I am struggling with Autolisp and I cannot find the answer I am looking for.

I have an empty list and I am filling it with point coordinates that I have turned into strings. The list that is produced is something like:

(12.5484,7.6054,0.0000 17.0626,8.1782,0.0000 17.5642,10.7199,0.0000
  12.0110,11.4716,0.0000)

Is there any possible way that the list filling can be made vertically and have an output something like:

(12.5484,7.6054,0.0000

17.0626,8.1782,0.0000

17.5642,10.7199,0.0000

12.0110,11.4716,0.0000)

The code I am using is:

```<code>(setq lst()) ;create empty list named lst

    (while
        (setq a (getpoint "\nTick the Point")) ;select points

        (setq x (rtos(car a))) ;get as X the x of a point (as string)
        (setq y (rtos(cadr a))) ;get as Y the y of a point (as string)
        (setq z (rtos(caddr a))) ;get as Z the z of a point (as string)
        (setq pnt (strcat x "," y ","z))

        (setq lst (cons pnt lst)) ;start filling the empty list with the coordinates of the points

    )
</code>```

答:
```<code>(setq ptlist '())
(mapcar '(lambda (pt)
        (strcat (rtos (car pt)) "," (rtos (cadr pt)) "," (rtos (caddr pt))))
        (reverse (while (setq pttemp(getpoint "Your point:"))
           (if pttemp (cons pttemp ptlist))
        ))
)
</code>```

mapcar expression will return to you a list of strings converted from dots. If you need to convert this list to a string, use the function (apply 'strcat (list-of-strings))

Title: Autolisp list manipulation

Body:
I am struggling with Autolisp and I cannot find the answer I am looking for.

I have an empty list and I am filling it with point coordinates that I have turned into strings. The list that is produced is something like:

(12.5484,7.6054,0.0000 17.0626,8.1782,0.0000 17.5642,10.7199,0.0000
  12.0110,11.4716,0.0000)

Is there any possible way that the list filling can be made vertically and have an output something like:

(12.5484,7.6054,0.0000

17.0626,8.1782,0.0000

17.5642,10.7199,0.0000

12.0110,11.4716,0.0000)

The code I am using is:

(setq lst()) ;create empty list named lst

    (while
        (setq a (getpoint "\nTick the Point")) ;select points

        (setq x (rtos(car a))) ;get as X the x of a point (as string)
        (setq y (rtos(cadr a))) ;get as Y the y of a point (as string)
        (setq z (rtos(caddr a))) ;get as Z the z of a point (as string)
        (setq pnt (strcat x "," y ","z))

        (setq lst (cons pnt lst)) ;start filling the empty list with the coordinates of the points

    )

Body:
(setq ptlist '())
(mapcar '(lambda (pt)
        (strcat (rtos (car pt)) "," (rtos (cadr pt)) "," (rtos (caddr pt))))
        (reverse (while (setq pttemp(getpoint "Your point:"))
           (if pttemp (cons pttemp ptlist))
        ))
)

mapcar expression will return to you a list of strings converted from dots. If you need to convert this list to a string, use the function (apply 'strcat (list-of-strings))


问:
incompatible types in assignment of 'int' to 'int [10]' in C
**i want to assign the pointers on the first element of each array but i get this message -->incompatible types in assignment of 'int' to 'int [10]' in C **    </p>

```<code>#include <stdio.h>
#include <stdlib.h>
#define ten 10
int main ()
{
  int min = 0, max = 0, *minptr, *maxptr, i;
  int arr1[ten], arr2[ten], *arr1_ptr[ten], *arr2_ptr[ten];
  arr1_ptr = &arr1[0];
  arr2_ptr = &arr2[0];
  minptr = &min;
  maxptr = &max;

  return 0;
}
</code>```

答:
The types are different. Type of &arr1[0] is int* but that of arr1_ptr is int*[10]. That's why this error message. You even copied the error message wrong.

Also note that maybe this is what you wanted

```<code>arr1_ptr[0] = &arr1[0];
</code>```

Because now the types match and also it means - you are assigning a int variables address to the first element of an array where each element of the array is of type int*.

Body:
**i want to assign the pointers on the first element of each array but i get this message -->incompatible types in assignment of 'int' to 'int [10]' in C **

#include <stdio.h>
#include <stdlib.h>
#define ten 10
int main ()
{
  int min = 0, max = 0, *minptr, *maxptr, i;
  int arr1[ten], arr2[ten], *arr1_ptr[ten], *arr2_ptr[ten];
  arr1_ptr = &arr1[0];
  arr2_ptr = &arr2[0];
  minptr = &min;
  maxptr = &max;

  return 0;
}

Body:
The types are different. Type of &arr1[0] is int* but that of arr1_ptr is int*[10]. That's why this error message. You even copied the error message wrong.

Also note that maybe this is what you wanted

arr1_ptr[0] = &arr1[0];

Because now the types match and also it means - you are assigning a int variables address to the first element of an array where each element of the array is of type int*.