问:
How do I convert a classic .ASP VB multidimensional array (from a recordset) for use in a javascript .js file?
The VB multidimensional array (arrHotelsProdCols) is created in classic .ASP vb thus:

```<code>strSQLHotelsProdCols = "SELECT * FROM qryHotelProdCols"
rsHotelsProdCols.Open strSQLHotelsProdCols, ConString
arrHotelsProdCols = rsHotelsProdCols.GetRows
</code>```

The VB array works fine, over 600 rows, 4 cols. I can loop through it and display it in a table in the source .asp file html, etc.

I want to add a function to my existing validateform.js ‘included’ file that will fire onchange of one dropdown in an existing form in the same .asp file as the VB multidimensional array, search for a unique value and populate other fields in the form with other values on the same row in the multidimensional array – that part is not so difficult for me and is another question if I get stuck when I get there.

1) How do I convert and pass my VB multidimensional array to a javascript array for use in my validateform.js file?

答:
Explanations

In fact, as your question is stating, a VB Array CAN BE multidimensional.
But the JScript Arrays CANNOT BE multidimensional : They are only one-dimension.
(see. https://wiki.mcneel.com/developer/scriptsamples/arrays)

Solution

So, the solution is to list all the elements of your JScript one-dimension array, and try to detect when you have reached a new "Row". How can we know that ? We can simply know that when the RowNumber Modulus NumberOfColumns is Zero, then it IS in fact a new row.
This may seem a bit "hacky", but it is 100% fully functional, even in a production environment :-)
Here is the source code of the VBScript part, and of the JScript part :

The VBScript Part

```<code><%
'Declare SQL Statement
Dim strSQLHotelsProdCols
strSQLHotelsProdCols = "SELECT * FROM qryHotelProdCols"

'Execute SQL Statement
rsHotelsProdCols.Open strSQLHotelsProdCols, ConString

'Populate Two-Dimensional VB Array
arrHotelsProdCols = rsHotelsProdCols.GetRows
%>
</code>```

The JScript Part

```<code><script runat="server" language="JavaScript">

    //Convert a VBScript Two-Dimensional array => To => JScript One-Dimensional array
    //Yes : Infortunately, JScript can only manage 1-Dimension Arrays !
    var tmp_VBArray = new VBArray(arrHotelsProdCols);
    var tmp_VBArrayInJs = (tmp_VBArray).toArray();

    //As all the "VB columns" (2-dimension array) have been converted into "JS rows" (1-dimension array),
    //We will manually detect when a new Row has started using the modulus (%) operator :-)

    //For each row in the One-Dimension JScript array
    for (var iRow = 0; iRow < tmp_VBArrayInJs.length; iRow++) {

        //Test if a new row has started
        var testNewRow = (iRow + 1) % (tmp_VBArray.ubound(1) + 1);

        //If a new row is detected
        if (testNewRow == true){
            response.write('<br>=> NEW ROW STARTED<br>');
        }

        //Write the fields
        response.write('<strong>'+iRow+'. </strong>');
        response.write(tmp_VBArrayInJs[iRow] + '<br>');
    }
</script>
</code>```

Body:
The VB multidimensional array (arrHotelsProdCols) is created in classic .ASP vb thus:

strSQLHotelsProdCols = "SELECT * FROM qryHotelProdCols"
rsHotelsProdCols.Open strSQLHotelsProdCols, ConString
arrHotelsProdCols = rsHotelsProdCols.GetRows

The VB array works fine, over 600 rows, 4 cols. I can loop through it and display it in a table in the source .asp file html, etc.

I want to add a function to my existing validateform.js ‘included’ file that will fire onchange of one dropdown in an existing form in the same .asp file as the VB multidimensional array, search for a unique value and populate other fields in the form with other values on the same row in the multidimensional array – that part is not so difficult for me and is another question if I get stuck when I get there.

1) How do I convert and pass my VB multidimensional array to a javascript array for use in my validateform.js file?

Body:
Explanations

In fact, as your question is stating, a VB Array CAN BE multidimensional.
But the JScript Arrays CANNOT BE multidimensional : They are only one-dimension.
(see. https://wiki.mcneel.com/developer/scriptsamples/arrays)

Solution

So, the solution is to list all the elements of your JScript one-dimension array, and try to detect when you have reached a new "Row". How can we know that ? We can simply know that when the RowNumber Modulus NumberOfColumns is Zero, then it IS in fact a new row.
This may seem a bit "hacky", but it is 100% fully functional, even in a production environment :-)
Here is the source code of the VBScript part, and of the JScript part :

The VBScript Part

<%
'Declare SQL Statement
Dim strSQLHotelsProdCols
strSQLHotelsProdCols = "SELECT * FROM qryHotelProdCols"

'Execute SQL Statement
rsHotelsProdCols.Open strSQLHotelsProdCols, ConString

'Populate Two-Dimensional VB Array
arrHotelsProdCols = rsHotelsProdCols.GetRows
%>

The JScript Part

<script runat="server" language="JavaScript">

    //Convert a VBScript Two-Dimensional array => To => JScript One-Dimensional array
    //Yes : Infortunately, JScript can only manage 1-Dimension Arrays !
    var tmp_VBArray = new VBArray(arrHotelsProdCols);
    var tmp_VBArrayInJs = (tmp_VBArray).toArray();

    //As all the "VB columns" (2-dimension array) have been converted into "JS rows" (1-dimension array),
    //We will manually detect when a new Row has started using the modulus (%) operator :-)

    //For each row in the One-Dimension JScript array
    for (var iRow = 0; iRow < tmp_VBArrayInJs.length; iRow++) {

        //Test if a new row has started
        var testNewRow = (iRow + 1) % (tmp_VBArray.ubound(1) + 1);

        //If a new row is detected
        if (testNewRow == true){
            response.write('<br>=> NEW ROW STARTED<br>');
        }

        //Write the fields
        response.write('<strong>'+iRow+'. </strong>');
        response.write(tmp_VBArrayInJs[iRow] + '<br>');
    }
</script>


来源: stackexchange

问:
iterate mysql database from specific record
$pic = $DBcon->query("SELECT * FROM tbl_pictures WHERE type='holidays' ASC LIMIT 200");

Lets say my database has 500 records. If i use the query above, it starts at 200 and stops at the last record.

So the first 200 won't be searched, am I getting that right? If that is true, how do I have to write my query to start at record 200, go towards 500, and afterwards search records 0 - 200, too?

note: as soon as one match was found, the iteration can stop. it's all just about the next picture

Thank you guys :)

thats my database if necessary:

```<code>CREATE TABLE IF NOT EXISTS `tbl_pictures` (
  `picture_id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` varchar(60) NOT NULL,
  `type` varchar(60) NOT NULL,
  `filename` varchar(60) NOT NULL,
  `title` mediumtext NOT NULL,
  `description` mediumtext NOT NULL,
  `date` varchar(60) NOT NULL,

  PRIMARY KEY (`picture_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
</code>```

答:
If you're looking for the next picture in a sequence where they're ordered by insertion ID:

```<code>SELECT * FROM tbl_pictures WHERE picture_id>?
  ORDER BY picture_id LIMIT 1
</code>```

LIMIT affects only the results given, not how many records are actually searched.

ContentLicense: CC BY-SA 3.0

Body:
$pic = $DBcon->query("SELECT * FROM tbl_pictures WHERE type='holidays' ASC LIMIT 200");

Lets say my database has 500 records. If i use the query above, it starts at 200 and stops at the last record.

So the first 200 won't be searched, am I getting that right? If that is true, how do I have to write my query to start at record 200, go towards 500, and afterwards search records 0 - 200, too?

note: as soon as one match was found, the iteration can stop. it's all just about the next picture

Thank you guys :)

thats my database if necessary:

CREATE TABLE IF NOT EXISTS `tbl_pictures` (
  `picture_id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` varchar(60) NOT NULL,
  `type` varchar(60) NOT NULL,
  `filename` varchar(60) NOT NULL,
  `title` mediumtext NOT NULL,
  `description` mediumtext NOT NULL,
  `date` varchar(60) NOT NULL,

  PRIMARY KEY (`picture_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

Body:
If you're looking for the next picture in a sequence where they're ordered by insertion ID:

SELECT * FROM tbl_pictures WHERE picture_id>?
  ORDER BY picture_id LIMIT 1

LIMIT affects only the results given, not how many records are actually searched.


问:
hasMany relationship Laravel 5.4 Trying to get property of non-object
I have a relationship in my models with foreing keys, protected table.

This is my models:

Lot.php:

```<code><?php

namespace App;

class Lot extends Model
{

    protected $table = 'auct_lots_full';

    protected $primaryKey = 'lot_id';

    public function comments()
    {
        return $this->hasMany(Comment::class,'lot_id', 'lot_id');
    }

}
</code>```

Than related model Comment.php:

```<code><?php

namespace App;

class Comment extends Model
{

    public function lot()
    {
        return $this->belongsTo(Lot::class, 'lot_id', 'lot_id');
    }
}
</code>```

In my view I try to do this:

```<code>@foreach ($comments as $comment)

   <dt>{{ $comment->lot }}</td>

@endforeach
</code>```

It result this:

{"lot_id":391959148,"date":"2017-05-21","company":"MITSUBISHI","model_year_en":2005"}

Than in view I need to get only company information and I do this:

```<code> @foreach ($comments as $comment)
    <td> {{ $comment->lot->company }}</td>
@endforeach
</code>```

this result Error:

Trying to get property of non-object

I try to do this:

```<code>@foreach ($comments as $comment)
    <td>
        @foreach($comment->lot as $lot)
           {{ $lot->company }}
        @endforeach
    </td>
@endforeach
</code>```

And it also gives error:

Trying to get property of non-object

How can I get $comment->lot->company work?

答:
Thanks, to Snapey from laracasts

when you do this

```<code>@foreach ($comments as $comment)
    <td> {{ $comment->lot->company }}</td>
@endforeach
</code>```

you are relying on EVERY comment having a lot and every lot having a company

You can use this to protect against empty properties

```<code>@foreach ($comments as $comment)
    <td> {{ $comment->lot->company or '---'}}</td>
@endforeach
</code>```

Then the loop will continue even if the lot does not have company

Body:
I have a relationship in my models with foreing keys, protected table.

This is my models:

Lot.php:

<?php

namespace App;

class Lot extends Model
{

    protected $table = 'auct_lots_full';

    protected $primaryKey = 'lot_id';

    public function comments()
    {
        return $this->hasMany(Comment::class,'lot_id', 'lot_id');
    }

}

Than related model Comment.php:

<?php

namespace App;

class Comment extends Model
{

    public function lot()
    {
        return $this->belongsTo(Lot::class, 'lot_id', 'lot_id');
    }
}

In my view I try to do this:

@foreach ($comments as $comment)

{{ $comment->lot }}

@endforeach

It result this:

{"lot_id":391959148,"date":"2017-05-21","company":"MITSUBISHI","model_year_en":2005"}

Than in view I need to get only company information and I do this:

 @foreach ($comments as $comment)
     {{ $comment->lot->company }}
@endforeach

this result Error:

Trying to get property of non-object

I try to do this:

@foreach ($comments as $comment)

        @foreach($comment->lot as $lot)
           {{ $lot->company }}
        @endforeach

@endforeach

And it also gives error:

Trying to get property of non-object

How can I get $comment->lot->company work?

Body:
Thanks, to Snapey from laracasts

when you do this

@foreach ($comments as $comment)
    <td> {{ $comment->lot->company }}</td>
@endforeach

you are relying on EVERY comment having a lot and every lot having a company

You can use this to protect against empty properties

@foreach ($comments as $comment)
    <td> {{ $comment->lot->company or '---'}}</td>
@endforeach

Then the loop will continue even if the lot does not have company


问:
Get Image Type and Metadata in Racket

How do I get a file's type and if it's an image, get its dimensions?

I want to read files from disk, determine if these files are indeed images, and get their dimensions to determine if they meet my program's criteria.

I noticed the racket/draw packages has a bitmap% type which can load images, but this seems beyond the scope of my task, as I think loading the files into a drawable datatype will exceed my memory-usage goals and lead to confounded code. In addition, if I use this, I'd have to use the bitmap%'s errors to screen out files that are not images.

I also saw a package to manipulate png images, however, I want to also get information on jpeg, gif, and possibly tiff.

So really my question is two fold - is there something like libmagic for Racket, and is there something like imagemagick for Racket?

答:
To determine the file type, you can

look at the file extension

or

read the first bytes of the file and compare with the magic number for some chosen the image formats

Information on magic numbers:https://en.wikipedia.org/wiki/Magic_number_%28programming%29

An alternative is to use an external utility file. The utility is available on many systems. This man page is for the Linux version: https://linux.die.net/man/1/file

With respect to getting information out of a jpeg file, see this package:

https://pkgs.racket-lang.org/package/binary-class-exif

Title: Get Image Type and Metadata in Racket


问:
HTML Input text side by side
i've been trying to figure out how to make the input text and input button side by side. Not only that, it seems my text-align : center is not applying for the text input.

I'm trying not to add multiple spaces just to indent the placeholder.

I've been trying various way but i'm still stuck :
Codepen :-

https://codepen.io/jayvicious/pen/dRyJKE
HTML :

```<code><div class="cell at-bottom">
      <input type="text" placeholder="All Japan Cities" class="formElement">
      <input type="text" placeholder="Check In Date" class="formElement">
      <input type="text" placeholder="Check Out Date" class="formElement">
      <select name="cars">
  <option value="Guest1">1 Guest</option>
  <option value="Guest2">2 Guest</option>
  <option value="Guest3">3 Guest</option>
  <option value="Guest4">4 Guest</option>
  <option value="Guest5">5 Guest</option>
</select>
      <input type="submit" value="Search" class="formElement">
    </div>
</code>```

CSS:

```<code>input[type=text], select {
text-allign:center;
padding: 12px 20px;
margin: auto;
display: inline-block;
border: 1px solid  #000000;

}

input[type=submit] {
    font-family: 'arial', sans-serif;
    background-color:white;
    text-align: center;
    color:red;
  padding: 14px 45px;
  margin: 8px 0;
  border: 1px solid  #000000;
  cursor: pointer;
}

.cell.at-bottom {
  height: 20px;
  padding: 20px;
}
</code>```

My expected output should be something like this :

EDIT : Center issue has been fixed by matthias gwiozda
Link that fixed it : Center HTML Input Text Field Placeholder

答:
This is a duplicate of Center HTML Input Text Field Placeholder .

As David mentioned, you can fix the type-mistake with "text-allign" or if you want to give only your placeholders the Text-align you can use this:

```<code>::-webkit-input-placeholder {
   text-align: center;
}

:-moz-placeholder { /* Firefox 18- */
   text-align: center;
}

::-moz-placeholder {  /* Firefox 19+ */
   text-align: center;
}

:-ms-input-placeholder {
   text-align: center;
}
</code>```

Edit:
The following solution is only working for Chroium Browsers. So its useless:

For you spacing - problem you can set the following Css for your Container of your Input-fields :

```<code>.cell.at-bottom    {
display: inline-table;
}
</code>```

Title: HTML Input text side by side

Body:
i've been trying to figure out how to make the input text and input button side by side. Not only that, it seems my text-align : center is not applying for the text input.

I'm trying not to add multiple spaces just to indent the placeholder.

I've been trying various way but i'm still stuck :
Codepen :-

https://codepen.io/jayvicious/pen/dRyJKE
HTML :

      <input type="text" placeholder="All Japan Cities" class="formElement">
      <input type="text" placeholder="Check In Date" class="formElement">
      <input type="text" placeholder="Check Out Date" class="formElement">
      <select name="cars">
  <option value="Guest1">1 Guest</option>
  <option value="Guest2">2 Guest</option>
  <option value="Guest3">3 Guest</option>
  <option value="Guest4">4 Guest</option>
  <option value="Guest5">5 Guest</option>
</select>
      <input type="submit" value="Search" class="formElement">

CSS:

input[type=text], select {
text-allign:center;
padding: 12px 20px;
margin: auto;
display: inline-block;
border: 1px solid  #000000;

}

input[type=submit] {
    font-family: 'arial', sans-serif;
    background-color:white;
    text-align: center;
    color:red;
  padding: 14px 45px;
  margin: 8px 0;
  border: 1px solid  #000000;
  cursor: pointer;
}

.cell.at-bottom {
  height: 20px;
  padding: 20px;
}

My expected output should be something like this :

EDIT : Center issue has been fixed by matthias gwiozda
Link that fixed it : Center HTML Input Text Field Placeholder

Body:
This is a duplicate of Center HTML Input Text Field Placeholder .

As David mentioned, you can fix the type-mistake with "text-allign" or if you want to give only your placeholders the Text-align you can use this:

::-webkit-input-placeholder {
   text-align: center;
}

:-moz-placeholder { /* Firefox 18- */
   text-align: center;
}

::-moz-placeholder {  /* Firefox 19+ */
   text-align: center;
}

:-ms-input-placeholder {
   text-align: center;
}

Edit:
The following solution is only working for Chroium Browsers. So its useless:

For you spacing - problem you can set the following Css for your Container of your Input-fields :

.cell.at-bottom    {
display: inline-table;
}


问:
Where is the arm interrupt handler for linux?
I'm looking through the source but I can't find where the low level asm interrupt_vector and fast_interrupt_vector code is or where the higher level C code called by low level vectors is. Where is the interrupt code for arm at?

答: The interrupt handlers are in the device driver code. Each device type has its own driver somewhere in the driver subdirectory. The driver initialization code typically requests an irq from the kernel, passing a function pointer to the handler as a parameter. This means that the service routines are not collected together, but are essentially "all over the place".

OwnerDisplayName: Johan Myréen


问:
When git rebasing, git displays that I'm currently more commits through the rebase than there are commits to rebase
Apologies for the confusing question, I'm not sure how to describe it generally. I typed git rebase master to place my 4 commits in my current branch at the end of master's history.

But instead I am stuck in a state that says:

```<code>user@CPUNAME MINGW64 /d/Code/ClientRepo (branchName|REBASE 5/4)
</code>```

5/4? How can I be 5 commits into the rebase if there are only 4 commits TO rebase?

git rebase --continue gives me the output: fatal: cannot resume: .git/rebase-apply/final-commit does not exist.

git rebase --abort seems to work, but after the command completes I still see branchName|REBASE 5/4 indicating the rebasing never aborted.

Totally stuck. Advice politely requested.

Edit: I have since unblocked myself by re-cloning the repo into a different directory. This meant that I lost my commits. Thankfully, there weren't too many changes and I re-created them.

However, I still have the old directory stuck in this state and am very curious what the fix might be as I've never seen this situation before. I'm leaving the question open and will try out suggestions - perhaps a potential answer could help someone else in the future.

Now, the main questions are, what could possibly lead to this state and how to unravel it?

答:
The first think to check is if the issue persists with:

a fresh clone

the latest Git for Windows (2.13)

You will have the new syntax git rebase --quit: that will help properly abort a rebase in progress.

I don't find yet a bug report I might have mentioned before, I will check the Git mailing list.

Body:
Apologies for the confusing question, I'm not sure how to describe it generally. I typed git rebase master to place my 4 commits in my current branch at the end of master's history.

But instead I am stuck in a state that says:

user@CPUNAME MINGW64 /d/Code/ClientRepo (branchName|REBASE 5/4)

5/4? How can I be 5 commits into the rebase if there are only 4 commits TO rebase?

git rebase --continue gives me the output: fatal: cannot resume: .git/rebase-apply/final-commit does not exist.

git rebase --abort seems to work, but after the command completes I still see branchName|REBASE 5/4 indicating the rebasing never aborted.

Totally stuck. Advice politely requested.

Edit: I have since unblocked myself by re-cloning the repo into a different directory. This meant that I lost my commits. Thankfully, there weren't too many changes and I re-created them.

However, I still have the old directory stuck in this state and am very curious what the fix might be as I've never seen this situation before. I'm leaving the question open and will try out suggestions - perhaps a potential answer could help someone else in the future.

Now, the main questions are, what could possibly lead to this state and how to unravel it?


问:
Header with three elements, one left, one center, one right
I'm just starting to develop in HTML and CSS, and despite reading about the box model I am still having trouble with some of the basics of positioning.

I want to create a header navigation bar with three elements - one to the left of the page, one to the right, and one in the center. I want these elements to be inline with each other.

At the moment, they are represented in HTML like so

```<code><body>
<div class="header">
    <ul class="child">
        <li id="lodestone"><a href="">The Lodestone</a></li>
        <li id="mogstation"><a href="">The Mog Station</a></li>
        <li id="user"><a href="">User Account</a></li>
    </ul>
</div>
</code>```

I have then attempted to align them using the 'text-align' property in CSS.

```<code>.header {
    background-color: #ffd9e7;
    border: black;
    display: block;
    box-sizing: border-box;
}

.header ul {
    display: inline-block;
}

.header > ul > li {
    display: inline-block;
}

#lodestone {
    text-align: left;
}

#user {
    text-align: right;
}

#mogstation {
    text-align: center;
}
</code>```

However, instead of the expected result it produces this.
The three items are aligned, next to each other, on the left.

Can anyone recommend what css property I should be using to solve this problem? My research has shown there are ways of using float, but other people recommend against it, and when I try I get issues with the text overflowing off the page.

答:
If you give the ul and lis a width and  (100 ul /30 for li s for example) then they should display correctly

.header {
    background-color: #ffd9e7;
    border: black;
    display: block;
    box-sizing: border-box;
}

.header ul {
    display: inline-block;
    width:100%;
}

.header > ul > li {
    display: inline-block;
    position:relative;
    vertical-align:top;
    width:30%;
}

#lodestone {
    text-align: left;
}

#user {
   text-align: right;
}

#mogstation {
    text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header">
    <ul class="child">
        <li id="lodestone">The Lodestone</li>
        <li id="mogstation">The Mog Station</li>
        <li id="user">User Account</li>
    </ul>
</div></code>```

I added vertical-align:top; but it's excess to requirements, you could take that out..

Fiddle

Hope this helps

Body:
I'm just starting to develop in HTML and CSS, and despite reading about the box model I am still having trouble with some of the basics of positioning.

I want to create a header navigation bar with three elements - one to the left of the page, one to the right, and one in the center. I want these elements to be inline with each other.

At the moment, they are represented in HTML like so

The Lodestone

The Mog Station

User Account

I have then attempted to align them using the 'text-align' property in CSS.

.header {
    background-color: #ffd9e7;
    border: black;
    display: block;
    box-sizing: border-box;
}

.header ul {
    display: inline-block;
}

.header > ul > li {
    display: inline-block;
}

#lodestone {
    text-align: left;
}

#user {
    text-align: right;
}

#mogstation {
    text-align: center;
}

However, instead of the expected result it produces this.
The three items are aligned, next to each other, on the left.

Can anyone recommend what css property I should be using to solve this problem? My research has shown there are ways of using float, but other people recommend against it, and when I try I get issues with the text overflowing off the page.

Body:
If you give the ul and lis a width and  (100 ul /30 for li s for example) then they should display correctly

.header {
    background-color: #ffd9e7;
    border: black;
    display: block;
    box-sizing: border-box;
}

.header ul {
    display: inline-block;
    width:100%;
}

.header > ul > li {
    display: inline-block;
    position:relative;
    vertical-align:top;
    width:30%;
}

#lodestone {
    text-align: left;
}

#user {
   text-align: right;
}

#mogstation {
    text-align: center;
}

<div class="header">
    <ul class="child">
        <li id="lodestone"><a href="">The Lodestone</a></li>
        <li id="mogstation"><a href="">The Mog Station</a></li>
        <li id="user"><a href="">User Account</a></li>
    </ul>
</div>

I added vertical-align:top; but it's excess to requirements, you could take that out..

Fiddle

Hope this helps


问:
Get IndexPath of CollectionViewCell outside of Cell
First of all I am a newbie in swift, so be gentle. I have a problem fetching the indexPath of the cell outside of the cell. I want to get that index path to a function and use it to send the content to another view. The image was created programatically in the cell, it has a tap gesture recogniser sending to this function (where "myIndex" is defined as an Int : var myIndex = 0):

```<code>// tap image to go at the indexpath of the user
func imageTapped(tapGestureRecognizer: UITapGestureRecognizer) {
   print("image tapped")

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let secondViewController = storyboard.instantiateViewController(withIdentifier: "patientProfile") as! PatientProfileVC
    secondViewController.userID = posts[myIndex].userID
    secondViewController.patientName = posts[myIndex].author

    print("Passed data to the other view")

    self.show(secondViewController, sender: self)

}
</code>```

I know that I could use didSelectItem at IndexPath where I also have the declaration of the myIndex but I have something that will be triggered from a segue there:

```<code>//standard functon for item selected
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    //get the index of the cell
    myIndex = indexPath.row

    print("Cell is selected")

    //perform the segue
    self.performSegue(withIdentifier: "CommentsVC", sender: self)
    print(myIndex)

}
</code>```

and my perform for segue looks like this:` override

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

```<code>    print("Segue Initiated")
    feed.navigationItem.title = nil

    //if segue.destination is CommentsFullVC{
        print("Comments segue initiated")
        let secondViewController = segue.destination as! CommentsFullVC
        secondViewController.questionData = posts[myIndex].postContent
        secondViewController.authorName = posts[myIndex].author
        secondViewController.date = posts[myIndex].normalDate
        secondViewController.profileImagePath = posts[myIndex].pathToImage
        secondViewController.typeOfClinic = posts[myIndex].clinic
        secondViewController.postID = posts[myIndex].postID
        secondViewController.followersForPost = posts[myIndex].followers

}
</code>```

So my question is, how do I pass those 2 fields to the other view without using prepareForSegue? I am struggling with this for 20 hours now and still can not figure it out.

```<code>secondViewController.userID = posts[myIndex].userID
secondViewController.patientName = posts[myIndex].author
</code>```

UPDATE: Got it to work thanks to Jose answer, now it looks like this... in case anybody has the same problem as I had.

```<code> // tap image to go at the indexpath of the user
func imageTapped(tapGestureRecognizer: UITapGestureRecognizer) {
   print("image tapped")

    let pointInCollectionView = tapGestureRecognizer.location(in: collectionView)
    let indexPath = collectionView?.indexPathForItem(at: pointInCollectionView)
    print(indexPath!)

    // this one works - show segue
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let secondViewController = storyboard.instantiateViewController(withIdentifier: "patientProfile") as! PatientProfileVC
    secondViewController.userID = posts[(indexPath?.row)!].userID
    secondViewController.patientName = posts[(indexPath?.row)!].author

    print("Passed data to the other view")

    self.show(secondViewController, sender: self)

}
</code>```

答:
I think this will be easy with a Delegate of the cell but its a little bit complicated. </p>

<p>The easy answer should be to store the index in the "tag" property of the imageView of the tapped image then extract from the gestureRecognizer
You can add a tag where you create the imageView and  the code where you recover the tag will look like this: </p>

```<code>func imageTapped(tapGestureRecognizer: UITapGestureRecognizer) {
    print("image tapped")
    var myIndex = 0
    if let imageView = tapGestureRecognizer.view {
        myIndex = imageView.tag
    }

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let secondViewController = storyboard.instantiateViewController(withIdentifier: "patientProfile") as! PatientProfileVC
    secondViewController.userID = posts[myIndex].userID
    secondViewController.patientName = posts[myIndex].author

    print("Passed data to the other view")

    self.show(secondViewController, sender: self)

}
</code>```

Body:
First of all I am a newbie in swift, so be gentle. I have a problem fetching the indexPath of the cell outside of the cell. I want to get that index path to a function and use it to send the content to another view. The image was created programatically in the cell, it has a tap gesture recogniser sending to this function (where "myIndex" is defined as an Int : var myIndex = 0):

// tap image to go at the indexpath of the user
func imageTapped(tapGestureRecognizer: UITapGestureRecognizer) {
   print("image tapped")

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let secondViewController = storyboard.instantiateViewController(withIdentifier: "patientProfile") as! PatientProfileVC
    secondViewController.userID = posts[myIndex].userID
    secondViewController.patientName = posts[myIndex].author

    print("Passed data to the other view")

    self.show(secondViewController, sender: self)

}

I know that I could use didSelectItem at IndexPath where I also have the declaration of the myIndex but I have something that will be triggered from a segue there:

//standard functon for item selected
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    //get the index of the cell
    myIndex = indexPath.row

    print("Cell is selected")

    //perform the segue
    self.performSegue(withIdentifier: "CommentsVC", sender: self)
    print(myIndex)

}

and my perform for segue looks like this:` override

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

    print("Segue Initiated")
    feed.navigationItem.title = nil

    //if segue.destination is CommentsFullVC{
        print("Comments segue initiated")
        let secondViewController = segue.destination as! CommentsFullVC
        secondViewController.questionData = posts[myIndex].postContent
        secondViewController.authorName = posts[myIndex].author
        secondViewController.date = posts[myIndex].normalDate
        secondViewController.profileImagePath = posts[myIndex].pathToImage
        secondViewController.typeOfClinic = posts[myIndex].clinic
        secondViewController.postID = posts[myIndex].postID
        secondViewController.followersForPost = posts[myIndex].followers

}

So my question is, how do I pass those 2 fields to the other view without using prepareForSegue? I am struggling with this for 20 hours now and still can not figure it out.

secondViewController.userID = posts[myIndex].userID
secondViewController.patientName = posts[myIndex].author

UPDATE: Got it to work thanks to Jose answer, now it looks like this... in case anybody has the same problem as I had.

 // tap image to go at the indexpath of the user
func imageTapped(tapGestureRecognizer: UITapGestureRecognizer) {
   print("image tapped")

    let pointInCollectionView = tapGestureRecognizer.location(in: collectionView)
    let indexPath = collectionView?.indexPathForItem(at: pointInCollectionView)
    print(indexPath!)

    // this one works - show segue
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let secondViewController = storyboard.instantiateViewController(withIdentifier: "patientProfile") as! PatientProfileVC
    secondViewController.userID = posts[(indexPath?.row)!].userID
    secondViewController.patientName = posts[(indexPath?.row)!].author

    print("Passed data to the other view")

    self.show(secondViewController, sender: self)

}

Body:
I think this will be easy with a Delegate of the cell but its a little bit complicated.

The easy answer should be to store the index in the "tag" property of the imageView of the tapped image then extract from the gestureRecognizer
You can add a tag where you create the imageView and  the code where you recover the tag will look like this:

func imageTapped(tapGestureRecognizer: UITapGestureRecognizer) {
    print("image tapped")
    var myIndex = 0
    if let imageView = tapGestureRecognizer.view {
        myIndex = imageView.tag
    }

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let secondViewController = storyboard.instantiateViewController(withIdentifier: "patientProfile") as! PatientProfileVC
    secondViewController.userID = posts[myIndex].userID
    secondViewController.patientName = posts[myIndex].author

    print("Passed data to the other view")

    self.show(secondViewController, sender: self)

}


问:
Dynamic Image for Facebook Opengraph og:image meta tag
I am trying to share an image from my website on facebook. The image can be dynamic, but other meta will remain the same.

Is there a way I can have dynamic data in OG:IMAGE tag, or will I have to go with the other option of FB Post APIs.

答:
Take a look at this Gist.

You should ping facebook to recrawl your page again every time you update your og:image tag.

```<code>def share_facebook_fanpage(link,msg,PAGE_ID,OAUTH_ACCESS_TOKEN,apiversion='v2.8'):
    BASE_URL = "https://graph.facebook.com/%s" % apiversion
    POST_URL = "%s/%s/feed" % (BASE_URL, PAGE_ID)

    # force facebook scape the link first to avoid not showing thumb
    f = requests.post(BASE_URL, data={
        'id': link,
        'scrape': True,
        'access_token': OAUTH_ACCESS_TOKEN
    })

    # share the link
    r = requests.post(POST_URL, data={'access_token': OAUTH_ACCESS_TOKEN, 'link': link, 'message':msg})
</code>```

Body:
Take a look at this Gist.

You should ping facebook to recrawl your page again every time you update your og:image tag.

def share_facebook_fanpage(link,msg,PAGE_ID,OAUTH_ACCESS_TOKEN,apiversion='v2.8'):
    BASE_URL = "https://graph.facebook.com/%s" % apiversion
    POST_URL = "%s/%s/feed" % (BASE_URL, PAGE_ID)

    # force facebook scape the link first to avoid not showing thumb
    f = requests.post(BASE_URL, data={
        'id': link,
        'scrape': True,
        'access_token': OAUTH_ACCESS_TOKEN
    })

    # share the link
    r = requests.post(POST_URL, data={'access_token': OAUTH_ACCESS_TOKEN, 'link': link, 'message':msg})


问:
Is it possible to keep same-named global variables unique across different scripts after importing them?
So I have a few Python scripts that I want to run simultaneously, so I made a new empty Python script that just imports all of my scripts so that I can run all of them with a single script. However, most of the scripts have global variable names in them that are the same name across some of the scripts, but I don't want them conflicting with each other. Is there a way without going into the scripts individually one by one to change the names of every single global variable that I can still "load" all the scripts into a single file and share the same global variable names without them conflicting with each other?

答:
You don't actually need to do that!

Every module has a seperate global scope. As an example, you can see this by doing this:

test.py

```<code>a = 1

def set_a(val):
    global a
    a = val

def get_a():
    return a
</code>```

test_two.py

```<code>import test

a = 4
test.set_a(5)
print(a)  # 4
print(test.a)  # 5
</code>```

As long as you don't import them into the same namespace. If you do, if you assign it anywhere with name = value, the name a in test would be different to the name in test_two:

test_two.py

```<code>from test import a, set_a, get_a

print((get_a(), a))  # (1, 1)
set_a(5)
print((get_a(), a))  # (5, 1)
a = 4
print((get_a(), a))  # (5, 4)
</code>```

But this won't happen if you mutate the value, for example, .appending to a list, the names will still point to the same values.

Body:
You don't actually need to do that!

Every module has a seperate global scope. As an example, you can see this by doing this:

test.py

a = 1

def set_a(val):
    global a
    a = val

def get_a():
    return a

test_two.py

import test

a = 4
test.set_a(5)
print(a)  # 4
print(test.a)  # 5

As long as you don't import them into the same namespace. If you do, if you assign it anywhere with name = value, the name a in test would be different to the name in test_two:

test_two.py

from test import a, set_a, get_a

print((get_a(), a))  # (1, 1)
set_a(5)
print((get_a(), a))  # (5, 1)
a = 4
print((get_a(), a))  # (5, 4)

But this won't happen if you mutate the value, for example, .appending to a list, the names will still point to the same values.


问:
flash fscommands and javascript
I try get the mp3 flash player to work with my javascript on all browsers. All went well for first, but fast realized that my code doesn't work on MSIE.

After trying to find out  I found this in the reference code:

```<code><!--[if IE]>
<script type="text/javascript" event="FSCommand(command,args)" for="myFlash">
eval(args);
</script>
<![endif]-->
</code>```

How to turn this into a javascript or jquery clause that I could stuff it where it belongs to (in audio.js)?

答:
Maybe this is more about embedding flash dynamically.

I got stuck on exactly the same thing with mp3 flash player. The thing is that IE doesn't care about the special script tag with 'event' and 'for' attribute, if it is added AFTER the page has loaded. My IE wouldn't event eat jquery's .html() when the page loaded, only document.write worked. But document.write can't really be used after the page has loaded, unless it is targeted in an iframe or some other devil worship mechanism.

What's good tho, is that IE doesn't distinguish between assigning an event handler in this bastard script tag or programatically. This means that:

```<code><script type="text/javascript" event="FSCommand(command,args)" for="myFlash">
    eval(args);
</script>
</code>```

in IE directly translates to:

```<code>function foo(command, args){
    eval(args);
}
var ie_sucks = document.getElementById('myFlash');
ie_sucks.attachEvent("FSCommand", foo);
</code>```

OwnerDisplayName: Cheery

ContentLicense: CC BY-SA 2.5

Title: flash fscommands and javascript

Body:
I try get the mp3 flash player to work with my javascript on all browsers. All went well for first, but fast realized that my code doesn't work on MSIE.

After trying to find out  I found this in the reference code:

How to turn this into a javascript or jquery clause that I could stuff it where it belongs to (in audio.js)?

LastEditorDisplayName: Ben Combee

Body:
Maybe this is more about embedding flash dynamically.

I got stuck on exactly the same thing with mp3 flash player. The thing is that IE doesn't care about the special script tag with 'event' and 'for' attribute, if it is added AFTER the page has loaded. My IE wouldn't event eat jquery's .html() when the page loaded, only document.write worked. But document.write can't really be used after the page has loaded, unless it is targeted in an iframe or some other devil worship mechanism.

What's good tho, is that IE doesn't distinguish between assigning an event handler in this bastard script tag or programatically. This means that:

<script type="text/javascript" event="FSCommand(command,args)" for="myFlash">
    eval(args);
</script>

in IE directly translates to:

function foo(command, args){
    eval(args);
}
var ie_sucks = document.getElementById('myFlash');
ie_sucks.attachEvent("FSCommand", foo);


问:
Uploading a file from a bootstrap modal using ajax
I am attempting to upload a file to a server from a bootstrap modal window, using ajax.

The modal html is

```<code><div class="modal-body">
<div>
<form class="form" role="form" id="attachform" enctype="multipart/form-data">
<input type="file" name="file" id="file">
<button type="submit" class="btn btn-primary">Upload</button>
</form>
</div>
</div>
</code>```

The Javascript

```<code>$("#attachform").on('submit',function(event){
event.preventDefault();
var postData = new FormData($("#attachform")[0]);
console.log(postData);
$.ajax({
   url: "attachment.php",
   type: "POST",
   data: data,
   processData: false,  // tell jQuery not to process the data
   contentType: false
   }).done(function(msg) {
   console.log(msg);
    $('#myAttachModal').modal('hide');
            });
    });
});
</code>```

The PHP server code

```<code>print_r($_POST);
print_r($_FILES);
</code>```

I am not seeing anything in the $_FILES array when I run this.

Any suggestions?

答:
```<code>$.ajax({
   url: "attachment.php",
   type: "POST",
   data: postData,
   processData: false,  // tell jQuery not to process the data
   contentType: false
   }).done(function(msg) {
   console.log(msg);
    $('#myAttachModal').modal('hide');
            });
    });
});
</code>```

Body:
I am attempting to upload a file to a server from a bootstrap modal window, using ajax.

The modal html is

<form class="form" role="form" id="attachform" enctype="multipart/form-data">
<input type="file" name="file" id="file">
<button type="submit" class="btn btn-primary">Upload</button>
</form>

The Javascript

$("#attachform").on('submit',function(event){
event.preventDefault();
var postData = new FormData($("#attachform")[0]);
console.log(postData);
$.ajax({
   url: "attachment.php",
   type: "POST",
   data: data,
   processData: false,  // tell jQuery not to process the data
   contentType: false
   }).done(function(msg) {
   console.log(msg);
    $('#myAttachModal').modal('hide');
            });
    });
});

The PHP server code

print_r($_POST);
print_r($_FILES);

I am not seeing anything in the $_FILES array when I run this.

Any suggestions?


问:
How can I select a specific tag in two different HTML structure?
I have two different HTML structure and I cannot change them. Now I need to write a jQuery code to get the href attribute of one specific  in them. Here is my code:

$(document).on('click', '.myclass', function(e){
  e.preventDefault(e);

  var url = $(this).attr('href');
  console.log(url);

  $(this).closest('li').css('background-color','#f1f1f1');
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>li{
  border: 1px solid gray;
}

a{
  display:block;
}

.myclass{
    cursor: pointer;
}</code>```

HTML1:

    sth
    something
    link

HTML2:

    something

sth

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

<p>Ok, let me explain. I want two things happen when the user clicks on <code>.myclass</code> element: <em>(as you see, <code>.myclass</code> element is different in two HTML structures)</em></p>

<ul>
<li><p>Setting a pale gray color to the background of <code>li</code>.</p></li>
<li><p>Printing the <code>href</code> value of the link in the console.</p></li>
</ul>

<p>My current code works correctly for the first HTML structure <em>(but not for the second one)</em>. </p>

<hr>

<p><strong>Note:</strong> For the second one, jQuery code should look like this:</p>

``` $(document).on('click', '.myclass', function(e){
  e.preventDefault(e);

  var url = $(this).find('a').attr('href');
  console.log(url);

  $(this).css('background-color','#f1f1f1');
})
```

See? I've added find('a') (there is always one  in the second kind of HTML) and removed closest('li').

Anyway, how can I write one jQuery code instead of both above?

答:
This would be cleaner using a css rule for the background

$(document).on('click', '.myclass', function(e){
  e.preventDefault(e);
  var $el = $(this),
    //if this is  tag use it for href, otherwise find it
    $link = $el.is('a') ? $el : $el.find('a:first'),
    url = $link.attr('href');

  $el.closest('li').toggleClass('active');
  console.log(url);

})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>li{
  border: 1px solid gray;
}

a{
  display:block;
}

.myclass{
    cursor: pointer;
}

li.active, .myclass.active{
  background-color:#f1f1f1
}</code>```

HTML1:

    sth
    something
    link

HTML2:

    something

sth

```

Body:
I have two different HTML structure and I cannot change them. Now I need to write a jQuery code to get the href attribute of one specific  in them. Here is my code:

$(document).on('click', '.myclass', function(e){
  e.preventDefault(e);

  var url = $(this).attr('href');
  console.log(url);

  $(this).closest('li').css('background-color','#f1f1f1');
})

li{
  border: 1px solid gray;
}

a{
  display:block;
}

.myclass{
    cursor: pointer;
}

HTML1:

    sth
    something
    link

HTML2:

    something

sth

Ok, let me explain. I want two things happen when the user clicks on .myclass element: (as you see, .myclass element is different in two HTML structures)

Setting a pale gray color to the background of li.

Printing the href value of the link in the console.

My current code works correctly for the first HTML structure (but not for the second one).

Note: For the second one, jQuery code should look like this:

 $(document).on('click', '.myclass', function(e){
  e.preventDefault(e);

  var url = $(this).find('a').attr('href');
  console.log(url);

  $(this).css('background-color','#f1f1f1');
})

See? I've added find('a') (there is always one  in the second kind of HTML) and removed closest('li').

Anyway, how can I write one jQuery code instead of both above?

Body:
This would be cleaner using a css rule for the background

$(document).on('click', '.myclass', function(e){
  e.preventDefault(e);
  var $el = $(this),
    //if this is <a> tag use it for href, otherwise find it
    $link = $el.is('a') ? $el : $el.find('a:first'),
    url = $link.attr('href');

  $el.closest('li').toggleClass('active');
  console.log(url);

})

li{
  border: 1px solid gray;
}

a{
  display:block;
}

.myclass{
    cursor: pointer;
}

li.active, .myclass.active{
  background-color:#f1f1f1
}

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

<ul>
  <li>
    <a href="#">sth</a>
    <span>something</span>
    <a class="myclass" href="./my/path">link</a>
  </li>
</ul>

<hr />

HTML2:

<ul>
  <li class="myclass">
    <a href="./my/path">
    <span>something</span>
    </a>
    <div>sth</div>
  </li>
</ul>


问:
How to change h1 tittle when clicked/make the section centered
I'm working on some simple questions as practice for my exam, but most of the questions don't have any answers for me to check if I don't know. There is one I'm really unsure about, so I thaught I'd check here. The question is:

Suppose we have an HTML document that contains these two lines:

```<code><Body>
<H1 title = "When this is clicked, the section changes"> Title </ h1>
<P id = "first" title = "When this is clicked, the title is centered"> First section: Original version. </ P>
</ Body>
</code>```

Type the code that would change the look of this page so that:

• When you click on the h1 title, the section changes from "First section: Original Version" to "First section: modified version ".

• When you click on the section, the position of the title changes and gets centered.

Hope someone can help learn me this so I have an answer if something similar shows up on my exam:)

答:
```<code>var h1 = document.querySelector('h1');
var first = document.querySelector('#first');

h1.addEventListener('click', function() {
  first.innerText = 'First section: modified version.';
});

first.addEventListener('click', function() {
  h1.style.textAlign = 'center';
});
</code>```

Body:
I'm working on some simple questions as practice for my exam, but most of the questions don't have any answers for me to check if I don't know. There is one I'm really unsure about, so I thaught I'd check here. The question is:

Suppose we have an HTML document that contains these two lines:

 Title

 First section: Original version.

Type the code that would change the look of this page so that:

• When you click on the h1 title, the section changes from "First section: Original Version" to "First section: modified version ".

• When you click on the section, the position of the title changes and gets centered.

Hope someone can help learn me this so I have an answer if something similar shows up on my exam:)


问:
Verify if there are any selected items in a gridview
im developing an app and implementing an onboarding to ask the user to select certain options that will be displayed in a grid view. I want the user to select and unselect and item for this im using a simple toggleSelected(){selected=!selected} declared in my item entry class.
I also have a button at the bottom that will be disabled if all the items in the gridview have isSelected() = false. What is the best way to check this?
Thanks for the help</p>

答: In the model class which actually contains the data,the list which you provide to the adapter of the recyclerView , add a variable isSelected and set its default value to false, whenever a grid item gets selected, set it to true and when it gets unselected, set it to false. In this way you could travel that list and then know which all are selected and which are not.</p>


答:
This could be done in a number of ways ranging from checking what type of tag it is, all the way to applying data attributes and then checking them against that what we have on the clicked class.

For this example, we're checking if it has a 'href' tag.

I have left the separate background colour setters in each if() in case you wish to change them to different values at some point.

Here's my take on it:

```<code> $(document).ready(function() {

  $('.myclass').click(function(e) {
  e.preventDefault();
   var url;

    if($(this).attr("href")) { //WE check if the "href" attribute exists
      //Found, it must be an link
      url = $(this).attr('href');
      console.log(url);
      $(this).closest('li').css('background-color','#f1f1f1');

    } else {
      //Not found
       url = $(this).find('a').attr('href');
       console.log(url);
       $(this).css('background-color','#f1f1f1');

    }

  });

});
</code>```

Title: How can I select a specific tag in two different HTML structure?

Body:
This could be done in a number of ways ranging from checking what type of tag it is, all the way to applying data attributes and then checking them against that what we have on the clicked class.

For this example, we're checking if it has a 'href' tag.

I have left the separate background colour setters in each if() in case you wish to change them to different values at some point.

Here's my take on it:

 $(document).ready(function() {

  $('.myclass').click(function(e) {
  e.preventDefault();
   var url;

    if($(this).attr("href")) { //WE check if the "href" attribute exists
      //Found, it must be an link
      url = $(this).attr('href');
      console.log(url);
      $(this).closest('li').css('background-color','#f1f1f1');

    } else {
      //Not found
       url = $(this).find('a').attr('href');
       console.log(url);
       $(this).css('background-color','#f1f1f1');

    }

  });

});


问:
How do I check if my EditText fields are empty?
I have 5 EditTexts in android. I would like to know if I could check if all 5 EditTexts are null. Is there any way to do this??

答:
You could call this function for each of the edit texts:</p>

```<code>public boolean isEmpty(EditText editText) {
    boolean isEmptyResult = false;
    if (editText.getText().length() == 0) {
        isEmptyResult = true;
    }
    return isEmptyResult;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You could call this function for each of the edit texts:

public boolean isEmpty(EditText editText) {
    boolean isEmptyResult = false;
    if (editText.getText().length() == 0) {
        isEmptyResult = true;
    }
    return isEmptyResult;
}


问:
When I open my website I want to move the input to my form (see screen so you know what I mean)
When I open my website I want to automatically start typing in my form instead of the default browser search bar.

from the scren:
I want to start typing in the Google bar for example.
scrn

答:
There is an autofocus attribute in Html 5

```<code><input type="text" autofocus>
</code>```

From MDN:

This Boolean attribute lets you specify that a form control should
  have input focus when the page loads, unless the user overrides it
  (e.g. by typing in a different control). Only one form element in a
  document can have the autofocus attribute, which is a Boolean. It
  cannot be applied if the type attribute is set to hidden (that is, you
  cannot automatically set focus to a hidden control). Note that the
  focusing of the control may occur before the firing of the
  DOMContentLoaded event.

Body:
There is an autofocus attribute in Html 5

<input type="text" autofocus>

From MDN:

This Boolean attribute lets you specify that a form control should
  have input focus when the page loads, unless the user overrides it
  (e.g. by typing in a different control). Only one form element in a
  document can have the autofocus attribute, which is a Boolean. It
  cannot be applied if the type attribute is set to hidden (that is, you
  cannot automatically set focus to a hidden control). Note that the
  focusing of the control may occur before the firing of the
  DOMContentLoaded event.


问:
JS Calculating and constantly showing result
I have a starting value 1000.
On button FIGHT (which already has onclikc) it needs to do 1000-20 and shows in html 980, another click 960..

function damagec() {
    var a = 500;
    var b = a/20;
    document.getElementById('resultl').innerHTML = b;
    document.getElementById('resultl').style.color = 'green';
    document.getElementById('resultlc').innerHTML = b;
    document.getElementById('resultlc').style.color = 'green';
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wall">
    <p id="wallvalue">1000</p>
</div>
<button onclick="damagec()"><b>FIGHT</b></button></code>```

答:
window.damagec = function(){
    var label = document.getElementById('wallvalue');
    label.innerHTML = parseInt(label.innerHTML) - 20;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wall">
    <p id="wallvalue">1000</p>
</div>
<BUTTON onclick="damagec()"><b>FIGHT</b></BUTTON></code>```

You can store the value from the element and subtract whatever value you want from it before assigning it back to the element

```<code>var label = document.getElementById('wallvalue');
label.innerHTML = parseInt(label.innerHTML) - 20;
</code>```

Body:
I have a starting value 1000.
On button FIGHT (which already has onclikc) it needs to do 1000-20 and shows in html 980, another click 960..

function damagec() {
    var a = 500;
    var b = a/20;
    document.getElementById('resultl').innerHTML = b;
    document.getElementById('resultl').style.color = 'green';
    document.getElementById('resultlc').innerHTML = b;
    document.getElementById('resultlc').style.color = 'green';
}

1000

<button onclick="damagec()">FIGHT</button>

Body:
window.damagec = function(){
    var label = document.getElementById('wallvalue');
    label.innerHTML = parseInt(label.innerHTML) - 20;
}

<div class="wall">
    <p id="wallvalue">1000</p>
</div>
<BUTTON onclick="damagec()"><b>FIGHT</b></BUTTON>

You can store the value from the element and subtract whatever value you want from it before assigning it back to the element

var label = document.getElementById('wallvalue');
label.innerHTML = parseInt(label.innerHTML) - 20;


问:
'No CMAKE_c_COMPILER could be found' with CMake
I'm having a lot of problems with the integrated CMake support in VS2017.

At first I had problems with getting the CXX compiler to work, but installing the "Win 8.1 and UCRT" package fixed it.

Now I'm having problems with getting it to compile C.

```<code>No CMAKE_c_COMPILER could be found.
</code>```

Is there anything I can do?
I can compile C no problem in the normal, non-cmake visual studio.

答:
If letters in CMAKE_c_COMPILER are precise, then you attempt to use "c" string as a language for project() call.

But proper language for C is "C" (uppercase).

Body:
I'm having a lot of problems with the integrated CMake support in VS2017.

At first I had problems with getting the CXX compiler to work, but installing the "Win 8.1 and UCRT" package fixed it.

Now I'm having problems with getting it to compile C.

No CMAKE_c_COMPILER could be found.

Is there anything I can do?
I can compile C no problem in the normal, non-cmake visual studio.


问:
Auth0 JWT plugin and ionic2 - No Authorization header send
I have problem with integrating JWT token plugin from Auth0 with least Ionic2. I have absolutly no error but request is send without authorization header. My code:

app.module

```<code>import { NgModule } from '@angular/core';
import { IonicApp, IonicModule } from 'ionic-angular';
import { MyApp } from './app.component';
import { AboutPage } from '../pages/about/about';
import { ContactPage } from '../pages/contact/contact';
import { HomePage } from '../pages/home/home';
import { TabsPage } from '../pages/tabs/tabs';
import { LoginPage } from '../pages/login/login';
import { AuthHttp, AuthConfig } from 'angular2-jwt';
import { Storage } from '@ionic/storage';
import { Http } from '@angular/http';

import { AuthService } from '../services/auth.service';
import { NoteService } from '../services/note.service';

let storage: Storage = new Storage();

export function getAuthHttp(http) {
  return new AuthHttp(new AuthConfig({
    headerPrefix: 'JWT',
    noJwtError: true,
    globalHeaders: [{'Accept': 'application/json'}],
    tokenGetter: (() => storage.get('id_token')),
  }), http);
}

@NgModule({
  declarations: [
    MyApp,
    AboutPage,
    ContactPage,
    HomePage,
    TabsPage,
    LoginPage
  ],
  imports: [
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    AboutPage,
    ContactPage,
    HomePage,
    TabsPage,
    LoginPage
  ],
  providers: [
    AuthService,
    AuthHttp,
     {
      provide: AuthHttp,
      useFactory: getAuthHttp,
      deps: [Http]
    },
    Storage,
    NoteService,
  ]
})
export class AppModule {}
</code>```

my service:

```<code>import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
import { AuthHttp } from 'angular2-jwt';
import { AppParameters } from '../parameters';
import { AuthFormModel } from '../models/authForm.model';

import 'rxjs/add/operator/toPromise';

@Injectable()
export class NoteService {
    private headers = new Headers({ 'Content-Type': 'application/json' });
    private note_url: string = AppParameters.ENDPOINT_URL + '/notes/';

    private notes: any;
    constructor(private authHttp: AuthHttp) {}

    getUserNotes(){
        return this.authHttp.get(this.note_url);
    }

}
</code>```

And component where I use service:

```<code>import { Component } from '@angular/core';
import { NoteService } from '../../services/note.service';

import { NavController } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  notes: any;

  constructor(
    public navCtrl: NavController,
    public noteService: NoteService
    ) {}

  ngOnInit(){
    this.noteService.getUserNotes().subscribe(
            data => this.notes = data,
            err => console.log(err),
            () => {
              console.log('request complete');
              console.log(this.notes);
            }
        );
  }

}
</code>```

package.json

```<code>{
  "name": "ionic-hello-world",
  "author": "Ionic Framework",
  "homepage": "http://ionicframework.com/",
  "private": true,
  "scripts": {
    "ionic:build": "ionic-app-scripts build",
    "ionic:serve": "ionic-app-scripts serve"
  },
  "dependencies": {
    "@angular/common": "2.1.1",
    "@angular/compiler": "2.1.1",
    "@angular/compiler-cli": "2.1.1",
    "@angular/core": "2.1.1",
    "@angular/forms": "2.1.1",
    "@angular/http": "2.1.1",
    "@angular/platform-browser": "2.1.1",
    "@angular/platform-browser-dynamic": "2.1.1",
    "@angular/platform-server": "2.1.1",
    "@ionic/storage": "1.1.6",
    "angular2-jwt": "^0.1.25",
    "ionic-angular": "2.0.0-rc.3",
    "ionic-native": "2.2.3",
    "ionicons": "3.0.0",
    "rxjs": "5.0.0-beta.12",
    "zone.js": "0.6.26"
  },
  "devDependencies": {
    "@ionic/app-scripts": "0.0.45",
    "typescript": "2.0.6"
  },
  "cordovaPlugins": [
    "cordova-plugin-whitelist",
    "cordova-plugin-console",
    "cordova-plugin-statusbar",
    "cordova-plugin-device",
    "cordova-plugin-splashscreen",
    "ionic-plugin-keyboard"
  ],
  "cordovaPlatforms": [],
  "description": "noteman_js: An Ionic project"
}
</code>```

Everything work, absolutly no error in console but header is still missing. Maybe i forget something? I try configuration from JWT plugin and lot of configurations from stack overflow.
Btw. Sorry for my terrible english :)

答:
Just use window.localStorage instead of ionic storage:

```<code>export function getAuthHttp(http) {
  return new AuthHttp(new AuthConfig({
    globalHeaders: [{'Accept': 'application/json'}],
    //tokenGetter: (() => storage.get('id_token').then((val)=>{return val}) ),
    tokenGetter: (() => JSON.parse(window.localStorage.getItem("id_token"))),
    noJwtError: true,
    headerPrefix: "JWT",
  }), http);
}
</code>```

As far as I can tell, the auth0 sdk is not using Ionic storage to store the id_token anyway... it's just using window.localStorage, so you might as well just use that too and its a synchronous method so avoids this promise stuff.

Body:
I have problem with integrating JWT token plugin from Auth0 with least Ionic2. I have absolutly no error but request is send without authorization header. My code:

app.module

import { NgModule } from '@angular/core';
import { IonicApp, IonicModule } from 'ionic-angular';
import { MyApp } from './app.component';
import { AboutPage } from '../pages/about/about';
import { ContactPage } from '../pages/contact/contact';
import { HomePage } from '../pages/home/home';
import { TabsPage } from '../pages/tabs/tabs';
import { LoginPage } from '../pages/login/login';
import { AuthHttp, AuthConfig } from 'angular2-jwt';
import { Storage } from '@ionic/storage';
import { Http } from '@angular/http';

import { AuthService } from '../services/auth.service';
import { NoteService } from '../services/note.service';

let storage: Storage = new Storage();

export function getAuthHttp(http) {
  return new AuthHttp(new AuthConfig({
    headerPrefix: 'JWT',
    noJwtError: true,
    globalHeaders: [{'Accept': 'application/json'}],
    tokenGetter: (() => storage.get('id_token')),
  }), http);
}

@NgModule({
  declarations: [
    MyApp,
    AboutPage,
    ContactPage,
    HomePage,
    TabsPage,
    LoginPage
  ],
  imports: [
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    AboutPage,
    ContactPage,
    HomePage,
    TabsPage,
    LoginPage
  ],
  providers: [
    AuthService,
    AuthHttp,
     {
      provide: AuthHttp,
      useFactory: getAuthHttp,
      deps: [Http]
    },
    Storage,
    NoteService,
  ]
})
export class AppModule {}

my service:

import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
import { AuthHttp } from 'angular2-jwt';
import { AppParameters } from '../parameters';
import { AuthFormModel } from '../models/authForm.model';

import 'rxjs/add/operator/toPromise';

@Injectable()
export class NoteService {
    private headers = new Headers({ 'Content-Type': 'application/json' });
    private note_url: string = AppParameters.ENDPOINT_URL + '/notes/';

    private notes: any;
    constructor(private authHttp: AuthHttp) {}

    getUserNotes(){
        return this.authHttp.get(this.note_url);
    }

}

And component where I use service:

import { Component } from '@angular/core';
import { NoteService } from '../../services/note.service';

import { NavController } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  notes: any;

  constructor(
    public navCtrl: NavController,
    public noteService: NoteService
    ) {}

  ngOnInit(){
    this.noteService.getUserNotes().subscribe(
            data => this.notes = data,
            err => console.log(err),
            () => {
              console.log('request complete');
              console.log(this.notes);
            }
        );
  }

}

package.json

{
  "name": "ionic-hello-world",
  "author": "Ionic Framework",
  "homepage": "http://ionicframework.com/",
  "private": true,
  "scripts": {
    "ionic:build": "ionic-app-scripts build",
    "ionic:serve": "ionic-app-scripts serve"
  },
  "dependencies": {
    "@angular/common": "2.1.1",
    "@angular/compiler": "2.1.1",
    "@angular/compiler-cli": "2.1.1",
    "@angular/core": "2.1.1",
    "@angular/forms": "2.1.1",
    "@angular/http": "2.1.1",
    "@angular/platform-browser": "2.1.1",
    "@angular/platform-browser-dynamic": "2.1.1",
    "@angular/platform-server": "2.1.1",
    "@ionic/storage": "1.1.6",
    "angular2-jwt": "^0.1.25",
    "ionic-angular": "2.0.0-rc.3",
    "ionic-native": "2.2.3",
    "ionicons": "3.0.0",
    "rxjs": "5.0.0-beta.12",
    "zone.js": "0.6.26"
  },
  "devDependencies": {
    "@ionic/app-scripts": "0.0.45",
    "typescript": "2.0.6"
  },
  "cordovaPlugins": [
    "cordova-plugin-whitelist",
    "cordova-plugin-console",
    "cordova-plugin-statusbar",
    "cordova-plugin-device",
    "cordova-plugin-splashscreen",
    "ionic-plugin-keyboard"
  ],
  "cordovaPlatforms": [],
  "description": "noteman_js: An Ionic project"
}

Everything work, absolutly no error in console but header is still missing. Maybe i forget something? I try configuration from JWT plugin and lot of configurations from stack overflow.
Btw. Sorry for my terrible english :)

Body:
Just use window.localStorage instead of ionic storage:

export function getAuthHttp(http) {
  return new AuthHttp(new AuthConfig({
    globalHeaders: [{'Accept': 'application/json'}],
    //tokenGetter: (() => storage.get('id_token').then((val)=>{return val}) ),
    tokenGetter: (() => JSON.parse(window.localStorage.getItem("id_token"))),
    noJwtError: true,
    headerPrefix: "JWT",
  }), http);
}

As far as I can tell, the auth0 sdk is not using Ionic storage to store the id_token anyway... it's just using window.localStorage, so you might as well just use that too and its a synchronous method so avoids this promise stuff.


问:
Create Hyperlink for row each entry in Excel Sheet but just in specific columns
In the attached code, I am looping through all the Excel files in a folder and searching for a keyword.  I then extract the file name, sheet number, cell number and row data and place that information into a newly created spreadsheet called "Summary".  How do I hyperlink just the worksheet # and cell # columns (Columns B and C) to point to the exact file, page, cell where the newly created row entry came from?

Here is a snippet of my code:

```<code> Sub SearchFolders()
'UpdatebySUPERtoolsforExcel2016
 ...
    Dim xOut As Worksheet
    Dim xWb As Workbook
    Dim xWk As Worksheet
    Dim xRow As Long
    Dim xFound As Range
    Dim xStrAddress As String
    Dim xCount As Long
    Set xFileDialog = Application.FileDialog(msoFileDialogFolderPicker)
    xFileDialog.AllowMultiSelect = False
    xFileDialog.Title = "Select a forlder"
    If xFileDialog.Show = -1 Then
        xStrPath = xFileDialog.SelectedItems(1)
    End If
  ...
    xUpdate = Application.ScreenUpdating
    Application.ScreenUpdating = False
    Set xOut = wsReport
    xRow = 1
    With xOut
        .Cells(xRow, 1) = "Workbook"
        .Cells(xRow, 2) = "Worksheet"
        .Cells(xRow, 3) = "Cell"
        .Cells(xRow, 4) = "Test"
        ...
        Set xFso = CreateObject("Scripting.FileSystemObject")
        Set xFld = xFso.GetFolder(xStrPath)
        xStrFile = Dir(xStrPath & "\*.xlsx")
        Do While xStrFile <> ""
            Set xWb = Workbooks.Open(Filename:=xStrPath & "\" & xStrFile, UpdateLinks:=0, ReadOnly:=True, AddToMRU:=False)
            For Each xWk In xWb.Worksheets
                Set xFound = xWk.UsedRange.Find(xStrSearch, LookIn:=xlValues)
                If Not xFound Is Nothing Then
                    xStrAddress = xFound.Address
                End If
                Do
                    If xFound Is Nothing Then
                        Exit Do
                    Else

                    xCount = xCount + 1
                    xRow = xRow + 1
                    .Cells(xRow, 1) = xWb.Name
                    .Cells(xRow, 2) = xWk.Name
                    .Cells(xRow, 3) = xFound.Address
                     WriteDetails rCellwsReport, xFound

                    End If
                    Set xFound = xWk.Cells.FindNext(After:=xFound)
                Loop While xStrAddress <> xFound.Address
            Next
            xWb.Close (False)
            xStrFile = Dir
        Loop
        .Columns("A:I").EntireColumn.AutoFit
        .Range("A1:A" & xCount + 1).Rows.EntireRow.AutoFit
    End With

    MsgBox xCount & "cells have been found", , "SUPERtools for Excel"
ExitHandler:
    Set xOut = Nothing
    ...
    Application.ScreenUpdating = xUpdate
    Exit Sub
ErrHandler:
    MsgBox Err.Description, vbExclamation
    Resume ExitHandler
End Sub

Private Sub WriteDetails(ByRef xReceiver As Range, ByRef xDonor As Range)
  xReceiver.Value = xDonor.Parent.Name
  xReceiver.Offset(, 1).Value = xDonor.Address

  xDonor.EntireRow.Resize(, 100).Copy xReceiver.Offset(, 2)

  Set xReceiver = xReceiver.Offset(1)

End Sub
</code>```

答:
To create a hyperlink to an external workbook/worksheet/cell you need to understand how the link forms

See this example

Let's say you have a file Joe.Xlsx in C:\. And let's assume that it has a worksheet called Sheet1 and you want to hyperlink to cell A1 of that sheet.

So in your current workbook, you will type

```<code>=HYPERLINK("[C:\Joe.xlsx]Sheet1!A1","CLICK HERE")
</code>```

So if you break it, it will look like this.

```<code>Dim FileName As String
Dim SheetName As String
Dim CellAddress As String

FileName = "C:\Joe.xlsx"
SheetName = "Sheet1"
CellAddress = "A1"

If InStr(1, SheetName, " ") Then SheetName = "'" & SheetName & "'"

Range("A1").Formula = "=HYPERLINK(" & Chr(34) & "[" & _
                      FileName & _
                      "]" & _
                      SheetName & _
                      "!" & _
                      CellAddress & _
                      Chr(34) & "," & Chr(34) & _
                      "CLICK HERE" & Chr(34) & ")"
</code>```

Simply use this in your code in a loop and create the hyperlinks

Body:
In the attached code, I am looping through all the Excel files in a folder and searching for a keyword.  I then extract the file name, sheet number, cell number and row data and place that information into a newly created spreadsheet called "Summary".  How do I hyperlink just the worksheet # and cell # columns (Columns B and C) to point to the exact file, page, cell where the newly created row entry came from?

Here is a snippet of my code:

 Sub SearchFolders()
'UpdatebySUPERtoolsforExcel2016
 ...
    Dim xOut As Worksheet
    Dim xWb As Workbook
    Dim xWk As Worksheet
    Dim xRow As Long
    Dim xFound As Range
    Dim xStrAddress As String
    Dim xCount As Long
    Set xFileDialog = Application.FileDialog(msoFileDialogFolderPicker)
    xFileDialog.AllowMultiSelect = False
    xFileDialog.Title = "Select a forlder"
    If xFileDialog.Show = -1 Then
        xStrPath = xFileDialog.SelectedItems(1)
    End If
  ...
    xUpdate = Application.ScreenUpdating
    Application.ScreenUpdating = False
    Set xOut = wsReport
    xRow = 1
    With xOut
        .Cells(xRow, 1) = "Workbook"
        .Cells(xRow, 2) = "Worksheet"
        .Cells(xRow, 3) = "Cell"
        .Cells(xRow, 4) = "Test"
        ...
        Set xFso = CreateObject("Scripting.FileSystemObject")
        Set xFld = xFso.GetFolder(xStrPath)
        xStrFile = Dir(xStrPath & "\*.xlsx")
        Do While xStrFile <> ""
            Set xWb = Workbooks.Open(Filename:=xStrPath & "\" & xStrFile, UpdateLinks:=0, ReadOnly:=True, AddToMRU:=False)
            For Each xWk In xWb.Worksheets
                Set xFound = xWk.UsedRange.Find(xStrSearch, LookIn:=xlValues)
                If Not xFound Is Nothing Then
                    xStrAddress = xFound.Address
                End If
                Do
                    If xFound Is Nothing Then
                        Exit Do
                    Else

                    xCount = xCount + 1
                    xRow = xRow + 1
                    .Cells(xRow, 1) = xWb.Name
                    .Cells(xRow, 2) = xWk.Name
                    .Cells(xRow, 3) = xFound.Address
                     WriteDetails rCellwsReport, xFound

                    End If
                    Set xFound = xWk.Cells.FindNext(After:=xFound)
                Loop While xStrAddress <> xFound.Address
            Next
            xWb.Close (False)
            xStrFile = Dir
        Loop
        .Columns("A:I").EntireColumn.AutoFit
        .Range("A1:A" & xCount + 1).Rows.EntireRow.AutoFit
    End With

    MsgBox xCount & "cells have been found", , "SUPERtools for Excel"
ExitHandler:
    Set xOut = Nothing
    ...
    Application.ScreenUpdating = xUpdate
    Exit Sub
ErrHandler:
    MsgBox Err.Description, vbExclamation
    Resume ExitHandler
End Sub

Private Sub WriteDetails(ByRef xReceiver As Range, ByRef xDonor As Range)
  xReceiver.Value = xDonor.Parent.Name
  xReceiver.Offset(, 1).Value = xDonor.Address

  xDonor.EntireRow.Resize(, 100).Copy xReceiver.Offset(, 2)

  Set xReceiver = xReceiver.Offset(1)

End Sub

Body:
To create a hyperlink to an external workbook/worksheet/cell you need to understand how the link forms

See this example

Let's say you have a file Joe.Xlsx in C:\. And let's assume that it has a worksheet called Sheet1 and you want to hyperlink to cell A1 of that sheet.

So in your current workbook, you will type

=HYPERLINK("[C:\Joe.xlsx]Sheet1!A1","CLICK HERE")

So if you break it, it will look like this.

Dim FileName As String
Dim SheetName As String
Dim CellAddress As String

FileName = "C:\Joe.xlsx"
SheetName = "Sheet1"
CellAddress = "A1"

If InStr(1, SheetName, " ") Then SheetName = "'" & SheetName & "'"

Range("A1").Formula = "=HYPERLINK(" & Chr(34) & "[" & _
                      FileName & _
                      "]" & _
                      SheetName & _
                      "!" & _
                      CellAddress & _
                      Chr(34) & "," & Chr(34) & _
                      "CLICK HERE" & Chr(34) & ")"

Simply use this in your code in a loop and create the hyperlinks


问:
onclick function not executing to change image
In the following codepen I'm trying to change the image of an image with id="chrome" using JavaScript but it does not appear to be doing anything. What am I doing wrong and how do I fix. Thank you in advanced.

The first image has an id of chrome and when clicked I'm trying to change the image.

https://codepen.io/centem/pen/NgKEmG

Here is the js I'm using.

```<code>function changeImage() {

    if (document.getElementById("chrome").src == "https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png")
    {
        document.getElementById("chrome").src = "https://www.centerpointe.com/v2/wp-content/uploads/2014/01/red-x.png";
    }
    else
    {
        document.getElementById("chrome").src = "https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png";
    }
}
</code>```

Basically, for the first row that has an chrome icon I would like to change it to an x image upon click.

答: Change  to

Body:
In the following codepen I'm trying to change the image of an image with id="chrome" using JavaScript but it does not appear to be doing anything. What am I doing wrong and how do I fix. Thank you in advanced.

The first image has an id of chrome and when clicked I'm trying to change the image.

https://codepen.io/centem/pen/NgKEmG

Here is the js I'm using.

function changeImage() {

    if (document.getElementById("chrome").src == "https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png")
    {
        document.getElementById("chrome").src = "https://www.centerpointe.com/v2/wp-content/uploads/2014/01/red-x.png";
    }
    else
    {
        document.getElementById("chrome").src = "https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png";
    }
}

Basically, for the first row that has an chrome icon I would like to change it to an x image upon click.

Body: Change <img onclick()="changeImage()"> to <img onclick="changeImage()">


问:
sql server 2000 backup directly to a separate server
SQL Server 2000 on Windows Server 2003.

I am trying to run a backup, from within EM, directly over to another server, as follows:

backup database AbraEmployeeSelfService
to disk = '\\servername\f$\Backup\myDB_backup.bak'

I get this error:
Cannot open backup device '\\servername\f$\Backup\myDB_backup.bak'.
Device error or device off-line. See the SQL Server error log for more details.
Msg 3013, Level 16, State 1, Line 1
BACKUP DATABASE is terminating abnormally.

The error log shows this message:
BackupDiskFile::CreateMedia: Backup device '\\servername\f$\Backup\myDB_backup.bak' failed to create. Operating system error = 5(Access is denied.).

I am running the command using a windows login that has full rights on the destination path. At least, from my desktop I can open a run window, enter \\servername\f$\Backup, and in the resulting Explorer window I can add/edit/delete files in that directory.

What do I need to do to get past that access denial?

答: What user account is the MSSQLSERVER service running under? I believe LocalSystem is restricted and cannot access remote resources.</p>

LastEditorDisplayName: Oliver

OwnerDisplayName: hunterjrj


问:
What is the best kind of diagram to illustrate the workings of a semaphores / multiprocess / shared memory program?
I have made a small project in which I have used various processes / shared memory / semaphores.

I am now going to have to explain my code and the program logic to both my lecturer and a couple of colleagues.

I am thus wondering what kind of notation/diagrams do people usually use for depicting this kind of programs. Activity diagrams? Flowchart Diagrams? What else?

Thanks

答:
In my course threading issues are explained to us by using something like graphs, mark the critical points (more precisely the points where syncronization is need) and explained how do you solve the problem. It works really well this way if you mark the critical points for example:

```<code>          T1           T2            T3
        method A      method A       method A
               \         /             /
                \       /             /
                 critical    section 1
                  /
                 /
              method B
</code>```

and so on

Body:
In my course threading issues are explained to us by using something like graphs, mark the critical points (more precisely the points where syncronization is need) and explained how do you solve the problem. It works really well this way if you mark the critical points for example:

          T1           T2            T3
        method A      method A       method A
               \         /             /
                \       /             /
                 critical    section 1
                  /
                 /
              method B

and so on


问:
How can i pass multiple variables to my template in django?
Hey guys my files are organized as follows.

urls.py:

```<code>from django.conf.urls import url, include
from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^contact/', views.eurusd, name='eur'),
    url(r'^contact/', views.VaR, name='lol'),

]
</code>```

views.py:

```<code>from django.shortcuts import render
from django.http import HttpResponse

from yahoo_finance import Currency

def eurusd (request):
    eur_usd = Currency('EURUSD')
    eur = ('EUR/USD Bid/Ask Price:    ' +eur_usd.get_bid() +' /   '+eur_usd.get_ask())
    return render(request, 'personal/basic.html', {'eur': eur})

def VaR (request):
    hallo = "this is a python sting"
    return render(request, 'personal/basic.html', {'lol': hallo})
</code>```

basic.html

```<code>{% extends "personal/header.html" %}

{% block content %}
<p>{{eur}}</p>
<p>{{lol}}</p>
{% endblock %}
</code>```

My question now is:
why is only the string from eur dictionary being returned in my template named basic.html and not the lol?
how can i pass multiple variables to my basic.html?

答:
you just need one url pattern and with one function in your view, change your code to:

urls.py:

```<code>from django.conf.urls import url, include
from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^contact/', views.eurusd, name='eur'),
]
</code>```

views.py:

```<code>from django.shortcuts import render
from django.http import HttpResponse

from yahoo_finance import Currency

def eurusd(request):
    eur_usd = Currency('EURUSD')
    eur = ('EUR/USD Bid/Ask Price:    ' +eur_usd.get_bid() +' /   '+eur_usd.get_ask())
    hallo = "this is a python sting"
    return render(request, 'personal/basic.html', {'eur': eur,'lol': hallo})
</code>```

Body:
Hey guys my files are organized as follows.

urls.py:

from django.conf.urls import url, include
from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^contact/', views.eurusd, name='eur'),
    url(r'^contact/', views.VaR, name='lol'),

]

views.py:

from django.shortcuts import render
from django.http import HttpResponse

from yahoo_finance import Currency

def eurusd (request):
    eur_usd = Currency('EURUSD')
    eur = ('EUR/USD Bid/Ask Price:    ' +eur_usd.get_bid() +' /   '+eur_usd.get_ask())
    return render(request, 'personal/basic.html', {'eur': eur})

def VaR (request):
    hallo = "this is a python sting"
    return render(request, 'personal/basic.html', {'lol': hallo})

basic.html

{% extends "personal/header.html" %}

{% block content %}

{{eur}}

{{lol}}

{% endblock %}

My question now is:
why is only the string from eur dictionary being returned in my template named basic.html and not the lol?
how can i pass multiple variables to my basic.html?

Body:
you just need one url pattern and with one function in your view, change your code to:

urls.py:

from django.conf.urls import url, include
from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^contact/', views.eurusd, name='eur'),
]

views.py:

from django.shortcuts import render
from django.http import HttpResponse

from yahoo_finance import Currency

def eurusd(request):
    eur_usd = Currency('EURUSD')
    eur = ('EUR/USD Bid/Ask Price:    ' +eur_usd.get_bid() +' /   '+eur_usd.get_ask())
    hallo = "this is a python sting"
    return render(request, 'personal/basic.html', {'eur': eur,'lol': hallo})


问:
Unicode / Umlauts in urllib.request XML parsing
I’m struggling with urllib.request and unicode. I have a script that gets a list of city names, builds geonames.org API-request URLs from them and parses the output XML Data to display geonames information exactly in the way I need it. The script works fine as long as the cities names don’t contain any non-ASCII character like ö in Köln (I have to use german city names).

```<code># -*- coding: utf-8 -*-
import urllib.request
from xml.etree import ElementTree as ET

urllist = []
citylist = ['Hamburg', 'Bremen']

for city in citylist:
    requestURL = 'http://api.geonames.org/search?name=' + city + '&maxRows=1&lang=de&username=demo'
    urllist.append(requestURL)

for url in urllist:
    root = ET.parse(urllib.request.urlopen(url)).getroot()
    items = root.findall('geoname')
    for item in items:
        print(item.find('name').text + ', ' + item.find('countryName').text + ' [' + item.find('lat').text + ',' + item.find('lng').text + '] [id:' + item.find('geonameId').text + ']')
</code>```

When I switch Hamburg with Köln the Script exits with the error message UnicodeEncodeError: 'ascii' codec can't encode character '\xf6' in position 18: ordinal not in range(128).

One other thing that does not work is city names with blanks in it like Bad Godesberg. Am I using the wrong method to request the XML or is it that I have to decode my city names before building the URL (which is nearly definitely the case for two-word cities as when I use Bad%20Godesberg it works)?

Thanks for your help!

答:
You have to use urlencode, for instance

Python » Documentation 21.8.4. URL Quoting

Here is an example session that uses the GET method to retrieve a URL containing parameters:

    urllib-examples

```<code>   >>> import urllib.request
   >>> import urllib.parse
   >>> params = urllib.parse.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
   >>> url = "http://www.musi-cal.com/cgi-bin/query?%s" % params
   >>> with urllib.request.urlopen(url) as f:
           print(f.read().decode('utf-8'))
</code>```

Body:
I’m struggling with urllib.request and unicode. I have a script that gets a list of city names, builds geonames.org API-request URLs from them and parses the output XML Data to display geonames information exactly in the way I need it. The script works fine as long as the cities names don’t contain any non-ASCII character like ö in Köln (I have to use german city names).

# -*- coding: utf-8 -*-
import urllib.request
from xml.etree import ElementTree as ET

urllist = []
citylist = ['Hamburg', 'Bremen']

for city in citylist:
    requestURL = 'http://api.geonames.org/search?name=' + city + '&maxRows=1&lang=de&username=demo'
    urllist.append(requestURL)

for url in urllist:
    root = ET.parse(urllib.request.urlopen(url)).getroot()
    items = root.findall('geoname')
    for item in items:
        print(item.find('name').text + ', ' + item.find('countryName').text + ' [' + item.find('lat').text + ',' + item.find('lng').text + '] [id:' + item.find('geonameId').text + ']')

When I switch Hamburg with Köln the Script exits with the error message UnicodeEncodeError: 'ascii' codec can't encode character '\xf6' in position 18: ordinal not in range(128).

One other thing that does not work is city names with blanks in it like Bad Godesberg. Am I using the wrong method to request the XML or is it that I have to decode my city names before building the URL (which is nearly definitely the case for two-word cities as when I use Bad%20Godesberg it works)?

Thanks for your help!

Body:
You have to use urlencode, for instance

Python » Documentation 21.8.4. URL Quoting

Here is an example session that uses the GET method to retrieve a URL containing parameters:

    urllib-examples

   >>> import urllib.request
   >>> import urllib.parse
   >>> params = urllib.parse.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
   >>> url = "http://www.musi-cal.com/cgi-bin/query?%s" % params
   >>> with urllib.request.urlopen(url) as f:
           print(f.read().decode('utf-8'))


问:
RecyclerView.ViewHolder On Click Items
I'm working with RecyclerView (Xamarin.Android) on Visual Studio 2017, this is my first Xamarin project since I'm a native Android developer, and I'm kinda confused respect to implementing the On Items Clicks events on the Recycler View. I just created the RecyclerView.Adapter using the default template that the IDE provides (RecyclerAdapter class), it looks a lot like the native implementation:

Here my Code:

```<code>using System;
using Android.Views;
using Android.Widget;
using Android.Support.V7.Widget;

namespace Airlink
{
    class PdfAdapter : RecyclerView.Adapter
    {
        public event EventHandler<PdfAdapterClickEventArgs> ItemClick;
        public event EventHandler<PdfAdapterClickEventArgs> ItemLongClick;
        Pdf[] items;

        public PdfAdapter(Pdf[] data)
        {
            items = data;
        }

        // Create new views (invoked by the layout manager)
        public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup
        parent, int viewType)
        {

            //Setup your layout here
            View itemView = null;
            //var id = Resource.Layout.__YOUR_ITEM_HERE;
            itemView=LayoutInflater.From(parent.Context).
            Inflate(Resource.Layout.pdf_item, parent, false);

            var vh = new PdfAdapterViewHolder(itemView, OnClick,
            OnLongClick);
            return vh;
        }

        // Replace the contents of a view (invoked by the layout manager)
        public override void OnBindViewHolder(RecyclerView.ViewHolder
        viewHolder, int position)
        {
            var item = items[position];

            // Replace the contents of the view with that element
            PdfAdapterViewHolder holder = viewHolder as
            PdfAdapterViewHolder;
            holder.pdf_name.Text = items[position].Name;
        }

        public override int ItemCount => items.Length;

        void OnClick(PdfAdapterClickEventArgs args) =>
        ItemClick?.Invoke(this, args);
        void OnLongClick(PdfAdapterClickEventArgs args) =>
        ItemLongClick?.Invoke(this, args);

    }

    public class PdfAdapterViewHolder : RecyclerView.ViewHolder
    {
        public TextView pdf_name { get; set; }

        public PdfAdapterViewHolder(View itemView,
            Action<PdfAdapterClickEventArgs> clickListener,
            Action<PdfAdapterClickEventArgs> longClickListener) :
        base(itemView)
        {
            pdf_name = itemView.FindViewById<TextView>
            (Resource.Id.pdf_name);
            itemView.Click += (sender, e) => clickListener(new
            PdfAdapterClickEventArgs { View = itemView, Position =
            AdapterPosition });
            itemView.LongClick += (sender, e) => longClickListener(new
            PdfAdapterClickEventArgs { View = itemView, Position =
            AdapterPosition });
        }
    }

    public class PdfAdapterClickEventArgs : EventArgs
    {
        public View View { get; set; }
        public int Position { get; set; }

    }
}
</code>```

So, given my code, I just want to know where I can handle the clicked View, I'm not sure if I have to implement some code on the PdfAdapterClickEventArgs Class or on the OnClick and OnLongClick voids that receive the PdfAdapterClickEventArgs object, let's say I want to show a Toast showing the name of the TextView inside the View clicked. I use to handle this action on native Android using:

```<code>  view.setOnClickListener(new View.OnClickListener() {

      @Override
      public void onClick(View v) {

         //my code here
      }
  }
</code>```

inside the ViewHolder constructor method.

I mean, I can change the default C# implementation in order to get something similar to the snippet above, but I would like to keep the original C# code.

答:
You will implement your OnClick event handler in the Activity/Fragment where instance of your Adapter is created.

This line means you are making the ItemClick event public in your adapter class.

```<code>public event EventHandler<PdfAdapterClickEventArgs> ItemClick;
</code>```

So you are now able to do this:

```<code>var adapter = new PdfAdapter(data);
adapter.ItemClick += OnItemClick;
   ....
   ....
myRecyclerView. SetAdapter(adapter);
</code>```

And you will have a method:

```<code>public void OnItemClick(object sender, PdfAdapterClickEventArgs e)
{
   var view = args.View; //this is your view
   Toast.MakeText(this, $"Item Position: {args?.Position}", ToastLength.Short).Show();
}
</code>```

Hope this helps.

Title: RecyclerView.ViewHolder On Click Items

Body:
I'm working with RecyclerView (Xamarin.Android) on Visual Studio 2017, this is my first Xamarin project since I'm a native Android developer, and I'm kinda confused respect to implementing the On Items Clicks events on the Recycler View. I just created the RecyclerView.Adapter using the default template that the IDE provides (RecyclerAdapter class), it looks a lot like the native implementation:

Here my Code:

using System;
using Android.Views;
using Android.Widget;
using Android.Support.V7.Widget;

namespace Airlink
{
    class PdfAdapter : RecyclerView.Adapter
    {
        public event EventHandler<PdfAdapterClickEventArgs> ItemClick;
        public event EventHandler<PdfAdapterClickEventArgs> ItemLongClick;
        Pdf[] items;

        public PdfAdapter(Pdf[] data)
        {
            items = data;
        }

        // Create new views (invoked by the layout manager)
        public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup
        parent, int viewType)
        {

            //Setup your layout here
            View itemView = null;
            //var id = Resource.Layout.__YOUR_ITEM_HERE;
            itemView=LayoutInflater.From(parent.Context).
            Inflate(Resource.Layout.pdf_item, parent, false);

            var vh = new PdfAdapterViewHolder(itemView, OnClick,
            OnLongClick);
            return vh;
        }

        // Replace the contents of a view (invoked by the layout manager)
        public override void OnBindViewHolder(RecyclerView.ViewHolder
        viewHolder, int position)
        {
            var item = items[position];

            // Replace the contents of the view with that element
            PdfAdapterViewHolder holder = viewHolder as
            PdfAdapterViewHolder;
            holder.pdf_name.Text = items[position].Name;
        }

        public override int ItemCount => items.Length;

        void OnClick(PdfAdapterClickEventArgs args) =>
        ItemClick?.Invoke(this, args);
        void OnLongClick(PdfAdapterClickEventArgs args) =>
        ItemLongClick?.Invoke(this, args);

    }

    public class PdfAdapterViewHolder : RecyclerView.ViewHolder
    {
        public TextView pdf_name { get; set; }

        public PdfAdapterViewHolder(View itemView,
            Action<PdfAdapterClickEventArgs> clickListener,
            Action<PdfAdapterClickEventArgs> longClickListener) :
        base(itemView)
        {
            pdf_name = itemView.FindViewById<TextView>
            (Resource.Id.pdf_name);
            itemView.Click += (sender, e) => clickListener(new
            PdfAdapterClickEventArgs { View = itemView, Position =
            AdapterPosition });
            itemView.LongClick += (sender, e) => longClickListener(new
            PdfAdapterClickEventArgs { View = itemView, Position =
            AdapterPosition });
        }
    }

    public class PdfAdapterClickEventArgs : EventArgs
    {
        public View View { get; set; }
        public int Position { get; set; }

    }
}

So, given my code, I just want to know where I can handle the clicked View, I'm not sure if I have to implement some code on the PdfAdapterClickEventArgs Class or on the OnClick and OnLongClick voids that receive the PdfAdapterClickEventArgs object, let's say I want to show a Toast showing the name of the TextView inside the View clicked. I use to handle this action on native Android using:

  view.setOnClickListener(new View.OnClickListener() {

      @Override
      public void onClick(View v) {

         //my code here
      }
  }

inside the ViewHolder constructor method.

I mean, I can change the default C# implementation in order to get something similar to the snippet above, but I would like to keep the original C# code.

Body:
You will implement your OnClick event handler in the Activity/Fragment where instance of your Adapter is created.

This line means you are making the ItemClick event public in your adapter class.

public event EventHandler<PdfAdapterClickEventArgs> ItemClick;

So you are now able to do this:

var adapter = new PdfAdapter(data);
adapter.ItemClick += OnItemClick;
   ....
   ....
myRecyclerView. SetAdapter(adapter);

And you will have a method:

public void OnItemClick(object sender, PdfAdapterClickEventArgs e)
{
   var view = args.View; //this is your view
   Toast.MakeText(this, $"Item Position: {args?.Position}", ToastLength.Short).Show();
}

Hope this helps.