问:
Modal not popping up on link click
I need to pop up a modal dialog on clicking a link. I have scanned related questions and followed similar instructions,however, none of the solutions seem to work.
Picture below is how my page looks like. Clicking on "Update" should open a modal window.

Here is my EJS file.

<!DOCTYPE html>

  <meta charset="UTF8">

  <link href="javascripts/frontend.js">
  <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
  <link href="/stylesheets/userlist.css" rel="stylesheet">
  <link href='//fonts.googleapis.com/css?family=Amatic SC' rel='stylesheet'>
  <link href='//fonts.googleapis.com/css?family=NTR' rel='stylesheet'>

  <title>Userlist</title>

FORM

      <form action="/users/add_user" class="form-horizontal" id="user_form" method="post" name="user_form">
        <fieldset>

            Name :

              <input class="form-control input-md" id="nameinput" name="name" onfocus="if (this.value=='Name') this.value='';" placeholder="Enter Username" type="text" value="Name">

            Age :

              <input class="form-control input-md" id="ageinput" name="age" placeholder="Enter Age" type="number">

              <button class="btn btn-success" id="singlebutton" type="submit">Add User</button>

        </fieldset>
      </form>

USERS

          <%for(var i=0; i<userlist.length; i++) {%>

                <button aria-label="Close" class="close" data-dismiss="modal" type="button">×</button>

Edit :

                HEY!!

                <button class="btn btn-default" data-dismiss="modal" type="button">Close</button> <button class="btn btn-primary" type="button">Save changes</button>

          <%= userlist[i].name %>:
            <%= userlist[i].age %> " href="#" id="delete" title="Delete this User">Delete || ">Update

        <%} %>

```

I am using bootstrap 3.2.0 and have included jquery before bootstrap.

答:
simply you used submit button

```<code><button class="btn btn-success" id="singlebutton" type="submit"><b>Add User</b></button>
</code>```

which will submit your form or at least will refresh the page

change it to button and it will be okay

```<code><button class="btn btn-success" id="singlebutton" type="button"><b>Add User</b></button>
</code>```

Title: Modal not popping up on link click

Body:
I need to pop up a modal dialog on clicking a link. I have scanned related questions and followed similar instructions,however, none of the solutions seem to work.
Picture below is how my page looks like. Clicking on "Update" should open a modal window.

Here is my EJS file.

<!DOCTYPE html>

  <meta charset="UTF8">

  <link href="javascripts/frontend.js">
  <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
  <link href="/stylesheets/userlist.css" rel="stylesheet">
  <link href='//fonts.googleapis.com/css?family=Amatic SC' rel='stylesheet'>
  <link href='//fonts.googleapis.com/css?family=NTR' rel='stylesheet'>

  <title>Userlist</title>

FORM

      <form action="/users/add_user" class="form-horizontal" id="user_form" method="post" name="user_form">
        <fieldset>

            Name :

              <input class="form-control input-md" id="nameinput" name="name" onfocus="if (this.value=='Name') this.value='';" placeholder="Enter Username" type="text" value="Name">

            Age :

              <input class="form-control input-md" id="ageinput" name="age" placeholder="Enter Age" type="number">

              <button class="btn btn-success" id="singlebutton" type="submit">Add User</button>

        </fieldset>
      </form>

USERS

          <%for(var i=0; i<userlist.length; i++) {%>

                <button aria-label="Close" class="close" data-dismiss="modal" type="button">×</button>

Edit :

                HEY!!

                <button class="btn btn-default" data-dismiss="modal" type="button">Close</button> <button class="btn btn-primary" type="button">Save changes</button>

          <%= userlist[i].name %>:
            <%= userlist[i].age %> <a class="delete_user" data-id="<%= userlist[i]._id %>" href="#" id="delete" title="Delete this User">Delete || <a href="#openModal" class="update_user" data-target="#openModal" data-toggle="modal" id="update" title="Update user info"
                data-id="<%= userlist[i]._id %>">Update

        <%} %>

I am using bootstrap 3.2.0 and have included jquery before bootstrap.

Body:
simply you used submit button

<button class="btn btn-success" id="singlebutton" type="submit"><b>Add User</b></button>

which will submit your form or at least will refresh the page

change it to button and it will be okay

<button class="btn btn-success" id="singlebutton" type="button"><b>Add User</b></button>


来源: stackexchange

问:
Echo only unique values
I've got an XML file that prints out press releases. I want to echo all the years when the press releases have been released, like an archive. Only unique values. The code below prints out all the years. Like "2017,2017,2017,2016,2016,2015,2015,2014" other than "2017,2016,2015,2014,2013".</p>

```<code><?php
$file = "file.xml";
$xml = simplexml_load_file($file);

foreach ($xml->Release as $release) {
   $date = $release['PublishDateUtc']; /* $date is now in format yyyy-mm-ddT06:30:00 */
   $year = substr($date, 0, 4);
   echo $year;
}

?>
</code>```

答:
Try This

```<code><?php
$file        = "file.xml";
$xml         = simplexml_load_file($file);
$yearArray   = array();
$uniqueArray = array();
foreach ($xml->Release as $release) {
    $date        = $release['PublishDateUtc'];
    /* $date is now in format yyyy-mm-ddT06:30:00 */
    $year        = substr($date, 0, 4);
    $yearArray[] = $year;
}

$uniqueArray = array_unique($yearArray);
print_r($uniqueArray);
?>
</code>```

initialized 2 extra variables and make array of years inside loop.then printed unique array.

ContentLicense: CC BY-SA 3.0

Title: Echo only unique values

Body:
I've got an XML file that prints out press releases. I want to echo all the years when the press releases have been released, like an archive. Only unique values. The code below prints out all the years. Like "2017,2017,2017,2016,2016,2015,2015,2014" other than "2017,2016,2015,2014,2013".

<?php
$file = "file.xml";
$xml = simplexml_load_file($file);

foreach ($xml->Release as $release) {
   $date = $release['PublishDateUtc']; /* $date is now in format yyyy-mm-ddT06:30:00 */
   $year = substr($date, 0, 4);
   echo $year;
}

?>

Body:
Try This

<?php
$file        = "file.xml";
$xml         = simplexml_load_file($file);
$yearArray   = array();
$uniqueArray = array();
foreach ($xml->Release as $release) {
    $date        = $release['PublishDateUtc'];
    /* $date is now in format yyyy-mm-ddT06:30:00 */
    $year        = substr($date, 0, 4);
    $yearArray[] = $year;
}

$uniqueArray = array_unique($yearArray);
print_r($uniqueArray);
?>

initialized 2 extra variables and make array of years inside loop.then printed unique array.


问:
Moment js date time comparison
I'm using moment.js to format my date time, here I have two date values, and I want to achieve a particular function when one date is greater than the other. I read most of their docs, but didn't find the function to achieve this. I know it will be there.

This is my code:

```<code>var date_time = 2013-03-24 + 'T' + 10:15:20:12 + 'Z'
var d = moment(date_time).tz('UTC'); // first date

var now = new Date(),
    dnow = moment(now).tz('UTC'),
    snow = dnow.minute() % 15,
    diffnow = 15 - snow,
    tonow = moment(dnow).add('minute', diffnow),
    ahead30now = moment(tonow).add('minute', 30);

if (d > ahead30now) {
    // allow input time
    console.log('UTC TIME DB', d.format());
} else {

}
</code>```

Edit

```<code>var date_time = req.body.date + 'T' + req.body.time + req.body.timezone; // 2014-03-24T01:15:000
var utc_input_time = moment(date_time).utc(); // 2014-03-24T01:15:000
console.log('utc converted date_time', moment(date_time).utc().format("YYYY-MM-DDTHH:mm:SSS"));
var isafter = moment(utc_input_time).isAfter(moment('2014-03-24T01:14:000')); // true
if(isafter === true){
    console.log('is after true');
} else {
    console.log('is after is false');
}
</code>```

Here, I am comparing two dates i.e. 2014-03-24T01:15:000 > 2014-03-24T01:14:000, expecting that the first one is greater than the second one, but it always goes to the else condition. I don't know why?

答:
pass date to moment like this it will compare and give result.
if you dont want format remove it</p>

```<code>moment(Date1).format("YYYY-MM-DD") > moment(Date2).format("YYYY-MM-DD")
</code>```

ContentLicense: CC BY-SA 4.0

Title: Moment js date time comparison

Body:
I'm using moment.js to format my date time, here I have two date values, and I want to achieve a particular function when one date is greater than the other. I read most of their docs, but didn't find the function to achieve this. I know it will be there.

This is my code:

var date_time = 2013-03-24 + 'T' + 10:15:20:12 + 'Z'
var d = moment(date_time).tz('UTC'); // first date

var now = new Date(),
    dnow = moment(now).tz('UTC'),
    snow = dnow.minute() % 15,
    diffnow = 15 - snow,
    tonow = moment(dnow).add('minute', diffnow),
    ahead30now = moment(tonow).add('minute', 30);

if (d > ahead30now) {
    // allow input time
    console.log('UTC TIME DB', d.format());
} else {

}

Edit

var date_time = req.body.date + 'T' + req.body.time + req.body.timezone; // 2014-03-24T01:15:000
var utc_input_time = moment(date_time).utc(); // 2014-03-24T01:15:000
console.log('utc converted date_time', moment(date_time).utc().format("YYYY-MM-DDTHH:mm:SSS"));
var isafter = moment(utc_input_time).isAfter(moment('2014-03-24T01:14:000')); // true
if(isafter === true){
    console.log('is after true');
} else {
    console.log('is after is false');
}

Here, I am comparing two dates i.e. 2014-03-24T01:15:000 > 2014-03-24T01:14:000, expecting that the first one is greater than the second one, but it always goes to the else condition. I don't know why?

Body:
pass date to moment like this it will compare and give result.
if you dont want format remove it

moment(Date1).format("YYYY-MM-DD") > moment(Date2).format("YYYY-MM-DD")


问:
How do you count the elements of an array in java
Say i have the array

```<code>int theArray = new int[20];
</code>```

The length of the array is 20 but the count is 0. How can i get the count?

答:
```<code>int theArray[] = new int[20];
System.out.println(theArray.length);
</code>```

Body:
Say i have the array

int theArray = new int[20];

The length of the array is 20 but the count is 0. How can i get the count?

ContentLicense: CC BY-SA 2.5


问:
Vagrant: How to sync folder from guest back to host?
Why, because it is difficult to work and edit code via legacy editors in the guest. The whole purpose of vagrant is to be more easily for the developer, right:)?

As such I please someone to guide me in this situation:

Need to work on a project. It is git repo. Requires mysql, php, etc, etc.

VM works great(provided)

But editing files in this repo not so easy via ssh and "legacy" editors. Want to use favorite IDE.

On the VM repo is in /home/vagrant/src.
I want it to be visible/editable in ../src in the host.

I read the docs and putted this in the Vagranfile:

config.vm.synced_folder '../src', '/home/vagrant/src'

This "works" except that it overwrites all contents from /home/vagrant/src with those from ../src which is empty.

Any workaround?
I considered the possibility to clone the repo via git(publicly available via github) and sync the folder to the VM but this does not feel right and lose production configs too.

答:
You can use rsync with Vagrant, it has built-in support. Here is the link to the documentation. While it is trivial for rsync to ignore excessive files at target (probably the default behavior) you can still sync accurately by protecting your target files using protect filter.

Unlike mounting, rsync has to be triggered manually. However, you can still use Vagrant's rsync-auto feature documented here for a simple filesystem watch.


问:
Adding ng-model directive to dynamically created input tag using AngularJs
I am trying that on a button click, a div and and input tag are created and the input tag contain ng-model and the div has binding with that input.
Kindly suggest some solution.</p>

答:
You can create the div and input beforehand and and do not show it by using ng-if="myVar". On click make the ng-if="true".

<button ng-click="myVar = true">

In controller : $scope.myVar = false;


问:
Color in link tag doesn't work but color in div in link tag works?
Why doesn't this work (in terms of text color):

```<code>.navbarDivText {
    color: #DAA520;
}
.navbarDiv {
    width: 150px;
    background-color: inherit;
    margin-left: 10px;
}

<li class="navbarDiv" >
   <a href="index.php" class = "navbarDivText">Main Page</a>
</li>
</code>```

But this does:

```<code><li class="navbarDiv" >
   <a href="index.php">
     <div class = "navbarDivText">Main Page</div>
   </a>
 </li>
</code>```

答:
Works fine to me, clear cookies and try.

.navbarDivText {
  color: #DAA520;
}

.navbarDiv {
  width: 150px;
  background-color: green;
  margin-left: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><li class="navbarDiv">Main Page</li></code>```

Could do this as well,

```<code>.navbarDiv a, a:visited {
  color: #DAA520;
}
</code>```

or

```<code>.navbarDivText:link, .navbarDivText:visited {
  color: #DAA520;
}
</code>```

Body:
Why doesn't this work (in terms of text color):

.navbarDivText {
    color: #DAA520;
}
.navbarDiv {
    width: 150px;
    background-color: inherit;
    margin-left: 10px;
}

   Main Page

But this does:

Main Page

Body:
Works fine to me, clear cookies and try.

.navbarDivText {
  color: #DAA520;
}

.navbarDiv {
  width: 150px;
  background-color: green;
  margin-left: 10px;
}

<li class="navbarDiv"><a href="index.php" class="navbarDivText">Main Page</a></li>

Could do this as well,

.navbarDiv a, a:visited {
  color: #DAA520;
}

or

.navbarDivText:link, .navbarDivText:visited {
  color: #DAA520;
}


问:
Chaining transclusion in nested components
I have the following structure of nested components.

```<code><app-root>
    <app-comp-1>
      <app-comp-2>
      </app-comp-2>
   </app-comp-1>
  <app-root>
</code>```

I want to transclude any content into the last child (app-comp-2). So, I need something like this.

```<code><app-comp-1>
    <app-comp-2>
        <ng-content></ng-content>
    </app-comp-2>
</app-comp-1>
</code>```

But in the app-root component is available only the app-comp-1 component. So, this is the place where I have to transclude my contents.

```<code><app-root>
    <app-comp-1>
        <content-I-want-to-transclude></content-I-want-to-transclude>
    </app-comp-1>
</app-root>
 ---------------------------
<app-comp-1>
    <ng-content></ng-content>
    <app-comp-2>
        ...
    </app-comp-2>
</app-comp-1>
</code>```

So I need a solution to get the content that has been transcluded into the first component and pass it down to the second one.

Plunker

答:
I had a similar problem, whereby I have a card component, which has a child card-header component as well as a selector for the card body.

The card-header component has a toggle button that dispatches actions for which cards are open / closed.

I then needed the ability to pass extra buttons into the card-header component from the parent component via the card component

I solved it by adding selectors at each level.

First I created a common card-header component, allowing me to have a single piece of code that handled toggling card content by dispatching actions to the NgRx store, which holds an array of cards that are hidden (using the supplied name input property).

The card-header component subscribes to the store and emits an event to the parent component when the toggled status changes

```<code>@Component({
  selector: 'po-card-header',
  template: `
    <div class="card-header">

      <span class="text-uppercase">{{ header }}</span>

      <div class="header-controls">
        <ng-content select=[card-header-option]></ng-content>
        <ng-content select=[header-option]></ng-content>

        <span class="header-action" (click)="onTogglePanel()">
         <i class="fa" [ngClass]="{ 'fa-caret-up': !collapsed, 'fa-caret-down': collapsed}"></i>
        </span>

      </div>

    </div>
  `
})
export class CardHeaderComponent implements OnInit, OnDestroy {
  ...
  @Input() name: string;
  @Output() togglePanel = new EventEmitter<boolean>();

  collapsed$: Observable<boolean>;
  collapsedSub: Subscription;

  constructor(private store: Store<State>) {
    this.collapsed$ = this.store.select(state => getPanelCollapsed(state, this.name);
  }

  ngOnInit(): void {
    this.collapsedSub = this.collapsed$.subscribe(collapsed => {
      this.collapsed = collapsed;
      this.togglePanel.emit(collapsed);
    });
  }

  .... unsubscribe on destroy.
}
</code>```

Notice the header has 2 ng-content sections.

The header-option selector is for any other icons I want to add when I explicitly use this component e.g.

```<code><div class="card">

  <po-card-header>
    ...
    <span header-option class="fa fa-whatever" (click)="doSomething()"></span>
  </po-card-header>

  ...

</div>
</code>```

My new icon will sit alongside the default toggle icon in the header.

The second card-header-option selector is for root components, that use the card component, not the card-header component, but still want to pass extra icons into the header.

```<code>@Component({
  selector: 'po-card',
  template: `

    <div class="card">
      <po-card-header>
        ...
        <ng-content select="[card-header-option] header-option></ng-content>
      </po-card-header>

      <div class="card-block">
        <ng-content select="[card-body]"></ng-content>
      </div>

    </div>
  `
})
...
</code>```

The [card-header-option] selector will select any elements with that attribute, then pass them down into the card-header component using the header-option attribute

The final usage of my card component looks like this.

```<code><div>
   Some component that uses the card
   <po-card
     header="Some text to go in the card header"
     name="a-unique-name-for-the-card">

     <span card-header-option class='fa fa-blah header-action'></span>

     <div card-body>
       Some content that gets put inside the [card-body] selector on the card component.
     </div>

   </po-card>
</div>
</code>```

The final result is that I can use my custom card component, and get the benefits of the toggle functionality that the card-header component gives, but also supply my own custom actions, which will also get rendered in the header

Hope you find this helpful :-)

Body:
I have the following structure of nested components.

<app-root>
    <app-comp-1>
      <app-comp-2>
      </app-comp-2>
   </app-comp-1>
  <app-root>

I want to transclude any content into the last child (app-comp-2). So, I need something like this.

<app-comp-1>
    <app-comp-2>
        <ng-content></ng-content>
    </app-comp-2>
</app-comp-1>

But in the app-root component is available only the app-comp-1 component. So, this is the place where I have to transclude my contents.

<app-root>
    <app-comp-1>
        <content-I-want-to-transclude></content-I-want-to-transclude>
    </app-comp-1>
</app-root>
 ---------------------------
<app-comp-1>
    <ng-content></ng-content>
    <app-comp-2>
        ...
    </app-comp-2>
</app-comp-1>

So I need a solution to get the content that has been transcluded into the first component and pass it down to the second one.

Plunker

Body:
I had a similar problem, whereby I have a card component, which has a child card-header component as well as a selector for the card body.

The card-header component has a toggle button that dispatches actions for which cards are open / closed.

I then needed the ability to pass extra buttons into the card-header component from the parent component via the card component

I solved it by adding selectors at each level.

First I created a common card-header component, allowing me to have a single piece of code that handled toggling card content by dispatching actions to the NgRx store, which holds an array of cards that are hidden (using the supplied name input property).

The card-header component subscribes to the store and emits an event to the parent component when the toggled status changes

@Component({
  selector: 'po-card-header',
  template: `
    <div class="card-header">

      <span class="text-uppercase">{{ header }}</span>

      <div class="header-controls">
        <ng-content select=[card-header-option]></ng-content>
        <ng-content select=[header-option]></ng-content>

        <span class="header-action" (click)="onTogglePanel()">
         <i class="fa" [ngClass]="{ 'fa-caret-up': !collapsed, 'fa-caret-down': collapsed}"></i>
        </span>

      </div>

    </div>
  `
})
export class CardHeaderComponent implements OnInit, OnDestroy {
  ...
  @Input() name: string;
  @Output() togglePanel = new EventEmitter<boolean>();

  collapsed$: Observable<boolean>;
  collapsedSub: Subscription;

  constructor(private store: Store<State>) {
    this.collapsed$ = this.store.select(state => getPanelCollapsed(state, this.name);
  }

  ngOnInit(): void {
    this.collapsedSub = this.collapsed$.subscribe(collapsed => {
      this.collapsed = collapsed;
      this.togglePanel.emit(collapsed);
    });
  }

  .... unsubscribe on destroy.
}

Notice the header has 2 ng-content sections.

The header-option selector is for any other icons I want to add when I explicitly use this component e.g.

<div class="card">

  <po-card-header>
    ...
    <span header-option class="fa fa-whatever" (click)="doSomething()"></span>
  </po-card-header>

  ...

</div>

My new icon will sit alongside the default toggle icon in the header.

The second card-header-option selector is for root components, that use the card component, not the card-header component, but still want to pass extra icons into the header.

@Component({
  selector: 'po-card',
  template: `

    <div class="card">
      <po-card-header>
        ...
        <ng-content select="[card-header-option] header-option></ng-content>
      </po-card-header>

      <div class="card-block">
        <ng-content select="[card-body]"></ng-content>
      </div>

    </div>
  `
})
...

The [card-header-option] selector will select any elements with that attribute, then pass them down into the card-header component using the header-option attribute

The final usage of my card component looks like this.

<div>
   Some component that uses the card
   <po-card
     header="Some text to go in the card header"
     name="a-unique-name-for-the-card">

     <span card-header-option class='fa fa-blah header-action'></span>

     <div card-body>
       Some content that gets put inside the [card-body] selector on the card component.
     </div>

   </po-card>
</div>

The final result is that I can use my custom card component, and get the benefits of the toggle functionality that the card-header component gives, but also supply my own custom actions, which will also get rendered in the header

Hope you find this helpful :-)


问:
DOM not updating after data changes in vue.js
so I'm using vue.js to render in the DOM a list of items i'm fetching from a server using an AJAX call and then I loop through a template in my html to print the labels of these items. But the problem is that after successfully fetching the data AND adding it to the array the DOM doesn't update with the new items. Here's the js code :

```<code>$(".wrench").click(function ()
{
lastClickedWrench = $(this).attr('id');
console.log("uri :" + lastClickedWrench);
var renderToolbox = new Vue({

    el: "#renderToolbox",
    data: function()
    {
        return {
            listOfStuff: []
        }

    },

    mounted: function()
    {
        var vueInstance = this;
        $.ajax({
            type: 'GET',
            url: '/roles/' + lastClickedWrench,

            success: function(responseData)
            {
                for(let i = 0; i<responseData.length; i++)
                {
                    vueInstance.$set(vueInstance.listOfStuff, i, responseData[i].label);
                    //vueInstance.listOfStuff.splice(i, 1, responseData[i])
                }
                //vueInstance.listOfStuff = responseData;
                console.log(vueInstance.listOfStuff);  // this gives me the correct list
            },
            error: function(error)
            {
                console.log('error', error);
                alert("error" + JSON.stringify(error));
            }
        });
    }
    });
});
</code>```

All the commented out lines are solutions I tried from old stackoverflow posts which don't seem to work for me.
Here's the html template :

```<code><div id="renderToolbox">
     <template v-for="item in listOfStuff">
         <li class="dd-item" data-id="null">
            <div class="dd-handle">
                <span> {{item}} </span>
            </div>
          </li>
     </template>
</div>
</code>```

I also know about the caveat about the v-for directive which is mentioned in the documentation here : https://v2.vuejs.org/v2/guide/list.html#Caveats

I really tried everything, but nothing seems to work. Would appreciate any input on my problem.

答:
Replace this:

```<code>vueInstance.$set(vueInstance.listOfStuff, i, responseData[i].label);
</code>```

with:

```<code>this.listOfStuff.push({i:responseData[i].label})
</code>```

Body:
so I'm using vue.js to render in the DOM a list of items i'm fetching from a server using an AJAX call and then I loop through a template in my html to print the labels of these items. But the problem is that after successfully fetching the data AND adding it to the array the DOM doesn't update with the new items. Here's the js code :

$(".wrench").click(function ()
{
lastClickedWrench = $(this).attr('id');
console.log("uri :" + lastClickedWrench);
var renderToolbox = new Vue({

    el: "#renderToolbox",
    data: function()
    {
        return {
            listOfStuff: []
        }

    },

    mounted: function()
    {
        var vueInstance = this;
        $.ajax({
            type: 'GET',
            url: '/roles/' + lastClickedWrench,

            success: function(responseData)
            {
                for(let i = 0; i<responseData.length; i++)
                {
                    vueInstance.$set(vueInstance.listOfStuff, i, responseData[i].label);
                    //vueInstance.listOfStuff.splice(i, 1, responseData[i])
                }
                //vueInstance.listOfStuff = responseData;
                console.log(vueInstance.listOfStuff);  // this gives me the correct list
            },
            error: function(error)
            {
                console.log('error', error);
                alert("error" + JSON.stringify(error));
            }
        });
    }
    });
});

All the commented out lines are solutions I tried from old stackoverflow posts which don't seem to work for me.
Here's the html template :

     <template v-for="item in listOfStuff">

                 {{item}}

     </template>

I also know about the caveat about the v-for directive which is mentioned in the documentation here : https://v2.vuejs.org/v2/guide/list.html#Caveats

I really tried everything, but nothing seems to work. Would appreciate any input on my problem.

Body:
Replace this:

vueInstance.$set(vueInstance.listOfStuff, i, responseData[i].label);

with:

this.listOfStuff.push({i:responseData[i].label})


答: There is no built-in functionality for this. This count is in its whole user-specific. Maintain a counter or whatever.</p>

Title: How do you count the elements of an array in java


问:
TypeError: list indices must be integers, not _io.TextIOWrapper
I am trying to search for a certain number within a Text Document. It reads the file fine, and using the same code later can print fine, but when I tell it to find a  certain number in the Text Document it tells me TypeError: list indices must be integers, not _io.TextIOWrapper. I have looked all around but all questions say 'not str' whereas mine says 'not _io.TextIOWrapper'

This is my code (I am going down route 'A' under 'menuOptions'

```<code>import time
import linecache
print("Welcome to the League Fixture Manager!")
time.sleep(3)
print("What would you like to do?")
time.sleep(1)
print("Press A to search for a fixture.")
time.sleep(0.1)
print("Press B to view Outstanding fixtures.")
time.sleep(0.1)
print("Press C to display the leader board")
time.sleep(0.1)
print("Or press Q to quit, this will exit the application.")
time.sleep(0.1)
menuOptions = input("What would you like to do? A, B, C, or Q.")
if menuOptions == 'A':
    print("Please enter the fixture number you are looking for... ")
    fixtureQuestion = input(int())
    fixtureQuestion = int(fixtureQuestion)
    fixtureQuestion = fixtureQuestion - (1)
    time.sleep(3)
    if fixtureQuestion < 1:
        print("This fixture is not available, please re-run the application...")
        time.sleep(2)
        exit()
    elif fixtureQuestion > 190:
        print("This fixture is not available, please re-run the application...")
        time.sleep(2)
        exit()
    else:
        searchData = open("Y:\Computing & Business\Students\Computing\Year 10\CA 2017 Edexcel\\firesideFixtures.txt")
        lines = searchData.readlines()
        print(lines[searchData])
        time.sleep(1)
        print("Return to menu?")
        menuReturn = input("Y or N")
        if menuReturn == 'Y':
            print("Press B to view outstanding fixtures.")
            time.sleep(0.1)
            print("Press C to display the leaderboard")
            time.sleep(0.1)
            print("Or press Q to exit the application.")
            time.sleep(0.1)
            print("You cannot review the fixture list now you have seen it however you can scroll up to view it again.")
            time.sleep(0.1)
            menuOptions2 = input("What would you like to do? B, C, or Q?")
            if menuOptions2 == 'B':
                print("~~incomplete~~")
            elif menuOptions2 == 'C':
                print("~~incomplete~~")
            elif menuOptions2 == 'Q':
                print("Exiting Application...")
                time.sleep(1)
                exit()
        elif menuReturn == 'N':
            print("Exiting Application...")
            time.sleep(2)
            exit()
elif menuOptions == 'B':
    print("Searching for fixtures...")
    time.sleep(3)
    data = [line.strip() for line in open(r"Y:\Computing & Business\Students\Computing\Year 10\CA 2017 Edexcel\firesideFixtures.txt").readlines()]
    for line in data:
        print(line)
    time.sleep(1)
    print("Return to menu?")
    menuReturn = input("Y or N")
    if menuReturn == 'Y':
        print("Press A to search for a fixture")
        time.sleep(0.1)
        print("Press C to display the leaderboard")
        time.sleep(0.1)
        print("Or press Q to exit the application.")
        time.sleep(0.1)
        print("You cannot review the fixture list now you have seen it however you can scroll up to view it again.")
        time.sleep(0.1)
        menuOptions2 = input("What would you like to do? B, C, or Q?")
        if menuOptions2 == 'A':
            fixtureQuestion = input(int("Please enter the fixture number you are looking for... "))
            fixtureQuestion = fixtureQuestion - 1
            time.sleep(3)
            if fixtureQuestion < 1:
                print("This fixture is not available, please re-run the application...")
                time.sleep(2)
                exit()
            elif fixtureQuestion > 190:
                print("This fixture is not available, please re-run the application...")
                time.sleep(2)
                exit()
            else:
                searchData = open(r"Y:\Computing & Business\Students\Computing\Year 10\CA 2017 Edexcel\firesideFixtures.txt").readlines()
                lines = searchData.readlines()
                print(lines[fixtureQuestion])
                time.sleep(1)
                print("Return to menu?")
                menuReturn = input("Y or N")
                if menuReturn == 'Y':
                    print("Press C to display the leaderboard")
                    time.sleep(0.1)
                    print("Or press Q to exit the application.")
                    time.sleep(0.1)
                    print("You cannot review the fixture list now you have seen it however you can scroll up to view it again.")
                    time.sleep(0.1)
                    menuOptions2 = input("What would you like to do? B, C, or Q?")
                    if menuOptions2 == 'C':
                        print("~~incomplete~~")
                    elif menuOptions2 == 'Q':
                        print("Exiting Application...")
                        time.sleep(1)
                        exit()
                elif menuReturn == 'N':
                    print("Exiting Application...")
                    time.sleep(2)
                    exit()
                elif menuOptions2 == 'Q':
                    print("Exiting Application...")
                    time.sleep(1)
                    exit()
elif menuOptions == 'C':
    while RetryForC == "Yes":
        RetryForC == "No"
        fireRead = open("Y:\Computing & Business\Students\Computing\Year 10\CA 2017 Edexcel\firesideResults.txt")
        for line in fireRead:
            fireRead = open("Y:\Computing & Business\Students\Computing\Year 10\CA 2017 Edexcel\firesideResults.txt")
            InfoOne = line.split(',')[0]
            InfoTwo = line.split(',')[1]
            InfoThree = line.split(',')[2]
            InfoFour = line.split(',')[3]
            PointCounter = int(line.split(',')[2])
            PointCounter = PointCounter * 3
            fireRead.close()
            print("Player:",InfoOne,"Has played:",InfoTwo,", has won:",InfoThree,", has lost:",InfoFour,", and therefore has",PointCounter,"many points.")
        print("Retry?")
        RestForC = str(input("Yes/No  "))
    print("The program will now close...")
    time.sleep(5)
    exit()
elif menuOptions == 'Q':
    print("Exiting Applicaion...")
    time.sleep(2)
    exit()
</code>```

And this is my result:

```<code>Welcome to the League Fixture Manager!
What would you like to do?
Press A to search for a fixture.
Press B to view Outstanding fixtures.
Press C to display the leader board
Or press Q to quit, this will exit the application.
What would you like to do? A, B, C, or Q.A
Please enter the fixture number you are looking for...
016
Traceback (most recent call last):
  File "E:\Python\Python Work\League\League3.py", line 33, in <module>
    print(lines[searchData])
TypeError: list indices must be integers, not _io.TextIOWrapper
</code>```

What can I do to fix this?

答:
This line:

```<code>print(lines[searchData])
</code>```

Doesn't make any sense. Indices of a list must be integers, so you can do:

```<code>>>> my_list = [1, 2, 3]
>>> my_list[0]
1
</code>```

lines is a list which contains the lines of the file and search_data is a file object. It looks like you're missing some basic python concepts. Please do read the documentation I pasted in your other question you asked 10 minutes ago!

Body:
I am trying to search for a certain number within a Text Document. It reads the file fine, and using the same code later can print fine, but when I tell it to find a  certain number in the Text Document it tells me TypeError: list indices must be integers, not _io.TextIOWrapper. I have looked all around but all questions say 'not str' whereas mine says 'not _io.TextIOWrapper'

This is my code (I am going down route 'A' under 'menuOptions'

import time
import linecache
print("Welcome to the League Fixture Manager!")
time.sleep(3)
print("What would you like to do?")
time.sleep(1)
print("Press A to search for a fixture.")
time.sleep(0.1)
print("Press B to view Outstanding fixtures.")
time.sleep(0.1)
print("Press C to display the leader board")
time.sleep(0.1)
print("Or press Q to quit, this will exit the application.")
time.sleep(0.1)
menuOptions = input("What would you like to do? A, B, C, or Q.")
if menuOptions == 'A':
    print("Please enter the fixture number you are looking for... ")
    fixtureQuestion = input(int())
    fixtureQuestion = int(fixtureQuestion)
    fixtureQuestion = fixtureQuestion - (1)
    time.sleep(3)
    if fixtureQuestion < 1:
        print("This fixture is not available, please re-run the application...")
        time.sleep(2)
        exit()
    elif fixtureQuestion > 190:
        print("This fixture is not available, please re-run the application...")
        time.sleep(2)
        exit()
    else:
        searchData = open("Y:\Computing & Business\Students\Computing\Year 10\CA 2017 Edexcel\\firesideFixtures.txt")
        lines = searchData.readlines()
        print(lines[searchData])
        time.sleep(1)
        print("Return to menu?")
        menuReturn = input("Y or N")
        if menuReturn == 'Y':
            print("Press B to view outstanding fixtures.")
            time.sleep(0.1)
            print("Press C to display the leaderboard")
            time.sleep(0.1)
            print("Or press Q to exit the application.")
            time.sleep(0.1)
            print("You cannot review the fixture list now you have seen it however you can scroll up to view it again.")
            time.sleep(0.1)
            menuOptions2 = input("What would you like to do? B, C, or Q?")
            if menuOptions2 == 'B':
                print("~~incomplete~~")
            elif menuOptions2 == 'C':
                print("~~incomplete~~")
            elif menuOptions2 == 'Q':
                print("Exiting Application...")
                time.sleep(1)
                exit()
        elif menuReturn == 'N':
            print("Exiting Application...")
            time.sleep(2)
            exit()
elif menuOptions == 'B':
    print("Searching for fixtures...")
    time.sleep(3)
    data = [line.strip() for line in open(r"Y:\Computing & Business\Students\Computing\Year 10\CA 2017 Edexcel\firesideFixtures.txt").readlines()]
    for line in data:
        print(line)
    time.sleep(1)
    print("Return to menu?")
    menuReturn = input("Y or N")
    if menuReturn == 'Y':
        print("Press A to search for a fixture")
        time.sleep(0.1)
        print("Press C to display the leaderboard")
        time.sleep(0.1)
        print("Or press Q to exit the application.")
        time.sleep(0.1)
        print("You cannot review the fixture list now you have seen it however you can scroll up to view it again.")
        time.sleep(0.1)
        menuOptions2 = input("What would you like to do? B, C, or Q?")
        if menuOptions2 == 'A':
            fixtureQuestion = input(int("Please enter the fixture number you are looking for... "))
            fixtureQuestion = fixtureQuestion - 1
            time.sleep(3)
            if fixtureQuestion < 1:
                print("This fixture is not available, please re-run the application...")
                time.sleep(2)
                exit()
            elif fixtureQuestion > 190:
                print("This fixture is not available, please re-run the application...")
                time.sleep(2)
                exit()
            else:
                searchData = open(r"Y:\Computing & Business\Students\Computing\Year 10\CA 2017 Edexcel\firesideFixtures.txt").readlines()
                lines = searchData.readlines()
                print(lines[fixtureQuestion])
                time.sleep(1)
                print("Return to menu?")
                menuReturn = input("Y or N")
                if menuReturn == 'Y':
                    print("Press C to display the leaderboard")
                    time.sleep(0.1)
                    print("Or press Q to exit the application.")
                    time.sleep(0.1)
                    print("You cannot review the fixture list now you have seen it however you can scroll up to view it again.")
                    time.sleep(0.1)
                    menuOptions2 = input("What would you like to do? B, C, or Q?")
                    if menuOptions2 == 'C':
                        print("~~incomplete~~")
                    elif menuOptions2 == 'Q':
                        print("Exiting Application...")
                        time.sleep(1)
                        exit()
                elif menuReturn == 'N':
                    print("Exiting Application...")
                    time.sleep(2)
                    exit()
                elif menuOptions2 == 'Q':
                    print("Exiting Application...")
                    time.sleep(1)
                    exit()
elif menuOptions == 'C':
    while RetryForC == "Yes":
        RetryForC == "No"
        fireRead = open("Y:\Computing & Business\Students\Computing\Year 10\CA 2017 Edexcel\firesideResults.txt")
        for line in fireRead:
            fireRead = open("Y:\Computing & Business\Students\Computing\Year 10\CA 2017 Edexcel\firesideResults.txt")
            InfoOne = line.split(',')[0]
            InfoTwo = line.split(',')[1]
            InfoThree = line.split(',')[2]
            InfoFour = line.split(',')[3]
            PointCounter = int(line.split(',')[2])
            PointCounter = PointCounter * 3
            fireRead.close()
            print("Player:",InfoOne,"Has played:",InfoTwo,", has won:",InfoThree,", has lost:",InfoFour,", and therefore has",PointCounter,"many points.")
        print("Retry?")
        RestForC = str(input("Yes/No  "))
    print("The program will now close...")
    time.sleep(5)
    exit()
elif menuOptions == 'Q':
    print("Exiting Applicaion...")
    time.sleep(2)
    exit()

And this is my result:

Welcome to the League Fixture Manager!
What would you like to do?
Press A to search for a fixture.
Press B to view Outstanding fixtures.
Press C to display the leader board
Or press Q to quit, this will exit the application.
What would you like to do? A, B, C, or Q.A
Please enter the fixture number you are looking for...
016
Traceback (most recent call last):
  File "E:\Python\Python Work\League\League3.py", line 33, in <module>
    print(lines[searchData])
TypeError: list indices must be integers, not _io.TextIOWrapper

What can I do to fix this?

Body:
This line:

print(lines[searchData])

Doesn't make any sense. Indices of a list must be integers, so you can do:

>>> my_list = [1, 2, 3]
>>> my_list[0]
1

lines is a list which contains the lines of the file and search_data is a file object. It looks like you're missing some basic python concepts. Please do read the documentation I pasted in your other question you asked 10 minutes ago!


问:
Installing Dolibarr on Codeigniter
I have a Codeigniter based website and I want to install Dolibarr on the same site. Where is the Dolibarr installation best placed, within the codeigniter folder structure or completely separately at the server root? If within codeigniter then where in the folder structure?</p>

答: it's too simple juste create under your codeigniter folder same location as "index.php" of codeigniter and next you your a simple installation by calling your dolibarr "install/index.php " file</p>

Title: Installing Dolibarr on Codeigniter


问:
How to Get POST ID from one page to another page
I have created a message system in wordpress. There s a consultation page fr each user.also a sidebar with certain menus. when the submit button is clicked the admin reviews the question and answers it. The message will be shown in the inbox sidebar menu on the same consultation page.

but whtever i tried am not getting the reply message of the corresponding user. my problem is that when i defined the link for inbox there is no id being passed.later in tht particular page whtever id s am calling its bring up the page id only and nothing else.

This is the sidebar code:

```<code><li>
    <a href="<?php echo site_url();?>/inbox/?id=<?php echo get_current_user_id();?>"><i class="fa fa-sort-alpha-asc " aria-hidden="true"> </i> <span style="margin-left:10px;">Inbox</span>  </a>
</li>
</code>```

now its bringing the id = 1. no matter which user it is.

this is the inbox code:

```<code><?php
global $post;
$idd= $post->ID;

$title= $post->post_title;
var_dump($title);

echo "<div class= 'col-lg-4'><table style='width:500px;'><tr><td><b>Reply:</b> ".get_post_meta( $idd, 'docreply', true)."</td></tr></div>";

echo "<div class= 'col-lg-4'><table style='width:500px;'><tr><td><b>Amount:</b> ".get_post_meta( $idd, 'amount', true)."</td></tr></div>";
</code>```

答:
you can get the post id by using get_the_ID() function.</p>

```<code><?php
echo get_the_ID();
?>
</code>```

Body:
I have created a message system in wordpress. There s a consultation page fr each user.also a sidebar with certain menus. when the submit button is clicked the admin reviews the question and answers it. The message will be shown in the inbox sidebar menu on the same consultation page.

but whtever i tried am not getting the reply message of the corresponding user. my problem is that when i defined the link for inbox there is no id being passed.later in tht particular page whtever id s am calling its bring up the page id only and nothing else.

This is the sidebar code:

    <a href="<?php echo site_url();?>/inbox/?id=<?php echo get_current_user_id();?>">  Inbox

now its bringing the id = 1. no matter which user it is.

this is the inbox code:

<?php
global $post;
$idd= $post->ID;

$title= $post->post_title;
var_dump($title);

echo "

Reply: ".get_post_meta( $idd, 'docreply', true)."

";

echo "

Amount: ".get_post_meta( $idd, 'amount', true)."

";

Body:
you can get the post id by using get_the_ID() function.

<?php
echo get_the_ID();
?>


问:
php placement of the dot in a long number
I want to display a large number with a leading zero and a dot after.

The balance i want to display starts with 0.000000000000000000 ( 18 zeros after the dot ). This should be able to go up to 99.00000000000000000.( 17 zeros after the dot ).

I did a lot of trial and error but i just can't seem to get the dot in there. As far as for the zeros i got it working. What i have now is:

```<code>$leadingBalance = sprintf("%019d", $balance);
echo $leadingBalance;
</code>```

This will display the correct balance but i need to place the dot in there. It means that if my balance has 17 or 18 numbers it should place the dot as 0.0000... If the balance has 19 numbers it should place the dot as 00.0000...

Whatever i try, how much i look up i can't figure it out.

答:
For eg:

```<code>$n1 = 0;
$n2 = 99;
 echo number_format($n1,18)."<br>";
 echo number_format($n2,18)."<br>";
</code>```

See the documentation for number_format: http://php.net/number_format

The functions parameters are:

```<code>string number_format ( float $number , int $decimals = 0 , string $dec_point = '.' , string $thousands_sep = ',' )
</code>```

So use:

```<code>number_format(1000000000000000, 2, '.', '');
</code>```

Which means that you don't use any (= empty string) thousands separator, only a decimal point.

or if you just want padding of 19 zero after decimal point

just use

```<code> sprintf("%0.19f",$number);
</code>```

or else

if u want a number always 20 digit without caring about whole no and decimal value than use  str_pad()

eg:

```<code>$no = sprintf("%0.2f",100); //100.00
</code>```

this will convert your no to decimal point with 2 digit after decimal now just pad some digit if require to make it 20 digit long

```<code>  echo str_pad($no,20,"0"); //100.00(15 zero after this)
</code>```

this will check no of digit available and pad 0 to make it 20 digit

for more ref:https://www.w3schools.com/php/func_string_number_format.asp

Body:
I want to display a large number with a leading zero and a dot after.

The balance i want to display starts with 0.000000000000000000 ( 18 zeros after the dot ). This should be able to go up to 99.00000000000000000.( 17 zeros after the dot ).

I did a lot of trial and error but i just can't seem to get the dot in there. As far as for the zeros i got it working. What i have now is:

$leadingBalance = sprintf("%019d", $balance);
echo $leadingBalance;

This will display the correct balance but i need to place the dot in there. It means that if my balance has 17 or 18 numbers it should place the dot as 0.0000... If the balance has 19 numbers it should place the dot as 00.0000...

Whatever i try, how much i look up i can't figure it out.

Body:
For eg:

$n1 = 0;
$n2 = 99;
 echo number_format($n1,18)."<br>";
 echo number_format($n2,18)."<br>";

See the documentation for number_format: http://php.net/number_format

The functions parameters are:

string number_format ( float $number , int $decimals = 0 , string $dec_point = '.' , string $thousands_sep = ',' )

So use:

number_format(1000000000000000, 2, '.', '');

Which means that you don't use any (= empty string) thousands separator, only a decimal point.

or if you just want padding of 19 zero after decimal point

just use

 sprintf("%0.19f",$number);

or else

if u want a number always 20 digit without caring about whole no and decimal value than use  str_pad()

eg:

$no = sprintf("%0.2f",100); //100.00

this will convert your no to decimal point with 2 digit after decimal now just pad some digit if require to make it 20 digit long

  echo str_pad($no,20,"0"); //100.00(15 zero after this)

this will check no of digit available and pad 0 to make it 20 digit

for more ref:https://www.w3schools.com/php/func_string_number_format.asp


问:
How to enable/disbale a button in mxml depending on whether count is less than 10 or not
I am trying to bind enabled property of my button to the maximum value that an integer can attain. I need this button to allow user to view next page and want to disable this button when all the components have been shown (as reflected in count).

Something like :

```<code><mx:Button label="Previous" click="nextHandler()" enabled="{count< 10}">
</code>```

But the compiler is throwing an error that '<' attribute can not be used in enabled tag.

Any ideas over this ?

Thanks in advance.

答:
Adrnans answer is spot on, but if you dont wish to use the XML/Html "&lt"; then the following also works:)</p>

```<code><mx:NumericStepper id="count" x="10" y="15" maximum="20"/>
<mx:Button label="Previous" enabled="{count.value >= 10 ? false : true}" x="10" y="45"/>
</code>```

Body:
I am trying to bind enabled property of my button to the maximum value that an integer can attain. I need this button to allow user to view next page and want to disable this button when all the components have been shown (as reflected in count).

Something like :

<mx:Button label="Previous" click="nextHandler()" enabled="{count< 10}">

But the compiler is throwing an error that '<' attribute can not be used in enabled tag.

Any ideas over this ?

Thanks in advance.

Body:
Adrnans answer is spot on, but if you dont wish to use the XML/Html "&lt"; then the following also works:)

<mx:NumericStepper id="count" x="10" y="15" maximum="20"/>
<mx:Button label="Previous" enabled="{count.value >= 10 ? false : true}" x="10" y="45"/>


问:
Getting Error when reading file in string using C++Builder Project
I want to read a whole file into a string. I am using Embarcadero C++Builder XE.

When I use the below code in my project, it is giving errors:

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

std::ifstream in(Path);
std::string s((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
</code>```

```
[ILINK32 Error] Error: Unresolved external 'std::_Mutex::_Lock()'
[ILINK32 Error] Error: Unresolved external 'std::_Mutex::_Unlock()'
[ILINK32 Error] Error: Unresolved external 'std::char_traits::eq_int_type(const int&, const int&)'
[ILINK32 Error] Error: Unresolved external 'std::char_traits::not_eof(const int&)'
[ILINK32 Error] Error: Unresolved external 'std::char_traits::to_char_type(const int&)'
[ILINK32 Error] Error: Unresolved external 'std::char_traits::eof()'
[ILINK32 Error] Error: Unresolved external 'std::char_traits::to_int_type(const char&)'
[ILINK32 Error] Error: Unresolved external 'std::locale::id::operator unsigned int()'
[ILINK32 Error] Error: Unresolved external 'std::locale::name() const'
[ILINK32 Error] Error: Unresolved external 'std::codecvt_base::codecvt_base(unsigned int)'
[ILINK32 Error] Error: Unresolved external 'std::locale::facet::_Incref()'
[ILINK32 Error] Error: Unresolved external 'std::ios_base::ios_base()'
[ILINK32 Error] Error: Unresolved external 'std::ios_base::getloc() const'
[ILINK32 Error] Error: Unresolved external 'std::ctype::_Getcat(std::locale::facet * *, std::locale *)'
[ILINK32 Error] Error: Unresolved external 'std::ctype::widen(char) const'
[ILINK32 Error] Error: Unresolved external 'std::ios_base::rdstate() const'
[ILINK32 Error] Error: Unable to perform link
```

Any other solutions for reading a file into a string?

答:
Lets create an empty VCL Form app and add a single TMemo control on it. The IDE will name it Memo1 automatically . The Memo object is a Text editor with 2 important properties:

Memo1->Text

Text is a System::String (automatically reallocable string class from VCL holding the whole text of the memo. String has a Length() function returning number of characters present, and each character is accessed using the [] operator like this (indexed from 1 !!!):

```<code>String s = _D("123456"); // set some string to s
int l = s.Length(); // get its length
for (int i = 1; i <= l; i++) s[i] = '0'; // change all the chars to zeros
Memo1->Text = s; // feed it to Memo
</code>```

There are tons of support functions inside String, the most important for you is formatted output:

```<code>Memo1->Text = String().sprintf(_D("float number: %7.3f"), float(123.456));
</code>```

You can use String as your local variables, too:

```<code>String s = _D("some text");
Memo1->Text = s;
</code>```

Also for backward compatibility, if you need a char* for some functions, then just assign the String to an AnsiString and call its c_str() method:

```<code>String s = _D("some text");
AnsiString as = s;
char *txt = as.c_str();
</code>```

But beware not to overwrite unallocated space, or use that pointer after any reallocation inside as, or after as goes out of scope. This is used mainly as input parameter for Win32 API functions, C functions, non-VCL LIBs/DLLs, etc.

Memo1->Lines

This is a TStrings class, which holds a dynamic array of Strings. In a TMemo, each element represents a line in the Text. You can dynamically add lines to Memo1 like this:

```<code>Memo1->Lines->Add(_D("text 1"));
Memo1->Lines->Add(_D("text 2"));
Memo1->Lines->Add(_D("text 3"));
</code>```

You can load/save the whole Memo contents like this:

```<code>Memo1->Lines->LoadFromFile("file1.txt");
Memo1->Lines->SaveToFile("file1.txt");
</code>```

Any change in Memo1->Lines will also change Memo1->Text, and vice versa, as they both represent the same thing. You can have your Memo hidden (invisible) and still use it in case you do not want to show what are you doing ...

You can also load an entire file into a char[] buffer using file access functions without any VCL component, like this:

```<code>int hnd = FileOpen("file1.txt", fmOpenRead); // open file hnd>=0 if all OK
int siz = FileSeek(hnd, 2, 0); // point to end of file and return position = file size
FileSeek(hnd, 0, 0); // point back to start of file
char *txt = new char[siz+1] // allocate space for text and null terminator
FileRead(hnd, txt, siz); // load the file into memory at once
FileClose(hnd); // close file as we do not need it anymore

txt[siz] = 0; // add null termination just to be safe (text files do not contains zeros usually)
// do your thing with txt[siz]

delete[] txt;
</code>```

Or:

```<code>TFileStream *strm = new TFileStream("file1.txt", fmOpenRead); // open file
int siz = strm->Size; // file size
char *txt = new char[siz+1] // allocate space for text and null terminator
strm->ReadBuffer(txt, siz); // load the file into memory at once
delete strm; // close file as we do not need it anymore

// do your thing with txt[siz]

delete[] txt;
</code>```

Or:

```<code>TMemoryStream *strm = new TMemoryStream;
strm->LoadFromFile("file1.txt"); // open file

// do your thing with strm->Memory up to strm->Size bytes...

delete strm;
</code>```

Unlike std::fstream, these will work for any file ... even if holding control codes.

Body:
I want to read a whole file into a string. I am using Embarcadero C++Builder XE.

When I use the below code in my project, it is giving errors:

#include <iostream>
#include <iomanip>
#include <iterator>
#include <fstream>

std::ifstream in(Path);
std::string s((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());

[ILINK32 Error] Error: Unresolved external 'std::_Mutex::_Lock()'
[ILINK32 Error] Error: Unresolved external 'std::_Mutex::_Unlock()'
[ILINK32 Error] Error: Unresolved external 'std::char_traits::eq_int_type(const int&, const int&)'
[ILINK32 Error] Error: Unresolved external 'std::char_traits::not_eof(const int&)'
[ILINK32 Error] Error: Unresolved external 'std::char_traits::to_char_type(const int&)'
[ILINK32 Error] Error: Unresolved external 'std::char_traits::eof()'
[ILINK32 Error] Error: Unresolved external 'std::char_traits::to_int_type(const char&)'
[ILINK32 Error] Error: Unresolved external 'std::locale::id::operator unsigned int()'
[ILINK32 Error] Error: Unresolved external 'std::locale::name() const'
[ILINK32 Error] Error: Unresolved external 'std::codecvt_base::codecvt_base(unsigned int)'
[ILINK32 Error] Error: Unresolved external 'std::locale::facet::_Incref()'
[ILINK32 Error] Error: Unresolved external 'std::ios_base::ios_base()'
[ILINK32 Error] Error: Unresolved external 'std::ios_base::getloc() const'
[ILINK32 Error] Error: Unresolved external 'std::ctype::_Getcat(std::locale::facet * *, std::locale *)'
[ILINK32 Error] Error: Unresolved external 'std::ctype::widen(char) const'
[ILINK32 Error] Error: Unresolved external 'std::ios_base::rdstate() const'
[ILINK32 Error] Error: Unable to perform link

Any other solutions for reading a file into a string?

Body:
Lets create an empty VCL Form app and add a single TMemo control on it. The IDE will name it Memo1 automatically . The Memo object is a Text editor with 2 important properties:

Memo1->Text

Text is a System::String (automatically reallocable string class from VCL holding the whole text of the memo. String has a Length() function returning number of characters present, and each character is accessed using the [] operator like this (indexed from 1 !!!):

String s = _D("123456"); // set some string to s
int l = s.Length(); // get its length
for (int i = 1; i <= l; i++) s[i] = '0'; // change all the chars to zeros
Memo1->Text = s; // feed it to Memo

There are tons of support functions inside String, the most important for you is formatted output:

Memo1->Text = String().sprintf(_D("float number: %7.3f"), float(123.456));

You can use String as your local variables, too:

String s = _D("some text");
Memo1->Text = s;

Also for backward compatibility, if you need a char* for some functions, then just assign the String to an AnsiString and call its c_str() method:

String s = _D("some text");
AnsiString as = s;
char *txt = as.c_str();

But beware not to overwrite unallocated space, or use that pointer after any reallocation inside as, or after as goes out of scope. This is used mainly as input parameter for Win32 API functions, C functions, non-VCL LIBs/DLLs, etc.

Memo1->Lines

This is a TStrings class, which holds a dynamic array of Strings. In a TMemo, each element represents a line in the Text. You can dynamically add lines to Memo1 like this:

Memo1->Lines->Add(_D("text 1"));
Memo1->Lines->Add(_D("text 2"));
Memo1->Lines->Add(_D("text 3"));

You can load/save the whole Memo contents like this:

Memo1->Lines->LoadFromFile("file1.txt");
Memo1->Lines->SaveToFile("file1.txt");

Any change in Memo1->Lines will also change Memo1->Text, and vice versa, as they both represent the same thing. You can have your Memo hidden (invisible) and still use it in case you do not want to show what are you doing ...

You can also load an entire file into a char[] buffer using file access functions without any VCL component, like this:

int hnd = FileOpen("file1.txt", fmOpenRead); // open file hnd>=0 if all OK
int siz = FileSeek(hnd, 2, 0); // point to end of file and return position = file size
FileSeek(hnd, 0, 0); // point back to start of file
char *txt = new char[siz+1] // allocate space for text and null terminator
FileRead(hnd, txt, siz); // load the file into memory at once
FileClose(hnd); // close file as we do not need it anymore

txt[siz] = 0; // add null termination just to be safe (text files do not contains zeros usually)
// do your thing with txt[siz]

delete[] txt;

Or:

TFileStream *strm = new TFileStream("file1.txt", fmOpenRead); // open file
int siz = strm->Size; // file size
char *txt = new char[siz+1] // allocate space for text and null terminator
strm->ReadBuffer(txt, siz); // load the file into memory at once
delete strm; // close file as we do not need it anymore

// do your thing with txt[siz]

delete[] txt;

Or:

TMemoryStream *strm = new TMemoryStream;
strm->LoadFromFile("file1.txt"); // open file

// do your thing with strm->Memory up to strm->Size bytes...

delete strm;

Unlike std::fstream, these will work for any file ... even if holding control codes.


问:
How to implement WatchKit sliding button?
Is there a way to implement a sliding button on the watch, similar to the power button linked below?

power off screen from watch

答: You can create a custom button with the help of SpriteKit in WatchOS 3 or later. Add SKScene and give pan gesture or swipe gesture to it.


问:
How to change an action bar title text when moving from one tab to another tabs in nativescript

When loading this mainactivity page for the first time, it is loading
the third tab page action bar text.

I need to load the action bar text based on clicking the tab.

For Eg: When I click the second tab means second tab action bar have
to get trigger.

main.activity.html:

```<code><ActionBar title="MainActivity" class="action-bar">

</ActionBar>

<TabView selectedIndex="0" (selectedIndexChange)="onIndexChanged($event)"  iosIconRenderingMode="alwaysTemplate" selectedTabTextColor="blue" sdkExampleTitle sdkToggleNavButton>
<TabView iosIconRenderingMode="alwaysOriginal"></TabView>

<StackLayout *tabItem="{title: 'First Tab',iconSource:'res://store'}" >
<first-page></first-page>
</StackLayout>

<StackLayout *tabItem="{title: 'Second Tab',iconSource:'res://myapps'}" >
<second-page></second-page>
</StackLayout>

<StackLayout *tabItem="{title: 'Third Tab',iconSource:'res://home'}" >
<third-page></third-page>
</StackLayout>

</TabView>
</code>```

main.activity.ts:

```<code>public onIndexChanged(args) {
        let tabView = <TabView>args.object;
        console.log("Selected index changed! New inxed: " + tabView.selectedIndex);
    }
</code>```

答:
For every tab position, we need to add the tabindex and add the title for appropriate page.</p>

```<code>   <ActionBar *ngIf="tabIndex == 1" title="My Apps" color="black"> </ActionBar>
</code>```

Body:
When loading this mainactivity page for the first time, it is loading
the third tab page action bar text.

I need to load the action bar text based on clicking the tab.

For Eg: When I click the second tab means second tab action bar have
to get trigger.

main.activity.html:

<ActionBar title="MainActivity" class="action-bar">

</ActionBar>

<TabView selectedIndex="0" (selectedIndexChange)="onIndexChanged($event)"  iosIconRenderingMode="alwaysTemplate" selectedTabTextColor="blue" sdkExampleTitle sdkToggleNavButton>
<TabView iosIconRenderingMode="alwaysOriginal"></TabView>

<StackLayout *tabItem="{title: 'First Tab',iconSource:'res://store'}" >
<first-page></first-page>
</StackLayout>

<StackLayout *tabItem="{title: 'Second Tab',iconSource:'res://myapps'}" >
<second-page></second-page>
</StackLayout>

<StackLayout *tabItem="{title: 'Third Tab',iconSource:'res://home'}" >
<third-page></third-page>
</StackLayout>

</TabView>

main.activity.ts:

public onIndexChanged(args) {
        let tabView = <TabView>args.object;
        console.log("Selected index changed! New inxed: " + tabView.selectedIndex);
    }

Body:
For every tab position, we need to add the tabindex and add the title for appropriate page.

   <ActionBar *ngIf="tabIndex == 1" title="My Apps" color="black"> </ActionBar>


问:
Can we add the Shipping and Billing addresses form in the cart.liquid file?
I want to add the Shipping and Billing addresses form in the cart.liquid file so it is possible to add these two addresses form in cart page if anybody known then give solution for this. </p>

答:
It is not possible as of now. Soon after user clicks on checkout button, they are redirected to shopify's checkout system. that is https://checkout.shopify.com.
You would not have any option to send your address data from cart page to checkout page.</p>


问:
Not updating value in database instead Inserting new entry
I am using below code to update database and putting where clause for date

```<code> ContentValues values = new ContentValues();
    values.put(DBTransactions.USER_ID_KEY, userId);
    values.put(DBTransactions.DATE_KEY, date);
    values.put(DBTransactions.DAY_KEY, day);
    values.put(DBTransactions.GOAL_KEY, dailyGoal);
    values.put(DBTransactions.VOLUME_KEY, dailyVolume);
    values.put(DBTransactions.IS_GOAL_MET_KEY, goalMet);
    db.getWritableDatabase().update(DBTransactions.TRANSACTION_TABLE_NAME, values, DBTransactions.DATE_KEY + " = ?", new String[]{date});
    closeDB();
</code>```

am I wrong somewhere in putting where clause? Its not updating database, Its creating new entry in database.

Its not updating database.
Thanks in Advance

答:
I am using  this code for update me Database and it's work fine , not a issue with me .

```<code>  public void updateItemToCartTable(String itemId, String subitemid, String cost, int quantity) {

    sdb = this.getWritableDatabase();

    ContentValues values = new ContentValues();

    values.put(ITEM_COST, cost);
    values.put(ITEM_QUANTITY, quantity);

    Log.d("DB", "Count : " + quantity);

    this.sdb.update(TABLE_NAME, values, ITEM_ID + " ='" + itemId + "'         AND " + SUB_ITEM_ID + " ='" + subitemid + "'", null);
    sdb.close();
}
</code>```

Use This Code For Updating your Database

Body:
I am using below code to update database and putting where clause for date

 ContentValues values = new ContentValues();
    values.put(DBTransactions.USER_ID_KEY, userId);
    values.put(DBTransactions.DATE_KEY, date);
    values.put(DBTransactions.DAY_KEY, day);
    values.put(DBTransactions.GOAL_KEY, dailyGoal);
    values.put(DBTransactions.VOLUME_KEY, dailyVolume);
    values.put(DBTransactions.IS_GOAL_MET_KEY, goalMet);
    db.getWritableDatabase().update(DBTransactions.TRANSACTION_TABLE_NAME, values, DBTransactions.DATE_KEY + " = ?", new String[]{date});
    closeDB();

am I wrong somewhere in putting where clause? Its not updating database, Its creating new entry in database.

Its not updating database.
Thanks in Advance

Body:
I am using  this code for update me Database and it's work fine , not a issue with me .

  public void updateItemToCartTable(String itemId, String subitemid, String cost, int quantity) {

    sdb = this.getWritableDatabase();

    ContentValues values = new ContentValues();

    values.put(ITEM_COST, cost);
    values.put(ITEM_QUANTITY, quantity);

    Log.d("DB", "Count : " + quantity);

    this.sdb.update(TABLE_NAME, values, ITEM_ID + " ='" + itemId + "'         AND " + SUB_ITEM_ID + " ='" + subitemid + "'", null);
    sdb.close();
}

Use This Code For Updating your Database


问:
How to send notification between two application
I want to send push notification from Device "A" with Application "A" to Device "B" with application "B" how I can achieve that?

Any help will be appreciated.

can I use firebase with that?

With parse I can define that with number like :

```<code>ParseQuery query = ParseInstallation.getQuery();
query.whereEqualTo("phone", "1234567890");
ParsePush push = new ParsePush();
push.setQuery(query);
push.sendPushInBackground();
</code>```

how can I achieve that in other cases ?

答:
First of all Parse no more exists

now coming to your question yes you can send the push from application A to application B

First implement FCM in App B and store the device id on server.

Now you have device id of App B  with user id on server.

Now send request to server to send the push from A to B.

Body:
I want to send push notification from Device "A" with Application "A" to Device "B" with application "B" how I can achieve that?

Any help will be appreciated.

can I use firebase with that?

With parse I can define that with number like :

ParseQuery query = ParseInstallation.getQuery();
query.whereEqualTo("phone", "1234567890");
ParsePush push = new ParsePush();
push.setQuery(query);
push.sendPushInBackground();

how can I achieve that in other cases ?


问:
Create tables from SQL dump generated by phpmyadmin using kohana
I have a PHPMyAdmin SQL dump in a file. I want to use PHP to execute this SQL. How could I do that? I've tried a simple query (with Kohana but without it is enough too!) but I got a syntax error.
How could I do that?</p>

答:
I agree with The Pixel Developer. However, you could use PHP to initiate the command using shell_exec Eg:

```<code>$result = shell_exec("mysql -h {$hostname} -u {$username} -p {$password} {$database} < $input_file");
</code>```

Body:
I agree with The Pixel Developer. However, you could use PHP to initiate the command using shell_exec Eg:

$result = shell_exec("mysql -h {$hostname} -u {$username} -p {$password} {$database} < $input_file");


问:
JS hide div if it has a class added via JS
I am working on a code where an active class is added to a div via JS.

What I would like to do is, when that div has active class, hide another div. But, due to the active class was added via JS, this code doesn't work:

```<code>if($("#section3").hasClass("active")) {
    $(".menu").fadeOut("fast");
}
</code>```

I think I would need to use the on function: .on()

Something like this, but it's not working... Any ideas?

```<code>$("#section3").on( function() {
    $(this).hasClass('active') {
        $(".menu").fadeOut("fast");
    }
});
</code>```

EDITED:

I'm afraid I cannot paste the code because I am using a plugin. This is the one that I am using, so you can see the functionality there.

I've added this bullet menu to it:

```<code><ul id="menu">
    <li data-menuanchor="slide1"><a href="#slide1"><span></span></a></li>
    <li data-menuanchor="slide2"><a href="#slide2"><span></span></a></li>
    <li data-menuanchor="slide3"><a href="#slide3"><span></span></a></li>
    <li data-menuanchor="slide4"><a href="#slide4"><span></span></a></li>
</ul>
</code>```

Each slide has a active class when it's on viewport, so what I would like to achieve is when the last slider is active, hide the menu

答:
oth the section and the li have active classes so you could use something like this or use the afterSlideLoad event if it is depeding of the slideshow

```<code>$(window).on("scroll",function() {
  if ($('#menu li:last-child').hasClass("active")) {
    ("#menu").fadeOut("fast")
  }
})
</code>```

or you can use slideIndex to check if you are on the last slide. see here > afterSlideLoad

Body:
I am working on a code where an active class is added to a div via JS.

What I would like to do is, when that div has active class, hide another div. But, due to the active class was added via JS, this code doesn't work:

if($("#section3").hasClass("active")) {
    $(".menu").fadeOut("fast");
}

I think I would need to use the on function: .on()

Something like this, but it's not working... Any ideas?

$("#section3").on( function() {
    $(this).hasClass('active') {
        $(".menu").fadeOut("fast");
    }
});

EDITED:

I'm afraid I cannot paste the code because I am using a plugin. This is the one that I am using, so you can see the functionality there.

I've added this bullet menu to it:

Each slide has a active class when it's on viewport, so what I would like to achieve is when the last slider is active, hide the menu

Body:
oth the section and the li have active classes so you could use something like this or use the afterSlideLoad event if it is depeding of the slideshow

$(window).on("scroll",function() {
  if ($('#menu li:last-child').hasClass("active")) {
    ("#menu").fadeOut("fast")
  }
})

or you can use slideIndex to check if you are on the last slide. see here > afterSlideLoad


问:
Query script not run in suggest box
In AppMaker, one my datasources has a simple query script associated with, because I need a filter everytime the datasource is requested. I'm talking about a normal SQL based datasource (not calculated).

Is it normal than this query script is not used when the datasource is used in a Suggest box ? Because it breaks my app (the user is able via the suggest box to select items he's not even supposed to see).

Thanks for your help

答:
The options for a suggest field text box can either be provided explicitly, by binding to the options property, or by specifying a database query on a model using a startsWith filter on a field. You can set the model and field for the latter option below.

So you can try to create calculated model with server script starts with

```<code>var name = query.filters.name.startsWith;
</code>```

name is field of model

Title: Query script not run in suggest box

Body:
The options for a suggest field text box can either be provided explicitly, by binding to the options property, or by specifying a database query on a model using a startsWith filter on a field. You can set the model and field for the latter option below.

So you can try to create calculated model with server script starts with

var name = query.filters.name.startsWith;

name is field of model


问:
Android Studio - Error: Failed to resolve: com.android.support.constraint:constraint-layout:1.0.0-alpha1
Screen Shot #1 - Android Studio Project Gradle Build View

Screen Shot #2 - Android Studio Project Gradle Sync View

Going through the "Android Studio 2.2 Development Essentials book" and following along with the tutorial in chapter 3. Everything was OK until I completed a task in the Development Essentials book (chapter 3, page 24 in book) that said,

As we can see from the component tree hierarchy, the user interface
  layout consists of a layout parent with a single child in the form of
  a TextView object. If Android Studio has used a RelativeLayout manager
  for the project, the first step is to convert it to a
  ConstraintLayout. ConstraintLayout is a new and flexible layout
  manager that is used in most projects in this book. To achieve this
  conversion, right-click on the content_android_sample entry in the
  Component Tree and select the Convert RelativeLayout to
  ConstraintLayout menu option as shown below:

Upon completion of the above quoted tutorial task (in chapt. 3 of the Development Essentials book), an error was presented that said:

Error: Failed to resolve: com.android.support.constraint:constraint-layout:1.0.0-alpha1

Also, a rendering error was listed as well that said:

Rendering Problems The following classes could not be found:
- android.support.constraint.ConstraintLayout (    Add constraint-layout library dependency to the project, Fix Build Path, Edit XML, Create Class)

Any thoughts on how to fix this? Please see screen shots attached (above). I'm new to Android Studio.

Thank you very much for your time.

I am using the following OS and Android Studio version below:

Win7 professional 64 bit OS

Android Studio 2.2

Build# AI-145,3330264, Built on October 6, 2016

答:
Or update your dependency to:</p>

```<code>compile 'com.android.support.constraint:constraint-layout:latest_version'
</code>```

Body:
Or update your dependency to:

compile 'com.android.support.constraint:constraint-layout:latest_version'


问:
C# json array to List
I want to populate a drop down list with a list of servers I have in a json file.  So I want to retrieve the list from json and use that list to add all of the servers to my drop down.  I have a simple json file with a simple array in it.  In an ideal world, all I want to do is something like this:

```<code>public static IConfigurationRoot Configuration { get; set; }
public static void Main(string[] args = null)
{
    var builder = new ConfigurationBuilder()
        .AddJsonFile("appsettings.json");

    Configuration = builder.Build();
    List<string> servers = Configuration["servers"];

    foreach (string server in servers)
        {
            cboSelectServer.Items.Add(server);
        }
}
</code>```

And my appsettings.json file looks like this:

```<code>{
    "servers": ["server1", "server2"]
}
</code>```

The message I get is

Cannot implicitly convert type 'string' to System.Collections.Generic.List<string>

What is really confusing me is that it obviously understands Configuration["servers"] is a list because if I look at Configuration["servers:0"] I get my first server.

答:
You need to make use of the GetChildren call from a ConfigurationSection as returned by GetSection:

```<code>var builder = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json");

Configuration = builder.Build();
List<string> servers = Configuration.GetSection("servers")
                                    .GetChildren()
                                    .Select(x => x.Value)
                                    .ToList()

foreach (string server in servers)
    {
        cboSelectServer.Items.Add(server);
    }
</code>```

You'll need a couple of using's at the top of your file:

```<code>using Microsoft.Extensions.Configuration;
using System.Linq;
</code>```

Title: C# json array to List

Body:
I want to populate a drop down list with a list of servers I have in a json file.  So I want to retrieve the list from json and use that list to add all of the servers to my drop down.  I have a simple json file with a simple array in it.  In an ideal world, all I want to do is something like this:

public static IConfigurationRoot Configuration { get; set; }
public static void Main(string[] args = null)
{
    var builder = new ConfigurationBuilder()
        .AddJsonFile("appsettings.json");

    Configuration = builder.Build();
    List<string> servers = Configuration["servers"];

    foreach (string server in servers)
        {
            cboSelectServer.Items.Add(server);
        }
}

And my appsettings.json file looks like this:

{
    "servers": ["server1", "server2"]
}

The message I get is

Cannot implicitly convert type 'string' to System.Collections.Generic.List<string>

What is really confusing me is that it obviously understands Configuration["servers"] is a list because if I look at Configuration["servers:0"] I get my first server.

Body:
You need to make use of the GetChildren call from a ConfigurationSection as returned by GetSection:

var builder = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json");

Configuration = builder.Build();
List<string> servers = Configuration.GetSection("servers")
                                    .GetChildren()
                                    .Select(x => x.Value)
                                    .ToList()

foreach (string server in servers)
    {
        cboSelectServer.Items.Add(server);
    }

You'll need a couple of using's at the top of your file:

using Microsoft.Extensions.Configuration;
using System.Linq;


问:
Laravel 5.4: Redirect::to not working
I want to redirect the user to another page if a certain condition is not true.

This is my first/index view:

```<code>    <html lang="en">
      <head>
      </head>

      <body>

        <?php
        if(5>4) {
        return Redirect::to('controllername@methodname')->with('status','Condition not true!');
        } else {
        ?>
    <p>It is Working</p>

<?php } ?>

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

If I change the condition to (5<4) then it works fine. but if the condition is true, it shows me a blank page. I want to write the condition in the view not in the controller and route. Please Help

答: Your redirect have to be at a place before showing content. You can read this in the docs based on phps header</p>

Title: Laravel 5.4: Redirect::to not working

Body:
I want to redirect the user to another page if a certain condition is not true.

This is my first/index view:

        <?php
        if(5>4) {
        return Redirect::to('controllername@methodname')->with('status','Condition not true!');
        } else {
        ?>

It is Working

<?php } ?>

If I change the condition to (5<4) then it works fine. but if the condition is true, it shows me a blank page. I want to write the condition in the view not in the controller and route. Please Help


问:
unable to get xpath of anchor element under span element
I have already learned to use xpath but i am kind of stuck here - http://phptravels.com/requirements/. Can anyone please tell me how to find xpath of "Demo" hyperlink on this website. I simply used //a[text()= 'Demo                 ']. keep whitespaces in mind.

答:
The white space is your problem. Use contains instead of equality

```<code>//a[contains(text(), 'Demo')]
</code>```

Or

```<code>//a[contains(., 'Demo')]
</code>```

Body:
The white space is your problem. Use contains instead of equality

//a[contains(text(), 'Demo')]

Or

//a[contains(., 'Demo')]


问:
Adding ng-model directive to dynamically created input tag using AngularJs
I am trying that on a button click, a div and and input tag are created and the input tag contain ng-model and the div has binding with that input.
Kindly suggest some solution.</p>

答:
```<code>$scope.addInputBox = function(){
//#myForm id of your form or container boxenter code here
$('#myForm').append('<div><input type="text" name="myfieldname" value="myvalue" ng-model="model-name" /></div>');
}
</code>```


问:
Not a single angular directive working in this code.The function define in submit button does not work
I have tried many angular directive in this code but none of them is
          working. Is there any library file is missing or something wrong in
          this code  or is there any effect due to jQuery file.
           The complete code is define below:</p>

```<code>        <!DOCTYPE html>
<html ng-app="myapp" ng-controller="ticketcontroller">

<head>
    <title>Ticket</title>

    <link href="css/style.css" rel="stylesheet"
    type="text/css" media="all" />
    <link rel="stylesheet" href="css/flexslider.css"
    type="text/css" media="screen" property=""
    />
    <link rel="stylesheet" href="css/flexslider.css"
    type="text/css" media="screen" property=""
    />
    <script src="js/jquery-2.2.3.min.js"></script>
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
    </script>
    <link href="//fonts.googleapis.com/css?family=Montserrat:400,700"
    rel="stylesheet">
</head>

<body>
    <div class="main">
        <h1>Ticket Details Forum</h1>

        <div class="w3_agile_main_grids">
            <section class="slider">
                <div class="flexslider">

                    <div class="agileits_w3layouts_main_grid">
                        <h3>Service Details</h3>
                        <form>
                            <span>
                                         <label>Category</label>
                                         <select  required="" ng-
                                          model="service">
                                             <option value="">Laptop
                                            Repair</option>
                                             <option value="">Refrigerator
                                             repair</option>
                                             <option value="">Microwave
                                                  repair</option>

                                         </select>
                                     </span>
                            <span>
                                         <label>Priority</label>
                                         <select  required="" ng-
                                           model="priority">
                                             <option value="">Low</option>
                                             <option
                                          value="">Normal</option>
                                             <option value="">High</option>

                                         </select>
                                     </span>

                            <span>
                                         <label>Description</label>
                                        <input name="description"
    type="text" placeholder="Enter Description here" ng-model="description">
                                     </span>

                            <div class="w3_agileits_submit">

                                <button class="btn btn-success" ng- click="submitdata()">submit</button>

                            </div>

                        </form>
                    </div>
            </section>
            </div>

        </div>

        <!-- flexSlider -->
        <script defer src="js/jquery.flexslider.js"></script>
        <script type="text/javascript">
            $(window).load(function() {
                $('.flexslider')
                    .flexslider({
                        animation: "slide",
                        start: function(
                            slider
                        ) {
                            $
                                (
                                    'body'
                                )
                                .removeClass(
                                    'loading'
                                );
                        }
                    });
            });
        </script>

</body>

</html>

<script>
    var ap = angular.module("myapp", []);
    ap.controller("ticketcontroller", [
                '$scope', '$http',
                '$window',
                function($scope, $http,
                    $window) {
                    $scope.submitdata =
                        function() {
                            $window.alert(
                                "dhbhhfgh);
                            }
                        }]);
</script>
</code>```

答: Try to name your controller in a CamelCase style. </p>

Body:
I have tried many angular directive in this code but none of them is
          working. Is there any library file is missing or something wrong in
          this code  or is there any effect due to jQuery file.
           The complete code is define below:

        <!DOCTYPE html>

    <title>Ticket</title>

    <link href="css/style.css" rel="stylesheet"
    type="text/css" media="all" />
    <link rel="stylesheet" href="css/flexslider.css"
    type="text/css" media="screen" property=""
    />
    <link rel="stylesheet" href="css/flexslider.css"
    type="text/css" media="screen" property=""
    />

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="//fonts.googleapis.com/css?family=Montserrat:400,700"
    rel="stylesheet">

Ticket Details Forum

Service Details

                        <form>

                                         Category
                                         <select  required="" ng-
                                          model="service">
                                             <option value="">Laptop
                                            Repair</option>
                                             <option value="">Refrigerator
                                             repair</option>
                                             <option value="">Microwave
                                                  repair</option>

                                         </select>

                                         Priority
                                         <select  required="" ng-
                                           model="priority">
                                             <option value="">Low</option>
                                             <option
                                          value="">Normal</option>
                                             <option value="">High</option>

                                         </select>

                                         Description
                                        <input name="description"
    type="text" placeholder="Enter Description here" ng-model="description">

                                <button class="btn btn-success" ng- click="submitdata()">submit</button>

                        </form>


问:
Add id css via rails enum
I would like to know I can set id via rails enum. For example,

```<code><% @products.each_with_index do |product, index| %>
            <tr id="<% #{index} %>" >
                      .
                      .
<% end %>
</code>```

答:
I don't like to mix HTML and ERB tags and would prefer content_tag to generate the tag. Furthermore, there is the dom_id method in rails that returns useful unique ids.

```<code><% @products.each do |product| %>
  <%= content_tag :tr, id: dom_id(product) do %>
    ...
  <% end %>
<% end %>
</code>```

Title: Add id css via rails enum

Body:
I would like to know I can set id via rails enum. For example,

<% @products.each_with_index do |product, index| %>
            <tr id="<% #{index} %>" >
                      .
                      .
<% end %>

Body:
I don't like to mix HTML and ERB tags and would prefer content_tag to generate the tag. Furthermore, there is the dom_id method in rails that returns useful unique ids.

<% @products.each do |product| %>
  <%= content_tag :tr, id: dom_id(product) do %>
    ...
  <% end %>
<% end %>


问:
Is it possible to convert a C++0x lambda to a clang block?
I've wondered if it is possible to convert a C++0x lambda to a clang block. So far anything I've seen on it has involved the discussion between their differences. My primary reason for looking into this, is to make an eventual wrapper for libdispatch, and while I'm quite aware of dispatch_*_f functions, any information on their use has been quite lacking, in comparison to their block counterpart.

So far I've been able to find information on converting a C++ lambda to a function pointer, but this is more in the realm of the reverse.

If anyone knows anything related to this, and could provide a link, or at least point me in the right direction, I would really appreciate it. (even a "This is not currently possible" answer will suffice)

答:
Well, Clang doesn't yet support lambdas, and neither does the Apple GCC. FSF GCCs recent enough to support lambdas don't support blocks AFAIK. So the question of conversion between them doesn't yet apply.

Once Clang supports both of these, there may be a way in ObjC++ mode to convert between them.


问:
How to search and replace matched text with PHP unless found within an HTML tag?
How can I search and replace all occurrences of a word or phrase of a string, unless it's been located within an HTML tag?

Currently have this:

```<code><?php
        public function add_acronyms($content){
            if(strpos($content, get_bloginfo('description')) !== false){
                $content = str_replace(get_bloginfo('description'), '<acronym title="'.get_bloginfo('name').'">'.get_bloginfo('description').'</acronym>', $content);
                if(strpos($content, '="<acronym title="'.get_bloginfo('name').'">'.get_bloginfo('description').'</acronym>') !== false){
                    $content = str_replace('="<acronym title="'.get_bloginfo('name').'">'.get_bloginfo('description').'</acronym>', get_bloginfo('description'), $content);
                }
            }
            return $content;
        }
?>
</code>```

But that will only work if the word or phrase is found at the start of an HTML attribute.

答:
found this while looking for something similar. my answer isn't the most elegant way of accomplishing it but it might help you- my question and answer are here- however as stated, there's almost certainly a better way to achieve this
In my instance, trying to replace a word was breaking some href tags, so i used the following code (this is in Wordpress by the way)

```<code>function replace_text_wps($text){
    $replace = array(
        // used mid-line
        ' YOUR_TEXT ' => ' <span class="YOUR_CLASS">YOUR_TEXT</span> ',
        ' YOUR_TEXT ' => ' <span class="YOUR_CLASS">YOUR_TEXT</span> ',
        ' YOUR_TEXT ' => ' <span class="YOUR_CLASS">YOUR_TEXT</span> ',
        // used at end of lines
        ' YOUR_TEXT' => ' <span class="YOUR_CLASS">YOUR_TEXT</span>',
        ' YOUR_TEXT' => ' <span class="YOUR_CLASS">YOUR_TEXT</span>',
        ' YOUR_TEXT' => ' <span class="YOUR_CLASS">YOUR_TEXT</span>',
        // used inside html tags like headers
        '>YOUR_TEXT' => '><span class="YOUR_CLASS">YOUR_TEXT</span>',
        '>YOUR_TEXT' => '><span class="YOUR_CLASS">YOUR_TEXT</span>',
        '>YOUR_TEXT' => '><span class="YOUR_CLASS">YOUR_TEXT</span>',
        //used directly after html tags
        '> YOUR_TEXT' => '> <span class="YOUR_CLASS">YOUR_TEXT</span>',
        '> YOUR_TEXT' => '> <span class="YOUR_CLASS">YOUR_TEXT</span>',
        '> YOUR_TEXT' => '> <span class="YOUR_CLASS">YOUR_TEXT</span>',
        //exclude alt tags on images, title attributes etc
        '"YOUR_TEXT' => '"YOUR_TEXT',
        'YOUR_TEXT"' => 'YOUR_TEXT"',
        '"YOUR_TEXT' => '"YOUR_TEXT',
        'YOUR_TEXT"' => 'YOUR_TEXT"'
    );
    $text = str_replace(array_keys($replace), $replace, $text);
    return $text;
}
add_filter('the_content', 'replace_text_wps');
add_filter('the_excerpt', 'replace_text_wps');
add_filter('the_title', 'replace_text_wps');
</code>```

exclude html attributes in str_replace

Body:
How can I search and replace all occurrences of a word or phrase of a string, unless it's been located within an HTML tag?

Currently have this:

<?php
        public function add_acronyms($content){
            if(strpos($content, get_bloginfo('description')) !== false){
                $content = str_replace(get_bloginfo('description'), '<acronym title="'.get_bloginfo('name').'">'.get_bloginfo('description').'</acronym>', $content);
                if(strpos($content, '="<acronym title="'.get_bloginfo('name').'">'.get_bloginfo('description').'</acronym>') !== false){
                    $content = str_replace('="<acronym title="'.get_bloginfo('name').'">'.get_bloginfo('description').'</acronym>', get_bloginfo('description'), $content);
                }
            }
            return $content;
        }
?>

But that will only work if the word or phrase is found at the start of an HTML attribute.

Body:
found this while looking for something similar. my answer isn't the most elegant way of accomplishing it but it might help you- my question and answer are here- however as stated, there's almost certainly a better way to achieve this
In my instance, trying to replace a word was breaking some href tags, so i used the following code (this is in Wordpress by the way)

function replace_text_wps($text){
    $replace = array(
        // used mid-line
        ' YOUR_TEXT ' => ' <span class="YOUR_CLASS">YOUR_TEXT</span> ',
        ' YOUR_TEXT ' => ' <span class="YOUR_CLASS">YOUR_TEXT</span> ',
        ' YOUR_TEXT ' => ' <span class="YOUR_CLASS">YOUR_TEXT</span> ',
        // used at end of lines
        ' YOUR_TEXT' => ' <span class="YOUR_CLASS">YOUR_TEXT</span>',
        ' YOUR_TEXT' => ' <span class="YOUR_CLASS">YOUR_TEXT</span>',
        ' YOUR_TEXT' => ' <span class="YOUR_CLASS">YOUR_TEXT</span>',
        // used inside html tags like headers
        '>YOUR_TEXT' => '><span class="YOUR_CLASS">YOUR_TEXT</span>',
        '>YOUR_TEXT' => '><span class="YOUR_CLASS">YOUR_TEXT</span>',
        '>YOUR_TEXT' => '><span class="YOUR_CLASS">YOUR_TEXT</span>',
        //used directly after html tags
        '> YOUR_TEXT' => '> <span class="YOUR_CLASS">YOUR_TEXT</span>',
        '> YOUR_TEXT' => '> <span class="YOUR_CLASS">YOUR_TEXT</span>',
        '> YOUR_TEXT' => '> <span class="YOUR_CLASS">YOUR_TEXT</span>',
        //exclude alt tags on images, title attributes etc
        '"YOUR_TEXT' => '"YOUR_TEXT',
        'YOUR_TEXT"' => 'YOUR_TEXT"',
        '"YOUR_TEXT' => '"YOUR_TEXT',
        'YOUR_TEXT"' => 'YOUR_TEXT"'
    );
    $text = str_replace(array_keys($replace), $replace, $text);
    return $text;
}
add_filter('the_content', 'replace_text_wps');
add_filter('the_excerpt', 'replace_text_wps');
add_filter('the_title', 'replace_text_wps');

exclude html attributes in str_replace


问:
SVN icon overlays not showing properly
I'm testing SVN. After the configuration, I can add/commit the files successfully.

However, I can't see the status icons on the files and folders. Can anybody tell me why?

答:
My overlays disappeared all of a sudden (or so I thought).  I came across this article https://corengen.wordpress.com/2014/07/30/my-tortoisesvn-icon-overlays-have-disappeared/ which points out that windows has 15 slots for overlay icons; 4 are reserved for windows, which leaves 11 for other applications.   Regardless of how many overlay keys are in the registry, Windows selects the first 11 in alphabetical order.

When I upgraded Office, OneDrive added overlay icons -- prefixed with a lot of spaces -- pushing down Tortoise's overlays below the threshold:  windows registry  Since I am not using OneDrive, the solution was to add a "z" to the OneDrive key names.

Title: SVN icon overlays not showing properly