问:
Automation server can't create object, ie7
```<code>var fSO = new ActiveXObject("Scripting.FileSystemObject");
var fh = fSO.CreateTextFile(path + fileName + ".xml", true, true);
</code>```

I get the following javascript error: Automation server can't create object, even though all my ActiveX settings are enabled in IE that i can think of (ActiveX and plug-ins section). The browser that i'm using for this is IE7.

What could possibly cause this errormessage?

Any help is MUCH appreciated!

Thanks in advance.

答:
Go to Tools > Internet options > Security > Custom Level
Under the ActiveX controls and plug-ins, select Enable for Initializing and Script ActiveX controls not marked as safe</p>

Body:
var fSO = new ActiveXObject("Scripting.FileSystemObject");
var fh = fSO.CreateTextFile(path + fileName + ".xml", true, true);

I get the following javascript error: Automation server can't create object, even though all my ActiveX settings are enabled in IE that i can think of (ActiveX and plug-ins section). The browser that i'm using for this is IE7.

What could possibly cause this errormessage?

Any help is MUCH appreciated!

Thanks in advance.


来源: stackexchange

问:
Styling html progress bar as health bar with value simple Css
I am trying to style a HTML progress bar as a health bar.

I am trying to make it look like this with health value

I tried this but not working

.progressplayer[value]::-webkit-progress-bar {
  background-color: #eee;
}

.progressplayer[value]::-webkit-progress-value {
  background-color: #FF0000;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><progress class="progressplayer" id="playerhealth" value="100" max="100"></progress></code>```

Comment to christians answer:

```<code><div class="progress-container">
  <progress id="playerhealth" *ngIf="state==1"   id="playerhealth" value="100" max="100"></progress>
  <p class="progress-label">
    {{playerhp}}
  </p>
  <progress id="enemyhealth" *ngIf="state==1"   id="enemyhealth" value="100" max="100"></progress>
  <p class="progress-label">
    {{mhp}}
  </p>
</div>
</code>```

with this i cant display second progress label.

答:
Because the progress element does not let you natively add text on top of the progress bar, we'll have to use a workaround: positioning a label on top of the progress bar.

As for the styling of the bar, you can style the progress element directly and use the pseudo elements to target the -webkit-progress-bar and -webkit-progress-value:

.progress-container {
    position: relative;
}

.progress-container progress {
    background-color: #eee;
    height: 40px;
}

.progress-container progress::-webkit-progress-bar {
    background-color: #eee;
}

.progress-container progress::-webkit-progress-value {
    background-color: red;
}

.progress-container .progress-label {
    position: absolute;
    top: 7px;
    margin: 0;
    left: 65px;
    font-size: 22px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>Player health:</h1>
<div class="progress-container player-health">
  <progress class="progressplayer" id="playerhealth" value="80" max="100"></progress>
  <p class="progress-label">
    80%
  </p>
</div>

<h1>Enemy health:</h1>
<div class="progress-container enemy-health">
  <progress class="progressplayer" id="playerhealth" value="80" max="100">
  </progress>
  <p class="progress-label">
    80%
  </p>
</div></code>```

You'll have to play around with the label's position, depending on how you want to position it and style the progress bar.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to style a HTML progress bar as a health bar.

I am trying to make it look like this with health value

I tried this but not working

.progressplayer[value]::-webkit-progress-bar {
  background-color: #eee;
}

.progressplayer[value]::-webkit-progress-value {
  background-color: #FF0000;
}

<progress class="progressplayer" id="playerhealth" value="100" max="100"></progress>

Comment to christians answer:

  <progress id="playerhealth" *ngIf="state==1"   id="playerhealth" value="100" max="100"></progress>

    {{playerhp}}

  <progress id="enemyhealth" *ngIf="state==1"   id="enemyhealth" value="100" max="100"></progress>

    {{mhp}}

with this i cant display second progress label.

Body:
Because the progress element does not let you natively add text on top of the progress bar, we'll have to use a workaround: positioning a label on top of the progress bar.

As for the styling of the bar, you can style the progress element directly and use the pseudo elements to target the -webkit-progress-bar and -webkit-progress-value:

.progress-container {
    position: relative;
}

.progress-container progress {
    background-color: #eee;
    height: 40px;
}

.progress-container progress::-webkit-progress-bar {
    background-color: #eee;
}

.progress-container progress::-webkit-progress-value {
    background-color: red;
}

.progress-container .progress-label {
    position: absolute;
    top: 7px;
    margin: 0;
    left: 65px;
    font-size: 22px;
}

<h1>Player health:</h1>
<div class="progress-container player-health">
  <progress class="progressplayer" id="playerhealth" value="80" max="100"></progress>
  <p class="progress-label">
    80%
  </p>
</div>

<h1>Enemy health:</h1>
<div class="progress-container enemy-health">
  <progress class="progressplayer" id="playerhealth" value="80" max="100">
  </progress>
  <p class="progress-label">
    80%
  </p>
</div>

You'll have to play around with the label's position, depending on how you want to position it and style the progress bar.


问:
Default text on textarea jQuery?
I have a textarea that i would like to show some default text on page load. Once the textarea is clicked i would like to have the text disappear and possibly if user clicked in textarea and did not type anything in and then clicked out of textarea the default text will show again.

I have searched Google and on here but i can only seem to find tutorials relating to text boxes and NOT textareas, plus i already am using a class on the textarea so cannot depend on class for it to work.

Does anyone have some simple jQuery code they would like to share with me to do what i want above?

答:
DEMO: http://jsfiddle.net/marcuswhybrow/eJP9C/2/

It is important to remember the edge case that the user types the value which is your default. My solution avoids this by giving each textarea an edited flag using jQuery's data() method.

The HTML

Define the default value of the textarea as you would normally:

```<code><textarea>This is the default text</textarea>
</code>```

The jQuery

```<code>$('textarea').each(function() {
    // Stores the default value for each textarea within each textarea
    $.data(this, 'default', this.value);
}).focus(function() {
    // If the user has NOT edited the text clear it when they gain focus
    if (!$.data(this, 'edited')) {
        this.value = "";
    }
}).change(function() {
    // Fires on blur if the content has been changed by the user
    $.data(this, 'edited', this.value != "");
}).blur(function() {
    // Put the default text back in the textarea if its not been edited
    if (!$.data(this, 'edited')) {
        this.value = $.data(this, 'default');
    }
});
</code>```

DEMO: http://jsfiddle.net/marcuswhybrow/eJP9C/2/

ContentLicense: CC BY-SA 2.5

Title: Default text on textarea jQuery?

Body:
DEMO: http://jsfiddle.net/marcuswhybrow/eJP9C/2/

It is important to remember the edge case that the user types the value which is your default. My solution avoids this by giving each textarea an edited flag using jQuery's data() method.

The HTML

Define the default value of the textarea as you would normally:

<textarea>This is the default text</textarea>

The jQuery

$('textarea').each(function() {
    // Stores the default value for each textarea within each textarea
    $.data(this, 'default', this.value);
}).focus(function() {
    // If the user has NOT edited the text clear it when they gain focus
    if (!$.data(this, 'edited')) {
        this.value = "";
    }
}).change(function() {
    // Fires on blur if the content has been changed by the user
    $.data(this, 'edited', this.value != "");
}).blur(function() {
    // Put the default text back in the textarea if its not been edited
    if (!$.data(this, 'edited')) {
        this.value = $.data(this, 'default');
    }
});

DEMO: http://jsfiddle.net/marcuswhybrow/eJP9C/2/


问:
How to set maximum execution time for a Promise await?
How would you wait for a Promise to resolve/reject, for a maximum execution time ? The code below is obviously wrong, it's just to explain what I'm trying to achieve. I'm clueless.

```<code>await doSomething();
if ( executionTime > maxExecutionTime ) {
    doSomethingElse();
}
</code>```

This is not for a bluebird promise.

答:
You can use Promise.race() which will immediately resolve/reject when the first promise in its iterable resolves or rejects. E.g.

const longTask = () => new Promise(resolve =>
  setTimeout(() => resolve("Long task complete."), 300))

const timeout = (cb, interval) => () =>
  new Promise(resolve => setTimeout(() => cb(resolve), interval))

const onTimeout = timeout(resolve =>
  resolve("The 'maybeLongTask' ran too long!"), 200)

Promise.race([longTask, onTimeout].map(f => f())).then(console.log)```

The only issue is you can't really cancel the 'longTask' just because of its long execution. In theory, you'd either set some flag (to tell it not to continue onto the next stage of its pipeline), or design your application with the consequences of the promise in mind.

See what happens when you swap the 200 and 300 intervals.

Edit: Per spsaucier's comment, I've delayed the execution of each promise until the Promise.line line.

Body:
How would you wait for a Promise to resolve/reject, for a maximum execution time ? The code below is obviously wrong, it's just to explain what I'm trying to achieve. I'm clueless.

await doSomething();
if ( executionTime > maxExecutionTime ) {
    doSomethingElse();
}

This is not for a bluebird promise.

Body:
You can use Promise.race() which will immediately resolve/reject when the first promise in its iterable resolves or rejects. E.g.

const longTask = () => new Promise(resolve =>
  setTimeout(() => resolve("Long task complete."), 300))

const timeout = (cb, interval) => () =>
  new Promise(resolve => setTimeout(() => cb(resolve), interval))

const onTimeout = timeout(resolve =>
  resolve("The 'maybeLongTask' ran too long!"), 200)

Promise.race([longTask, onTimeout].map(f => f())).then(console.log)

The only issue is you can't really cancel the 'longTask' just because of its long execution. In theory, you'd either set some flag (to tell it not to continue onto the next stage of its pipeline), or design your application with the consequences of the promise in mind.

See what happens when you swap the 200 and 300 intervals.

Edit: Per spsaucier's comment, I've delayed the execution of each promise until the Promise.line line.

ContentLicense: CC BY-SA 4.0


问:
Capture repeated characters and split using Python
I need to split a string by using repeated characters.

For example:

My string is "howhowhow"

I need output as 'how,how,how'.

I cant use 'how' directly in my reg exp. because my input varies. I should check the string whether it is repeating the character and need to split that characters.

答:
```<code>import re

string = "howhowhow"

print(','.join(re.findall(re.search(r"(.+?)\1", string).group(1), string)))
</code>```

OUTPUT

```<code>howhowhow -> how,how,how
howhowhowhow -> how,how,how,how
testhowhowhow -> how,how,how  # not clearly defined by OP
</code>```

The pattern is non-greedy so that howhowhowhow doesn't map to howhow,howhow which is also legitimate.  Remove the ? if you prefer the longest match.

Body:
import re

string = "howhowhow"

print(','.join(re.findall(re.search(r"(.+?)\1", string).group(1), string)))

OUTPUT

howhowhow -> how,how,how
howhowhowhow -> how,how,how,how
testhowhowhow -> how,how,how  # not clearly defined by OP

The pattern is non-greedy so that howhowhowhow doesn't map to howhow,howhow which is also legitimate.  Remove the ? if you prefer the longest match.


问:
Sorting by Date using Jquery & HTML
I'm trying to sort some a data by date. the data is actually saved in HTML under a div --> span.
However, I've made the following function but for some reason, it's not working on them as correct as I expect it to be.

```<code>case "Import_Date_asc":
    var elems = $.makeArray($review_items);

    elems.sort(function(a, b) {
        var a_date = $(a).find('.panel-heading .data-source').text(),
            b_date = $(b).find('.panel-heading .data-source').text();

        a_date = a_date.split(' / ');
        a_date = a_date[1].split(' UTC');

        b_date = b_date.split(' / ');
        b_date = b_date[1].split(' UTC');

        console.log(a_date[0], b_date[0]);

        //return new Date(a_date[0]) > new Date(b_date[0]);
        return Date.parse(a_date[0]) > Date.parse(b_date[0]);
    });

    $review_container.html(elems);

    break;

case "Import_Date_desc":
  var elems = $.makeArray($review_items);

  elems.sort(function(a, b) {
      var a_date = $(a).find('.panel-heading .data-source').text(),
          b_date = $(b).find('.panel-heading .data-source').text();

      a_date = a_date.split(' / ');
      a_date = a_date[1].split(' UTC');

      b_date = b_date.split(' / ');
      b_date = b_date[1].split(' UTC');

      console.log(a_date[0], b_date[0]);

      //return new Date(a_date[0]) < new Date(b_date[0]);
      return Date.parse(a_date[0]) < Date.parse(b_date[0]);
  });

  $review_container.html(elems);

  break;
</code>```

The html looks like this :

```<code><div class="review-item panel panel-primary" data-ldn="8643" data-pse="43460">
        <div class="panel-heading">
<span class="data-title">Dom(i23)</span>
<span class="data-source pull-right">Import / 2017-12-07 14:35 UTC</span>
</div></div>
</code>```

please if you know what am I doing wrong in here will be very aprociated.

答:
It seems like the parse not working to convert your date.
However, I believe using localCompare would work better

```<code>case "Import_Date_asc":
    var elems = $.makeArray($review_items);

    elems.sort(function(a, b) {
        var a_date = $(a).find('.panel-heading .data-source').text(),
            b_date = $(b).find('.panel-heading .data-source').text();

        a_date = a_date.split(' / ');
        a_date = a_date[1].split(' UTC');
        a_date = a_date[0];
        a_date = a_date.replace('-', '');
        a_date = a_date.replace('-', '');
        a_date = a_date.replace(' ', '');
        a_date = a_date.replace(':', '');

        b_date = b_date.split(' / ');
        b_date = b_date[1].split(' UTC');
        b_date = b_date[0];
        b_date = b_date.replace('-', '');
        b_date = b_date.replace('-', '');
        b_date = b_date.replace(' ', '');
        b_date = b_date.replace(':', '');

        return a_date.localeCompare(b_date);
    });

    $review_container.html(elems);

    break;

case "Import_Date_desc":
  var elems = $.makeArray($review_items);

  elems.sort(function(a, b) {
      var a_date = $(a).find('.panel-heading .data-source').text(),
          b_date = $(b).find('.panel-heading .data-source').text();

      a_date = a_date.split(' / ');
      a_date = a_date[1].split(' UTC');
      a_date = a_date[0];
      a_date = a_date.replace('-', '');
      a_date = a_date.replace('-', '');
      a_date = a_date.replace(' ', '');
      a_date = a_date.replace(':', '');

      b_date = b_date.split(' / ');
      b_date = b_date[1].split(' UTC');
      b_date = b_date[0];
      b_date = b_date.replace('-', '');
      b_date = b_date.replace('-', '');
      b_date = b_date.replace(' ', '');
      b_date = b_date.replace(':', '');

      return a_date.localeCompare(b_date) * -1;
  });

  $review_container.html(elems);

  break;
</code>```

Try this code I believe it should work. it works on my test.
Also look into the [localeCompare()][1] Method.

Title: Sorting by Date using Jquery & HTML

Body:
I'm trying to sort some a data by date. the data is actually saved in HTML under a div --> span.
However, I've made the following function but for some reason, it's not working on them as correct as I expect it to be.

case "Import_Date_asc":
    var elems = $.makeArray($review_items);

    elems.sort(function(a, b) {
        var a_date = $(a).find('.panel-heading .data-source').text(),
            b_date = $(b).find('.panel-heading .data-source').text();

        a_date = a_date.split(' / ');
        a_date = a_date[1].split(' UTC');

        b_date = b_date.split(' / ');
        b_date = b_date[1].split(' UTC');

        console.log(a_date[0], b_date[0]);

        //return new Date(a_date[0]) > new Date(b_date[0]);
        return Date.parse(a_date[0]) > Date.parse(b_date[0]);
    });

    $review_container.html(elems);

    break;

case "Import_Date_desc":
  var elems = $.makeArray($review_items);

  elems.sort(function(a, b) {
      var a_date = $(a).find('.panel-heading .data-source').text(),
          b_date = $(b).find('.panel-heading .data-source').text();

      a_date = a_date.split(' / ');
      a_date = a_date[1].split(' UTC');

      b_date = b_date.split(' / ');
      b_date = b_date[1].split(' UTC');

      console.log(a_date[0], b_date[0]);

      //return new Date(a_date[0]) < new Date(b_date[0]);
      return Date.parse(a_date[0]) < Date.parse(b_date[0]);
  });

  $review_container.html(elems);

  break;

The html looks like this :

Dom(i23)
Import / 2017-12-07 14:35 UTC

please if you know what am I doing wrong in here will be very aprociated.

Body:
It seems like the parse not working to convert your date.
However, I believe using localCompare would work better

case "Import_Date_asc":
    var elems = $.makeArray($review_items);

    elems.sort(function(a, b) {
        var a_date = $(a).find('.panel-heading .data-source').text(),
            b_date = $(b).find('.panel-heading .data-source').text();

        a_date = a_date.split(' / ');
        a_date = a_date[1].split(' UTC');
        a_date = a_date[0];
        a_date = a_date.replace('-', '');
        a_date = a_date.replace('-', '');
        a_date = a_date.replace(' ', '');
        a_date = a_date.replace(':', '');

        b_date = b_date.split(' / ');
        b_date = b_date[1].split(' UTC');
        b_date = b_date[0];
        b_date = b_date.replace('-', '');
        b_date = b_date.replace('-', '');
        b_date = b_date.replace(' ', '');
        b_date = b_date.replace(':', '');

        return a_date.localeCompare(b_date);
    });

    $review_container.html(elems);

    break;

case "Import_Date_desc":
  var elems = $.makeArray($review_items);

  elems.sort(function(a, b) {
      var a_date = $(a).find('.panel-heading .data-source').text(),
          b_date = $(b).find('.panel-heading .data-source').text();

      a_date = a_date.split(' / ');
      a_date = a_date[1].split(' UTC');
      a_date = a_date[0];
      a_date = a_date.replace('-', '');
      a_date = a_date.replace('-', '');
      a_date = a_date.replace(' ', '');
      a_date = a_date.replace(':', '');

      b_date = b_date.split(' / ');
      b_date = b_date[1].split(' UTC');
      b_date = b_date[0];
      b_date = b_date.replace('-', '');
      b_date = b_date.replace('-', '');
      b_date = b_date.replace(' ', '');
      b_date = b_date.replace(':', '');

      return a_date.localeCompare(b_date) * -1;
  });

  $review_container.html(elems);

  break;

Try this code I believe it should work. it works on my test.
Also look into the [localeCompare()][1] Method.


问:
How to generate a file for download in a Google Chrome Extension?
I want to generate a CSV file as the result of some user interactions and then prompt the user to download it. How can I do that?

I don't think it's possible in straight JS, but perhaps Chrome gives me some elevated privileges?

答: Chrome doesn't provide any help with this, but I think you should be able to trigger a file save dialog using downloadify js library which uses a flash component behind the scenes.</p>


问:
add created_at and updated_at fields to mongoose schemas
Is there a way to add created_at and updated_at fields to a mongoose schema, without having to pass them in everytime new MyModel() is called?

The created_at field would be a date and only added when a document is created.
The updated_at field would be updated with new date whenever save() is called on a document.

I have tried this in my schema, but the field does not show up unless I explicitly add it:

```<code>var ItemSchema = new Schema({
    name    : { type: String, required: true, trim: true },
    created_at    : { type: Date, required: true, default: Date.now }
});
</code>```

答:
Use machinepack-datetime to format the datetime.

```<code>tutorialSchema.virtual('createdOn').get(function () {
    const DateTime = require('machinepack-datetime');
    let timeAgoString = "";
    try {
        timeAgoString = DateTime.timeFrom({
            toWhen: DateTime.parse({
                datetime: this.createdAt
            }).execSync(),
            fromWhen: new Date().getTime()
        }).execSync();
    } catch(err) {
        console.log('error getting createdon', err);
    }
    return timeAgoString; // a second ago
});
</code>```

Machine pack is great with clear API unlike express or general Javascript world.

Body:
Is there a way to add created_at and updated_at fields to a mongoose schema, without having to pass them in everytime new MyModel() is called?

The created_at field would be a date and only added when a document is created.
The updated_at field would be updated with new date whenever save() is called on a document.

I have tried this in my schema, but the field does not show up unless I explicitly add it:

var ItemSchema = new Schema({
    name    : { type: String, required: true, trim: true },
    created_at    : { type: Date, required: true, default: Date.now }
});

Body:
Use machinepack-datetime to format the datetime.

tutorialSchema.virtual('createdOn').get(function () {
    const DateTime = require('machinepack-datetime');
    let timeAgoString = "";
    try {
        timeAgoString = DateTime.timeFrom({
            toWhen: DateTime.parse({
                datetime: this.createdAt
            }).execSync(),
            fromWhen: new Date().getTime()
        }).execSync();
    } catch(err) {
        console.log('error getting createdon', err);
    }
    return timeAgoString; // a second ago
});

Machine pack is great with clear API unlike express or general Javascript world.


问:
Writing data to SQL and dumping it into Excel
My C# application is significantly slower than I would like. The program accesses an Excel sheet and loops through each row on a sheet / does the following:

Collects variables from that row

Creates an SQL query based off those variables

Executes that query

then a reader goes out and puts it in its proper column on that same row.

*Note, each row has 6 different SQL queries/ final numbers that are calculated and input into the sheet, the code below is just showing the first 2 for brevity's sake. The sheet has around 300 rows, so the program is executing 300 * 6= 1,800 SQL queries each time its run. For each one of those 1,800 numbers, the program is accessing the sheet and inputting it into the sheet.

Instead of doing the excelWorksheet.get_Range and inputting the number into the Excel sheet for each number, one at a time, would it be faster to store each number into an array and then go back later and mass dump all of the numbers into the sheet, once all of the queries have been executed and the array is full?

```<code>using (SqlConnection conn = new SqlConnection())
        {
            conn.ConnectionString = "Data Source=WRDXPVSEPIRPT00;DATABASE=Epicor905;Workstation ID=SMEBPPL204TN;Trusted_Connection=true";

            try
            {
                //initiate the connection
                conn.Open();
            }
            catch(SqlException ex)
            {

                throw new ApplicationException(string.Format("You're not connected to the database, please close the program, re-connect to the network, and try again."), ex);

            }

            progressBar1.Value = 60;

            statusLabel.Text = "Retrieving account balances from database...";
            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //iterate through each row and pull information
            for (int i = 2; i < lastUsedRow + 1; i++)
            {
                //string iString = Convert.ToString(i);
                statusLabel.Text = "Retrieving balances for " + i + " of " + lastUsedRow + " accounts...";

                //declare excel sheet range variables
                var CompanyVar = excelWorksheet.get_Range("A" + i, "A" + i).Text;
                var FiscalYear = excelWorksheet.get_Range("B" + i, "B" + i).Text;

                var FiscalPeriod = excelWorksheet.get_Range("C" + i, "C" + i).Text;
                var segValue1 = excelWorksheet.get_Range("F" + i, "F" + i).Text;
                var segValue2 = excelWorksheet.get_Range("G" + i, "G" + i).Text;
                var segValue3 = excelWorksheet.get_Range("H" + i, "H" + i).Text;

                int FiscalYearHelper = Convert.ToInt32(FiscalYear);
                var FiscalYearPYY = FiscalYearHelper - 1;

                //begin filling in CY YTD column

                string SQLCode = "SELECT SUM(DebitAmount-CreditAmount) as BalanceAmt FROM GLJrnDtl WITH (NOLOCK) WHERE" +
                             " FiscalPeriod between 1 AND " + FiscalPeriod + "AND Company =" + "'" + CompanyVar + "'" +
                             "AND FiscalYear =" + "'" + FiscalYear + "'" + "AND SegValue1 LIKE " + "'" + segValue1 + "'" +
                             "AND SegValue2 LIKE " + "'" + segValue2 + "'" + "AND SegValue3 LIKE " + "'" + segValue3 + "'";

                SqlCommand command = new SqlCommand(SQLCode, conn);

                // Create new SqlDataReader object and read data from the command.
                using (SqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {

                        string cyAct = reader["BalanceAmt"].ToString();
                        if (cyAct == "")
                        {
                            goto CYM;
                            //cyAct = "0.00";
                        }
                        var cyAct1 = (float)Convert.ToDouble(cyAct);
                        int one = Convert.ToInt32(excelWorksheet.get_Range("E" + i, "E" + i).Text);
                        double cyAct2 = (cyAct1 * one);
                        string cyAct3 = cyAct2.ToString("0.##");
                        excelWorksheet.get_Range("I" + i, "I" + i).Value = cyAct3;
                    }
                }
                //end filling in column

                //begin filling in CY Month column
                CYM:
                string SQLCodeMonth = "SELECT SUM(DebitAmount-CreditAmount) as BalanceAmt FROM GLJrnDtl WITH (NOLOCK) WHERE" +
                             " FiscalPeriod = " + FiscalPeriod + "AND Company =" + "'" + CompanyVar + "'" +
                             "AND FiscalYear =" + "'" + FiscalYear + "'" + "AND SegValue1 LIKE " + "'" + segValue1 + "'" +
                             "AND SegValue2 LIKE " + "'" + segValue2 + "'" + "AND SegValue3 LIKE " + "'" + segValue3 + "'";

                SqlCommand commandMonth = new SqlCommand(SQLCodeMonth, conn);

                // Create new SqlDataReader object and read data from the command.
                using (SqlDataReader reader = commandMonth.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        string cyAct = reader["BalanceAmt"].ToString();
                        if (cyAct == "")
                        {
                            goto APY;
                            //cyAct = "0.00";
                        }
                        var cyAct1 = (float)Convert.ToDouble(cyAct);
                        int one = Convert.ToInt32(excelWorksheet.get_Range("E" + i, "E" + i).Text);
                        double cyAct2 = (cyAct1 * one);
                        string cyAct3 = cyAct2.ToString("0.##");
                        excelWorksheet.get_Range("J" + i, "J" + i).Value = cyAct3;
                    }
                }
                //end filling in column

                //begin filling in Act PY month column
</code>```

答: Instead of looping through each row and running a SQL query for each row, I found that it is faster to outer join the table I speak of in my question with another SQL table that has the account balances on it. I'm doing all of it within memory because I've been coding for 3 weeks and I don't have time to learn how to create a temp table in SQL server yet.

Body:
My C# application is significantly slower than I would like. The program accesses an Excel sheet and loops through each row on a sheet / does the following:

Collects variables from that row

Creates an SQL query based off those variables

Executes that query

then a reader goes out and puts it in its proper column on that same row.

*Note, each row has 6 different SQL queries/ final numbers that are calculated and input into the sheet, the code below is just showing the first 2 for brevity's sake. The sheet has around 300 rows, so the program is executing 300 * 6= 1,800 SQL queries each time its run. For each one of those 1,800 numbers, the program is accessing the sheet and inputting it into the sheet.

Instead of doing the excelWorksheet.get_Range and inputting the number into the Excel sheet for each number, one at a time, would it be faster to store each number into an array and then go back later and mass dump all of the numbers into the sheet, once all of the queries have been executed and the array is full?

using (SqlConnection conn = new SqlConnection())
        {
            conn.ConnectionString = "Data Source=WRDXPVSEPIRPT00;DATABASE=Epicor905;Workstation ID=SMEBPPL204TN;Trusted_Connection=true";

            try
            {
                //initiate the connection
                conn.Open();
            }
            catch(SqlException ex)
            {

                throw new ApplicationException(string.Format("You're not connected to the database, please close the program, re-connect to the network, and try again."), ex);

            }

            progressBar1.Value = 60;

            statusLabel.Text = "Retrieving account balances from database...";
            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //iterate through each row and pull information
            for (int i = 2; i < lastUsedRow + 1; i++)
            {
                //string iString = Convert.ToString(i);
                statusLabel.Text = "Retrieving balances for " + i + " of " + lastUsedRow + " accounts...";

                //declare excel sheet range variables
                var CompanyVar = excelWorksheet.get_Range("A" + i, "A" + i).Text;
                var FiscalYear = excelWorksheet.get_Range("B" + i, "B" + i).Text;

                var FiscalPeriod = excelWorksheet.get_Range("C" + i, "C" + i).Text;
                var segValue1 = excelWorksheet.get_Range("F" + i, "F" + i).Text;
                var segValue2 = excelWorksheet.get_Range("G" + i, "G" + i).Text;
                var segValue3 = excelWorksheet.get_Range("H" + i, "H" + i).Text;

                int FiscalYearHelper = Convert.ToInt32(FiscalYear);
                var FiscalYearPYY = FiscalYearHelper - 1;

                //begin filling in CY YTD column

                string SQLCode = "SELECT SUM(DebitAmount-CreditAmount) as BalanceAmt FROM GLJrnDtl WITH (NOLOCK) WHERE" +
                             " FiscalPeriod between 1 AND " + FiscalPeriod + "AND Company =" + "'" + CompanyVar + "'" +
                             "AND FiscalYear =" + "'" + FiscalYear + "'" + "AND SegValue1 LIKE " + "'" + segValue1 + "'" +
                             "AND SegValue2 LIKE " + "'" + segValue2 + "'" + "AND SegValue3 LIKE " + "'" + segValue3 + "'";

                SqlCommand command = new SqlCommand(SQLCode, conn);

                // Create new SqlDataReader object and read data from the command.
                using (SqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {

                        string cyAct = reader["BalanceAmt"].ToString();
                        if (cyAct == "")
                        {
                            goto CYM;
                            //cyAct = "0.00";
                        }
                        var cyAct1 = (float)Convert.ToDouble(cyAct);
                        int one = Convert.ToInt32(excelWorksheet.get_Range("E" + i, "E" + i).Text);
                        double cyAct2 = (cyAct1 * one);
                        string cyAct3 = cyAct2.ToString("0.##");
                        excelWorksheet.get_Range("I" + i, "I" + i).Value = cyAct3;
                    }
                }
                //end filling in column

                //begin filling in CY Month column
                CYM:
                string SQLCodeMonth = "SELECT SUM(DebitAmount-CreditAmount) as BalanceAmt FROM GLJrnDtl WITH (NOLOCK) WHERE" +
                             " FiscalPeriod = " + FiscalPeriod + "AND Company =" + "'" + CompanyVar + "'" +
                             "AND FiscalYear =" + "'" + FiscalYear + "'" + "AND SegValue1 LIKE " + "'" + segValue1 + "'" +
                             "AND SegValue2 LIKE " + "'" + segValue2 + "'" + "AND SegValue3 LIKE " + "'" + segValue3 + "'";

                SqlCommand commandMonth = new SqlCommand(SQLCodeMonth, conn);

                // Create new SqlDataReader object and read data from the command.
                using (SqlDataReader reader = commandMonth.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        string cyAct = reader["BalanceAmt"].ToString();
                        if (cyAct == "")
                        {
                            goto APY;
                            //cyAct = "0.00";
                        }
                        var cyAct1 = (float)Convert.ToDouble(cyAct);
                        int one = Convert.ToInt32(excelWorksheet.get_Range("E" + i, "E" + i).Text);
                        double cyAct2 = (cyAct1 * one);
                        string cyAct3 = cyAct2.ToString("0.##");
                        excelWorksheet.get_Range("J" + i, "J" + i).Value = cyAct3;
                    }
                }
                //end filling in column

                //begin filling in Act PY month column


问:
Confirm internet data connection before making Firestore Query
I have the following situation:

The application has the option to like the posts of a user. And also has a Dislike option.

It is working properly when it is on a wifi or mobile network (with online connection).

Problem:

When the network is mobile, it is often connected but has no data transmission and does not work. It is a geographical and operator problem in certain locations in the country.

So it's taking a long time for the Like option to have its effect for either Like or DisLike.

Code:

```<code>@Override
    public void onLikeSelected(final DocumentSnapshot like) {

        if (checkConnection()){

            final String idCurrentUser = mCurrentUser.getUid();

            Task<QuerySnapshot> query = mDb.collection("Postagens").document(like.getId()).collection("Likes").whereEqualTo("id_userLike", idCurrentUser)
                    .get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
                        @Override
                        public void onSuccess(QuerySnapshot documentSnapshots) {

                            if(documentSnapshots.size() == 0) {

                                Map<String, Object> dado_usuario = new HashMap<>();
                                dado_usuario.put("id_userLike", mCurrentUser.getUid());
                                dado_usuario.put("timestamp", FieldValue.serverTimestamp());

                                mDb.collection("Postagens").document(like.getId()).collection("Likes").document(idCurrentUser).set(dado_usuario).addOnCompleteListener(new OnCompleteListener<Void>() {
                                    @Override
                                    public void onComplete(@NonNull Task<Void> task) {

                                    }
                                });

                            } else { //utilizando else

                                mDb.collection("Postagens").document(like.getId()).collection("Likes").document(idCurrentUser).delete().addOnSuccessListener(new OnSuccessListener<Void>() {
                                    @Override
                                    public void onSuccess(Void aVoid) {

                                    }
                                });

                            }

                        }
                    });

        } else {

            Toast.makeText(getActivity(), "Not Connection", Toast.LENGTH_SHORT).show();
        }

}

 public  boolean checkConnection() {
        boolean conectado;
        ConnectivityManager conectivtyManager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        if (conectivtyManager.getActiveNetworkInfo() != null
                && conectivtyManager.getActiveNetworkInfo().isAvailable()
                && conectivtyManager.getActiveNetworkInfo().isConnected()) {
            conectado = true;
        } else {
            conectado = false;
        }
        return conectado;
}
</code>```

How can I do this when the mobile connection is bad or weak

I do not know if it would be the case of handling the data connection or changing the treatment of the Like (onLikeSelected()) option in the Firestore Database.

Thanks!!

答:
There are two ways to do this thing one is check at a instance and another is making a broadcast receiver

```<code>    public static boolean internetAvailable(Context context) {
    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = null;
    if (connectivityManager != null) {
        activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    }
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
</code>```

And the other one is

```<code>public class NetworkChangeReceiver extends BroadcastReceiver {
public static final String TAG = "NetworkChangeReceiver";
public static ConnectivityReceiverListener connectivityReceiverListener;

public NetworkChangeReceiver() {
    super();
}

@Override
public void onReceive(Context context, Intent intent) {
    ConnectivityManager cm = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = null;
    if (cm != null) {
        activeNetwork = cm.getActiveNetworkInfo();
    }
    boolean isConnected = activeNetwork != null
            && activeNetwork.isConnectedOrConnecting();

    if (connectivityReceiverListener != null) {
        connectivityReceiverListener.onNetworkConnectionChanged(isConnected);
    }
}

public interface ConnectivityReceiverListener {
    void onNetworkConnectionChanged(boolean isConnected);
}
</code>```

}

Happy Coding :)

Body:
I have the following situation:

The application has the option to like the posts of a user. And also has a Dislike option.

It is working properly when it is on a wifi or mobile network (with online connection).

Problem:

When the network is mobile, it is often connected but has no data transmission and does not work. It is a geographical and operator problem in certain locations in the country.

So it's taking a long time for the Like option to have its effect for either Like or DisLike.

Code:

@Override
    public void onLikeSelected(final DocumentSnapshot like) {

        if (checkConnection()){

            final String idCurrentUser = mCurrentUser.getUid();

            Task<QuerySnapshot> query = mDb.collection("Postagens").document(like.getId()).collection("Likes").whereEqualTo("id_userLike", idCurrentUser)
                    .get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
                        @Override
                        public void onSuccess(QuerySnapshot documentSnapshots) {

                            if(documentSnapshots.size() == 0) {

                                Map<String, Object> dado_usuario = new HashMap<>();
                                dado_usuario.put("id_userLike", mCurrentUser.getUid());
                                dado_usuario.put("timestamp", FieldValue.serverTimestamp());

                                mDb.collection("Postagens").document(like.getId()).collection("Likes").document(idCurrentUser).set(dado_usuario).addOnCompleteListener(new OnCompleteListener<Void>() {
                                    @Override
                                    public void onComplete(@NonNull Task<Void> task) {

                                    }
                                });

                            } else { //utilizando else

                                mDb.collection("Postagens").document(like.getId()).collection("Likes").document(idCurrentUser).delete().addOnSuccessListener(new OnSuccessListener<Void>() {
                                    @Override
                                    public void onSuccess(Void aVoid) {

                                    }
                                });

                            }

                        }
                    });

        } else {

            Toast.makeText(getActivity(), "Not Connection", Toast.LENGTH_SHORT).show();
        }

}

 public  boolean checkConnection() {
        boolean conectado;
        ConnectivityManager conectivtyManager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        if (conectivtyManager.getActiveNetworkInfo() != null
                && conectivtyManager.getActiveNetworkInfo().isAvailable()
                && conectivtyManager.getActiveNetworkInfo().isConnected()) {
            conectado = true;
        } else {
            conectado = false;
        }
        return conectado;
}

How can I do this when the mobile connection is bad or weak

I do not know if it would be the case of handling the data connection or changing the treatment of the Like (onLikeSelected()) option in the Firestore Database.

Thanks!!

Body:
There are two ways to do this thing one is check at a instance and another is making a broadcast receiver

    public static boolean internetAvailable(Context context) {
    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = null;
    if (connectivityManager != null) {
        activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    }
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

And the other one is

public class NetworkChangeReceiver extends BroadcastReceiver {
public static final String TAG = "NetworkChangeReceiver";
public static ConnectivityReceiverListener connectivityReceiverListener;

public NetworkChangeReceiver() {
    super();
}

@Override
public void onReceive(Context context, Intent intent) {
    ConnectivityManager cm = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = null;
    if (cm != null) {
        activeNetwork = cm.getActiveNetworkInfo();
    }
    boolean isConnected = activeNetwork != null
            && activeNetwork.isConnectedOrConnecting();

    if (connectivityReceiverListener != null) {
        connectivityReceiverListener.onNetworkConnectionChanged(isConnected);
    }
}

public interface ConnectivityReceiverListener {
    void onNetworkConnectionChanged(boolean isConnected);
}

}

Happy Coding :)


问:
How to make an HTTP get() on a local json file using rxjs?
I am trying to make a request to my local JSON file using Ionic typescript, and retrieve all of the game objects in my JSON file. Here is what I have so far:

```<code>import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { map } from 'rxjs/operators/map';
import { catchError } from 'rxjs/operators/catchError';
import { Observable } from "rxjs/Observable";
import { Game } from "../../models/Game";

import { Http, Response, RequestOptions, Headers } from '@angular/http';

/*
  Generated class for the GamesProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class GamesProvider {
  constructor(public http: HttpClient) {

  }

  public getGames(): Observable<Array<Game>> {

      return this.http.get('/assets/games.json').pipe(
        map((res: Response) => res.json().games),
        catchError(this.handleError)
      );
  }

  public handleError(error: any) {
      // log error
      // could be something more sofisticated
      let errorMsg = error.message || `Yikes! There was a problem with our hyperdrive device and we couldn't retrieve your data!`
      console.error(errorMsg);

      // throw an application level error
      return Observable.throw(errorMsg);
  }
}
</code>```

I am getting a result that looks like this when I call the getGames() function:

```<code>operator
    :CatchOperator {caught: Observable, selector: ƒ}
    source
    :Observable {_isScalar: false, source: Observable, operator: MapOperator}
    _isScalar
    :false
    __proto__
    :Object
</code>```

What I am expecting is an Observable Array of Game objects.

Game.ts:

```<code>export class Game {
    gameid: number
    genres: string
    images: string
    name: string
    developer: string
    publisher: string
    date: string
    description: string
    players: number
}
</code>```

This is what my JSON file looks like:

```<code>{
    "games":[
  {
    "Id": 1,
    "name": "007: GoldenEye",
    "genres": "Action/First-Person Shooter",
    "date": "25-Aug-97",
    "images": "007: GoldenEye.png",
    "developer": "Rare",
    "publisher": "Nintendo",
    "description": "A video game released for the Nintendo 64.",
    "players": 4
  },
  {
    "Id": 2,
    "name": "007: The World Is Not Enough",
    "genres": "Action/First-Person Shooter",
    "date": "1-Nov-00",
    "images": "007: The World Is Not Enough.png",
    "developer": "Eurocom",
    "publisher": "Electronic Arts",
    "description": "A video game released for the Nintendo 64.",
    "players": 4
  },
...
...
...
 ]
}
</code>```

答:
if your Game class change to

```<code>export class Game {
    id: number
    genres: string
    images: string
    name: string
    developer: string
    publisher: string
    date: string
    description: string
    players: number
}
</code>```

you can cast output of http.get to your Games class:

```<code>return this.http.get('/assets/games.json').map(
(res: Response) => <Game>res.json().games).catch(this.handleError);
</code>```

for handling error can use this method

```<code>protected handleError(error: any): Observable<any> {
    console.log(error.message || error);
    const response = 'some error occurred!';
    return Observable.of(response);
  }
</code>```

Body:
I am trying to make a request to my local JSON file using Ionic typescript, and retrieve all of the game objects in my JSON file. Here is what I have so far:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { map } from 'rxjs/operators/map';
import { catchError } from 'rxjs/operators/catchError';
import { Observable } from "rxjs/Observable";
import { Game } from "../../models/Game";

import { Http, Response, RequestOptions, Headers } from '@angular/http';

/*
  Generated class for the GamesProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class GamesProvider {
  constructor(public http: HttpClient) {

  }

  public getGames(): Observable<Array<Game>> {

      return this.http.get('/assets/games.json').pipe(
        map((res: Response) => res.json().games),
        catchError(this.handleError)
      );
  }

  public handleError(error: any) {
      // log error
      // could be something more sofisticated
      let errorMsg = error.message || `Yikes! There was a problem with our hyperdrive device and we couldn't retrieve your data!`
      console.error(errorMsg);

      // throw an application level error
      return Observable.throw(errorMsg);
  }
}

I am getting a result that looks like this when I call the getGames() function:

operator
    :CatchOperator {caught: Observable, selector: ƒ}
    source
    :Observable {_isScalar: false, source: Observable, operator: MapOperator}
    _isScalar
    :false
    __proto__
    :Object

What I am expecting is an Observable Array of Game objects.

Game.ts:

export class Game {
    gameid: number
    genres: string
    images: string
    name: string
    developer: string
    publisher: string
    date: string
    description: string
    players: number
}

This is what my JSON file looks like:

{
    "games":[
  {
    "Id": 1,
    "name": "007: GoldenEye",
    "genres": "Action/First-Person Shooter",
    "date": "25-Aug-97",
    "images": "007: GoldenEye.png",
    "developer": "Rare",
    "publisher": "Nintendo",
    "description": "A video game released for the Nintendo 64.",
    "players": 4
  },
  {
    "Id": 2,
    "name": "007: The World Is Not Enough",
    "genres": "Action/First-Person Shooter",
    "date": "1-Nov-00",
    "images": "007: The World Is Not Enough.png",
    "developer": "Eurocom",
    "publisher": "Electronic Arts",
    "description": "A video game released for the Nintendo 64.",
    "players": 4
  },
...
...
...
 ]
}

Body:
if your Game class change to

export class Game {
    id: number
    genres: string
    images: string
    name: string
    developer: string
    publisher: string
    date: string
    description: string
    players: number
}

you can cast output of http.get to your Games class:

return this.http.get('/assets/games.json').map(
(res: Response) => <Game>res.json().games).catch(this.handleError);

for handling error can use this method

protected handleError(error: any): Observable<any> {
    console.log(error.message || error);
    const response = 'some error occurred!';
    return Observable.of(response);
  }


问:
How to set custom labels on X axis?
I have function:

```<code>qplot(gender, salary, data = uof)
</code>```

How can I set custom labels on X axis? There you can
check picture.

For example i would like to turn 0.00 on X axis to "rabbit" and 1.00 on X axis to "elephant"

答:
gender is currently a numeric variable.

uof$gender = as.character(uof$gender)

uof$gender[uof$gender == 0] = 'rabbit'

uof$gender[uof$gender == 1] = 'elephant'

qplot(gender, salary, data = uof)

Title: How to set custom labels on X axis?

Body:
I have function:

qplot(gender, salary, data = uof)

How can I set custom labels on X axis? There you can
check picture.

For example i would like to turn 0.00 on X axis to "rabbit" and 1.00 on X axis to "elephant"


问:
Even and odd buffers in UIView drawRect?
Hello again (I thank you all for your previous invaluable help).

The new issue: I am working up physics simulation but have encountered a problem with a toy version.  All it does is draw a random rectangle on the iPhone/Touch screen each time NSStimer timer calls the tick method.  I've indexed these calls by int frameCount.  What one sees is two sets of images gradually building up: one set for the even frames, another for the odd.  I validated this by drawing frameCount to the screen with the even and odd counts in slightly different positions.  Thus one sees the counts blinking back and forth synchronously with the image in the frame.  The abbreviated code is below.  I appreciate any suggestions you might have.  It seems to me that there must be two offscreen buffers.  But I'm in the dark here:-)  And even if this is true, I don't know how to merge them, or copy one to the other.

```<code>#define MAXFRAMES 1000
</code>```

// Relevant parts of implemenation of FooBar, a subclass of UIView:

```<code> - (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {

        // Initialization code
        // Start a timer that will call the tick method of this class
        // 30 times per second  -- slowed way down for diagnostics

        timer = [NSTimer scheduledTimerWithTimeInterval:(3.0/1.0)
                    target:self selector:@selector(tick) userInfo:nil repeats:YES];

        frameCount = 0;
        self.clearsContextBeforeDrawing = NO;
        NSLog(@"frame initialized");
    }
    return self;
}

- (void)tick
{
    // Tell the view that it needs to re-draw itself
    if (frameCount < MAXFRAMES) {
        [self setNeedsDisplay];
        frameCount++;
    }
}

- (void)drawRect:(CGRect)rect
{

    CGContextRef ctx = UIGraphicsGetCurrentContext();

    // Draw a random rectangle with CGContextFillRect
    // after calling CGContextSetRGBFillColor
    // Both called with suitable random parameters

    // Draw the frameCount for diagnostic purposes

}
</code>```

答: The number of buffers that a UIView might use in its drawing layer is unspecified.  If you want to copy drawings, you should draw from and into your own CG drawing context(s), and then use or draw your result into an image that you can use as a view's CALayer contents.</p>

Body:
Hello again (I thank you all for your previous invaluable help).

The new issue: I am working up physics simulation but have encountered a problem with a toy version.  All it does is draw a random rectangle on the iPhone/Touch screen each time NSStimer timer calls the tick method.  I've indexed these calls by int frameCount.  What one sees is two sets of images gradually building up: one set for the even frames, another for the odd.  I validated this by drawing frameCount to the screen with the even and odd counts in slightly different positions.  Thus one sees the counts blinking back and forth synchronously with the image in the frame.  The abbreviated code is below.  I appreciate any suggestions you might have.  It seems to me that there must be two offscreen buffers.  But I'm in the dark here:-)  And even if this is true, I don't know how to merge them, or copy one to the other.

#define MAXFRAMES 1000

// Relevant parts of implemenation of FooBar, a subclass of UIView:

 - (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {

        // Initialization code
        // Start a timer that will call the tick method of this class
        // 30 times per second  -- slowed way down for diagnostics

        timer = [NSTimer scheduledTimerWithTimeInterval:(3.0/1.0)
                    target:self selector:@selector(tick) userInfo:nil repeats:YES];

        frameCount = 0;
        self.clearsContextBeforeDrawing = NO;
        NSLog(@"frame initialized");
    }
    return self;
}

- (void)tick
{
    // Tell the view that it needs to re-draw itself
    if (frameCount < MAXFRAMES) {
        [self setNeedsDisplay];
        frameCount++;
    }
}

- (void)drawRect:(CGRect)rect
{

    CGContextRef ctx = UIGraphicsGetCurrentContext();

    // Draw a random rectangle with CGContextFillRect
    // after calling CGContextSetRGBFillColor
    // Both called with suitable random parameters

    // Draw the frameCount for diagnostic purposes

}


问:
Firebase single call?
I'm using firebase in a React application and I'm having a bit of an issue.

I'm querying N items from my collection. But in this particular query I'm not interested in the real-time aspects of Firebase, since I'm loading the data into the state of my component and the event listener makes the state constantly refresh changing the page content (which I don't want).

So, is there a way to make a "static" query as you would do with MongoDb or any other non real-time DBs?.

Also is there a way to retrieve all elements from a collection at once without having to listen for changes? I'm using it right now like this:

```<code>postsRef.startAt().orderByChild('likes')
        .on(
          'child_added',
          (snapshot) => {
            this.setState({
              media: [...this.state.media, snapshot.val()],
            });
          },
        );
</code>```

But its far from ideal since I'm getting them one by one and I would prefer to get a single array or object with all of them.

Thanks!

答:
If you want to get all items in one go, use on('value' or once('value'. This gives you a snapshot of all matching child nodes in one go. You then use Snapshot.forEach() to loop over the results:

```<code>postsRef.startAt().orderByChild('likes')
        .on(
          'value',
          (snapshot) => {
            snapshot.forEach((child) => {
              this.setState({
                media: [...this.state.media, child.val()],
              });
            });
          },
        );
</code>```

Title: Firebase single call?

Body:
I'm using firebase in a React application and I'm having a bit of an issue.

I'm querying N items from my collection. But in this particular query I'm not interested in the real-time aspects of Firebase, since I'm loading the data into the state of my component and the event listener makes the state constantly refresh changing the page content (which I don't want).

So, is there a way to make a "static" query as you would do with MongoDb or any other non real-time DBs?.

Also is there a way to retrieve all elements from a collection at once without having to listen for changes? I'm using it right now like this:

postsRef.startAt().orderByChild('likes')
        .on(
          'child_added',
          (snapshot) => {
            this.setState({
              media: [...this.state.media, snapshot.val()],
            });
          },
        );

But its far from ideal since I'm getting them one by one and I would prefer to get a single array or object with all of them.

Thanks!

Body:
If you want to get all items in one go, use on('value' or once('value'. This gives you a snapshot of all matching child nodes in one go. You then use Snapshot.forEach() to loop over the results:

postsRef.startAt().orderByChild('likes')
        .on(
          'value',
          (snapshot) => {
            snapshot.forEach((child) => {
              this.setState({
                media: [...this.state.media, child.val()],
              });
            });
          },
        );


问:
Excel Sorting not working due to Range object
This macro is based off one I recorded, but have tweaked to cope with possible absence of 3 of the 4 sorting criteria. I can't figure out why my Macro works when the range criteria is specific, but not when I'm referencing a single cell and extrapolating.

With this line the sorting works
        .SetRange Range("A1:W162")

With this line it doesn't sort.
        .SetRange Range("A1").End(xlDown).End(xlToRight)
I've stepped through and can confirm it's selecting the correct range

I don't want use the line with specific cells because future exports will be different sized.

This is the full subroutine (the relevant bit is near the bottom).

Thanks!

```<code>Sub SortByScoreAndCost()

Dim Score As Range
Dim Cost As Range
Dim YN As Range
Dim OriginalScore As Range

Set Score = Cells.Find("Score")
Set Cost = Cells.Find("Cost")
Set YN = Cells.Find("Y/N")
Set OriginalScore = Cells.Find("Original Score")

Range("A1").CurrentRegion.Select

ActiveSheet.Sort.SortFields.Clear

ActiveSheet.Sort.SortFields.Add Key:=Range( _
    Score.Offset(1, 0), Score.End(xlDown)), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:= _
    xlSortNormal

        If Cells.Find("Cost") Is Nothing _
            Then
            Else: ActiveSheet.Sort.SortFields.Add Key:=Range _
                (Cost.Offset(1, 0), Cost.End(xlDown)), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption _
                :=xlSortNormal
        End If

        If Cells.Find("Y/N") Is Nothing _
            Then
            Else: ActiveSheet.Sort.SortFields.Add Key:=Range _
                (YN.Offset(1, 0), YN.End(xlDown)), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption _
                :=xlSortNormal
        End If

        If Cells.Find("Original Score") Is Nothing _
            Then
            Else: ActiveSheet.Sort.SortFields.Add Key:=Range _
                (OriginalScore.Offset(1, 0), Original.End(xlDown)), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption _
                :=xlSortNormal
        End If

With ActiveSheet.Sort
    .SetRange Range("A1:W162") 'works with this line
    .SetRange Range("A1").End(xlDown).End(xlToRight) 'doesn't work if replaced with this line
    .Header = xlYes
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With

End Sub
</code>```

答:
Range("A1").End(xlDown).End(xlToRight) refers to a single cell range, not similar to A1:W162. Assuming A1:W162 is the range where all the data on your sheet is. The line refers to W162 only. The Range.End property is explained here and it shows that it does not retain the starting point.

Try Range("A1:"& Range("A1").End(xlDown).End(xlToRight).Address) instead as this should create a range similar to A1:W162. The first part is the string "A1:" and Range("A1).End(xlDown).end(xlToRight).Address returns the string "$W$162" Together they form "A1:$W$162"

With the comment I made on your question in mind I would suggest the code below.

```<code>Dim wsData as Worksheet 'Add worksheet variable

Set wsData = ThisworkBook.Worksheets("Name of your data sheet")

With wsData.Sort 'Instead of using ActiveSheet
    .SetRange wsData.Range(wsData.Cells(1, 1), wsData.Cells(1, 1).End(xlDown).End(xlToRight))
</code>```

Body:
This macro is based off one I recorded, but have tweaked to cope with possible absence of 3 of the 4 sorting criteria. I can't figure out why my Macro works when the range criteria is specific, but not when I'm referencing a single cell and extrapolating.

With this line the sorting works
        .SetRange Range("A1:W162")

With this line it doesn't sort.
        .SetRange Range("A1").End(xlDown).End(xlToRight)
I've stepped through and can confirm it's selecting the correct range

I don't want use the line with specific cells because future exports will be different sized.

This is the full subroutine (the relevant bit is near the bottom).

Thanks!

Sub SortByScoreAndCost()

Dim Score As Range
Dim Cost As Range
Dim YN As Range
Dim OriginalScore As Range

Set Score = Cells.Find("Score")
Set Cost = Cells.Find("Cost")
Set YN = Cells.Find("Y/N")
Set OriginalScore = Cells.Find("Original Score")

Range("A1").CurrentRegion.Select

ActiveSheet.Sort.SortFields.Clear

ActiveSheet.Sort.SortFields.Add Key:=Range( _
    Score.Offset(1, 0), Score.End(xlDown)), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:= _
    xlSortNormal

        If Cells.Find("Cost") Is Nothing _
            Then
            Else: ActiveSheet.Sort.SortFields.Add Key:=Range _
                (Cost.Offset(1, 0), Cost.End(xlDown)), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption _
                :=xlSortNormal
        End If

        If Cells.Find("Y/N") Is Nothing _
            Then
            Else: ActiveSheet.Sort.SortFields.Add Key:=Range _
                (YN.Offset(1, 0), YN.End(xlDown)), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption _
                :=xlSortNormal
        End If

        If Cells.Find("Original Score") Is Nothing _
            Then
            Else: ActiveSheet.Sort.SortFields.Add Key:=Range _
                (OriginalScore.Offset(1, 0), Original.End(xlDown)), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption _
                :=xlSortNormal
        End If

With ActiveSheet.Sort
    .SetRange Range("A1:W162") 'works with this line
    .SetRange Range("A1").End(xlDown).End(xlToRight) 'doesn't work if replaced with this line
    .Header = xlYes
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With

End Sub

Body:
Range("A1").End(xlDown).End(xlToRight) refers to a single cell range, not similar to A1:W162. Assuming A1:W162 is the range where all the data on your sheet is. The line refers to W162 only. The Range.End property is explained here and it shows that it does not retain the starting point.

Try Range("A1:"& Range("A1").End(xlDown).End(xlToRight).Address) instead as this should create a range similar to A1:W162. The first part is the string "A1:" and Range("A1).End(xlDown).end(xlToRight).Address returns the string "$W$162" Together they form "A1:$W$162"

With the comment I made on your question in mind I would suggest the code below.

Dim wsData as Worksheet 'Add worksheet variable

Set wsData = ThisworkBook.Worksheets("Name of your data sheet")

With wsData.Sort 'Instead of using ActiveSheet
    .SetRange wsData.Range(wsData.Cells(1, 1), wsData.Cells(1, 1).End(xlDown).End(xlToRight))


问:
ImportError while performing pip install
While in my virtual environment, i'm trying to perform 'pip install .' with a setup.py such as :

```<code>from setuptools import setup
import pbr

... some functions ...

setup(
    name='example',
    setup_requires=['pbr'],
    py_modules=['example'],

    entry_points='''
        [console_scripts]
        example=example:main
    ''',
)
</code>```

The thing is that i get the following error ImportError: No module named pbr

This seems quite legit as i didn't install pbr in my virtual environment BUT i thought that specifying 'setup_requires' would do the trick ... :/

Does someone understand why this does not work and knows how to fix it ? :)

答:
The script does import pbr before running setup() so setup() was not given a chance to install pbr.

The fix is to not import pbr before running setup(). See https://docs.openstack.org/pbr/latest/user/using.html:

```<code>#!/usr/bin/env python

from setuptools import setup

setup(
    setup_requires=['pbr'],
    pbr=True,
)
</code>```

Body:
While in my virtual environment, i'm trying to perform 'pip install .' with a setup.py such as :

from setuptools import setup
import pbr

... some functions ...

setup(
    name='example',
    setup_requires=['pbr'],
    py_modules=['example'],

    entry_points='''
        [console_scripts]
        example=example:main
    ''',
)

The thing is that i get the following error ImportError: No module named pbr

This seems quite legit as i didn't install pbr in my virtual environment BUT i thought that specifying 'setup_requires' would do the trick ... :/

Does someone understand why this does not work and knows how to fix it ? :)

Body:
The script does import pbr before running setup() so setup() was not given a chance to install pbr.

The fix is to not import pbr before running setup(). See https://docs.openstack.org/pbr/latest/user/using.html:

#!/usr/bin/env python

from setuptools import setup

setup(
    setup_requires=['pbr'],
    pbr=True,
)


问:
Replacing text certain line with some other text (python) closed
I have tryed a bunch of other ways of doing it from other forums. But none of them seem to work. Maybe i am just writing them wrong. I have a text file that I want python to replace the "0" with a "1" my text file looks like this

```<code>0
hello
more stuff
meh
</code>```

i want it to be

```<code>1
hello
more stuff
meh
</code>```

Thanks, this is probably really simple.
If anyone can post a way to replace the 0 with a 1 or delete a whole line and then rewrite it. Either one works.
Thanks
I also want it to work if the 0 was on the third line or some other line. You would of course have to change what line it targets

答:
Supposing you want to replace the 0 on the first line of the file:

```<code>def replace_first_line(path, value, condition=None):
    with open(path, 'r') as file:
        lines = file.read().split('\n')
    if lines:
        first_line = lines[0]
        if not condition or first_line.strip() == condition:
            first_line = first_line.replace(condition or first_line, value)
        lines[0] = first_line
    with open(path, 'w') as file:
        file.write('\n'.join(lines))

# Change 'your_file.txt' to the name of your file
replace_first_line('your_file.txt', '1', condition='0')
</code>```

Body:
I have tryed a bunch of other ways of doing it from other forums. But none of them seem to work. Maybe i am just writing them wrong. I have a text file that I want python to replace the "0" with a "1" my text file looks like this

0
hello
more stuff
meh

i want it to be

1
hello
more stuff
meh

Thanks, this is probably really simple.
If anyone can post a way to replace the 0 with a 1 or delete a whole line and then rewrite it. Either one works.
Thanks
I also want it to work if the 0 was on the third line or some other line. You would of course have to change what line it targets

Body:
Supposing you want to replace the 0 on the first line of the file:

def replace_first_line(path, value, condition=None):
    with open(path, 'r') as file:
        lines = file.read().split('\n')
    if lines:
        first_line = lines[0]
        if not condition or first_line.strip() == condition:
            first_line = first_line.replace(condition or first_line, value)
        lines[0] = first_line
    with open(path, 'w') as file:
        file.write('\n'.join(lines))

# Change 'your_file.txt' to the name of your file
replace_first_line('your_file.txt', '1', condition='0')


问:
Why can I not call upon the property of this object? (Angular, MongoDB)
I am making an angular application which uses a MongoDB database and NodeJS server.

The idea is that I make an application which for now only has a list of posts and beside that the detailed-post. The components are nicely standing next to eachother and working but I have one problem. When I try to retrieve a single post I can see via console.dir(post) that all is good and the object has been transmitted to the angular app. The problem is that when I try to use post.content I get an undefined message.

I have searched for hours but can not seem to find the cause of this. I would greatly appreciate any help you can give me. Beneath here is all the information, if you need to see something else, please tell me.

Thanks in advance.

This is the post-detail.component.html where I want to display the data.

```<code><div class="row">
<div class="col-xs-12">
<p>Content:</p>
<h1>{{ post.content }}</h1>
</div>
</div>
</code>```

The detail.ts file (I left out the imports)

```<code>    @Component({
  selector: 'app-post-detail',
  templateUrl: './post-detail.component.html',
  styleUrls: ['./post-detail.component.css']
})
export class PostDetailComponent implements OnInit {
  post: Post = new Post();
  id: string;

constructor(private postService: PostService,
            private route: ActivatedRoute,
            private router: Router) {
}

ngOnInit() {
  this.route.params
    .subscribe(
      (params: Params) => {
        this.id = params['id'];
        this.postService.getPost(this.id).then(res => {
          console.dir(res);
          console.dir(res.content);
          this.post = res;
        });
      }
    );
  }
}
</code>```

The post.service.ts which I am using to retrieve the actual data:

```<code>@Injectable()
export class PostService {
  postChanged = new Subject<Post[]>();

  private headers = new Headers({'Content-Type': 'application/json'});
  private serverUrl = environment.serverUrl + '/blogPosts/'; // URL to web api
  private posts: Post[];

  constructor(private http: Http) {
  }

  //this one DOES work
  getPosts() {
    console.log('Fetching BlogPosts from database.')
    return this.http.get(this.serverUrl, {headers: this.headers})
      .toPromise()
      .then(response => {
        this.posts = response.json() as Post[];
        return response.json() as Post[];
      })
      .catch(error => {
        return error;
      });
  }

  getPost(index: string) {
    console.log('Fetching individual BlogPost from database.');
    console.log('index' + index);
    if (index == null) {
      console.log('null');
      return null;
    }
    return this.http.get(this.serverUrl + index, {headers: this.headers})
      .toPromise()
      .then(response => {
        console.dir(response.json().content);
        console.dir(response.json());
        return response.json() as Post;
      })
      .catch(error => {

        return this.handleError(error);
      });
  }
}
</code>```

The Post model:

```<code>export class Post {

  private id: string;
  private _content: string;

  constructor(values: Object = {}) {
    Object.assign(this, values);
  }
  public get _id(): string {
    return this.id;
  }

  public set _id(n: string) {
    this.id = n;
  }

  public get content(): string {
    return this._content;
  }

  public set content(n: string) {
    this._content = n;
  }
}
</code>```

And I added in the Postman GET /blogPost/id and the console log as images.
Thanks!

Console log

Postman GET route

答:
```<code>return response.json() as Post;
</code>```

In post.service.ts should be:

```<code>return response.json()[0] as Post;
</code>```

I did not see that the object was wrapped in an array, by accessing it I was able to get it out and use it.

Body:
I am making an angular application which uses a MongoDB database and NodeJS server.

The idea is that I make an application which for now only has a list of posts and beside that the detailed-post. The components are nicely standing next to eachother and working but I have one problem. When I try to retrieve a single post I can see via console.dir(post) that all is good and the object has been transmitted to the angular app. The problem is that when I try to use post.content I get an undefined message.

I have searched for hours but can not seem to find the cause of this. I would greatly appreciate any help you can give me. Beneath here is all the information, if you need to see something else, please tell me.

Thanks in advance.

This is the post-detail.component.html where I want to display the data.

Content:

{{ post.content }}

The detail.ts file (I left out the imports)

    @Component({
  selector: 'app-post-detail',
  templateUrl: './post-detail.component.html',
  styleUrls: ['./post-detail.component.css']
})
export class PostDetailComponent implements OnInit {
  post: Post = new Post();
  id: string;

constructor(private postService: PostService,
            private route: ActivatedRoute,
            private router: Router) {
}

ngOnInit() {
  this.route.params
    .subscribe(
      (params: Params) => {
        this.id = params['id'];
        this.postService.getPost(this.id).then(res => {
          console.dir(res);
          console.dir(res.content);
          this.post = res;
        });
      }
    );
  }
}

The post.service.ts which I am using to retrieve the actual data:

@Injectable()
export class PostService {
  postChanged = new Subject<Post[]>();

  private headers = new Headers({'Content-Type': 'application/json'});
  private serverUrl = environment.serverUrl + '/blogPosts/'; // URL to web api
  private posts: Post[];

  constructor(private http: Http) {
  }

  //this one DOES work
  getPosts() {
    console.log('Fetching BlogPosts from database.')
    return this.http.get(this.serverUrl, {headers: this.headers})
      .toPromise()
      .then(response => {
        this.posts = response.json() as Post[];
        return response.json() as Post[];
      })
      .catch(error => {
        return error;
      });
  }

  getPost(index: string) {
    console.log('Fetching individual BlogPost from database.');
    console.log('index' + index);
    if (index == null) {
      console.log('null');
      return null;
    }
    return this.http.get(this.serverUrl + index, {headers: this.headers})
      .toPromise()
      .then(response => {
        console.dir(response.json().content);
        console.dir(response.json());
        return response.json() as Post;
      })
      .catch(error => {

        return this.handleError(error);
      });
  }
}

The Post model:

export class Post {

  private id: string;
  private _content: string;

  constructor(values: Object = {}) {
    Object.assign(this, values);
  }
  public get _id(): string {
    return this.id;
  }

  public set _id(n: string) {
    this.id = n;
  }

  public get content(): string {
    return this._content;
  }

  public set content(n: string) {
    this._content = n;
  }
}

And I added in the Postman GET /blogPost/id and the console log as images.
Thanks!

Console log

Postman GET route

Body:
return response.json() as Post;

In post.service.ts should be:

return response.json()[0] as Post;

I did not see that the object was wrapped in an array, by accessing it I was able to get it out and use it.


问:
Xcode - Help implementing some code into a view based app?
Can someone help me with implementing this code into a view based app?

This is the code that I have:

```<code>- (void)webViewUIWebView *)newsweb didFailLoadWithErrorNSError *)error {
   UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Connection Error1!"       message:@"Please confirm network connectivity and try again!" delegate:self     cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
   [alert show];
   [alert release];
}
</code>```

With this code and any other code that I may need, but don't know, I would like to know what code to implement into the .h + .m view controller files.

What I am trying to achieve is an error after starting the app if there is no network connection available. What I'm worried about also but not quite sure if it will happen, is that this will repeat the error "x" times for how many UIViews I have. If that would be the case could you also help me should that it would only show the error once.

答:
Put a Boolean in your header file, and when the alert fires, change it. If the Boolean is false, then simply don't show the alert. </p>

```<code>
@interface
    BOOL alertShown;
@end
</code>```

```<code>
@implementation
    -(void)applicationDidFinishLaunching{
           alertShown = NO;
}

    -(void)webViewError{
          if(alertShown == NO){
              //show the alert
              alertShown = YES;
    }
}
@end
</code>```

Body:
Can someone help me with implementing this code into a view based app?

This is the code that I have:

- (void)webViewUIWebView *)newsweb didFailLoadWithErrorNSError *)error {
   UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Connection Error1!"       message:@"Please confirm network connectivity and try again!" delegate:self     cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
   [alert show];
   [alert release];
}

With this code and any other code that I may need, but don't know, I would like to know what code to implement into the .h + .m view controller files.

What I am trying to achieve is an error after starting the app if there is no network connection available. What I'm worried about also but not quite sure if it will happen, is that this will repeat the error "x" times for how many UIViews I have. If that would be the case could you also help me should that it would only show the error once.

Body:
Put a Boolean in your header file, and when the alert fires, change it. If the Boolean is false, then simply don't show the alert.

@interface
    BOOL alertShown;
@end

@implementation
    -(void)applicationDidFinishLaunching{
           alertShown = NO;
}

    -(void)webViewError{
          if(alertShown == NO){
              //show the alert
              alertShown = YES;
    }
}
@end


问:
MySql syntax error on procedure parameter
I am trying to write a simple procedure but am encountering a syntax error at the first parameter. As best I can tell I'm following the syntax of CREATE PROCEDURE correctly.

I am limited to accessing my database with phpMyAdmin. Here is the create script I'm trying to run:

```<code>DROP PROCEDURE IF EXISTS product_index_swap/
CREATE PROCEDURE product_index_swap (@id INT, @oldIndex INT, @newIndex INT)
BEGIN
    DECLARE @swapID;
    SET @swapID = (SELECT `id` FROM `product` WHERE `order_index` = @newIndex LIMIT 1);
    UPDATE `products` SET `order_index` = (CASE WHEN `id` = @id THEN @newIndex
                                                WHEN `id` = @swapID THEN @oldIndex END)
    WHERE `id` IN (@id, @swapID);
END
</code>```

I am using the option on phpMyAdmin to change the delimiter to /.

I receive a syntax error "near '@id INT, @oldIndex INT....". I thought I may encounter more delimiter errors since I'm not entirely clear on the scope of them. I believe if that was the problem the error would be on a new line in the procedure when it failed to understand a semicolon, not at the parameters declaration.

答:
In MySQL, the @var variables are session level variables.

Use normal variables without the @ and make sure you do not have conflict with column names:

```<code>CREATE PROCEDURE product_index_swap (in_id INT, in_oldIndex INT, in_newIndex INT)
BEGIN
    DECLARE v_swapID int;

    SELECT id into v_swapID
    FROM product
    WHERE order_index = in_newIndex
    LIMIT 1;

    UPDATE products
    SET order_index = CASE WHEN id = in_id THEN in_newIndex
                           WHEN id = v_swapID THEN in_oldIndex
                      END
    WHERE id IN (in_id, v_swapID);
END
</code>```

Body:
I am trying to write a simple procedure but am encountering a syntax error at the first parameter. As best I can tell I'm following the syntax of CREATE PROCEDURE correctly.

I am limited to accessing my database with phpMyAdmin. Here is the create script I'm trying to run:

DROP PROCEDURE IF EXISTS product_index_swap/
CREATE PROCEDURE product_index_swap (@id INT, @oldIndex INT, @newIndex INT)
BEGIN
    DECLARE @swapID;
    SET @swapID = (SELECT `id` FROM `product` WHERE `order_index` = @newIndex LIMIT 1);
    UPDATE `products` SET `order_index` = (CASE WHEN `id` = @id THEN @newIndex
                                                WHEN `id` = @swapID THEN @oldIndex END)
    WHERE `id` IN (@id, @swapID);
END

I am using the option on phpMyAdmin to change the delimiter to /.

I receive a syntax error "near '@id INT, @oldIndex INT....". I thought I may encounter more delimiter errors since I'm not entirely clear on the scope of them. I believe if that was the problem the error would be on a new line in the procedure when it failed to understand a semicolon, not at the parameters declaration.

Body:
In MySQL, the @var variables are session level variables.

Use normal variables without the @ and make sure you do not have conflict with column names:

CREATE PROCEDURE product_index_swap (in_id INT, in_oldIndex INT, in_newIndex INT)
BEGIN
    DECLARE v_swapID int;

    SELECT id into v_swapID
    FROM product
    WHERE order_index = in_newIndex
    LIMIT 1;

    UPDATE products
    SET order_index = CASE WHEN id = in_id THEN in_newIndex
                           WHEN id = v_swapID THEN in_oldIndex
                      END
    WHERE id IN (in_id, v_swapID);
END


问:
apache beam 2.2 pipeline.apply no such method exception
```<code>    public static void main(String[] args) {
            //Pipeline p = Pipeline.create(PipelineOptionsFactory.fromArgs(args).withValidation().create());
            DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class);
            options.setRunner(DataflowRunner.class);
            options.setStagingLocation("gs://bucketname/stageapache");
            options.setTempLocation("gs://bucketname/stageapachetemp");
            options.setProject("projectid");
            Pipeline p=Pipeline.create(options);
    p.apply(TextIO.read().from("gs://bucketname/filename.csv"));
//p.apply(FileIO.match().filepattern("gs://bucketname/f.csv"));
            p.run();
        }
</code>```

pom.xml

```<code><dependency>
  <groupId>org.apache.beam</groupId>
  <artifactId>beam-sdks-java-core</artifactId>
  <version>2.2.0</version>
</dependency>
<dependency>
    <groupId>org.apache.beam</groupId>
    <artifactId>beam-sdks-java-io-google-cloud-platform</artifactId>
    <version>2.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.beam/beam-runners-google-cloud-dataflow-java -->
<dependency>
    <groupId>org.apache.beam</groupId>
    <artifactId>beam-runners-google-cloud-dataflow-java</artifactId>
    <version>2.0.0</version>
</dependency>
</code>```

Error

```<code>Dec 08, 2017 5:09:35 PM org.apache.beam.runners.dataflow.DataflowRunner fromOptions
INFO: PipelineOptions.filesToStage was not specified. Defaulting to files from the classpath: will stage 85 files. Enable logging at DEBUG level to see which files will be staged.
Exception in thread "main" java.lang.NoSuchMethodError: org.apache.beam.sdk.values.PCollection.createPrimitiveOutputInternal(Lorg/apache/beam/sdk/Pipeline;Lorg/apache/beam/sdk/values/WindowingStrategy;Lorg/apache/beam/sdk/values/PCollection$IsBounded;)Lorg/apache/beam/sdk/values/PCollection;
    at org.apache.beam.runners.dataflow.PrimitiveParDoSingleFactory$ParDoSingle.expand(PrimitiveParDoSingleFactory.java:68)
    at org.apache.beam.runners.dataflow.PrimitiveParDoSingleFactory$ParDoSingle.expand(PrimitiveParDoSingleFactory.java:58)
    at org.apache.beam.sdk.Pipeline.applyReplacement(Pipeline.java:550)
    at org.apache.beam.sdk.Pipeline.replace(Pipeline.java:280)
    at org.apache.beam.sdk.Pipeline.replaceAll(Pipeline.java:201)
    at org.apache.beam.runners.dataflow.DataflowRunner.replaceTransforms(DataflowRunner.java:688)
    at org.apache.beam.runners.dataflow.DataflowRunner.run(DataflowRunner.java:498)
    at org.apache.beam.runners.dataflow.DataflowRunner.run(DataflowRunner.java:153)
    at org.apache.beam.sdk.Pipeline.run(Pipeline.java:303)
    at org.apache.beam.sdk.Pipeline.run(Pipeline.java:289)
    at com.pearson.apachebeam.StarterPipeline.main(StarterPipeline.java:60)
</code>```

In the above code if add FileIO/TextIO line i am getting the above error, with out adding that line if i run it is creating job since there is no operations in it is failing. i am stuck up at this in my development i migrated to apache beam 2.2 to get control of the file we read  from storage

Help will be appreciated

Thanks

答: The issue is that your pom.xml is depending on different components of the Beam SDK at different versions: beam-sdks-java-core at 2.2.0, but beam-sdks-java-io-google-cloud-platform and beam-runners-google-cloud-dataflow-java at 2.0.0. They need to be at the same version.

Body:
    public static void main(String[] args) {
            //Pipeline p = Pipeline.create(PipelineOptionsFactory.fromArgs(args).withValidation().create());
            DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class);
            options.setRunner(DataflowRunner.class);
            options.setStagingLocation("gs://bucketname/stageapache");
            options.setTempLocation("gs://bucketname/stageapachetemp");
            options.setProject("projectid");
            Pipeline p=Pipeline.create(options);
    p.apply(TextIO.read().from("gs://bucketname/filename.csv"));
//p.apply(FileIO.match().filepattern("gs://bucketname/f.csv"));
            p.run();
        }

pom.xml

<dependency>
  <groupId>org.apache.beam</groupId>
  <artifactId>beam-sdks-java-core</artifactId>
  <version>2.2.0</version>
</dependency>
<dependency>
    <groupId>org.apache.beam</groupId>
    <artifactId>beam-sdks-java-io-google-cloud-platform</artifactId>
    <version>2.0.0</version>
</dependency>

<dependency>
    <groupId>org.apache.beam</groupId>
    <artifactId>beam-runners-google-cloud-dataflow-java</artifactId>
    <version>2.0.0</version>
</dependency>

Error

Dec 08, 2017 5:09:35 PM org.apache.beam.runners.dataflow.DataflowRunner fromOptions
INFO: PipelineOptions.filesToStage was not specified. Defaulting to files from the classpath: will stage 85 files. Enable logging at DEBUG level to see which files will be staged.
Exception in thread "main" java.lang.NoSuchMethodError: org.apache.beam.sdk.values.PCollection.createPrimitiveOutputInternal(Lorg/apache/beam/sdk/Pipeline;Lorg/apache/beam/sdk/values/WindowingStrategy;Lorg/apache/beam/sdk/values/PCollection$IsBounded;)Lorg/apache/beam/sdk/values/PCollection;
    at org.apache.beam.runners.dataflow.PrimitiveParDoSingleFactory$ParDoSingle.expand(PrimitiveParDoSingleFactory.java:68)
    at org.apache.beam.runners.dataflow.PrimitiveParDoSingleFactory$ParDoSingle.expand(PrimitiveParDoSingleFactory.java:58)
    at org.apache.beam.sdk.Pipeline.applyReplacement(Pipeline.java:550)
    at org.apache.beam.sdk.Pipeline.replace(Pipeline.java:280)
    at org.apache.beam.sdk.Pipeline.replaceAll(Pipeline.java:201)
    at org.apache.beam.runners.dataflow.DataflowRunner.replaceTransforms(DataflowRunner.java:688)
    at org.apache.beam.runners.dataflow.DataflowRunner.run(DataflowRunner.java:498)
    at org.apache.beam.runners.dataflow.DataflowRunner.run(DataflowRunner.java:153)
    at org.apache.beam.sdk.Pipeline.run(Pipeline.java:303)
    at org.apache.beam.sdk.Pipeline.run(Pipeline.java:289)
    at com.pearson.apachebeam.StarterPipeline.main(StarterPipeline.java:60)

In the above code if add FileIO/TextIO line i am getting the above error, with out adding that line if i run it is creating job since there is no operations in it is failing. i am stuck up at this in my development i migrated to apache beam 2.2 to get control of the file we read  from storage

Help will be appreciated

Thanks


问:
Python coding flaw for making acronyms
The code written below should give results like below. For example, if input is ' Lion head and Snake tail', output should be - 'LHAST'.

Instead the result is 'LLLLL'. Please check my code. If possible please suggest better practice and help me with better code.

Code is as follows:

```<code>#ask for Input
name = input('Input words to make acroname :')

#make all in caps
name = name.upper()

#turn them in list
listname = name.split()

#cycle through
for namee in listname:
    #Get the first letter & type in same line
    print(name[0],end="")
print()

input (' press a key to move out' )
</code>```

答:
Simply:

```<code>print ''.join([P[0] for P in input('Input words to make acroname :').upper().split()])
</code>```

Use input('') for python 3 and raw_input('') for python 2

Title: Python coding flaw for making acronyms

Body:
The code written below should give results like below. For example, if input is ' Lion head and Snake tail', output should be - 'LHAST'.

Instead the result is 'LLLLL'. Please check my code. If possible please suggest better practice and help me with better code.

Code is as follows:

#ask for Input
name = input('Input words to make acroname :')

#make all in caps
name = name.upper()

#turn them in list
listname = name.split()

#cycle through
for namee in listname:
    #Get the first letter & type in same line
    print(name[0],end="")
print()

input (' press a key to move out' )

Body:
Simply:

print ''.join([P[0] for P in input('Input words to make acroname :').upper().split()])

Use input('') for python 3 and raw_input('') for python 2


问:
Image galley with Jquery (click on "next" button)
first of all sorry for my bad grammar as English is not my first language.

Anyway, I'm totally new to Jquery / Javascript.

I'm trying to create an image gallery with image swap effect using Jquery.

What I want to achieve is, when I click on a thumbnail (let's say No. 4), the main image would display image No. 4. Well, I've already successfully written a code for this matter.

Now, there's another thing I want to achieve:

I have a "next"-button. If the main image is displaying image No. 4, clicking on the "next"-button should result in the main image displaying image No. 5. Or, if the main image is displaying image No. 7, clicking on "next"-button would show image No. 8 and so on.

Using the code I've written, clicking on the "next"-button will cause the main image showing the 2nd image. Clicking it again then it shows the 3rd image, but not the next No. from where I clicked the thumbnail.

This is my Array:

```<code>var bilder = ["../../images/galerie/assassin_2_01.jpg",
              "../../images/galerie/assassin_2_02.jpg",
              "../../images/galerie/assassin_2_03.jpg",
              "../../images/galerie/assassin_2_04.jpg",
              "../../images/galerie/assassin_2_05.jpg",
              "../../images/galerie/assassin_2_06.jpg",
              "../../images/galerie/assassin_2_07.jpg",
              "../../images/galerie/assassin_2_08.jpg",
              "../../images/galerie/assassin_2_09.jpg",
              "../../images/galerie/assassin_2_10.jpg",
              "../../images/galerie/assassin_2_11.jpg",
              "../../images/galerie/assassin_2_12.jpg",
              "../../images/galerie/assassin_2_13.jpg",
              "../../images/galerie/assassin_2_14.jpg",
              "../../images/galerie/assassin_2_15.jpg"];
</code>```

This is my Jquery:

```<code>function mainimage(nr) {
    $("div.mainimg ul li:eq(0) div img").fadeOut({"duration":300, complete:function() {
        $(this).attr("src",bilder[nr]).fadeIn(500);
    }});
}
function next() {
    if (index < bilder.length) {
        index++;
        mainimage(index);
    }
}
</code>```

And this is my HTML-structure:

```<code><div class="mainimg">
    <ul>
        <li><div><img class="img1" src="../../images/galerie/assassin_2_01.jpg" /></div></li>
    </ul>
        <div class="caption">
            <div>Assassin's Creed 2</div>
            <div><a href="#">back/a>  |  <a onclick="next();">next</a></div>
        </div>
</div>

<div class="thumbsrow">
    <div class="galeriethumbs"><img onclick="mainimage(0);" /></div>
    <div class="galeriethumbs"><img onclick="mainimage(1);" /></div>
    <div class="galeriethumbs"><img onclick="mainimage(2);" /></div>
</div>
<div class="thumbsrow">
    <div class="galeriethumbs"><img onclick="mainimage(3);" /></div>
    <div class="galeriethumbs"><img onclick="mainimage(4);" /></div>
    <div class="galeriethumbs"><img onclick="mainimage(5);" /></div>
</div>
</code>```

I'm thankful for any help!

答: where do you maintain the index variable? perhaps you need to set it when you call mainimage function

Body:
first of all sorry for my bad grammar as English is not my first language.

Anyway, I'm totally new to Jquery / Javascript.

I'm trying to create an image gallery with image swap effect using Jquery.

What I want to achieve is, when I click on a thumbnail (let's say No. 4), the main image would display image No. 4. Well, I've already successfully written a code for this matter.

Now, there's another thing I want to achieve:

I have a "next"-button. If the main image is displaying image No. 4, clicking on the "next"-button should result in the main image displaying image No. 5. Or, if the main image is displaying image No. 7, clicking on "next"-button would show image No. 8 and so on.

Using the code I've written, clicking on the "next"-button will cause the main image showing the 2nd image. Clicking it again then it shows the 3rd image, but not the next No. from where I clicked the thumbnail.

This is my Array:

var bilder = ["../../images/galerie/assassin_2_01.jpg",
              "../../images/galerie/assassin_2_02.jpg",
              "../../images/galerie/assassin_2_03.jpg",
              "../../images/galerie/assassin_2_04.jpg",
              "../../images/galerie/assassin_2_05.jpg",
              "../../images/galerie/assassin_2_06.jpg",
              "../../images/galerie/assassin_2_07.jpg",
              "../../images/galerie/assassin_2_08.jpg",
              "../../images/galerie/assassin_2_09.jpg",
              "../../images/galerie/assassin_2_10.jpg",
              "../../images/galerie/assassin_2_11.jpg",
              "../../images/galerie/assassin_2_12.jpg",
              "../../images/galerie/assassin_2_13.jpg",
              "../../images/galerie/assassin_2_14.jpg",
              "../../images/galerie/assassin_2_15.jpg"];

This is my Jquery:

function mainimage(nr) {
    $("div.mainimg ul li:eq(0) div img").fadeOut({"duration":300, complete:function() {
        $(this).attr("src",bilder[nr]).fadeIn(500);
    }});
}
function next() {
    if (index < bilder.length) {
        index++;
        mainimage(index);
    }
}

And this is my HTML-structure:

Assassin's Creed 2

back/a>  |  next

I'm thankful for any help!