问:
Syntax highlighting in Angular 2
I'm creating simple web app using angular 2. I have two components there. First is basically table with some data rows. When click on row is performed, data corresponding to row are displayed in the second component. Data are XML, loaded to code element. It looks something like

```<code>@Component
export class TableComponent {
    items: Data[];
    selectedItemsXml: string;
    // ...other stuff

    //when row is clicked
    toggleSelectedRow(rowIndex: number) {
        // ...other stuff related to change row's background color
        this.selectedItemsXml = this.items[i].xml;
    }
    // ...other stuff again
}

//TableComponent's template
<div>
    <table>
        ...
        ...*ngFor="let item of items; let i = index;"...
        <tr (click)="toggleSelectedRow(i)">
            <td>{{item.id}}</td>
            <td>{{item.time}}</td>
        </tr>
        ...
    </table>
</div>
<xml-detail [xml]="selectedItemsXml"></xml-detail>

@Component
export class XmlDetailComponent {
    @Input() xml: string;
}

//XmlDetailComponent's template
<div>
    ```{{xml}}```
</div>
</code>```

Everything worked fine until I wanted to add syntax highlighting for xml. First I wanted to use plugin ng2-prism, but I had problems to make it work correctly. After I saw issues in its git repo, I threw it away. What I tried next was to create directive using highlight.js based on this post: highlight.js does not work with Angular 2. Xml is highlighted using this method, but only the first time row is clicked. When another row is clicked, new xml is not even displayed. I also tried to use prism.js but I'm getting the same behavior. Once some xml string is first time binded, displayed in code element and highlighted using either highlight.js or prism.js, it remains.

My guess is it is related with how DOM and data binding works in angular 2, because without using syntax highlighting, I'm binding and passing string to code element every time row is selected. Using highlighting causes to bind string, pass it to code element and then pretiffy it. That means there is no simple string inside code element, but a lot of styled span elements, what causes problems to load new xml string when new row is selected. I also tried to bind "pre-prettified" string using Prism.highlight(text_to_prettify), but using this method causes to display xml with all of the span elements added by Prism.

Right now, I'm scratching my head thinking about how to solve this problem. Please give me some push how could I make it work.

答:
I would create a component that leverages prismjs.

Include the prismjs scripts including any from the components folder that you need.

Index.html

<link href="node_modules/prismjs/themes/prism.css" rel="stylesheet" />

```

<p>Install the latest type definition files for Prism (this will give you type-safety): </p>

<pre class="lang-ts prettyprint-override"><code>npm install @ryancavanaugh/prismjs
</code>```

Note: don't install @types/prismjs - its either out-of-date or not authored correctly. The author of prismjs recommends @ryancvanaugh/prismjs for the type definitions.

Add the folder to your typeRoots list property in tsconfig.json so that the typescript compiler can find it:

tsconfig.json (under compilerOptions)

"typeRoots": [
  "node_modules/@types",
  "node_modules/@ryancavanaugh"
]
```

<p>Create a custom <code>prism</code> component that calls <code>Prism.highlight</code>: </p>

<p><strong>prism.component.ts</strong></p>

<pre class="lang-ts prettyprint-override"><code>/// <reference path="../node_modules/@ryancavanaugh/prismjs/prism.d.ts" />
import {
    Component,
    AfterViewInit,
    Input,
    ElementRef,
    ViewChild
} from '@angular/core';

@Component({
    moduleId: module.id,
    selector: 'prism',
    template: `
        <div hidden="true" #rawContent>
            <ng-content></ng-content>
        </div>
        ```

        ```

    `
})
export class PrismComponent implements AfterViewInit {
    @Input() language: string;
    @ViewChild("rawContent") rawContent: ElementRef;
    content: string;

    constructor(private elementRef:ElementRef) {
     }

    ngAfterViewInit() {
        this.content = Prism.highlight(this.rawContent.nativeElement.innerHTML, Prism.languages[this.language]);
     }
}
</code>```

Declare the Prism component in app.module:

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule  } from '@angular/platform-browser';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { PrismComponent } from './prism.component';

@NgModule({
    imports: [
        BrowserModule,
        HttpModule
        ],
    declarations: [AppComponent, PrismComponent],
    providers: [/* TODO: Providers go here */],
    bootstrap: [AppComponent],
})
export class AppModule { }
```

<p>Use it like this: </p>

<pre class="lang-ts prettyprint-override"><code><prism language="csharp">
    var x = 3;
    class T
    {{ '{' }}
    {{ '}' }}
</prism>
</code>```

Title: Syntax highlighting in Angular 2

Body:
I'm creating simple web app using angular 2. I have two components there. First is basically table with some data rows. When click on row is performed, data corresponding to row are displayed in the second component. Data are XML, loaded to code element. It looks something like

@Component
export class TableComponent {
    items: Data[];
    selectedItemsXml: string;
    // ...other stuff

    //when row is clicked
    toggleSelectedRow(rowIndex: number) {
        // ...other stuff related to change row's background color
        this.selectedItemsXml = this.items[i].xml;
    }
    // ...other stuff again
}

//TableComponent's template

        ...
        ...*ngFor="let item of items; let i = index;"...

            {{item.id}}
            {{item.time}}

        ...

<xml-detail [xml]="selectedItemsXml"></xml-detail>

@Component
export class XmlDetailComponent {
    @Input() xml: string;
}

//XmlDetailComponent's template

{{xml}}

Everything worked fine until I wanted to add syntax highlighting for xml. First I wanted to use plugin ng2-prism, but I had problems to make it work correctly. After I saw issues in its git repo, I threw it away. What I tried next was to create directive using highlight.js based on this post: highlight.js does not work with Angular 2. Xml is highlighted using this method, but only the first time row is clicked. When another row is clicked, new xml is not even displayed. I also tried to use prism.js but I'm getting the same behavior. Once some xml string is first time binded, displayed in code element and highlighted using either highlight.js or prism.js, it remains.

My guess is it is related with how DOM and data binding works in angular 2, because without using syntax highlighting, I'm binding and passing string to code element every time row is selected. Using highlighting causes to bind string, pass it to code element and then pretiffy it. That means there is no simple string inside code element, but a lot of styled span elements, what causes problems to load new xml string when new row is selected. I also tried to bind "pre-prettified" string using Prism.highlight(text_to_prettify), but using this method causes to display xml with all of the span elements added by Prism.

Right now, I'm scratching my head thinking about how to solve this problem. Please give me some push how could I make it work.

Body:
I would create a component that leverages prismjs.

Include the prismjs scripts including any from the components folder that you need.

Index.html

<link href="node_modules/prismjs/themes/prism.css" rel="stylesheet" />
<script src="node_modules/prismjs/prism.js"></script>
<script src="node_modules/prismjs/components/prism-core.js"></script>
<script src="node_modules/prismjs/components/prism-clike.js"></script>
<script src="node_modules/prismjs/components/prism-csharp.js"></script>

Install the latest type definition files for Prism (this will give you type-safety):

npm install @ryancavanaugh/prismjs

Note: don't install @types/prismjs - its either out-of-date or not authored correctly. The author of prismjs recommends @ryancvanaugh/prismjs for the type definitions.

Add the folder to your typeRoots list property in tsconfig.json so that the typescript compiler can find it:

tsconfig.json (under compilerOptions)

"typeRoots": [
  "node_modules/@types",
  "node_modules/@ryancavanaugh"
]

Create a custom prism component that calls Prism.highlight:

prism.component.ts

/// <reference path="../node_modules/@ryancavanaugh/prismjs/prism.d.ts" />
import {
    Component,
    AfterViewInit,
    Input,
    ElementRef,
    ViewChild
} from '@angular/core';

@Component({
    moduleId: module.id,
    selector: 'prism',
    template: `
        <div hidden="true" #rawContent>
            <ng-content></ng-content>
        </div>
        <pre>
            <code [innerHTML]="content">
            </code>
        </pre>

    `
})
export class PrismComponent implements AfterViewInit {
    @Input() language: string;
    @ViewChild("rawContent") rawContent: ElementRef;
    content: string;

    constructor(private elementRef:ElementRef) {
     }

    ngAfterViewInit() {
        this.content = Prism.highlight(this.rawContent.nativeElement.innerHTML, Prism.languages[this.language]);
     }
}

Declare the Prism component in app.module:

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule  } from '@angular/platform-browser';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { PrismComponent } from './prism.component';

@NgModule({
    imports: [
        BrowserModule,
        HttpModule
        ],
    declarations: [AppComponent, PrismComponent],
    providers: [/* TODO: Providers go here */],
    bootstrap: [AppComponent],
})
export class AppModule { }

Use it like this:

<prism language="csharp">
    var x = 3;
    class T
    {{ '{' }}
    {{ '}' }}
</prism>


来源: stackexchange

问:
Removing white space on the right side of a page
I am aware this is very basic but I have been trying so many ways of removing the white space on the right side of my page yet still it's been a little problem for me as a learner. The sign_in and paratext are inline as shown but when I used set the margins and paddings to 0 to remove the white space from the right side of my page, the sign in (which is the login form) moves below the paratext instead of staying inline.</p>

答:
Here you go. Hope this helps you.

body {
  margin: 0;
  padding: 0;
}

.sign_in {
  display: inline-block;
  width: 55%;
  font-size: 3vw;
  margin-left: 30px;
}

.paratext {
  display: inline-block;
  font-size: 3vw;
  width: 35%;
  color: #008B8B;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
  <title>Example</title>
</head>
<body>
<div class="paratext">
  <h1>Get ready to sell Smarter, Better, Faster.</h1>
  <p>Dosty CRM is the latest e-customer relationship management system being used currently by tech companies. Easy and Secure. </p>
</div>

<div class="sign_in" id="sign_in">
  <form (ngSubmit)="submitForm(l)" #l="ngForm">

    <h1 style="color:#008B8B; font-weight: 900; font-size: 40px;" >     <b>Sign In </b></h1><br>
    <div class="row">
      <div class="col-sm-6">
        <div class="form-group">
          <label for="email">Email</label>
          <input type="text" class="form-control" id="email" name="email" placeholder="First Name" [(ngModel)]="login.email" required>

        </div>
    </div>
</div>

<div class="row">
  <div class="col-sm-6">
    <div class="form-group">
      <label for="password">Password</label>
      <input type="password" class="form-control" id="password"  name="password" placeholder="password" [(ngModel)]="login.password">
    </div>
  </div>
</div>

<div class="row">
  <div class="col-sm-3">
    <div class="form-group">
      <input type="checkbox" value="Remember Me" id="remember_me" >
      <label >Remember Me  </label>
    </div>
</div>
<div class="col-sm-3">
  <div class="form-group">
    <p class="text-right"><span class="forgot-password">Forgot password?</span></p>
  </div>
</div>
</div>
  <div class="row">
    <div class="col-sm-2">
      <div class="form-group">
        <button class="button" type="submit" style="font-weight: 900; background-color:#008B8B;" ><span>Login </span></button>
    </div>
  </div>
</div>

  <div class="row">
    <div class="col-sm-6">
      <div class="form-group">
        <p class="text-right">
        <span>Already a member?</span></p>
      </div>
    </div>
  </div>
</form>
</div>
</body>
<html></code>```

ContentLicense: CC BY-SA 4.0

Body:
Here you go. Hope this helps you.

body {
  margin: 0;
  padding: 0;
}

.sign_in {
  display: inline-block;
  width: 55%;
  font-size: 3vw;
  margin-left: 30px;
}

.paratext {
  display: inline-block;
  font-size: 3vw;
  width: 35%;
  color: #008B8B;
}

<html>
<head>
  <title>Example</title>
</head>
<body>
<div class="paratext">
  <h1>Get ready to sell Smarter, Better, Faster.</h1>
  <p>Dosty CRM is the latest e-customer relationship management system being used currently by tech companies. Easy and Secure. </p>
</div>

<div class="sign_in" id="sign_in">
  <form (ngSubmit)="submitForm(l)" #l="ngForm">

    <h1 style="color:#008B8B; font-weight: 900; font-size: 40px;" >     <b>Sign In </b></h1><br>
    <div class="row">
      <div class="col-sm-6">
        <div class="form-group">
          <label for="email">Email</label>
          <input type="text" class="form-control" id="email" name="email" placeholder="First Name" [(ngModel)]="login.email" required>

        </div>
    </div>
</div>

<div class="row">
  <div class="col-sm-6">
    <div class="form-group">
      <label for="password">Password</label>
      <input type="password" class="form-control" id="password"  name="password" placeholder="password" [(ngModel)]="login.password">
    </div>
  </div>
</div>

<div class="row">
  <div class="col-sm-3">
    <div class="form-group">
      <input type="checkbox" value="Remember Me" id="remember_me" >
      <label >Remember Me  </label>
    </div>
</div>
<div class="col-sm-3">
  <div class="form-group">
    <p class="text-right"><span class="forgot-password"><a style=" color:#008B8B;"  href="#">Forgot password?</a></span></p>
  </div>
</div>
</div>
  <div class="row">
    <div class="col-sm-2">
      <div class="form-group">
        <button class="button" type="submit" style="font-weight: 900; background-color:#008B8B;" ><span>Login </span></button>
    </div>
  </div>
</div>

  <div class="row">
    <div class="col-sm-6">
      <div class="form-group">
        <p class="text-right">
        <span><a style="color:#008B8B;" href="#">Already a member?</a></span></p>
      </div>
    </div>
  </div>
</form>
</div>
</body>
<html>

ContentLicense: CC BY-SA 3.0


问:
Swift 3: How to Insert Array of an NSObject to another Array
I have an Array of [Hashtag]. The Hashtag NSObject simply holds a variable for the hashtagName which is a String?. One array is a categoriesArray and the other is a fashionArray. What I would like is when I tap a certain indexPath in my didSelectItemAtIndexPath method, I want to insert the fashionArray into the categoriesArray at the selected Index. The issue I have is that it wants an array of Strings and not an array of Hashtag. How do I achieve this? Thanks guys. Code is below:

```<code>import UIKit

class Hashtag: NSObject {

    var hashtagName: String?
}

private let reuseIdentifier = "Cell"

class HashtagView: UICollectionViewController, UICollectionViewDelegateFlowLayout {

    var categoriesArray = [Hashtag]()

    var fashionArray = [Hashtag]()

    override func viewDidLoad() {
        super.viewDidLoad()

        self.navigationController?.navigationBar.tintColor = .white
        navigationItem.title = "Hashtag"

        self.collectionView?.backgroundColor = .white
        self.collectionView?.register(HashtagCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        self.collectionView?.contentInset = UIEdgeInsetsMake(10, 0, 0, 0)

        handleFetchCategories()
        handleFetchFashionHashtags()
    }

    override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        if indexPath.item == 1 {
            // insert here
            self.categoriesArray.insert(fashionArray[indexPath.item].hashtagName, at: 1)
            print(categoriesArray)
        }

    }
</code>```

答:
To insert that
Better is use dictionary>, where key is your indexpath.row and value is collection of all objects of Hashtag.</p>

Body:
I have an Array of [Hashtag]. The Hashtag NSObject simply holds a variable for the hashtagName which is a String?. One array is a categoriesArray and the other is a fashionArray. What I would like is when I tap a certain indexPath in my didSelectItemAtIndexPath method, I want to insert the fashionArray into the categoriesArray at the selected Index. The issue I have is that it wants an array of Strings and not an array of Hashtag. How do I achieve this? Thanks guys. Code is below:

import UIKit

class Hashtag: NSObject {

    var hashtagName: String?
}

private let reuseIdentifier = "Cell"

class HashtagView: UICollectionViewController, UICollectionViewDelegateFlowLayout {

    var categoriesArray = [Hashtag]()

    var fashionArray = [Hashtag]()

    override func viewDidLoad() {
        super.viewDidLoad()

        self.navigationController?.navigationBar.tintColor = .white
        navigationItem.title = "Hashtag"

        self.collectionView?.backgroundColor = .white
        self.collectionView?.register(HashtagCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        self.collectionView?.contentInset = UIEdgeInsetsMake(10, 0, 0, 0)

        handleFetchCategories()
        handleFetchFashionHashtags()
    }

    override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        if indexPath.item == 1 {
            // insert here
            self.categoriesArray.insert(fashionArray[indexPath.item].hashtagName, at: 1)
            print(categoriesArray)
        }

    }


问:
chai-webdriver (node) ... describe is not a function
I keep getting the error that describe is not a function.
How can I fix this

```<code>// Require chai.js expect module for assertions
var chai = require('chai');
var expect = require('chai').expect;
chai.use = require ('chai-as-promised')
// Application Server
var serverUri = '0.0.0.0:3000';

// Official selenium webdriver testing setup
var webdriver = require('selenium-webdriver');

describe('basic test', function () {
    var driver;
    before(function(){
        // Start of test use this
        driver = new webdriver.Builder().
        withCapabilities(webdriver.Capabilities.chrome()).
        build();
        console.log("Selenium Webdriver Chrome Started");
    });

    after(function(){
        // End of test use this.
        driver.quit();
    });

    it('should be on correct page', function (done) {
        this.timeout(10000);
        driver.get(serverUri);
        driver.getTitle().then(function(title) {
            expect(title).to.equal('Some String Here');
            done();
            console.log("Selenium Webdriver Chrome Shutdown");
        })
    });
});
</code>```

the error I get after running this is :

describe is not a function

答:
You forgot to require mocha (assuming you installed it)..

Try adding

const { describe, it, before, after } = require('mocha');

Body:
I keep getting the error that describe is not a function.
How can I fix this

// Require chai.js expect module for assertions
var chai = require('chai');
var expect = require('chai').expect;
chai.use = require ('chai-as-promised')
// Application Server
var serverUri = '0.0.0.0:3000';

// Official selenium webdriver testing setup
var webdriver = require('selenium-webdriver');

describe('basic test', function () {
    var driver;
    before(function(){
        // Start of test use this
        driver = new webdriver.Builder().
        withCapabilities(webdriver.Capabilities.chrome()).
        build();
        console.log("Selenium Webdriver Chrome Started");
    });

    after(function(){
        // End of test use this.
        driver.quit();
    });

    it('should be on correct page', function (done) {
        this.timeout(10000);
        driver.get(serverUri);
        driver.getTitle().then(function(title) {
            expect(title).to.equal('Some String Here');
            done();
            console.log("Selenium Webdriver Chrome Shutdown");
        })
    });
});

the error I get after running this is :

describe is not a function


问:
PHP explode specific text beetwen different elements
I have result

```<code>{"success":true,"data":{"id":6583879,"listingId":"11745/3470/OMS"}}
</code>```

I need to explode it on two arrays:

```<code>$id = 6583879;
</code>```

and

```<code>$listid = 11745/3470/OMS
</code>```

I'd like to avoid counting characters, this response may be another in future. I was thinking about taking:

everything between "id": and comma

everything between "listingId":" and "

答:
just decode the json data

```<code>$data = '{"success":true,"data":[{"id":6583879,"listingId":"11745/3470/OMS"}]}';

$arr = json_decode($data);
$id = array();
$listing = array();

for($i=0; $i < count($arr->data); $i++){
    $id[$i] = $arr->data[$i]->id;
    $listing[$i] = $arr->data[$i]->listingId;
}

//loop array to view data
foreach($id as $value){
   echo $value.'<br>';
}

?>
</code>```

Body:
I have result

{"success":true,"data":{"id":6583879,"listingId":"11745/3470/OMS"}}

I need to explode it on two arrays:

$id = 6583879;

and

$listid = 11745/3470/OMS

I'd like to avoid counting characters, this response may be another in future. I was thinking about taking:

everything between "id": and comma

everything between "listingId":" and "

Body:
just decode the json data

$data = '{"success":true,"data":[{"id":6583879,"listingId":"11745/3470/OMS"}]}';

$arr = json_decode($data);
$id = array();
$listing = array();

for($i=0; $i < count($arr->data); $i++){
    $id[$i] = $arr->data[$i]->id;
    $listing[$i] = $arr->data[$i]->listingId;
}

//loop array to view data
foreach($id as $value){
   echo $value.'<br>';
}

?>


问:
Copy Data in some other sheet based on search Criteria and also follow matching rule or procedure
I have sheet that contains Data from (A10: I37). I want to sort Data based on specific word in Column A. In My case it is Yes and then I want to copy the Data in front of the word Yes to some other sheet 2 but I want the data to be assigned in front of their specific words like Info 1 Info 2 Info 3.    I want my data to be copied to sheet2 based on search criteria like Yes and under their respective words assigned in Row 10. I have tried to write something but still I am unable to approach what I want. Any guidance will be appreciated.

Let’s make it simple.

```<code>         **Sheet1**                              **Sheet 2**
 10 Col A    Info 1   Info 2   Info 3   Info 4

    Yes       Car      Bus     Plane    Truck    Info 1   Car   1  Bat  tall

    No        1         2       3         4      Info 2   Bus   2  Pen   5
    Yes      bat       pen      copy     ball    Info 3   Plane 3  copy  6
    No       tall       5       6         7      Info 4   truck 4  ball  7
</code>```

Code

```<code>       Dim i As Integer
       Dim Percent As Variant
       Dim Search As String
       Search = InputBox("Enter your search word here")
       If Search = "" Then Exit Sub
       For i = 1 To Range("A65536").Cells.End(xlUp).Row
           If Cells(i, 1) = Search Then GoTo Other
         Next i
               MsgBox "Nicht in Spalte enthalten"
          Exit Sub
       Other:
         For i = 1 To Range("A65536").Cells.End(xlUp).Row
          If Cells(i, 1) = Search Then
            Cells(i, 2).Select
             'Range("B17").Select
            Selection.Copy
             'Range("K18").Select
            Sheets("Sheet1").Cells(i, 2).Copy Destination:=Sheets("Sheet2").Range("C16")

          End If
          Next i
</code>```

Code 2
This code I found from somewhere tried to modify it as par my demand but but till unable to mold it.

```<code>Dim c As Range
Dim j As Integer
Dim Source As Worksheet
Dim Target As Worksheet

' Change worksheet designations as needed
Set Source = ActiveWorkbook.Worksheets("Sheet1")
Set Target = ActiveWorkbook.Worksheets("Sheet2")

j = 1     ' Start copying to row 1 in target sheet
For Each c In Source.Range("A1:A1000")   ' Do 1000 rows
    If c = "yes" Then
     Source.Rows(c.Row).Copy Target.Rows(j)

       j = j + 1
    End If
Next c
</code>```

This code only searches for Yes word and copy the whole row into sheet 2 but I want to data to be copied in next sheet based on matching criteria .

Any help would be appreciated as I have tried but remained unable to find a way. Thanks.

答:
I would modify the second macro that you found to consider the cell instead of a range and transpose the copied range in the target sheet:</p>

```<code> Dim i As Integer
 Dim j As Integer
 Dim Source As Worksheet
 Dim Target As Worksheet

 ' Change worksheet designations as needed
 Set Source = ActiveWorkbook.Worksheets("Sheet1")
 Set Target = ActiveWorkbook.Worksheets("Sheet2")

 Rows(1).Select.Copy
 Target.Cells(1,1).PasteSpecial Transpose:=True

 j = 2     ' Start copying to column 2 in target sheet
 i = 1     ' Start Searching from the first row in source sheet

 While Source.Cells(i,1) <> ""

    If Source.Cells(i,1) = "yes" Then
       Rows(i).Select.Copy
       Target.Cells(1,j).PasteSpecial Transpose:=True
       j = j + 1
    End If

    i = i + 1
 Wend
</code>```

Body:
I have sheet that contains Data from (A10: I37). I want to sort Data based on specific word in Column A. In My case it is Yes and then I want to copy the Data in front of the word Yes to some other sheet 2 but I want the data to be assigned in front of their specific words like Info 1 Info 2 Info 3.    I want my data to be copied to sheet2 based on search criteria like Yes and under their respective words assigned in Row 10. I have tried to write something but still I am unable to approach what I want. Any guidance will be appreciated.

Let’s make it simple.

         **Sheet1**                              **Sheet 2**
 10 Col A    Info 1   Info 2   Info 3   Info 4

    Yes       Car      Bus     Plane    Truck    Info 1   Car   1  Bat  tall

    No        1         2       3         4      Info 2   Bus   2  Pen   5
    Yes      bat       pen      copy     ball    Info 3   Plane 3  copy  6
    No       tall       5       6         7      Info 4   truck 4  ball  7

Code

       Dim i As Integer
       Dim Percent As Variant
       Dim Search As String
       Search = InputBox("Enter your search word here")
       If Search = "" Then Exit Sub
       For i = 1 To Range("A65536").Cells.End(xlUp).Row
           If Cells(i, 1) = Search Then GoTo Other
         Next i
               MsgBox "Nicht in Spalte enthalten"
          Exit Sub
       Other:
         For i = 1 To Range("A65536").Cells.End(xlUp).Row
          If Cells(i, 1) = Search Then
            Cells(i, 2).Select
             'Range("B17").Select
            Selection.Copy
             'Range("K18").Select
            Sheets("Sheet1").Cells(i, 2).Copy Destination:=Sheets("Sheet2").Range("C16")

          End If
          Next i

Code 2
This code I found from somewhere tried to modify it as par my demand but but till unable to mold it.

Dim c As Range
Dim j As Integer
Dim Source As Worksheet
Dim Target As Worksheet

' Change worksheet designations as needed
Set Source = ActiveWorkbook.Worksheets("Sheet1")
Set Target = ActiveWorkbook.Worksheets("Sheet2")

j = 1     ' Start copying to row 1 in target sheet
For Each c In Source.Range("A1:A1000")   ' Do 1000 rows
    If c = "yes" Then
     Source.Rows(c.Row).Copy Target.Rows(j)

       j = j + 1
    End If
Next c

This code only searches for Yes word and copy the whole row into sheet 2 but I want to data to be copied in next sheet based on matching criteria .

Any help would be appreciated as I have tried but remained unable to find a way. Thanks.

Body:
I would modify the second macro that you found to consider the cell instead of a range and transpose the copied range in the target sheet:

 Dim i As Integer
 Dim j As Integer
 Dim Source As Worksheet
 Dim Target As Worksheet

 ' Change worksheet designations as needed
 Set Source = ActiveWorkbook.Worksheets("Sheet1")
 Set Target = ActiveWorkbook.Worksheets("Sheet2")

 Rows(1).Select.Copy
 Target.Cells(1,1).PasteSpecial Transpose:=True

 j = 2     ' Start copying to column 2 in target sheet
 i = 1     ' Start Searching from the first row in source sheet

 While Source.Cells(i,1) <> ""

    If Source.Cells(i,1) = "yes" Then
       Rows(i).Select.Copy
       Target.Cells(1,j).PasteSpecial Transpose:=True
       j = j + 1
    End If

    i = i + 1
 Wend


问:
IBM Watson Alchemy API VerifyError
I'm working on alchemy API. The Reference link used Alchemy Ref.

My Android code

```<code> Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            try
            {
                AlchemyLanguage service = new AlchemyLanguage();
                service.setApiKey("xxx - My API Key");

                Map<String,Object> param = new HashMap<String, Object>();
                param.put(AlchemyLanguage.TEXT, TextValue);
                DocumentSentiment sentiment = service.getSentiment(param).execute();
                SentimentValue = sentiment.getText();
                System.out.println(sentiment);

                SentimentType = sentiment.getSentiment().getType().name();
            }
            catch (Exception ex)
            {
                Log.d("Exception : " , ex.toString());
            }
        }
    });

    thread.start();
    Toast.makeText(MainActivity.this, SentimentType+" ", Toast.LENGTH_SHORT).show();
</code>```

The program terminates during the initialization of the class

```<code> AlchemyLanguage service = new AlchemyLanguage();
</code>```

Log :

```<code>E/dalvikvm: Could not find class 'javax.naming.InitialContext', referenced from method com.ibm.watson.developer_cloud.util.CredentialUtils.getKeyUsingJNDI
W/dalvikvm: VFY: unable to resolve new-instance 2848 (Ljavax/naming/InitialContext;) in Lcom/ibm/watson/developer_cloud/util/CredentialUtils;
D/dalvikvm: VFY: replacing opcode 0x22 at 0x0007
W/dalvikvm: VFY: unable to resolve exception class 2849 (Ljavax/naming/NamingException;)
W/dalvikvm: VFY: unable to find exception handler at addr 0x2e
W/dalvikvm: VFY:  rejected Lcom/ibm/watson/developer_cloud/util/CredentialUtils;.getKeyUsingJNDI (Ljava/lang/String;)Ljava/lang/String;
W/dalvikvm: VFY:  rejecting opcode 0x0d at 0x002e
W/dalvikvm: VFY:  rejected Lcom/ibm/watson/developer_cloud/util/CredentialUtils;.getKeyUsingJNDI (Ljava/lang/String;)Ljava/lang/String;
W/dalvikvm: Verifier rejected class Lcom/ibm/watson/developer_cloud/util/CredentialUtils;
W/dalvikvm: threadid=12: thread exiting with uncaught exception (group=0x40d9e468)
E/AndroidRuntime: FATAL EXCEPTION: Thread-754
                  java.lang.VerifyError: com/ibm/watson/developer_cloud/util/CredentialUtils
                      at com.ibm.watson.developer_cloud.service.WatsonService.<init>(WatsonService.java:102)
                      at com.ibm.watson.developer_cloud.service.AlchemyService.<init>(AlchemyService.java:55)
                      at com.ibm.watson.developer_cloud.alchemy.v1.AlchemyLanguage.<init>(AlchemyLanguage.java:54)
                      at com.numarga.alchemyinbuildtest.MainActivity$1$1.run(MainActivity.java:53)
                      at java.lang.Thread.run(Thread.java:856)
I/Process: Sending signal. PID: 23131 SIG: 9
Application terminated.
</code>```

答:
This was a bug in the Java SDK. Make sure you use a version > 3.5.0 in gradle, use something like 3.7.1

```<code>'com.ibm.watson.developer_cloud:alchemy:3.7.1'
</code>```

Then call AlchemyLanguage sentiment analysis:

```<code>AlchemyLanguage service = new AlchemyLanguage();
service.setApiKey("xxx - My API Key");

Map<String,Object> param = new HashMap<String, Object>();
param.put(AlchemyLanguage.TEXT, TextValue);

DocumentSentiment sentiment = service.getSentiment(param).execute();
System.out.println(sentiment);
</code>```

Title: IBM Watson Alchemy API VerifyError

Body:
I'm working on alchemy API. The Reference link used Alchemy Ref.

My Android code

 Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            try
            {
                AlchemyLanguage service = new AlchemyLanguage();
                service.setApiKey("xxx - My API Key");

                Map<String,Object> param = new HashMap<String, Object>();
                param.put(AlchemyLanguage.TEXT, TextValue);
                DocumentSentiment sentiment = service.getSentiment(param).execute();
                SentimentValue = sentiment.getText();
                System.out.println(sentiment);

                SentimentType = sentiment.getSentiment().getType().name();
            }
            catch (Exception ex)
            {
                Log.d("Exception : " , ex.toString());
            }
        }
    });

    thread.start();
    Toast.makeText(MainActivity.this, SentimentType+" ", Toast.LENGTH_SHORT).show();

The program terminates during the initialization of the class

 AlchemyLanguage service = new AlchemyLanguage();

Log :

E/dalvikvm: Could not find class 'javax.naming.InitialContext', referenced from method com.ibm.watson.developer_cloud.util.CredentialUtils.getKeyUsingJNDI
W/dalvikvm: VFY: unable to resolve new-instance 2848 (Ljavax/naming/InitialContext;) in Lcom/ibm/watson/developer_cloud/util/CredentialUtils;
D/dalvikvm: VFY: replacing opcode 0x22 at 0x0007
W/dalvikvm: VFY: unable to resolve exception class 2849 (Ljavax/naming/NamingException;)
W/dalvikvm: VFY: unable to find exception handler at addr 0x2e
W/dalvikvm: VFY:  rejected Lcom/ibm/watson/developer_cloud/util/CredentialUtils;.getKeyUsingJNDI (Ljava/lang/String;)Ljava/lang/String;
W/dalvikvm: VFY:  rejecting opcode 0x0d at 0x002e
W/dalvikvm: VFY:  rejected Lcom/ibm/watson/developer_cloud/util/CredentialUtils;.getKeyUsingJNDI (Ljava/lang/String;)Ljava/lang/String;
W/dalvikvm: Verifier rejected class Lcom/ibm/watson/developer_cloud/util/CredentialUtils;
W/dalvikvm: threadid=12: thread exiting with uncaught exception (group=0x40d9e468)
E/AndroidRuntime: FATAL EXCEPTION: Thread-754
                  java.lang.VerifyError: com/ibm/watson/developer_cloud/util/CredentialUtils
                      at com.ibm.watson.developer_cloud.service.WatsonService.<init>(WatsonService.java:102)
                      at com.ibm.watson.developer_cloud.service.AlchemyService.<init>(AlchemyService.java:55)
                      at com.ibm.watson.developer_cloud.alchemy.v1.AlchemyLanguage.<init>(AlchemyLanguage.java:54)
                      at com.numarga.alchemyinbuildtest.MainActivity$1$1.run(MainActivity.java:53)
                      at java.lang.Thread.run(Thread.java:856)
I/Process: Sending signal. PID: 23131 SIG: 9
Application terminated.

Body:
This was a bug in the Java SDK. Make sure you use a version > 3.5.0 in gradle, use something like 3.7.1

'com.ibm.watson.developer_cloud:alchemy:3.7.1'

Then call AlchemyLanguage sentiment analysis:

AlchemyLanguage service = new AlchemyLanguage();
service.setApiKey("xxx - My API Key");

Map<String,Object> param = new HashMap<String, Object>();
param.put(AlchemyLanguage.TEXT, TextValue);

DocumentSentiment sentiment = service.getSentiment(param).execute();
System.out.println(sentiment);


问:
Ionic 2 Tabs reset view when clicking another tab
Wondering how I can do this. When using ionic tabs, lets say I have a simple structure like

```<code>Home
About
Product -> Product Info
</code>```

In my Products page (product.ts) I have something like

```<code>viewItem(payload) {
this.navCtrl.push(ResultPage, {
  data: payload
});
}
// ^ Pass data to new Product info page.
</code>```

The product info page loads fine all data passes in and I get a back arrow in the nav bar.

Now if I click another tab like About and go back to Product it still shows the pushed Product Info page.

How can I get it to reset back to the Product page when I leave the view and navigate back?

Update:

If I do this

```<code>ionViewDidLeave() {
this.viewCtrl.dismiss().catch(() => console.log('Some bug going on..'));
}
</code>```

Works, but have to catch the error otherwise returns

```<code>Runtime Error Uncaught (in promise): false
</code>```

Looks like its a bug  - https://github.com/driftyco/ionic/issues/10046

If anyone has any other suggestion its much appreciated.

答:
NavController comes with events. One of them is ionViewDidLeave.

In that you can pop the page you don't want to be kept stacked.

```<code>ionViewDidLeave() {
   this.navCtrl.pop();
}
</code>```

Body:
Wondering how I can do this. When using ionic tabs, lets say I have a simple structure like

Home
About
Product -> Product Info

In my Products page (product.ts) I have something like

viewItem(payload) {
this.navCtrl.push(ResultPage, {
  data: payload
});
}
// ^ Pass data to new Product info page.

The product info page loads fine all data passes in and I get a back arrow in the nav bar.

Now if I click another tab like About and go back to Product it still shows the pushed Product Info page.

How can I get it to reset back to the Product page when I leave the view and navigate back?

Update:

If I do this

ionViewDidLeave() {
this.viewCtrl.dismiss().catch(() => console.log('Some bug going on..'));
}

Works, but have to catch the error otherwise returns

Runtime Error Uncaught (in promise): false

Looks like its a bug  - https://github.com/driftyco/ionic/issues/10046

If anyone has any other suggestion its much appreciated.

Body:
NavController comes with events. One of them is ionViewDidLeave.

In that you can pop the page you don't want to be kept stacked.

ionViewDidLeave() {
   this.navCtrl.pop();
}


问:
Change the url based on current_user - ROR
Say for instance I have a posts controller that currently has a method user_posts which shows all of the posts that are associated with the user with the associated id as so:

```<code>def user_posts
    @user = User.find(params[:id])
    @posts = @user.posts.all
end
</code>```

I want the url to be: foo.com/my_posts when the posts have the same ID as my current_user; How would I do this? currently my routes are set up as so:

```<code>get 'user/posts/:id', to: 'posts#user_posts', as: 'user/posts'
</code>```

I know that I could create an entirely new controller action for my_posts but I want to know if there is a way to do it in the config/routes.

If for example I am browsing throughout the site and tap on a link that says "user posts" I would expect to go the the users posts and if that user happens to be me I would like the url to show website.com/my_posts

答:
If I understand well, you have a list of users (including the currently connected user) and each has a link 'user posts' to see the user's posts.

You can simply do:

views

In your views, change the user post link according to the user id. As you loop through your users, check if the user's id is the same as the currently logged user. If yes, change the link to the /my_posts route as follow:

```<code><% if user.id == current_user.id %>
  <%= link_to "My posts", my_posts_path %>
<% else %>
  <%= link_to "User posts", user_posts_path(user) %>
<% end %>
</code>```

routes.rb

Add a my_posts route that points to the same controller method as user/posts.

```<code>get 'user/posts/:id', to: 'posts#user_posts', as: 'user/posts'
get 'my_posts', to: 'posts#user_posts', as: 'my_posts'
</code>```

controller

In your controller method, we need to instantiate the @user to get its posts. If there is no :id in the params (like the /my_posts route), then set the @user to the current_user. If an :id is passed, set the @user by fetching it from the db.

```<code>def user_posts
    @user = params[:id].present? ? User.find(params[:id]) : current_user
    @posts = @user.posts.all
end
</code>```

No need to do checking in the routes.rb file. This is simple and more "Rails" like.

Is this what you are looking for?

Body:
Say for instance I have a posts controller that currently has a method user_posts which shows all of the posts that are associated with the user with the associated id as so:

def user_posts
    @user = User.find(params[:id])
    @posts = @user.posts.all
end

I want the url to be: foo.com/my_posts when the posts have the same ID as my current_user; How would I do this? currently my routes are set up as so:

get 'user/posts/:id', to: 'posts#user_posts', as: 'user/posts'

I know that I could create an entirely new controller action for my_posts but I want to know if there is a way to do it in the config/routes.

If for example I am browsing throughout the site and tap on a link that says "user posts" I would expect to go the the users posts and if that user happens to be me I would like the url to show website.com/my_posts

Body:
If I understand well, you have a list of users (including the currently connected user) and each has a link 'user posts' to see the user's posts.

You can simply do:

views

In your views, change the user post link according to the user id. As you loop through your users, check if the user's id is the same as the currently logged user. If yes, change the link to the /my_posts route as follow:

<% if user.id == current_user.id %>
  <%= link_to "My posts", my_posts_path %>
<% else %>
  <%= link_to "User posts", user_posts_path(user) %>
<% end %>

routes.rb

Add a my_posts route that points to the same controller method as user/posts.

get 'user/posts/:id', to: 'posts#user_posts', as: 'user/posts'
get 'my_posts', to: 'posts#user_posts', as: 'my_posts'

controller

In your controller method, we need to instantiate the @user to get its posts. If there is no :id in the params (like the /my_posts route), then set the @user to the current_user. If an :id is passed, set the @user by fetching it from the db.

def user_posts
    @user = params[:id].present? ? User.find(params[:id]) : current_user
    @posts = @user.posts.all
end

No need to do checking in the routes.rb file. This is simple and more "Rails" like.

Is this what you are looking for?


问:
Wordpress & Secure Forms
Question on which way to take this project. Im creating a site that is in its simplest, a form that people can submit ideas. I want to have it post automatically to a home page.

Questions is, what is the best software out there to do this? Was thinking wordpress just because I know some php and how I could do it quickly.

Its almost similar to stackoverflow in that you ask a question, add tags to it, etc.

Any ideas?

答: getsatisfaction.com is a service that allows users to submit ideas or help requests.</p>

ContentLicense: CC BY-SA 2.5

Title: Wordpress & Secure Forms


问:
django rest framework changing id to url
Suppose, I have a model Collection and one-to-many relationship to CollectionImage

```<code>class Collection(models.Model):
    name = models.CharField(max_length=500)
    description = models.TextField(max_length=5000)
    publish = models.DateTimeField(auto_now=False, auto_now_add=True)
    author = models.CharField(max_length=500)

    def __str__(self):
        return self.name

class CollectionImage(models.Model):
    collection = models.ForeignKey('Collection', related_name='images')
    image = models.ImageField(height_field='height_field', width_field='width_field')
    height_field = models.IntegerField(default=0)
    width_field = models.IntegerField(default=0)

    def __str__(self):
        return self.collection.name
</code>```

I created a Serializer class for my model

```<code>class CollectionSerializer(ModelSerializer):

    class Meta:
        model = Collection
        fields = [
            'id',
            'name',
            'description',
            'publish',
            'author',
            'images',
        ]
</code>```

and a API View

```<code>class CollectionList(ListAPIView):
    queryset = Collection.objects.all()
    serializer_class = CollectionSerializer
</code>```

The problem that i have, is that the field images gives an array of ids, where i would like it to be an array of Image urls, is it possible to do ?

答:
Yes, DRF is extremely flexible and can support this. I would suggest using a SerializerMethodField for this capability. It essentially allows you to map a serializer field to the result of a custom function.

Your implementation would look like this:

```<code>class CollectionSerializer(ModelSerializer):
    images = serializers.SerializerMethodField()

    class Meta:
        model = Collection
        fields = [
            'id',
            'name',
            'description',
            'publish',
            'author',
            'images',
        ]

    def get_images(self, obj):
        return [collection_image.image.url for collection_image in obj.images]
</code>```

Source:
http://www.django-rest-framework.org/api-guide/fields/#serializermethodfield

** the field is mapped to the method via the "get_" naming convention

Body:
Suppose, I have a model Collection and one-to-many relationship to CollectionImage

class Collection(models.Model):
    name = models.CharField(max_length=500)
    description = models.TextField(max_length=5000)
    publish = models.DateTimeField(auto_now=False, auto_now_add=True)
    author = models.CharField(max_length=500)

    def __str__(self):
        return self.name

class CollectionImage(models.Model):
    collection = models.ForeignKey('Collection', related_name='images')
    image = models.ImageField(height_field='height_field', width_field='width_field')
    height_field = models.IntegerField(default=0)
    width_field = models.IntegerField(default=0)

    def __str__(self):
        return self.collection.name

I created a Serializer class for my model

class CollectionSerializer(ModelSerializer):

    class Meta:
        model = Collection
        fields = [
            'id',
            'name',
            'description',
            'publish',
            'author',
            'images',
        ]

and a API View

class CollectionList(ListAPIView):
    queryset = Collection.objects.all()
    serializer_class = CollectionSerializer

The problem that i have, is that the field images gives an array of ids, where i would like it to be an array of Image urls, is it possible to do ?

Body:
Yes, DRF is extremely flexible and can support this. I would suggest using a SerializerMethodField for this capability. It essentially allows you to map a serializer field to the result of a custom function.

Your implementation would look like this:

class CollectionSerializer(ModelSerializer):
    images = serializers.SerializerMethodField()

    class Meta:
        model = Collection
        fields = [
            'id',
            'name',
            'description',
            'publish',
            'author',
            'images',
        ]

    def get_images(self, obj):
        return [collection_image.image.url for collection_image in obj.images]

Source:
http://www.django-rest-framework.org/api-guide/fields/#serializermethodfield

** the field is mapped to the method via the "get_" naming convention


问:
Creating a wrapper for Google Play/Apple app
I have created an app using AppSheet and I am looking for information on how to create a wrapper that will turn my AppSheet into an app that can be purchased/downloaded in the Google Play or Apple stores.
I have checked with AppSheet, they don't have anything in place at the moment to do this through them but they also said that there is nothing in their user agreement that prevents someone from doing what I am looking for.
I'm just new to app development, I've done websites, just not apps and am looking for a little help. </p>

答:
AppSheet now supports white-label apps. Please see What is a White Label Native App?

Also, most support for AppSheet questions happens via http://community.appsheet.com so that's the best place to get questions answered.


问:
static STL map of int and tuple returns 0
Building a calendar for my C++ class. I have a utility class of static methods and static containers. Most notably:

Dictionary.h

```<code>static std::map<int,std::tuple<std::string,int>>months;
static std::map<int,std::tuple<std::string,int>>::iterator mitr;
</code>```

This map contains, as keys, months 0-11. The tuple value contains the string representation of each month and the number of days of each month. For instance:

Dictionary.cpp

```<code>map<int,tuple<string,int>> Dictionary::initMonths(){
   map<int,tuple<string,int>>m;
   map<int,tuple<string,int>>::iterator mapitr = m.begin();
   m.insert(mapitr, make_pair(0,make_tuple("January",31)));
   m.insert(mapitr, make_pair(1,make_tuple("February",28)));
   // insert remaining months...
   return m;
}
</code>```

The problem occurs when I attempt to access this map from another class:

Calendar.cpp

```<code>Calendar::Calendar(){
  Dictionary::init();
  time_t t = chrono::system_clock::to_time_t(chrono::system_clock::now());
  tm* t2 = localtime(&t);
  int mo = (t2->tm_mon);
  Dictionary::mitr = Dictionary::months.find(mo);
  cout<<(*Dictionary::mitr).first<<endl; // => 0
  cout<<get<0>((*Dictionary::mitr).second)<<endl; // nothing
  }
</code>```

I'm not sure what I'm doing wrong here. Any suggestions would be appreciated.

EDIT:

```<code>void Dictionary::init(){
  packaged_task<map<int,tuple<string,int>>()>task3(initMonths);
  future<map<int,tuple<string,int>>>fu3 = task3.get_future();
  guarded_thread t3(std::move(task3));
  map<int,tuple<string,int>>months = fu3.get();
 }
</code>```

答:
How exactly do you init the map? Your Dictonary code shows a function Dictionary::initMonths(), which returns a map, but your example application code just calls  Dictionary::init(). If those functions are actually the same and this is just a typo, then you forgot to assign the return value of initMonths to the static months variable.

Just as a suggestion, having a map here seems really a bit like overkill - you actually don't want the property of map that it arranges sparse keys in a tree-like structure in this case. It might be easier (and faster, for what it's worth) to just use a vector or a fixed array and just access by index, without iterator etc.

Body:
Building a calendar for my C++ class. I have a utility class of static methods and static containers. Most notably:

Dictionary.h

static std::map<int,std::tuple<std::string,int>>months;
static std::map<int,std::tuple<std::string,int>>::iterator mitr;

This map contains, as keys, months 0-11. The tuple value contains the string representation of each month and the number of days of each month. For instance:

Dictionary.cpp

map<int,tuple<string,int>> Dictionary::initMonths(){
   map<int,tuple<string,int>>m;
   map<int,tuple<string,int>>::iterator mapitr = m.begin();
   m.insert(mapitr, make_pair(0,make_tuple("January",31)));
   m.insert(mapitr, make_pair(1,make_tuple("February",28)));
   // insert remaining months...
   return m;
}

The problem occurs when I attempt to access this map from another class:

Calendar.cpp

Calendar::Calendar(){
  Dictionary::init();
  time_t t = chrono::system_clock::to_time_t(chrono::system_clock::now());
  tm* t2 = localtime(&t);
  int mo = (t2->tm_mon);
  Dictionary::mitr = Dictionary::months.find(mo);
  cout<<(*Dictionary::mitr).first<<endl; // => 0
  cout<<get<0>((*Dictionary::mitr).second)<<endl; // nothing
  }

I'm not sure what I'm doing wrong here. Any suggestions would be appreciated.

EDIT:

void Dictionary::init(){
  packaged_task<map<int,tuple<string,int>>()>task3(initMonths);
  future<map<int,tuple<string,int>>>fu3 = task3.get_future();
  guarded_thread t3(std::move(task3));
  map<int,tuple<string,int>>months = fu3.get();
 }


问:
template specialization for static member functions; howto?
I am trying to implement a template function with handles void differently using template specialization.

The following code gives me an "Explicit specialization in non-namespace scope" in gcc:

```<code>template <typename T>
static T safeGuiCall(boost::function<T ()> _f)
{
    if (_f.empty())
        throw GuiException("Function pointer empty");
    {
        ThreadGuard g;
        T ret = _f();
        return ret;
    }
}

// template specialization for functions wit no return value
template <>
static void safeGuiCall<void>(boost::function<void ()> _f)
{
    if (_f.empty())
        throw GuiException("Function pointer empty");
    {
        ThreadGuard g;
        _f();
    }
}
</code>```

I have tried moving it out of the class (the class is not templated) and into the namespace but then I get the error "Explicit specialization cannot have a storage class". I have read many discussions about this, but people don't seem to agree how to specialize function templates. Any ideas?

答: I had a similar problem. If you look at the original post, I left the first static in, but took out the second and BOTH errors went away.</p>

Body:
I am trying to implement a template function with handles void differently using template specialization.

The following code gives me an "Explicit specialization in non-namespace scope" in gcc:

template <typename T>
static T safeGuiCall(boost::function<T ()> _f)
{
    if (_f.empty())
        throw GuiException("Function pointer empty");
    {
        ThreadGuard g;
        T ret = _f();
        return ret;
    }
}

// template specialization for functions wit no return value
template <>
static void safeGuiCall<void>(boost::function<void ()> _f)
{
    if (_f.empty())
        throw GuiException("Function pointer empty");
    {
        ThreadGuard g;
        _f();
    }
}

I have tried moving it out of the class (the class is not templated) and into the namespace but then I get the error "Explicit specialization cannot have a storage class". I have read many discussions about this, but people don't seem to agree how to specialize function templates. Any ideas?


问:
How to automatically execute FreeAndNill() after thread termination
At the moment I'm using additional thread to nicely free memory after thread.
Before you ask. No I can't use FreeOnTerminate:=true because I need .waitfor.
I also need FreeAndNil() because only in this way I can check if thread is running using Assigned(). Example code. </p>

```<code>procedure TForm1.Button1Click(Sender: TObject);
begin

  SupervisorThread:= TSupervisorThread.Create(True);
  SupervisorThread.FreeOnTerminate:=false; //MUST BE FALSE!
  SupervisorThread.Priority := tpNormal;
  SupervisorThread.Resume;

end;

procedure TSupervisorThread.Execute;
begin

  CleaningThread:= TCleaningThread.Create(True);
  CleaningThread.FreeOnTerminate:=true;
  CleaningThread.Priority := tpNormal;
  CleaningThread.Resume;

  //some loops here

end;

procedure TCleaningThread.Execute;
begin

  if Assigned(SupervisorThread)=true then
  begin
    SupervisorThread.WaitFor;
    FreeAndNil(SupervisorThread);
  end;

end;

procedure TForm2.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin

  if Assigned(SupervisorThread)=false then CanClose:=true
  else
  begin
    CanClose:=false;
    ShowMessage('Cannot close form because SiupervisorThread is still working');
  end;

end;
</code>```

答:
Use the TThread.OnTerminate event:

```<code>private
  procedure DoTerminateEvent(Sender: TObject);

var
  isRunning: Boolean;

procedure TForm2.DoTerminateEvent(Sender: TObject);
begin
  isRunning := False;
end;

procedure TForm2.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
  if (isRunning) then
  begin
    CanClose := false;
    ShowMessage('Cannot close form because SupervisorThread is still working')
  end else
    CanClose := true;
end;
</code>```

Set the OnTerminate handler when creating the Thread:

```<code>SupervisorThread := TSupervisorThread.Create(True);
...
SupervisorThread.OnTerminate := DoTerminateEvent;
SupervisorThread.Resume;
</code>```

Or, pass it as a parameter to the Thread's constructor:

```<code>TSupervisorThread = class(TThread)
public
  constructor Create(OnTerminatEvent: TNotifyEvent);
end;

procedure TThreadCustom.Create(OnTerminateEvent: TNotifyEvent);
begin
  inherited Create(True);
  OnTerminate := OnTerminateEvent;
end;
</code>```

```<code>SupervisorThread := TSupervisorThread.Create(DoTerminateEvent);
</code>```

Body:
At the moment I'm using additional thread to nicely free memory after thread.
Before you ask. No I can't use FreeOnTerminate:=true because I need .waitfor.
I also need FreeAndNil() because only in this way I can check if thread is running using Assigned(). Example code.

procedure TForm1.Button1Click(Sender: TObject);
begin

  SupervisorThread:= TSupervisorThread.Create(True);
  SupervisorThread.FreeOnTerminate:=false; //MUST BE FALSE!
  SupervisorThread.Priority := tpNormal;
  SupervisorThread.Resume;

end;

procedure TSupervisorThread.Execute;
begin

  CleaningThread:= TCleaningThread.Create(True);
  CleaningThread.FreeOnTerminate:=true;
  CleaningThread.Priority := tpNormal;
  CleaningThread.Resume;

  //some loops here

end;

procedure TCleaningThread.Execute;
begin

  if Assigned(SupervisorThread)=true then
  begin
    SupervisorThread.WaitFor;
    FreeAndNil(SupervisorThread);
  end;

end;

procedure TForm2.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin

  if Assigned(SupervisorThread)=false then CanClose:=true
  else
  begin
    CanClose:=false;
    ShowMessage('Cannot close form because SiupervisorThread is still working');
  end;

end;

Body:
Use the TThread.OnTerminate event:

private
  procedure DoTerminateEvent(Sender: TObject);

var
  isRunning: Boolean;

procedure TForm2.DoTerminateEvent(Sender: TObject);
begin
  isRunning := False;
end;

procedure TForm2.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
  if (isRunning) then
  begin
    CanClose := false;
    ShowMessage('Cannot close form because SupervisorThread is still working')
  end else
    CanClose := true;
end;

Set the OnTerminate handler when creating the Thread:

SupervisorThread := TSupervisorThread.Create(True);
...
SupervisorThread.OnTerminate := DoTerminateEvent;
SupervisorThread.Resume;

Or, pass it as a parameter to the Thread's constructor:

TSupervisorThread = class(TThread)
public
  constructor Create(OnTerminatEvent: TNotifyEvent);
end;

procedure TThreadCustom.Create(OnTerminateEvent: TNotifyEvent);
begin
  inherited Create(True);
  OnTerminate := OnTerminateEvent;
end;

SupervisorThread := TSupervisorThread.Create(DoTerminateEvent);


问:
Private double variable, never gets updated
Here is my code:

My result never changes and always goes to 0.

I am doing a dot product of two vectors. I can not use STL algorithms such as std::inner_product. So I need to write an iterator. The operator= should do the accumulation

```<code>template <uint32_t DIM>
double Vector<DIM>::dot(const Vector& rhs) const
{
    return  std::transform(begin(),end(),rhs.begin(),accumulator(),multiply()).getresult();
}

class accumulator
{
    public:
        accumulator& operator++(){
            return *this;
        }

        accumulator operator++(int){
            return *this;
        }

        accumulator operator*(){
            return *this;
        };

        void operator=(double a){
            result=result+a;
        }

        double& getresult(){
            return result;
        }

    private:
        double result;
}
</code>```

答: Your returning by value in your dereference operator, creating a copy, which means that the value that has the multiply assigned to is a different instance for each assignment and is not the iterator instance.</p>

Body:
Here is my code:

My result never changes and always goes to 0.

I am doing a dot product of two vectors. I can not use STL algorithms such as std::inner_product. So I need to write an iterator. The operator= should do the accumulation

template <uint32_t DIM>
double Vector<DIM>::dot(const Vector& rhs) const
{
    return  std::transform(begin(),end(),rhs.begin(),accumulator(),multiply()).getresult();
}

class accumulator
{
    public:
        accumulator& operator++(){
            return *this;
        }

        accumulator operator++(int){
            return *this;
        }

        accumulator operator*(){
            return *this;
        };

        void operator=(double a){
            result=result+a;
        }

        double& getresult(){
            return result;
        }

    private:
        double result;
}


问:
Why Maven dependency exclusion would not cause compile error?
Newly exposed to Maven, I can understand the use case of the <exclusion> tag, but not sure why it wouldn't cause compile error:

```<code><dependencies>
<dependency>
  <groupId>org.apache.maven</groupId>
  <artifactId>maven-embedder</artifactId>
  <version>2.0</version>
  <exclusions>
    <exclusion>
      <groupId>org.apache.maven</groupId>
      <artifactId>maven-core</artifactId>
    </exclusion>
  </exclusions>
</dependency>
...
</code>```

Is this only possible only when you have another direct dependency on maven-core? otherwise, compile error should happen. (assuming maven-core is used somewhere in maven-embedder)

答: The error will not thrown in the compile time, It will thrown in run time if you use any feature depends on maven-core</p>

Body:
Newly exposed to Maven, I can understand the use case of the <exclusion> tag, but not sure why it wouldn't cause compile error:

<dependencies>
<dependency>
  <groupId>org.apache.maven</groupId>
  <artifactId>maven-embedder</artifactId>
  <version>2.0</version>
  <exclusions>
    <exclusion>
      <groupId>org.apache.maven</groupId>
      <artifactId>maven-core</artifactId>
    </exclusion>
  </exclusions>
</dependency>
...

Is this only possible only when you have another direct dependency on maven-core? otherwise, compile error should happen. (assuming maven-core is used somewhere in maven-embedder)


问:
Get background-image src from div and set that as an image's src
So I'm trying to grab the background-image from a div when it is clicked and set it as the src of an img element somewhere else on the page. The issue is that I'm getting an error saying that the file is not found. I understand that this has something to do with the path that I'm assigning to the img's src, however I am unable to see what's wrong with the code.

When the div in question is clicked it calls a function

```<code>document.getElementById('rice-bowl').onclick=openModal;
</code>```

And below is the actual function

```<code>var openModal=function(){
        var image= $(this).css('background-image').slice(4,-1);
        console.log(image);
        var modalImg = document.getElementById("img01");
        modalImg.src = image;
        console.log(modalImg.src);
    }
</code>```

The two outputs to console should be the same according to this logic however, they are not. Again, any help would be greatly appreciated!

答:
this should be:

```<code>$("#rice-bowl").click(function() {
    var bg = $(this).css('background-image');
    bg = bg.replace('url(','').replace(')','').replace(/\"/gi, "");
    var modalImg = document.getElementById("img01");
    modalImg.src = bg;
}
</code>```

Keep rocking!

Body:
So I'm trying to grab the background-image from a div when it is clicked and set it as the src of an img element somewhere else on the page. The issue is that I'm getting an error saying that the file is not found. I understand that this has something to do with the path that I'm assigning to the img's src, however I am unable to see what's wrong with the code.

When the div in question is clicked it calls a function

document.getElementById('rice-bowl').onclick=openModal;

And below is the actual function

var openModal=function(){
        var image= $(this).css('background-image').slice(4,-1);
        console.log(image);
        var modalImg = document.getElementById("img01");
        modalImg.src = image;
        console.log(modalImg.src);
    }

The two outputs to console should be the same according to this logic however, they are not. Again, any help would be greatly appreciated!

Body:
this should be:

$("#rice-bowl").click(function() {
    var bg = $(this).css('background-image');
    bg = bg.replace('url(','').replace(')','').replace(/\"/gi, "");
    var modalImg = document.getElementById("img01");
    modalImg.src = bg;
}

Keep rocking!


问:
How to Get Selected Value from Dropdown List C# ASP.NET
i have created simple website asp.net webform using C#. i have code to display data in dropdownlist when page load like this:

```<code>private void DisplayData()
{
    List<ListItem> items = new List<ListItem>();
    items.Add(new ListItem("User", "1"));
    items.Add(new ListItem("Administrator", "0"));
    DropdownList1.DataSource = items;
    DropdownList1.DataBind();
}
</code>```

I call it in page load:

```<code>protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        DisplayData()
    }
}
</code>```

i try to get value from DropdownList1 in btnSubmit

```<code>protected void btnSubmit_Click(object sender, EventArgs e)
{
    lblResult.Text = DropdownList1.SelectedValue;
}
</code>```

this result always get value User or Administartor string. but, it doesn't i want. I wanna get value just from the values in DropdownList1 as 0 or 1. How to do this?

答:
Try specifying DataValueField of DropDownList1:</p>

```<code>DropdownList1.DataSource = items;
DropdownList1.DataValueField = "Value";
DropdownList1.DataTextField = "Text";
DropdownList1.DataBind();
</code>```

Body:
i have created simple website asp.net webform using C#. i have code to display data in dropdownlist when page load like this:

private void DisplayData()
{
    List<ListItem> items = new List<ListItem>();
    items.Add(new ListItem("User", "1"));
    items.Add(new ListItem("Administrator", "0"));
    DropdownList1.DataSource = items;
    DropdownList1.DataBind();
}

I call it in page load:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        DisplayData()
    }
}

i try to get value from DropdownList1 in btnSubmit

protected void btnSubmit_Click(object sender, EventArgs e)
{
    lblResult.Text = DropdownList1.SelectedValue;
}

this result always get value User or Administartor string. but, it doesn't i want. I wanna get value just from the values in DropdownList1 as 0 or 1. How to do this?

Body:
Try specifying DataValueField of DropDownList1:

DropdownList1.DataSource = items;
DropdownList1.DataValueField = "Value";
DropdownList1.DataTextField = "Text";
DropdownList1.DataBind();


问:
index + 1 array null pointer
Problem: Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

Example
Given input array A = [1,1,2],

Your function should return length = 2, and A is now [1,2].

My solution:

```<code>public int removeDuplicates(int[] nums) {

    if(nums.length == 0) {
        return 0;
    }

    int size = 0;
    for(int i = 0; i < nums.length; i++) {
        if((i + 1) <= nums.length && (nums[i] != nums[i + 1])) {
            nums[size] = nums[i];
            size++;
        }
    }

}
</code>```

The problem that I am running into is a ArrayIndexOutOfBoundsException in the second if statement:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at Solution.removeDuplicates(Solution.java:15) at Main.main(Main.java:10)

I do not understand why because I am checking if i+1 <= the length of the array, which should prevent the overflow error.

答:
You should change the "i + 1 <= nums.length" to "i + 1 < nums.length". When your variable (i) is at the end of loop (i + 1) will be out of array. For example A = [1,1,2] and the length is 3. In the for loop i will be 2 and i+1 will be 3 so nums[3] wil be out of bound.</p>

```<code>     for(int i = 0; i < nums.length; i++) {
        if((i + 1) < nums.length && (nums[i] != nums[i + 1])) {
            nums[size] = nums[i];
            size++;
        }
        else if(i + 1 == nums.length)
            num[size] = nums[i];
     }
</code>```

Title: index + 1 array null pointer

Body:
Problem: Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

Example
Given input array A = [1,1,2],

Your function should return length = 2, and A is now [1,2].

My solution:

public int removeDuplicates(int[] nums) {

    if(nums.length == 0) {
        return 0;
    }

    int size = 0;
    for(int i = 0; i < nums.length; i++) {
        if((i + 1) <= nums.length && (nums[i] != nums[i + 1])) {
            nums[size] = nums[i];
            size++;
        }
    }

}

The problem that I am running into is a ArrayIndexOutOfBoundsException in the second if statement:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at Solution.removeDuplicates(Solution.java:15) at Main.main(Main.java:10)

I do not understand why because I am checking if i+1 <= the length of the array, which should prevent the overflow error.

Body:
You should change the "i + 1 <= nums.length" to "i + 1 < nums.length". When your variable (i) is at the end of loop (i + 1) will be out of array. For example A = [1,1,2] and the length is 3. In the for loop i will be 2 and i+1 will be 3 so nums[3] wil be out of bound.

     for(int i = 0; i < nums.length; i++) {
        if((i + 1) < nums.length && (nums[i] != nums[i + 1])) {
            nums[size] = nums[i];
            size++;
        }
        else if(i + 1 == nums.length)
            num[size] = nums[i];
     }


问:
How to determine whether an array is contained in another array
The question is, given [1,2,3,4,5] and [2,4,5], to determine whether (every element in) the second array is contained in the first one. The answer is true.

What's the most succinct and efficient way to do better than:

```<code>arr2.reject { |e| arr1.include?(e) } .empty?
</code>```

答:
Array subtraction should work, as in

```<code>(arr2 - arr1).empty?
</code>```

Description of method:

Returns a new array that is a copy of the original array, removing any
  items that also appear in [the second array]. The order is preserved from the
  original array.

It compares elements using their hash and eql? methods for efficiency.

I don't consider myself an expert on efficiency, but @Ryan indicated in comments to his answer that it's reasonably efficient at scale.

Body:
The question is, given [1,2,3,4,5] and [2,4,5], to determine whether (every element in) the second array is contained in the first one. The answer is true.

What's the most succinct and efficient way to do better than:

arr2.reject { |e| arr1.include?(e) } .empty?

Body:
Array subtraction should work, as in

(arr2 - arr1).empty?

Description of method:

Returns a new array that is a copy of the original array, removing any
  items that also appear in [the second array]. The order is preserved from the
  original array.

It compares elements using their hash and eql? methods for efficiency.

I don't consider myself an expert on efficiency, but @Ryan indicated in comments to his answer that it's reasonably efficient at scale.


问:
How to add particle effects to an iOS App that is not a game using iOS 7 SpriteKit Particle?
I need to add a rain particle effect to my app, I have been having a tough time finding ways to actually execute this idea.

I tried following this CALayer approach tutorial : Link  but I am not quite sure if this is the best approach, considering the new iOS 7 SpriteKit Particle Emitter available in Xcode 5.

I have already created the .sks file and it's in my Hierarchy, but I am still unable to add it to my storyboard / project.

With that being said, How exactly do I add a SpriteKit Particle (sks) to my view? I am not at all familiar with scenes, layering , etc in the SpriteKit framework as I am not a game developer.
I need the most details and sample code possible so that I can figure this out please

UPDATE:
I have followed the direction provided in an answer by fellow SO member: AyatollahAndy, please see his answer below. Although I was able to display the SKScene in my view the app crashes when any touch event is received. I get the following:

Thanks

答:
Here's approach totally different approach to try. My buddy gave me this cool way to go. Using CAEmitterCell.  All in code! Looks like you need a spark.png image.

```<code>extension UIView {
    final public func ignite() {
        let emitter = CAEmitterLayer()
        emitter.frame = self.bounds
        emitter.renderMode = kCAEmitterLayerAdditive
        emitter.emitterPosition = self.center
        self.layer.addSublayer(emitter)

        let cell = CAEmitterCell()
        let bundle = Bundle.init(for: UIColor.self)
        let image = UIImage(named: "spark", in: bundle, compatibleWith: traitCollection)

        cell.contents = image?.cgImage
        cell.birthRate = 1500
        cell.lifetime = 5.0
        cell.color = UIColor(red: 1.0, green: 0.5, blue: 0.1, alpha: 1).cgColor
        cell.alphaSpeed = -0.4
        cell.velocity = 50
        cell.velocityRange = 250
        cell.emissionRange = CGFloat.pi * 2.0

        emitter.emitterCells = [cell]
    }
}
</code>```

Enjoy.

Body:
Here's approach totally different approach to try. My buddy gave me this cool way to go. Using CAEmitterCell.  All in code! Looks like you need a spark.png image.

extension UIView {
    final public func ignite() {
        let emitter = CAEmitterLayer()
        emitter.frame = self.bounds
        emitter.renderMode = kCAEmitterLayerAdditive
        emitter.emitterPosition = self.center
        self.layer.addSublayer(emitter)

        let cell = CAEmitterCell()
        let bundle = Bundle.init(for: UIColor.self)
        let image = UIImage(named: "spark", in: bundle, compatibleWith: traitCollection)

        cell.contents = image?.cgImage
        cell.birthRate = 1500
        cell.lifetime = 5.0
        cell.color = UIColor(red: 1.0, green: 0.5, blue: 0.1, alpha: 1).cgColor
        cell.alphaSpeed = -0.4
        cell.velocity = 50
        cell.velocityRange = 250
        cell.emissionRange = CGFloat.pi * 2.0

        emitter.emitterCells = [cell]
    }
}

Enjoy.


问:
vba line continuation with bracket expression
```<code>varData = [{"Interbank Placement", "LIBOR/IB/COF"; "cat", "goku"; 4, "cow"; 6, "soccer"; "test", 8; "drinks", "goal"}]
</code>```

<p>I have a code like this. It is too long and I would like to break it into lines. I tried the code below but it still says missing bracket. How can I do this? </p>

```<code>    varData = [{"Interbank Placement", "LIBOR/IB/COF"; _
"cat", "goku"; 4, "cow"; 6, "soccer"; "test", 8; "drinks", "goal"}]
</code>```

答:
You can do it by using Evaluate on a string with the array data - but only if the strings are properly quoted. This is a bit of pain, but possible - see below:

```<code>Option Explicit

Sub Test()

    Dim strData As String
    Dim varData As Variant

    strData = "{""Interbank Placement"", ""LIBOR/IB/COF"";" & _
        """cat"", ""goku"";" & _
        "4, ""cow"";" & _
        "6, ""soccer"";" & _
        """test"", 8;" & _
        """drinks"", ""goal""}"

    varData = Evaluate(strData)

    MsgBox "varData is array of: " & UBound(varData, 1) & "x" & UBound(varData, 2)

End Sub
</code>```

Body:
varData = [{"Interbank Placement", "LIBOR/IB/COF"; "cat", "goku"; 4, "cow"; 6, "soccer"; "test", 8; "drinks", "goal"}]

I have a code like this. It is too long and I would like to break it into lines. I tried the code below but it still says missing bracket. How can I do this?

    varData = [{"Interbank Placement", "LIBOR/IB/COF"; _
"cat", "goku"; 4, "cow"; 6, "soccer"; "test", 8; "drinks", "goal"}]

Body:
You can do it by using Evaluate on a string with the array data - but only if the strings are properly quoted. This is a bit of pain, but possible - see below:

Option Explicit

Sub Test()

    Dim strData As String
    Dim varData As Variant

    strData = "{""Interbank Placement"", ""LIBOR/IB/COF"";" & _
        """cat"", ""goku"";" & _
        "4, ""cow"";" & _
        "6, ""soccer"";" & _
        """test"", 8;" & _
        """drinks"", ""goal""}"

    varData = Evaluate(strData)

    MsgBox "varData is array of: " & UBound(varData, 1) & "x" & UBound(varData, 2)

End Sub


问:
Error:Correct the Invalid Field entries in SalesForce
I am new to the salesforce and doing trailhead from link: https://trailhead.salesforce.com/projects/flow_satisfaction/steps/flow_satisfaction_thanks.

I am performing the Thank Customer step, which is failing why ?

I am not too sure what the heck is going on ?

答:
You are using the same unique name. On the general info tab, enter the following values:

Name: Thank Customer

Unique Name: Thank_Customer

Then click on Field Settings tab and enter the following values:

Unique Name: ThankCustomer

Textbox: Thank you for your time. On behalf of everyone at Acme
Wireless, we'd like to thank you for being a customer. Have a great
day!


问:
Why is everything a property in iOS SDK tutorials?
In most of the iOS SDK tutorials I've read online both from Apple and elsewhere, so many instance variables are made properties, even when they are only accessed from within their own class.

E.G. in Facebook's latest iOS SDK a user is encouraged to maintain an instance of the Facebook class called facebook in the app delegate. facebook" is a property. This is then referred to throughout the sample code as "self.facebook". But the "facebook" property is not referenced anywhere from outside the app delegate.

Why is this? What am I missing? If an instance variable is only used within its own class, my inclination would be not to make it a property so that it is not publicly visible, and refer to it simply as facebook rather than self.facebook or  self->facebook from within the class.

Frankly, even if I needed the facebook property, I think I'd rather refer to it within the app delegate as simply "facebook" rather than "self.facebook".

So what gives? Why am I seeing properties everywhere?

答: Usually it's better to access to the instance variable through an accessor, rather than directly. Properties create these accessors, and also provide things like proper key-value change notifications and atomic access.</p>


问:
Mule Salesforce Analytics Connector Requirements does not match the schema
We are using the Mulesoft sfdc-analytics connector. When we installed the connector into Anypoint Stuido and used the connector's Operation "Create data set", the connector requires additional attributes one of those being Operation; however, in the schema (http://mulesoft.github.io/salesforce-analytics-connector/1.0.0/mule/sfdc-analytics-schema.html) the create-data-set element does not have "operation" defined so when we go to run the application package fails with the follow issue:</p>

```<code>INFO  2017-04-01 22:21:28,431 [main] org.mule.lifecycle.AbstractLifecycleManager: Disposing RegistryBroker
ERROR 2017-04-01 22:21:28,493 [main] org.mule.module.launcher.application.DefaultMuleApplication: null
org.xml.sax.SAXParseException: cvc-complex-type.3.2.2: Attribute 'operation' is not allowed to appear in element 'sfdc-analytics:create-data-set'.
</code>```

答: It seems to me that you are using an old version of the Salesforce Analytics Connector. That schema belongs to version 1.0.0 which does not have the "operation" element. That property was added in version 2.0.0 (latest is 2.1.0), as stated in the official Release Notes. And the related schema is here.

Body:
We are using the Mulesoft sfdc-analytics connector. When we installed the connector into Anypoint Stuido and used the connector's Operation "Create data set", the connector requires additional attributes one of those being Operation; however, in the schema (http://mulesoft.github.io/salesforce-analytics-connector/1.0.0/mule/sfdc-analytics-schema.html) the create-data-set element does not have "operation" defined so when we go to run the application package fails with the follow issue:

INFO  2017-04-01 22:21:28,431 [main] org.mule.lifecycle.AbstractLifecycleManager: Disposing RegistryBroker
ERROR 2017-04-01 22:21:28,493 [main] org.mule.module.launcher.application.DefaultMuleApplication: null
org.xml.sax.SAXParseException: cvc-complex-type.3.2.2: Attribute 'operation' is not allowed to appear in element 'sfdc-analytics:create-data-set'.


答:
One approach is to use the DropDownList SelectedItem Property to get the selectedItem(ListItem), then use the ListItem.Value Property to get the corresponding value for the ListItem.

```<code>lblResult.Text = DropdownList1.SelectedItem.Value; // Value property Gets or sets the value associated with the ListItem.
</code>```

Title: How to Get Selected Value from Dropdown List C# ASP.NET

Body:
One approach is to use the DropDownList SelectedItem Property to get the selectedItem(ListItem), then use the ListItem.Value Property to get the corresponding value for the ListItem.

lblResult.Text = DropdownList1.SelectedItem.Value; // Value property Gets or sets the value associated with the ListItem.


答: You are excluding that artifact from that specific dependency, but it could be getting pulled in from another dependency.  Using something mvn dependency:tree -Dverbose -Dincludes=maven-core should show you what else is introducing the dependency.  The Maven Enforcer plugin can also help exclude transitive dependencies.

Title: Why Maven dependency exclusion would not cause compile error?


问:
Extract Previous row Value based on Condition
To analyse some data for a paper I need to extract the entire row previous to a met condition.

For example I have an error column and a Response Time column

```<code>Error    ResponseTime
0        0.22
0        0.28
1        0.89
0        0.92
1        0.21
</code>```

Desired output

```<code>Error    ResponseTime
0        0.28
0        0.92
</code>```

So if error == 1
extract previous row and put it in a new dataframe.

I tried to use the zoo library but I could not manage to make it work.

I tried this solution :

```<code>Dfa1test <- Dfa1test[c(FALSE, head(Dfa1test$error, -1) == 1), , drop = FALSE]
</code>```

The problem with the last solution is that I get row + 1  and not row -1.

I tried to find other solutions but I did not get close to my desired output.

答:
Here is an option using data.table

```<code>library(data.table)
setDT(df1)[df1[,.I[which(Error==1)-1]]]
#   Error ResponseTime
#1:     0         0.28
#2:     0         0.92
</code>```

If we need only the rows which have 0 as previous element in 'Error' when the current element is 1

```<code>setDT(df)[df[, .I[which(shift(Error, fill=999)==0 & Error==1)-1]]]
</code>```

NOTE: In this example, both of them give the same result

Body:
To analyse some data for a paper I need to extract the entire row previous to a met condition.

For example I have an error column and a Response Time column

Error    ResponseTime
0        0.22
0        0.28
1        0.89
0        0.92
1        0.21

Desired output

Error    ResponseTime
0        0.28
0        0.92

So if error == 1
extract previous row and put it in a new dataframe.

I tried to use the zoo library but I could not manage to make it work.

I tried this solution :

Dfa1test <- Dfa1test[c(FALSE, head(Dfa1test$error, -1) == 1), , drop = FALSE]

The problem with the last solution is that I get row + 1  and not row -1.

I tried to find other solutions but I did not get close to my desired output.

Body:
Here is an option using data.table

library(data.table)
setDT(df1)[df1[,.I[which(Error==1)-1]]]
#   Error ResponseTime
#1:     0         0.28
#2:     0         0.92

If we need only the rows which have 0 as previous element in 'Error' when the current element is 1

setDT(df)[df[, .I[which(shift(Error, fill=999)==0 & Error==1)-1]]]

NOTE: In this example, both of them give the same result


问:
Building an App Builder - how do they do it?
The internet is full of solutions where someone with no coding experience can design an app, and then have it deployed to their phones via another app. So for example you can log on to appsheet, create all the parameters for an application, then download appsheet to your phone. from there, you log into your appsheet account, and download any of the apps you have created.Does anyone know how this is accomplished? </p>

<p>My use case is that I have an app that I would like to offer to Universities, but would like each universities' mobile application to be custom built for their needs. I have developed web, android and ios apps in the past, and have a Software Engineering background, so I am looking for the right methodology to accomplish something like this. Are there any specific frameworks or technologies you would advise me look at to accomplish this tasking? If you have any questions or concerns for me, please do not hesitate to ask! </p>

答: I work at AppSheet. There are two basic approaches an app builder can follow: (a) act as a code generator, or (b) implement an intepreter. In the former case, it spits out code that gets compiled into an executable package that can be installed and run on a device. In the latter case, the "app" you define is meta-data in a higher-level definition that is interpreted in a host wrapper app. Each has its strengths and weaknesses. AppSheet uses the latter approach. </p>

Body:
The internet is full of solutions where someone with no coding experience can design an app, and then have it deployed to their phones via another app. So for example you can log on to appsheet, create all the parameters for an application, then download appsheet to your phone. from there, you log into your appsheet account, and download any of the apps you have created.Does anyone know how this is accomplished?

My use case is that I have an app that I would like to offer to Universities, but would like each universities' mobile application to be custom built for their needs. I have developed web, android and ios apps in the past, and have a Software Engineering background, so I am looking for the right methodology to accomplish something like this. Are there any specific frameworks or technologies you would advise me look at to accomplish this tasking? If you have any questions or concerns for me, please do not hesitate to ask!


问:
What if you had an Abstract class with only abstract methods? How would that be different from an interface?
From my experience I think the following is true. If I am missing a major point please let me know.

Interface:

Every single Method declared in an Interface will have to be implemented in the subclass. Only Events, Delegates, Properties (C#) and Methods can exist in a Interface. A class can implement multiple Interfaces.

Abstract Class:

Only Abstract methods have to be implemented by the subclass. An Abstract class can have normal methods with implementations. Abstract class can also have class variables beside Events, Delegates, Properties and Methods. A class can only implement one abstract class only due non-existence of Multi-inheritance in C#.

So even that difference doesn't explain the question

1) What if you had an Abstract class with only abstract methods? How would that be different from an interface?

2) What if you had a Public variable inside the interface, how would that be different than in Abstract Class?

So any explanation will be vary help full.

答:
In case of abstract class.

```<code>class Dog : abstractAnimal
</code>```

When we create object of Dog, we will have to create object of abstractAnimal to, it will lead to extra object creation.

In case of interface.

```<code>class Dog : IAnimal
</code>```

When we create object of Dog, we will not be creating any extra object of anything.

Body:
In case of abstract class.

class Dog : abstractAnimal

When we create object of Dog, we will have to create object of abstractAnimal to, it will lead to extra object creation.

In case of interface.

class Dog : IAnimal

When we create object of Dog, we will not be creating any extra object of anything.


问:
How to get all connected Sql Servers in Visual Studio Sql Server Object Explorer
i want to develop a Visual Studio Extension.

Therefore i need all Databases that are connected via Visual Studio Sql Server Object Explorer.
I want to connect to some of them during my programm execution.

I already tried to get all connected databases via

System.Data.Sql.SqlDataSourceEnumerator.Instance.GetDataSources();

But the result is not the right set of databases.

If its possible to get all the information about the connected Databases my program should like:

```<code>var databases = GetAllConnectedDatabases();
foreach (database in databases)
{
   database.Connect();
   // do something
}
</code>```

Is it possible to get information about all
Sql-Servers i connected via Visual Studio Sql Server Object Explorer?

Thanks for your help.

答:
We could retrieve related connections via IVsDataExplorerConnectionManager Interface. Here is a simple demo for your reference.

```<code> IVsDataExplorerConnectionManager decMgr = (IVsDataExplorerConnectionManager)this.ServiceProvider.GetService(typeof(IVsDataExplorerConnectionManager));

 foreach (var conn in decMgr.Connections)
 {
      var state = conn.Value.Connection.State;
      if (state == DataConnectionState.Closed)
      {
          conn.Value.Connection.Open();
      }
 }
</code>```

Body:
i want to develop a Visual Studio Extension.

Therefore i need all Databases that are connected via Visual Studio Sql Server Object Explorer.
I want to connect to some of them during my programm execution.

I already tried to get all connected databases via

System.Data.Sql.SqlDataSourceEnumerator.Instance.GetDataSources();

But the result is not the right set of databases.

If its possible to get all the information about the connected Databases my program should like:

var databases = GetAllConnectedDatabases();
foreach (database in databases)
{
   database.Connect();
   // do something
}

Is it possible to get information about all
Sql-Servers i connected via Visual Studio Sql Server Object Explorer?

Thanks for your help.

Body:
We could retrieve related connections via IVsDataExplorerConnectionManager Interface. Here is a simple demo for your reference.

 IVsDataExplorerConnectionManager decMgr = (IVsDataExplorerConnectionManager)this.ServiceProvider.GetService(typeof(IVsDataExplorerConnectionManager));

 foreach (var conn in decMgr.Connections)
 {
      var state = conn.Value.Connection.State;
      if (state == DataConnectionState.Closed)
      {
          conn.Value.Connection.Open();
      }
 }


问:
Python 3.4 Installing bs4- Running Python2 not Python3
Today is a terrible day for me. I'm so frustrated because I've spent the last 4 hours trying to install beautifulsoup4. I've searched every tutorial I can get my hands on.
It is installed on my computer, but when I do import bs4 on the shell it gives me this message:

```<code>Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    import bs4
  File "C:\Python34\lib\bs4\__init__.py", line 48
    'You are trying to run the Python 2 version of Beautiful Soup under Python 3. This will not work.'<>'You need to convert the code, either by installing it (`python setup.py install`) or by running 2to3 (`2to3 -w bs4`).'
</code>```

Does anyone have any idea what I can do? it tells me to run a command but it doesn't tell me how to run it.

答:
I have the same issue. Got the following error multiple times.
"'You are trying to run the Python 2 version of Beautiful Soup under Python 3. This will not work.'<>'You need to convert the code, either by installing it (python setup.py install) or by running 2to3 (2to3 -w bs4).'"

This is what i did. (On MAC)

Step 1: Install python 2.7.(I had trouble installing BS4 with python3, so I use the latest version of serie 2 for installation.)

Step 2: Install latest version of beautiful soup. Then relocate the downloaded folder to somewhere easily accessible.

Step 3: Open TERMINAL and type in "cd *" (note: DON'T include the quote. Also, * in this case refer to the directory of the beautiful soup folder. If you don't know the directory of the folder, simply drag the folder to the terminal and you will get it!)

Step 4: Type "python setup.py install" in terminal(note: same thing. no quote)

Step 5: Wait for it to finish. Open IDLE/Python Shell

Step 6: Type "import os"
Step 7: Type "os.chdir(***)" (Note: same directory like the above)
Step 8: Type "from bs4 import BeautifulSoup"

AND you're good to go! GL

Body:
Today is a terrible day for me. I'm so frustrated because I've spent the last 4 hours trying to install beautifulsoup4. I've searched every tutorial I can get my hands on.
It is installed on my computer, but when I do import bs4 on the shell it gives me this message:

Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    import bs4
  File "C:\Python34\lib\bs4\__init__.py", line 48
    'You are trying to run the Python 2 version of Beautiful Soup under Python 3. This will not work.'<>'You need to convert the code, either by installing it (`python setup.py install`) or by running 2to3 (`2to3 -w bs4`).'

Does anyone have any idea what I can do? it tells me to run a command but it doesn't tell me how to run it.


问:
Profile model for Devise users?
I want to extend the sign up form of my devise installation. I created a Profile model and am asking myself now, how can I add specific data of the form to this model. Where is the UserController of devise located?

Thanks in advance!

答:
Assuming you have a User model with a has_one Profile association, you simply need to allow nested attributes in User and modify your devise registration view.

Run the rails generate devise:views command, then modify the devise registrations#new.html.erb view as shown below using the fields_for form helper to have your sign up form update your Profile model along with your User model.

```<code><div class="register">
  <h1>Sign up</h1>

  <% resource.build_profile %>
  <%= form_for(resource, :as => resource_name,
                         :url => registration_path(resource_name)) do |f| %>
    <%= devise_error_messages! %>

    <h2><%= f.label :email %></h2>
    <p><%= f.text_field :email %></p>

    <h2><%= f.label :password %></h2>
    <p><%= f.password_field :password %></p>

    <h2><%= f.label :password_confirmation %></h2>
    <p><%= f.password_field :password_confirmation %></p>

    <%= f.fields_for :profile do |profile_form| %>
      <h2><%= profile_form.label :first_name %></h2>
      <p><%= profile_form.text_field :first_name %></p>

      <h2><%= profile_form.label :last_name %></h2>
      <p><%= profile_form.text_field :last_name %></p>
    <% end %>

    <p><%= f.submit "Sign up" %></p>

    <br/>
    <%= render :partial => "devise/shared/links" %>
  <% end %>
</div>
</code>```

And in your User model:

```<code>class User < ActiveRecord::Base
  ...
  attr_accessible :email, :password, :password_confirmation, :remember_me, :profile_attributes
  has_one :profile
  accepts_nested_attributes_for :profile
  ...
end
</code>```

Title: Profile model for Devise users?

Body:
Assuming you have a User model with a has_one Profile association, you simply need to allow nested attributes in User and modify your devise registration view.

Run the rails generate devise:views command, then modify the devise registrations#new.html.erb view as shown below using the fields_for form helper to have your sign up form update your Profile model along with your User model.

<div class="register">
  <h1>Sign up</h1>

  <% resource.build_profile %>
  <%= form_for(resource, :as => resource_name,
                         :url => registration_path(resource_name)) do |f| %>
    <%= devise_error_messages! %>

    <h2><%= f.label :email %></h2>
    <p><%= f.text_field :email %></p>

    <h2><%= f.label :password %></h2>
    <p><%= f.password_field :password %></p>

    <h2><%= f.label :password_confirmation %></h2>
    <p><%= f.password_field :password_confirmation %></p>

    <%= f.fields_for :profile do |profile_form| %>
      <h2><%= profile_form.label :first_name %></h2>
      <p><%= profile_form.text_field :first_name %></p>

      <h2><%= profile_form.label :last_name %></h2>
      <p><%= profile_form.text_field :last_name %></p>
    <% end %>

    <p><%= f.submit "Sign up" %></p>

    <br/>
    <%= render :partial => "devise/shared/links" %>
  <% end %>
</div>

And in your User model:

class User < ActiveRecord::Base
  ...
  attr_accessible :email, :password, :password_confirmation, :remember_me, :profile_attributes
  has_one :profile
  accepts_nested_attributes_for :profile
  ...
end