问:
How do I sync data with remote database in case of offline-first applications?

I am building a "TODO" application which uses Service Workers to cache the request's responses and in case a user is offline, the cached data is displayed to the user.

The Server exposes an REST-ful endpoint which has POST, PUT, DELETE and GET endpoints exposed for the resources.

Considering that when the user is offline and submitting a TODO item, I save that to local IndexedDB, but I can't send this POST request for the server since there is no network connection.  The same is true for the PUT, DELETE requests where a user updates or deletes an existing TODO item

Questions

What patterns are in use to sync the pending requests with the REST-ful Server when the connection is back online?

答:
At the moment I can think of two approaches and it depend on what storage options you are using at your backend.

If you are using an RDBMS to backup all data:

The problem with offline first systems in this approach is the possibility of conflict that you may face when posting new data or updating existing data.

As a first measure to avoid conflicts from happening you will have to generate unique IDs for all objects from your clients and in such a way that they remain unique when posted on the server and saved in a data base. For this you can safely rely on UUIDs for generating unique IDs for objects. UUID guarantees uniqueness across systems in a distributed system and depending on what your language of implementation is you will have methods to generate UUIDs without any hassle.

Design your local database such that you can use UUIDs as primary key in your local database. On the server end you can have both, an integer type auto incremented and indexed, primary key and a VARCHAR type to hold the UUIDs. The primary key on server uniquely identifies objects in that table while UUID uniquely identifies records across tables and databases.

So when posting your object to server at the time of syncing you will have to just check if any object with the UDID is already present and take appropriate action from there. When your are fetching objects from the server send both the primary key of the object from your table and the UDID for the objects. This why when you serialise the response in model objects or save them in local database you can tell the objects which have been synced from the ones which haven't as the objects that needs syncing will not have a primary key in your local database, just the UUID.

There may be a case when your server malfunctions and refuses to save data when you are syncing. In this case you can keep an integer variable in your objects that will keep a count of the number of times you have tried syncing it. If this number exceed by a certain value, say 3, you move on to sync the next object. Now what you do with the unsynced objects is up you the policy you have for such objects, as a solution you could discard them or keep them just locally.

If you are not using RDBMS

As an alternate approach, instead of keeping all objects you could keep transactions that each client perform locally to the server. Each client syncs just the transactions and the while fetching you get the current state by working all the transactions from bottom up. This is very similar to what Git uses. It saves changes in your repository in form of transactions like what has been added (or removed) and by whom. The current state of the repository for each user is worked from the transactions. This approach will not result in conflicts but as you can see its a little tricky to develop.


来源: stackexchange

问:
Centering my Logo Div
I have tried every possible method to center my logo div but no luck. I even ended up going back to old school align="center" but no luck.

Please help - http://rezaee.me/kel/

Cheers

答: Get rid of position:fixed and it'll be fine :)

ContentLicense: CC BY-SA 2.5

Title: Centering my Logo Div

ContentLicense: CC BY-SA 3.0


问:
Flex property not working in Safari browser
```<code> .rq-search-container {
    position: relative;
    width: 100%;
    background: white;
    display: flex;
    flex-direction: row;
    align-items: flex-start;
    border-radius: 2px;
    z-index: 30;
    -webkit-flex: 1 0 15em;
  }
</code>```

It's perfectly working with chrome, Mozilla browsers but not working in Safari browser.

I was already tried many ways like -web-kit-flex, etc. but not working.
please suggest me!

答:
Try this style display:-webkit-flex

similarly for all the browser use below css

```<code>display: -webkit-box;   /* OLD - iOS 6-, Safari 3.1-6, BB7 */
display: -ms-flexbox;  /* TWEENER - IE 10 */
display: -webkit-flex; /* NEW - Safari 6.1+. iOS 7.1+, BB10 */
display: flex;         /* NEW, Spec - Firefox, Chrome, Opera */
</code>```

Your code

```<code>.rq-search-container {

 position: relative;
 width: 100%;
 background: #fff;
 display: -webkit-box;   /* OLD - iOS 6-, Safari 3.1-6, BB7 */
 display: -ms-flexbox;  /* TWEENER - IE 10 */
 display: -webkit-flex; /* NEW - Safari 6.1+. iOS 7.1+, BB10 */
 display: flex;         /* NEW, Spec - Firefox, Chrome, Opera */
 flex-direction: row;
 align-items: flex-start;
 border-radius: 2px;
 /*box-shadow: 0px 0px 28px 5px rgba(0, 0, 0, 0.3); margin-top: 45px;*/
 z-index: 30;

}
</code>```

Body:
 .rq-search-container {
    position: relative;
    width: 100%;
    background: white;
    display: flex;
    flex-direction: row;
    align-items: flex-start;
    border-radius: 2px;
    z-index: 30;
    -webkit-flex: 1 0 15em;
  }

It's perfectly working with chrome, Mozilla browsers but not working in Safari browser.

I was already tried many ways like -web-kit-flex, etc. but not working.
please suggest me!

Body:
Try this style display:-webkit-flex

similarly for all the browser use below css

display: -webkit-box;   /* OLD - iOS 6-, Safari 3.1-6, BB7 */
display: -ms-flexbox;  /* TWEENER - IE 10 */
display: -webkit-flex; /* NEW - Safari 6.1+. iOS 7.1+, BB10 */
display: flex;         /* NEW, Spec - Firefox, Chrome, Opera */

Your code

.rq-search-container {

 position: relative;
 width: 100%;
 background: #fff;
 display: -webkit-box;   /* OLD - iOS 6-, Safari 3.1-6, BB7 */
 display: -ms-flexbox;  /* TWEENER - IE 10 */
 display: -webkit-flex; /* NEW - Safari 6.1+. iOS 7.1+, BB10 */
 display: flex;         /* NEW, Spec - Firefox, Chrome, Opera */
 flex-direction: row;
 align-items: flex-start;
 border-radius: 2px;
 /*box-shadow: 0px 0px 28px 5px rgba(0, 0, 0, 0.3); margin-top: 45px;*/
 z-index: 30;

}


问:
ng2-toasty in angular2 is not working
I installed ng2-toasty: "^2.3.0" in my angular 2.0.0 application.

I included these lines in app module

```<code>import { ToastyModule } from 'ng2-toasty';

@NgModule({
    imports: [
        UniversalModule, // Must be first import. This automatically imports BrowserModule, HttpModule, and JsonpModule too.
        ToastyModule.forRoot()
    ],
</code>```

And in my ts file I have code like

```<code>import { ToastyService, ToastyConfig, ToastOptions, ToastData } from 'ng2-toasty';

constructor(private toastyService: ToastyService, private toastyConfig: ToastyConfig) {
        this.toastyConfig.theme = 'default';
    }

 onClick() {
        debugger;
        this.toastyService.default({
            title: "Toast It!",
            msg: "Mmmm, tasties...",
            showClose: true,
            timeout: 5000,
            theme: "default"
        });

        // Or create the instance of ToastOptions
        var toastOptions: ToastOptions = {
            title: "My title",
            msg: "The message",
            showClose: true,
            timeout: 5000,
            theme: 'default',
            onAdd: (toast: ToastData) => {
                console.log('Toast ' + toast.id + ' has been added!');
            },
            onRemove: function (toast: ToastData) {
                console.log('Toast ' + toast.id + ' has been removed!');
            }
        };
        // Add see all possible types in one shot
        this.toastyService.info(toastOptions);
        this.toastyService.success(toastOptions);
        this.toastyService.wait(toastOptions);
        this.toastyService.error(toastOptions);
        this.toastyService.warning(toastOptions);
    }
</code>```

and in HTML I have

```<code><button (click)="onClick()">Click</button>
        <ng2-toasty></ng2-toasty>
</code>```

I am able to get the message, but it does not come as notification , it just comes as plain text message. Can you please let me what is missed out.

答:
I had the same issue.  You need to import one of the .css files from the module in your html.
I ended up copying the bootstrap.css into its own file /assets/vendors/toasty-bootstrap.css (since I didn't want to reference inside of my ng_modules directory).

There might be a better way to reference the file inside of the component but

```<code><link href="/assets/vendors/toasty-bootstrap.css" rel="stylesheet">

<button (click)="onClick()">Click</button>
    <ng2-toasty></ng2-toasty>
</code>```

Title: ng2-toasty in angular2 is not working

Body:
I installed ng2-toasty: "^2.3.0" in my angular 2.0.0 application.

I included these lines in app module

import { ToastyModule } from 'ng2-toasty';

@NgModule({
    imports: [
        UniversalModule, // Must be first import. This automatically imports BrowserModule, HttpModule, and JsonpModule too.
        ToastyModule.forRoot()
    ],

And in my ts file I have code like

import { ToastyService, ToastyConfig, ToastOptions, ToastData } from 'ng2-toasty';

constructor(private toastyService: ToastyService, private toastyConfig: ToastyConfig) {
        this.toastyConfig.theme = 'default';
    }

 onClick() {
        debugger;
        this.toastyService.default({
            title: "Toast It!",
            msg: "Mmmm, tasties...",
            showClose: true,
            timeout: 5000,
            theme: "default"
        });

        // Or create the instance of ToastOptions
        var toastOptions: ToastOptions = {
            title: "My title",
            msg: "The message",
            showClose: true,
            timeout: 5000,
            theme: 'default',
            onAdd: (toast: ToastData) => {
                console.log('Toast ' + toast.id + ' has been added!');
            },
            onRemove: function (toast: ToastData) {
                console.log('Toast ' + toast.id + ' has been removed!');
            }
        };
        // Add see all possible types in one shot
        this.toastyService.info(toastOptions);
        this.toastyService.success(toastOptions);
        this.toastyService.wait(toastOptions);
        this.toastyService.error(toastOptions);
        this.toastyService.warning(toastOptions);
    }

and in HTML I have

<button (click)="onClick()">Click</button>
        <ng2-toasty></ng2-toasty>

I am able to get the message, but it does not come as notification , it just comes as plain text message. Can you please let me what is missed out.

Body:
I had the same issue.  You need to import one of the .css files from the module in your html.
I ended up copying the bootstrap.css into its own file /assets/vendors/toasty-bootstrap.css (since I didn't want to reference inside of my ng_modules directory).

There might be a better way to reference the file inside of the component but

<link href="/assets/vendors/toasty-bootstrap.css" rel="stylesheet">

<button (click)="onClick()">Click</button>
    <ng2-toasty></ng2-toasty>


问:
Total by Date in Pivot sql
I have curret query like this to create pivot table and count the items

CREATE TABLE #SampleData
(
    Name varchar(10),
    Location varchar(20),
    Item varchar(10),
    Date varchar(8)
)
INSERT INTO #SampleData
VALUES
('Ron', 'Loc A', 'Pencil', '20170610'),
('Ron', 'Loc A', 'Pencil', '20170611'),
('Ron', 'Loc B', 'Pen', '20170610'),
('Ron', 'Loc B', 'Laptop', '20170611'),
('Tom', 'Loc A', 'Pencil', '20170611'),
('Tom', 'Loc B', 'Pencil', '20170610'),
('Tom', 'Loc B', 'Pen', '20170610'),
('Tom', 'Loc A', 'Pencil', '20170610'),
('Tom', 'Loc A', 'Laptop', '20170610'),
('Tom', 'Loc A', 'Pencil', '20170610')

 DECLARE @Pivot_Columns  AS VARCHAR(MAX),
   @select_Columns VARCHAR(max)

 SELECT @Pivot_Columns = Stuff((SELECT DISTINCT ',' + Quotename(Item) FROM #SampleData FOR xml path('')), 1, 1, '')
 SELECT @select_Columns = Stuff((SELECT DISTINCT ',Sum(' + Quotename(Item) + ') as '+Quotename(Item) FROM #SampleData FOR xml path('')), 1, 1, '')

 DECLARE @SQL AS VARCHAR(MAX)

 SET @SQL = 'SELECT case when grouping(location) = 1 and grouping(name) = 0 then ''Total''+ '' '' + name
 when grouping(location) = 1 and grouping(name) = 1 then ''Total''
 else name end Name, location, '
      + @select_Columns + '
 FROM
 (
  SELECT name, location, item
  FROM #SampleData

 ) as PivotData
 PIVOT
 (
  count(item)
  for item  IN ('
      + @Pivot_Columns + ')
 ) AS PivotResult
 group by name,location with rollup
 '

 EXEC(@SQL) ```

and the result like this

how to create Total by date below the grand total?

i've tried to using union and it doesn't work.
how to create total like my image?
Thanks in advance.

答:
Not sure why you are using dynamic SQL. Try this static SQL:</p>

```<code>SELECT case when grouping(location) = 1 and grouping(name) = 0 then 'Total'+ ' ' + name
when grouping(location) = 1 and grouping(name) = 1 then 'Total'
else name end Name, location, Sum([Laptop]) as [Laptop],Sum([Pen]) as [Pen],Sum([Pencil]) as [Pencil]
FROM
(
    SELECT name, location, item
    FROM #SampleData

) as PivotData
PIVOT
(
    count(item)
    for item  IN ([Laptop],[Pen],[Pencil])
) AS PivotResult
group by name,location with rollup
UNION ALL
SELECT 'Total' Name, location, Sum([Laptop]) as [Laptop],Sum([Pen]) as [Pen],Sum([Pencil]) as [Pencil]
FROM
(
    SELECT [date] as location, item
    FROM #SampleData

) as PivotData
PIVOT
(
    count(item)
    for item  IN ([Laptop],[Pen],[Pencil])
) AS PivotResult
group by location
;
</code>```

Title: Total by Date in Pivot sql

Body:
I have curret query like this to create pivot table and count the items

CREATE TABLE #SampleData
(
    Name varchar(10),
    Location varchar(20),
    Item varchar(10),
    Date varchar(8)
)
INSERT INTO #SampleData
VALUES
('Ron', 'Loc A', 'Pencil', '20170610'),
('Ron', 'Loc A', 'Pencil', '20170611'),
('Ron', 'Loc B', 'Pen', '20170610'),
('Ron', 'Loc B', 'Laptop', '20170611'),
('Tom', 'Loc A', 'Pencil', '20170611'),
('Tom', 'Loc B', 'Pencil', '20170610'),
('Tom', 'Loc B', 'Pen', '20170610'),
('Tom', 'Loc A', 'Pencil', '20170610'),
('Tom', 'Loc A', 'Laptop', '20170610'),
('Tom', 'Loc A', 'Pencil', '20170610')

 DECLARE @Pivot_Columns  AS VARCHAR(MAX),
   @select_Columns VARCHAR(max)

 SELECT @Pivot_Columns = Stuff((SELECT DISTINCT ',' + Quotename(Item) FROM #SampleData FOR xml path('')), 1, 1, '')
 SELECT @select_Columns = Stuff((SELECT DISTINCT ',Sum(' + Quotename(Item) + ') as '+Quotename(Item) FROM #SampleData FOR xml path('')), 1, 1, '')

 DECLARE @SQL AS VARCHAR(MAX)

 SET @SQL = 'SELECT case when grouping(location) = 1 and grouping(name) = 0 then ''Total''+ '' '' + name
 when grouping(location) = 1 and grouping(name) = 1 then ''Total''
 else name end Name, location, '
      + @select_Columns + '
 FROM
 (
  SELECT name, location, item
  FROM #SampleData

 ) as PivotData
 PIVOT
 (
  count(item)
  for item  IN ('
      + @Pivot_Columns + ')
 ) AS PivotResult
 group by name,location with rollup
 '

 EXEC(@SQL)

and the result like this

how to create Total by date below the grand total?

i've tried to using union and it doesn't work.
how to create total like my image?
Thanks in advance.

Body:
Not sure why you are using dynamic SQL. Try this static SQL:

SELECT case when grouping(location) = 1 and grouping(name) = 0 then 'Total'+ ' ' + name
when grouping(location) = 1 and grouping(name) = 1 then 'Total'
else name end Name, location, Sum([Laptop]) as [Laptop],Sum([Pen]) as [Pen],Sum([Pencil]) as [Pencil]
FROM
(
    SELECT name, location, item
    FROM #SampleData

) as PivotData
PIVOT
(
    count(item)
    for item  IN ([Laptop],[Pen],[Pencil])
) AS PivotResult
group by name,location with rollup
UNION ALL
SELECT 'Total' Name, location, Sum([Laptop]) as [Laptop],Sum([Pen]) as [Pen],Sum([Pencil]) as [Pencil]
FROM
(
    SELECT [date] as location, item
    FROM #SampleData

) as PivotData
PIVOT
(
    count(item)
    for item  IN ([Laptop],[Pen],[Pencil])
) AS PivotResult
group by location
;


问:
Toast not working in Service
I try to create my first Service, of course without success. But this app successfully compiled and not give any error in AndroidMonitor.
In short, buttons no react for pressing.
I added to Android Manifest required line:

```<code><service android:name=".MyService"></service>
</code>```

ClientActivity

```<code>package com.example.servicetest;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class ClientActivity extends Activity {
    private Button btnStartService;
    private Button btnStopService;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnStartService = (Button) findViewById(R.id.btnStartService);
        btnStopService = (Button) findViewById(R.id.btnStopService);
        initButtonsOnClick();
    }

    private void initButtonsOnClick() {
        OnClickListener listener = new OnClickListener() {
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.btnStartService:
                        startMyService();
                        break;
                    case R.id.btnStopService:
                        stopMyService();
                        break;
                    default:
                        break;
                }
            }
        };
        btnStartService.setOnClickListener(listener);
        btnStopService.setOnClickListener(listener);
    }

    private void startMyService() {
        Intent serviceIntent = new Intent(this, MyService.class);
        startService(serviceIntent);
    }

    private void stopMyService() {
        Intent serviceIntent = new Intent(this, MyService.class);
        stopService(serviceIntent);
    }
}
</code>```

MyService

```<code>package com.example.servicetest;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import java.util.Timer;
import java.util.TimerTask;
import android.widget.Toast;

public class MyService extends Service {
    private Toast toast;
    private Timer timer;
    private TimerTask timerTask;
    private class MyTimerTask extends TimerTask {
        @Override
        public void run() {
             Toast.makeText(getApplicationContext(), "Your service is still working", Toast.LENGTH_SHORT).show();
        }
    }

    private void writeToLogs(String message) {
        Log.d("HelloServices", message);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        writeToLogs("Called onCreate() method.");
        timer = new Timer();
        Toast.makeText(getApplicationContext(), "", Toast.LENGTH_SHORT).show();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        writeToLogs("Called onStartCommand() methond");
        clearTimerSchedule();
        initTask();
        timer.scheduleAtFixedRate(timerTask, 4 * 1000, 4 * 1000);
        Toast.makeText(getApplicationContext(), "Your service has been started", Toast.LENGTH_SHORT).show();
        return super.onStartCommand(intent, flags, startId);
    }

    private void clearTimerSchedule() {
        if(timerTask != null) {
            timerTask.cancel();
            timer.purge();
        }
    }

    private void initTask() {
        timerTask = new MyTimerTask();
    }

    @Override
    public void onDestroy() {
        writeToLogs("Called onDestroy() method");
        clearTimerSchedule();
        Toast.makeText(getApplicationContext(), "Your service has been stopped", Toast.LENGTH_SHORT).show();
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
}
</code>```

答:
A Service is an application component that can perform long-running operations in the background, and it does not provide a user interface. - from official Android Documentation.

Now as service doesn't have ui, you can not show toast while using service.

Title: Toast not working in Service

Body:
I try to create my first Service, of course without success. But this app successfully compiled and not give any error in AndroidMonitor.
In short, buttons no react for pressing.
I added to Android Manifest required line:

<service android:name=".MyService"></service>

ClientActivity

package com.example.servicetest;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class ClientActivity extends Activity {
    private Button btnStartService;
    private Button btnStopService;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnStartService = (Button) findViewById(R.id.btnStartService);
        btnStopService = (Button) findViewById(R.id.btnStopService);
        initButtonsOnClick();
    }

    private void initButtonsOnClick() {
        OnClickListener listener = new OnClickListener() {
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.btnStartService:
                        startMyService();
                        break;
                    case R.id.btnStopService:
                        stopMyService();
                        break;
                    default:
                        break;
                }
            }
        };
        btnStartService.setOnClickListener(listener);
        btnStopService.setOnClickListener(listener);
    }

    private void startMyService() {
        Intent serviceIntent = new Intent(this, MyService.class);
        startService(serviceIntent);
    }

    private void stopMyService() {
        Intent serviceIntent = new Intent(this, MyService.class);
        stopService(serviceIntent);
    }
}

MyService

package com.example.servicetest;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import java.util.Timer;
import java.util.TimerTask;
import android.widget.Toast;

public class MyService extends Service {
    private Toast toast;
    private Timer timer;
    private TimerTask timerTask;
    private class MyTimerTask extends TimerTask {
        @Override
        public void run() {
             Toast.makeText(getApplicationContext(), "Your service is still working", Toast.LENGTH_SHORT).show();
        }
    }

    private void writeToLogs(String message) {
        Log.d("HelloServices", message);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        writeToLogs("Called onCreate() method.");
        timer = new Timer();
        Toast.makeText(getApplicationContext(), "", Toast.LENGTH_SHORT).show();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        writeToLogs("Called onStartCommand() methond");
        clearTimerSchedule();
        initTask();
        timer.scheduleAtFixedRate(timerTask, 4 * 1000, 4 * 1000);
        Toast.makeText(getApplicationContext(), "Your service has been started", Toast.LENGTH_SHORT).show();
        return super.onStartCommand(intent, flags, startId);
    }

    private void clearTimerSchedule() {
        if(timerTask != null) {
            timerTask.cancel();
            timer.purge();
        }
    }

    private void initTask() {
        timerTask = new MyTimerTask();
    }

    @Override
    public void onDestroy() {
        writeToLogs("Called onDestroy() method");
        clearTimerSchedule();
        Toast.makeText(getApplicationContext(), "Your service has been stopped", Toast.LENGTH_SHORT).show();
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
}


问:
convert array in to associative array
i have following array. and i want to dynamically update this array.

```<code>Array
(
[0] => Array
    (
        [id] =>
        [cip] => 172.35.2.45
        [ctime] => 1498718978
        [uip] => 172.35.2.40
        [utime] => 1498712478
        [interface] => wan
        [type] => pass
        [disabled] => no
    )
[1] => Array
    (
        [id] =>
        [cip] => 172.35.2.24
        [ctime] => 1498778578
        [uip] => 172.35.2.41
        [utime] => 1498532478
        [interface] => wan
        [type] => pass
        [disabled] => no
    )
)
</code>```

and i want it convert into.

```<code>Array
(
[0] => Array
    (
        [id] =>
        updated => Array
        (
            [time] => 1498712478
            [username] => admin@172.35.2.40
        )
        created => Array
        (
            [time] => 1498712478
            [username] => admin@172.35.2.45
        )
        [interface] => wan
        [type] => pass
        [disabled] => no
    )
[1] => Array
    (
        [id] =>
        [updated] => Array
        (
            [time] => 1498532478
            [username] => admin@172.35.2.41
        )
        created => Array
        (
            [time] => 1498778578
            [username] => admin@172.35.2.24
        )
        [interface] => wan
        [type] => pass
        [disabled] => no
    )
)
</code>```

here we have two element in main array and it can be very, i tried it by using foreach loop and some other thing. but i am not near to the answer i want please help me to sort this

答:
it's been done by doing this.</p>

```<code>foreach($oldarray as $key => $value){
    $newarray['created']['time'] = '"'.strtotime($value['ctime']).'"';
    $newarray['created']['username'] = 'admin@'.$value['cip'];
    $newarray['updated']['time'] = '"'.strtotime($value['utime']).'"';
    $newarray['updated']['username'] = 'admin@'.$value['uip'];
}
</code>```

Title: convert array in to associative array

Body:
i have following array. and i want to dynamically update this array.

Array
(
[0] => Array
    (
        [id] =>
        [cip] => 172.35.2.45
        [ctime] => 1498718978
        [uip] => 172.35.2.40
        [utime] => 1498712478
        [interface] => wan
        [type] => pass
        [disabled] => no
    )
[1] => Array
    (
        [id] =>
        [cip] => 172.35.2.24
        [ctime] => 1498778578
        [uip] => 172.35.2.41
        [utime] => 1498532478
        [interface] => wan
        [type] => pass
        [disabled] => no
    )
)

and i want it convert into.

Array
(
[0] => Array
    (
        [id] =>
        updated => Array
        (
            [time] => 1498712478
            [username] => admin@172.35.2.40
        )
        created => Array
        (
            [time] => 1498712478
            [username] => admin@172.35.2.45
        )
        [interface] => wan
        [type] => pass
        [disabled] => no
    )
[1] => Array
    (
        [id] =>
        [updated] => Array
        (
            [time] => 1498532478
            [username] => admin@172.35.2.41
        )
        created => Array
        (
            [time] => 1498778578
            [username] => admin@172.35.2.24
        )
        [interface] => wan
        [type] => pass
        [disabled] => no
    )
)

here we have two element in main array and it can be very, i tried it by using foreach loop and some other thing. but i am not near to the answer i want please help me to sort this

Body:
it's been done by doing this.

foreach($oldarray as $key => $value){
    $newarray['created']['time'] = '"'.strtotime($value['ctime']).'"';
    $newarray['created']['username'] = 'admin@'.$value['cip'];
    $newarray['updated']['time'] = '"'.strtotime($value['utime']).'"';
    $newarray['updated']['username'] = 'admin@'.$value['uip'];
}


问:
Set password with Telegram TL
I'd like to enable Two-Step Verification for my telegram client and set a password for it.

I couldn't find any hint in official documents or any function for this purpose but I tried following functions anyway:

```<code>auth.recoverPassword#4ea56e92 code:string = auth.Authorization
auth.requestPasswordRecovery#d897bc66 = auth.PasswordRecovery
auth.checkPassword#0a63011e password_hash:bytes = auth.Authorization
auth.signUp#1b067634 phone_number:string phone_code_hash:string phone_code:string first_name:string last_name:string = auth.Authorization;
</code>```

None of them have any related parameter neither return anything useful.

答:
I use this unofficial site, try this:</p>

```<code>account.updatePasswordSettings#fa7c4b86 current_password_hash:bytes new_settings:account.PasswordInputSettings = Bool;
</code>```

Title: Set password with Telegram TL

Body:
I'd like to enable Two-Step Verification for my telegram client and set a password for it.

I couldn't find any hint in official documents or any function for this purpose but I tried following functions anyway:

auth.recoverPassword#4ea56e92 code:string = auth.Authorization
auth.requestPasswordRecovery#d897bc66 = auth.PasswordRecovery
auth.checkPassword#0a63011e password_hash:bytes = auth.Authorization
auth.signUp#1b067634 phone_number:string phone_code_hash:string phone_code:string first_name:string last_name:string = auth.Authorization;

None of them have any related parameter neither return anything useful.

Body:
I use this unofficial site, try this:

account.updatePasswordSettings#fa7c4b86 current_password_hash:bytes new_settings:account.PasswordInputSettings = Bool;


问:
unexpected '$fridays' (T_VARIABLE), expecting function (T_FUNCTION)
I am getting syntax error in the following code:

```<code>function getFridays($year='', $format='', $timezone = 'UTC') {

$fridays = array();
$startDate = new DateTime("{$year}-01-01 Friday", new DateTimezone($timezone));

$year++;
$endDate = new DateTime("{$year}-01-01", new DateTimezone($timezone));

$int = new DateInterval('P7D');

foreach (new DatePeriod($startDate, $int, $endDate) as $d) {
    $fridays[] = $d->format($format);

}

return $fridays;
}

$fridays = getFridays($year, 'Y-m-d', 'America/New_York');
</code>```

Error: unexpected '$fridays' (T_VARIABLE), expecting function (T_FUNCTION)

答:
Problem is with this line

```<code>$fridays = getFridays($year, 'Y-m-d', 'America/New_York');
</code>```

You cannot put this outside of the function and called another function. If you want to call this you have to put it in another function. Just try to var_dump the $friday after the return outside of the for loop.

```<code>var_dump($friday);
exit;
</code>```

you can see your array.

Body:
I am getting syntax error in the following code:

function getFridays($year='', $format='', $timezone = 'UTC') {

$fridays = array();
$startDate = new DateTime("{$year}-01-01 Friday", new DateTimezone($timezone));

$year++;
$endDate = new DateTime("{$year}-01-01", new DateTimezone($timezone));

$int = new DateInterval('P7D');

foreach (new DatePeriod($startDate, $int, $endDate) as $d) {
    $fridays[] = $d->format($format);

}

return $fridays;
}

$fridays = getFridays($year, 'Y-m-d', 'America/New_York');

Error: unexpected '$fridays' (T_VARIABLE), expecting function (T_FUNCTION)

Body:
Problem is with this line

$fridays = getFridays($year, 'Y-m-d', 'America/New_York');

You cannot put this outside of the function and called another function. If you want to call this you have to put it in another function. Just try to var_dump the $friday after the return outside of the for loop.

var_dump($friday);
exit;

you can see your array.


问:
ASP.NET MVC: how to prevent unauthenticated user to directly GET images?
I have confidential images that I only want to show to authenticated users. On the  razor view, which is only accessible to authenticated users, I have

How do I prevent an unauthenticated user to bypass my razor view and directly request this photo through a HTTP GET?

答:
Check this answer, it has multiple ways to do this.

Https://stackoverflow.com/questions/11726848/asp-net-mvc-4-intercept-all-incoming-requests


问:
getContentResolver().query() android for getting images of specific width and height
getContentResolver().query() for getting images of specific width and height
this is the normal query</p>

```<code>final String[] columns = {
    MediaStore.Images.Media.DATA,
    MediaStore.Images.Media.WIDTH,
    MediaStore.Images.Media.HEIGHT
    };

Cursor mCursor = _context.getContentResolver().
                     query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                          columns,null,null,
                          MediaStore.Images.Media.DEFAULT_SORT_ORDER);
</code>```

答:
This would be helpful for people looking for an answer</p>

```<code>String[] projection1 = {MediaStore.Images.Media.DATA};
        cursor1 = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                projection1, // Which columns to return
                (MediaStore.Images.Media.HEIGHT + " <= 600" + " AND "
                        + MediaStore.Images.Media.WIDTH + " <= 600"),       // Return all rows
                null,
                null);
</code>```

Body:
getContentResolver().query() for getting images of specific width and height
this is the normal query

final String[] columns = {
    MediaStore.Images.Media.DATA,
    MediaStore.Images.Media.WIDTH,
    MediaStore.Images.Media.HEIGHT
    };

Cursor mCursor = _context.getContentResolver().
                     query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                          columns,null,null,
                          MediaStore.Images.Media.DEFAULT_SORT_ORDER);

Body:
This would be helpful for people looking for an answer

String[] projection1 = {MediaStore.Images.Media.DATA};
        cursor1 = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                projection1, // Which columns to return
                (MediaStore.Images.Media.HEIGHT + " <= 600" + " AND "
                        + MediaStore.Images.Media.WIDTH + " <= 600"),       // Return all rows
                null,
                null);


问:
Wordpress query for posts is pulling up revisions as results
I have the following wordpress query which is displaying the post title multiple times, I have checked and it's getting all the revisions for each post.

Here is the query:

```<code>SELECT DISTINCT post_title, ID
FROM wpblog_posts
WHERE post_title LIKE '%Kimberley%'
OR post_title LIKE '%Camping%'
AND wpblog_posts.post_type = 'post'
AND post_status = 'publish'
ORDER BY post_title DESC LIMIT 0, 6;
</code>```

Anyone know why this might be happening.

Update

Removed from query string as not relevant and will make it
  easier to debug.

```<code>LEFT JOIN wpblog_term_relationships rel ON rel.object_id = wpblog_posts.ID
LEFT JOIN wpblog_term_taxonomy tax ON tax.term_taxonomy_id = rel.term_taxonomy_id
LEFT JOIN wpblog_terms t ON t.term_id = tax.term_id
</code>```

Cheers

答:
Check this query if it works for you:

```<code>SELECT DISTINCT post_title, ID
FROM wpblog_posts
WHERE (post_title LIKE '%Kimberley%' OR post_title LIKE '%Camping%')
AND wpblog_posts.post_type = 'post'
AND post_status = 'publish'
ORDER BY post_title DESC LIMIT 0, 6;
</code>```

The query was looking for posts LIKE '%Kimberley%' - any type of post OR LIKE '%Camping%' AND wpblog_posts.post_type = 'post' ....

Body:
I have the following wordpress query which is displaying the post title multiple times, I have checked and it's getting all the revisions for each post.

Here is the query:

SELECT DISTINCT post_title, ID
FROM wpblog_posts
WHERE post_title LIKE '%Kimberley%'
OR post_title LIKE '%Camping%'
AND wpblog_posts.post_type = 'post'
AND post_status = 'publish'
ORDER BY post_title DESC LIMIT 0, 6;

Anyone know why this might be happening.

Update

Removed from query string as not relevant and will make it
  easier to debug.

LEFT JOIN wpblog_term_relationships rel ON rel.object_id = wpblog_posts.ID
LEFT JOIN wpblog_term_taxonomy tax ON tax.term_taxonomy_id = rel.term_taxonomy_id
LEFT JOIN wpblog_terms t ON t.term_id = tax.term_id

Cheers

Body:
Check this query if it works for you:

SELECT DISTINCT post_title, ID
FROM wpblog_posts
WHERE (post_title LIKE '%Kimberley%' OR post_title LIKE '%Camping%')
AND wpblog_posts.post_type = 'post'
AND post_status = 'publish'
ORDER BY post_title DESC LIMIT 0, 6;

The query was looking for posts LIKE '%Kimberley%' - any type of post OR LIKE '%Camping%' AND wpblog_posts.post_type = 'post' ....


问:
Why does passing a dictionary as a parameter take more time?
I tried to a leetcode problem. I find one of the following code throws a time limit exceeded error. I created the following testing code. I found the first one pass dictionary as a parameter takes more time the the other one. 0.94s vs 0.84s.
Can anyone explain this ?</p>

```<code>class Solution(object):
    def longestPalindromeSubseq(self, x):
        """
        :type s: str
        :rtype: int
        """

        #dic = {}

        def helper(s, dic):
            if len(s) == 0:
                return 0
            if len(s) == 1:
                return 1

            if s in dic:
                return dic[s]

            if s[0] == s[-1]:
                res = helper(s[1:-1], dic)+2
            else:
                l1 = helper(s[:-1], dic)
                l2 = helper(s[1:], dic)
                res = max(l1,l2)
            dic[s] = res
            #print (id(dic), dic)
            return res
        d = {}
        ans = helper(x, d)
        #print (id(d), d)
        return ans

class Solution1(object):
    def longestPalindromeSubseq(self, x):
        """
        :type s: str
        :rtype: int
        """

        dic = {}

        def helper(s):
            if len(s) == 0:
                return 0
            if len(s) == 1:
                return 1

            if s in dic:
                return dic[s]

            if s[0] == s[-1]:
                res = helper(s[1:-1])+2
            else:
                l1 = helper(s[:-1])
                l2 = helper(s[1:])
                res = max(l1,l2)
            dic[s] = res
            #print (id(dic), dic)
            return res
        ans = helper(x)
        #print (id(dic), dic)
        return ans

import time
if __name__ == "__main__":
    x = "gphyvqruxjmwhonjjrgumxjhfyupajxbjgthzdvrdqmdouuukeaxhjumkmmhdglqrrohydrmbvtuwstgkobyzjjtdtjroqpyusfsbjlusekghtfbdctvgmqzeybnwzlhdnhwzptgkzmujfldoiejmvxnorvbiubfflygrkedyirienybosqzrkbpcfidvkkafftgzwrcitqizelhfsruwmtrgaocjcyxdkovtdennrkmxwpdsxpxuarhgusizmwakrmhdwcgvfljhzcskclgrvvbrkesojyhofwqiwhiupujmkcvlywjtmbncurxxmpdskupyvvweuhbsnanzfioirecfxvmgcpwrpmbhmkdtckhvbxnsbcifhqwjjczfokovpqyjmbywtpaqcfjowxnmtirdsfeujyogbzjnjcmqyzciwjqxxgrxblvqbutqittroqadqlsdzihngpfpjovbkpeveidjpfjktavvwurqrgqdomiibfgqxwybcyovysydxyyymmiuwovnevzsjisdwgkcbsookbarezbhnwyqthcvzyodbcwjptvigcphawzxouixhbpezzirbhvomqhxkfdbokblqmrhhioyqubpyqhjrnwhjxsrodtblqxkhezubprqftrqcyrzwywqrgockioqdmzuqjkpmsyohtlcnesbgzqhkalwixfcgyeqdzhnnlzawrdgskurcxfbekbspupbduxqxjeczpmdvssikbivjhinaopbabrmvscthvoqqbkgekcgyrelxkwoawpbrcbszelnxlyikbulgmlwyffurimlfxurjsbzgddxbgqpcdsuutfiivjbyqzhprdqhahpgenjkbiukurvdwapuewrbehczrtswubthodv"
    print (x)
    t0 = time.time()
    sol = Solution()
    print (sol.longestPalindromeSubseq(x))
    t1 = time.time()
    print(t1- t0)

    sol1 = Solution1()
    print (sol1.longestPalindromeSubseq(x))
    t2 = time.time()
    print(t2-t1)
</code>```

答:
Python uses something that is called call by sharing. The function gets only the alias on the parameter. With that in mind, it does't matter what you pass to the function.

But the script may take different time to execute. It is not constant. Using recursion makes it even harder to predict

Body:
I tried to a leetcode problem. I find one of the following code throws a time limit exceeded error. I created the following testing code. I found the first one pass dictionary as a parameter takes more time the the other one. 0.94s vs 0.84s.
Can anyone explain this ?

class Solution(object):
    def longestPalindromeSubseq(self, x):
        """
        :type s: str
        :rtype: int
        """

        #dic = {}

        def helper(s, dic):
            if len(s) == 0:
                return 0
            if len(s) == 1:
                return 1

            if s in dic:
                return dic[s]

            if s[0] == s[-1]:
                res = helper(s[1:-1], dic)+2
            else:
                l1 = helper(s[:-1], dic)
                l2 = helper(s[1:], dic)
                res = max(l1,l2)
            dic[s] = res
            #print (id(dic), dic)
            return res
        d = {}
        ans = helper(x, d)
        #print (id(d), d)
        return ans

class Solution1(object):
    def longestPalindromeSubseq(self, x):
        """
        :type s: str
        :rtype: int
        """

        dic = {}

        def helper(s):
            if len(s) == 0:
                return 0
            if len(s) == 1:
                return 1

            if s in dic:
                return dic[s]

            if s[0] == s[-1]:
                res = helper(s[1:-1])+2
            else:
                l1 = helper(s[:-1])
                l2 = helper(s[1:])
                res = max(l1,l2)
            dic[s] = res
            #print (id(dic), dic)
            return res
        ans = helper(x)
        #print (id(dic), dic)
        return ans

import time
if __name__ == "__main__":
    x = "gphyvqruxjmwhonjjrgumxjhfyupajxbjgthzdvrdqmdouuukeaxhjumkmmhdglqrrohydrmbvtuwstgkobyzjjtdtjroqpyusfsbjlusekghtfbdctvgmqzeybnwzlhdnhwzptgkzmujfldoiejmvxnorvbiubfflygrkedyirienybosqzrkbpcfidvkkafftgzwrcitqizelhfsruwmtrgaocjcyxdkovtdennrkmxwpdsxpxuarhgusizmwakrmhdwcgvfljhzcskclgrvvbrkesojyhofwqiwhiupujmkcvlywjtmbncurxxmpdskupyvvweuhbsnanzfioirecfxvmgcpwrpmbhmkdtckhvbxnsbcifhqwjjczfokovpqyjmbywtpaqcfjowxnmtirdsfeujyogbzjnjcmqyzciwjqxxgrxblvqbutqittroqadqlsdzihngpfpjovbkpeveidjpfjktavvwurqrgqdomiibfgqxwybcyovysydxyyymmiuwovnevzsjisdwgkcbsookbarezbhnwyqthcvzyodbcwjptvigcphawzxouixhbpezzirbhvomqhxkfdbokblqmrhhioyqubpyqhjrnwhjxsrodtblqxkhezubprqftrqcyrzwywqrgockioqdmzuqjkpmsyohtlcnesbgzqhkalwixfcgyeqdzhnnlzawrdgskurcxfbekbspupbduxqxjeczpmdvssikbivjhinaopbabrmvscthvoqqbkgekcgyrelxkwoawpbrcbszelnxlyikbulgmlwyffurimlfxurjsbzgddxbgqpcdsuutfiivjbyqzhprdqhahpgenjkbiukurvdwapuewrbehczrtswubthodv"
    print (x)
    t0 = time.time()
    sol = Solution()
    print (sol.longestPalindromeSubseq(x))
    t1 = time.time()
    print(t1- t0)

    sol1 = Solution1()
    print (sol1.longestPalindromeSubseq(x))
    t2 = time.time()
    print(t2-t1)


问:
JAWS not reading select box value when changing options using keyboard down arrow
I'm testing my web page for accessibility using JAWS reader. Below is a sample HTML markup from my page.

```<code><label for="MySelectBox">Select a color</label>
<select id="MySelectBox">
    <option>Red</option>
    <option>Blue</option>
    <option>Green</option>
</select>
</code>```

When navigating the page through keyboard and changing the select box value using Down arrow key, JAWS is not reading the changing values as you press down arrow.

Anything I'm missing in here? Should I add any additional ARIA labels to make JAWS recognize the change event?

答:
You need to add aria-live="assertive" to the select tag.
Reference : http://www.freedomscientific.com/Training/Surfs-Up/AriaLiveRegions.htm</p>

Body:
I'm testing my web page for accessibility using JAWS reader. Below is a sample HTML markup from my page.

Select a color
<select id="MySelectBox">
    <option>Red</option>
    <option>Blue</option>
    <option>Green</option>
</select>

When navigating the page through keyboard and changing the select box value using Down arrow key, JAWS is not reading the changing values as you press down arrow.

Anything I'm missing in here? Should I add any additional ARIA labels to make JAWS recognize the change event?


问:
Adam optimizer goes haywire after 200k batches, training loss grows
I've been seeing a very strange behavior when training a network, where after a couple of 100k iterations (8 to 10 hours) of learning fine, everything breaks and the training loss grows:

The training data itself is randomized and spread across many .tfrecord files containing 1000 examples each, then shuffled again in the input stage and batched to 200 examples.

The background

I am designing a network that performs four different regression tasks at the same time, e.g. determining the likelihood of an object appearing in the image and simultanously determining its orientation. The network starts with a couple of convolutional layers, some with residual connections, and then branches into the four fully-connected segments.

Since the first regression results in a probability, I'm using cross entropy for the loss, whereas the others use classical L2 distance. However, due to their nature, the probability loss is around the order of 0..1, while the orientation losses can be much larger, say 0..10. I already normalized both input and output values and use clipping

```<code>normalized = tf.clip_by_average_norm(inferred.sin_cos, clip_norm=2.)
</code>```

in cases where things can get really bad.

I've been (successfully) using the Adam optimizer to optimize on the tensor containing all distinct losses (rather than reduce_suming them), like so:

```<code>reg_loss = tf.reduce_sum(tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES))
loss = tf.pack([loss_probability, sin_cos_mse, magnitude_mse, pos_mse, reg_loss])

optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate,
                                   epsilon=self.params.adam_epsilon)
op_minimize = optimizer.minimize(loss, global_step=global_step)
</code>```

In order to display the results in TensorBoard, I then actually do

```<code>loss_sum = tf.reduce_sum(loss)
</code>```

for a scalar summary.

Adam is set to learning rate 1e-4 and epsilon 1e-4 (I see the same behavior with the default value for epislon and it breaks even faster when I keep the learning rate on 1e-3). Regularization also has no influence on this one, it does this sort-of consistently at some point.

I should also add that stopping the training and restarting from the last checkpoint - implying that the training input files are shuffled again as well - results in the same behavior. The training always seems to behave similarly at that point.

答:
Yes this could be some sort of super complicated unstable numbers/equations case, but most certainty your training rate is just simply to high as your loss quickly decreases until 25K and then oscillates a lot in the same level. Try to decrease it by factor of 0.1 and see what happens. You should be able to reach even lower loss value.

Keep exploring! :)

Body:
I've been seeing a very strange behavior when training a network, where after a couple of 100k iterations (8 to 10 hours) of learning fine, everything breaks and the training loss grows:

The training data itself is randomized and spread across many .tfrecord files containing 1000 examples each, then shuffled again in the input stage and batched to 200 examples.

The background

I am designing a network that performs four different regression tasks at the same time, e.g. determining the likelihood of an object appearing in the image and simultanously determining its orientation. The network starts with a couple of convolutional layers, some with residual connections, and then branches into the four fully-connected segments.

Since the first regression results in a probability, I'm using cross entropy for the loss, whereas the others use classical L2 distance. However, due to their nature, the probability loss is around the order of 0..1, while the orientation losses can be much larger, say 0..10. I already normalized both input and output values and use clipping

normalized = tf.clip_by_average_norm(inferred.sin_cos, clip_norm=2.)

in cases where things can get really bad.

I've been (successfully) using the Adam optimizer to optimize on the tensor containing all distinct losses (rather than reduce_suming them), like so:

reg_loss = tf.reduce_sum(tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES))
loss = tf.pack([loss_probability, sin_cos_mse, magnitude_mse, pos_mse, reg_loss])

optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate,
                                   epsilon=self.params.adam_epsilon)
op_minimize = optimizer.minimize(loss, global_step=global_step)

In order to display the results in TensorBoard, I then actually do

loss_sum = tf.reduce_sum(loss)

for a scalar summary.

Adam is set to learning rate 1e-4 and epsilon 1e-4 (I see the same behavior with the default value for epislon and it breaks even faster when I keep the learning rate on 1e-3). Regularization also has no influence on this one, it does this sort-of consistently at some point.

I should also add that stopping the training and restarting from the last checkpoint - implying that the training input files are shuffled again as well - results in the same behavior. The training always seems to behave similarly at that point.


问:
Install TFS for Business Intelligence Development Studio 2005
I have just installed BIDS via the SQL Server 2005 Developer Edition, but now I need to access and work with a TFS project.  Will I be able to install TFS suporting tools in BIDS, or will I need to do a full install of VS 2005, which I would really rather do without.  Then, I believe it is quite a process to install TFS for VS 2005, with more than  one install that must be done in the correct order etc.  Where can I find guidance on this?</p>

答:
You can install the Team Explorer 2005, You then need to install SP1 of VS2005, and then the forward compatibility update to be able to connect with TFS 2010. See also http://www.ewaldhofman.nl/post/2010/04/29/How-to-connect-VS-2003-VS-2005-and-VS-2008-to-TFS-2010.aspx

If you have TFS 2008, installing Team Explorer 2005 is enough


问:
XCode 8.2.1 UIView Has no member 'load request'
I am running the following code and receiving the following error. I have searched but cannot see the precise answer. Really appreciate all assistance.
New to IOS Development so still working through
Thanks

```<code>import UIKit

class ViewController: UIViewController {
    @IBOutlet var WebView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        view.translatesAutoresizingMaskIntoConstraints = false

        WebView.loadRequest(NSURLRequest(URL:NSURL(fileURLWithPath:Bundle.mainbundle().pathForResource("mashupcode",ofType:"html")!)!))
        // This is the web mashup
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    }
</code>```

ERROR

Valueoftype 'UIView' has no member 'loadRequest

答:
Look:

```<code>@IBOutlet var WebView: **UIView**!
</code>```

Your webView variable is actually a UIView object. You need an actual UIWebView here instead of UIView. Probably check your storyboard and make sure you have connected the proper iboutlet.

Body:
I am running the following code and receiving the following error. I have searched but cannot see the precise answer. Really appreciate all assistance.
New to IOS Development so still working through
Thanks

import UIKit

class ViewController: UIViewController {
    @IBOutlet var WebView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        view.translatesAutoresizingMaskIntoConstraints = false

        WebView.loadRequest(NSURLRequest(URL:NSURL(fileURLWithPath:Bundle.mainbundle().pathForResource("mashupcode",ofType:"html")!)!))
        // This is the web mashup
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    }

ERROR

Valueoftype 'UIView' has no member 'loadRequest

Body:
Look:

@IBOutlet var WebView: **UIView**!

Your webView variable is actually a UIView object. You need an actual UIWebView here instead of UIView. Probably check your storyboard and make sure you have connected the proper iboutlet.


问:
c++ shared_ptr of stack object
I have been learning managed pointers lately and ran into the following scenario.

I am implementing a model/controller class for a game view. My view, will render things in the model. Pretty straight forward. In my main function, I instantiate all three like this:

```<code>RenderModel m;
m.AddItem(rect); // rect gets added just fine, it's an "entity" derivee
RenderView v;
v.SetModel(m);
</code>```

My render view class is pretty straightforward:

```<code>class RenderView
{
public:
explicit RenderView();
~RenderView();

void Update();

void SetModel(RenderModel& model);

private:
// disable
RenderView(const RenderView& other);
RenderView& operator=(const RenderView& other);

// private members
boost::scoped_ptr<RenderModel> _model;
};
</code>```

The implementation for setView is pretty standard:

```<code>void RenderView::SetModel(RenderModel& model)
{
    _model.reset(&model);
}
</code>```

The key to this is, the view stores a model in a smart pointer. However in main, the model was allocated on the stack. When the program exits, the memory gets deleted twice. This makes sense. My current understanding tells me that anything which gets stored in a smart_ptr (of any kind) should not have been allocated on the stack.

After all the above setup, my question is simple: how do I dictate that a parameter was not allocated on the stack? Is accepting a smart pointer as a parameter the only solution? Even then I could not ensure that someone using my view class could not do something incorrect such as:

```<code>// If I implemented SetModel this way:
void RenderView::SetModel(const std::shared_ptr<RenderModel>& model)
{
    _model.reset(&*model);
}

RenderModel m;
RenderView v;
std::shared_ptr<RenderModel> ptr(&m); // create a shared_ptr from a stack-object.
v.SetModel(ptr);
</code>```

答:
In short: define custom deleter.
In case of a smart pointer on a stack object, you can construct the smart pointer with a custom deleter, in this case a "Null Deleter" (or "StackObjectDeleter")

```<code>class StackObjectDeleter {
public:
    void operator () (void*) const {}
};

std::shared_ptr<RenderModel> ptr(&m, StackObjectDeleter());
</code>```

The StackObjectDeleter replaces the default_delete as the deleter object. default_delete simply calls delete (or delete []). In case of StackObjectDeleter, nothing will happen.

Title: c++ shared_ptr of stack object

Body:
I have been learning managed pointers lately and ran into the following scenario.

I am implementing a model/controller class for a game view. My view, will render things in the model. Pretty straight forward. In my main function, I instantiate all three like this:

RenderModel m;
m.AddItem(rect); // rect gets added just fine, it's an "entity" derivee
RenderView v;
v.SetModel(m);

My render view class is pretty straightforward:

class RenderView
{
public:
explicit RenderView();
~RenderView();

void Update();

void SetModel(RenderModel& model);

private:
// disable
RenderView(const RenderView& other);
RenderView& operator=(const RenderView& other);

// private members
boost::scoped_ptr<RenderModel> _model;
};

The implementation for setView is pretty standard:

void RenderView::SetModel(RenderModel& model)
{
    _model.reset(&model);
}

The key to this is, the view stores a model in a smart pointer. However in main, the model was allocated on the stack. When the program exits, the memory gets deleted twice. This makes sense. My current understanding tells me that anything which gets stored in a smart_ptr (of any kind) should not have been allocated on the stack.

After all the above setup, my question is simple: how do I dictate that a parameter was not allocated on the stack? Is accepting a smart pointer as a parameter the only solution? Even then I could not ensure that someone using my view class could not do something incorrect such as:

// If I implemented SetModel this way:
void RenderView::SetModel(const std::shared_ptr<RenderModel>& model)
{
    _model.reset(&*model);
}

RenderModel m;
RenderView v;
std::shared_ptr<RenderModel> ptr(&m); // create a shared_ptr from a stack-object.
v.SetModel(ptr);

Body:
In short: define custom deleter.
In case of a smart pointer on a stack object, you can construct the smart pointer with a custom deleter, in this case a "Null Deleter" (or "StackObjectDeleter")

class StackObjectDeleter {
public:
    void operator () (void*) const {}
};

std::shared_ptr<RenderModel> ptr(&m, StackObjectDeleter());

The StackObjectDeleter replaces the default_delete as the deleter object. default_delete simply calls delete (or delete []). In case of StackObjectDeleter, nothing will happen.


问:
Angular 1.4.8 :angular module/ng-app error
I have written few very simple lines of code using angular 1.4.8 and I was getting

Error: [$injector:nomod] Module 'a' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

Followed this link as I am also using the same version of angular.
Angular js 1.4.8 Injection module error

```<code><div ng-app='a'>
<div ng-controller="myctrl as ctrl">
<input type="text" ng-model="ctrl.name"/>
<input type="submit" ng-click="call();"/>
</div>
</div>
</code>```

```<code>var a=angular.module('a',[]);
a.controller("myctrl",['$scope',function($scope){

var ctrl=this;

$scope.call=function(){
alert(ctrl.name);
};

}]);
</code>```

here is link to my fiddle.
https://jsfiddle.net/rakotkar/mumv3uwf/4/

答:
There are few things,

(i) Angular reference is not getting loaded ,  you just need to change

Javascript settings -> Load type -> Wrap in

(ii)You need to change the controller code as,

```<code>var a=angular.module('a',[]);
a.controller("myctrl",function(){
var ctrl=this;
ctrl.call=function(){
alert(ctrl.name);
};
});
</code>```

WORKING FIDDLE

Body:
I have written few very simple lines of code using angular 1.4.8 and I was getting

Error: [$injector:nomod] Module 'a' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

Followed this link as I am also using the same version of angular.
Angular js 1.4.8 Injection module error

<input type="text" ng-model="ctrl.name"/>
<input type="submit" ng-click="call();"/>

var a=angular.module('a',[]);
a.controller("myctrl",['$scope',function($scope){

var ctrl=this;

$scope.call=function(){
alert(ctrl.name);
};

}]);

here is link to my fiddle.
https://jsfiddle.net/rakotkar/mumv3uwf/4/

Body:
There are few things,

(i) Angular reference is not getting loaded ,  you just need to change

Javascript settings -> Load type -> Wrap in <Head>

(ii)You need to change the controller code as,

var a=angular.module('a',[]);
a.controller("myctrl",function(){
var ctrl=this;
ctrl.call=function(){
alert(ctrl.name);
};
});

WORKING FIDDLE


问:
JUnit test — analysing expected Exceptions
In JUnit, I'm currently using annotation to expect an exception in my tests.

Is there a way to analyse this exception? For example, I expect a CriticalServerException, but I also want to verify the content of the getMessage method.

答: I don't think there is a way of doing it using annotation. You may have to fall back to try-catch way where in the catch block you can verify the message</p>


问:
Braintree payment rails
Is anyone familiar with Braintree?? According their documents for rails I have to do this: https://developers.braintreepayments.com/reference/request/plan/all/ruby   in order to retrieve plans from api.
Then why is it returning this error: NameError in PlansController#index...uninitialized constant PlansController::BraintreeRails

```<code>class PlansController < ApplicationController
  def index
    @plans = BraintreeRails::Plan.all
  end

  def show
    @plans = BraintreeRails::Plan.find(params[:id])
  end
end
</code>```

答:
Replace BraintreeRails with just Braintree, as it says in the documentation you linked to.

The error is basically telling you that Ruby does not know of a constant called BraintreeRails within the context of your PlansController, as you have mistyped the name.

Title: Braintree payment rails

Body:
Is anyone familiar with Braintree?? According their documents for rails I have to do this: https://developers.braintreepayments.com/reference/request/plan/all/ruby   in order to retrieve plans from api.
Then why is it returning this error: NameError in PlansController#index...uninitialized constant PlansController::BraintreeRails

class PlansController < ApplicationController
  def index
    @plans = BraintreeRails::Plan.all
  end

  def show
    @plans = BraintreeRails::Plan.find(params[:id])
  end
end


问:
How can I set a UITableViewCell's accessory color?
I'd like to set the accessory view icon to be white, similarly to how icons are colored white automatically in a black TabBar, but it's not immediately obvious to me how to do this. Does anyone have experience with this?</p>

答:
Swift 3.0

Two ways:

Use your own UIImageView as accessoryView of the tableview cell.

If you are using the system accessory type, like Disclosure Indicator the arrow icon (>), you can change the UIImageView tintColor to achieve it. Like below:

```<code>cell?.subviews.forEach({
        if let btn = $0 as? UIButton {
            btn.subviews.forEach({
                if let imageView = $0 as? UIImageView {
                    let image = imageView.image?.withRenderingMode(.alwaysTemplate)
                    imageView.image = image
                    imageView.tintColor = UIColor.red
                }
            })
        }
    })
</code>```

Body:
Swift 3.0

Two ways:

Use your own UIImageView as accessoryView of the tableview cell.

If you are using the system accessory type, like Disclosure Indicator the arrow icon (>), you can change the UIImageView tintColor to achieve it. Like below:

cell?.subviews.forEach({
        if let btn = $0 as? UIButton {
            btn.subviews.forEach({
                if let imageView = $0 as? UIImageView {
                    let image = imageView.image?.withRenderingMode(.alwaysTemplate)
                    imageView.image = image
                    imageView.tintColor = UIColor.red
                }
            })
        }
    })


问:
how to make dynamic diagonal view list
i m adding diagonal cut layout to RecyclerView, but i m not getting expected result. my second view start with end of first view, and thats obvious. but what i want is that each view is join with each-other like this.

My Output:

and this is what i wanted:

CutLayout.class:

```<code>public class CutLayout extends FrameLayout {
    private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    private Xfermode pdMode = new PorterDuffXfermode(PorterDuff.Mode.CLEAR);
    private Path path = new Path();

    public CutLayout(Context context) {
        super(context);
    }

    public CutLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CutLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public CutLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        int saveCount = canvas.saveLayer(0, 0, getWidth(), getHeight(), null, Canvas.ALL_SAVE_FLAG);
        super.dispatchDraw(canvas);

        paint.setXfermode(pdMode);
        path.reset();
        path.moveTo(0, getHeight());
        path.lineTo(getWidth(), getHeight());
        path.lineTo(getWidth(), getHeight() - TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50, getResources().getDisplayMetrics()));
        path.close();
        canvas.drawPath(path, paint);

        canvas.restoreToCount(saveCount);
        paint.setXfermode(null);
    }
}
</code>```

item.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".SampleActivity">

    <com.yarolegovich.slidingrootnav.sample.helper.CutLayout
        android:layout_width="match_parent"
        android:layout_height="200dp">

        <ImageView
            android:scaleType="centerCrop"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:src="@drawable/homebulding" />
    </com.yarolegovich.slidingrootnav.sample.helper.CutLayout>
</LinearLayout>
</code>```

答:
Change your CutLayout to have the same path on top like so:

```<code>public class CutLayout extends FrameLayout {
    private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    private Xfermode pdMode = new PorterDuffXfermode(PorterDuff.Mode.CLEAR);
    private Path path = new Path();

    public CutLayout(Context context) {
        super(context);
    }

    public CutLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CutLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public CutLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        int saveCount = canvas.saveLayer(0, 0, getWidth(), getHeight(), null, Canvas.ALL_SAVE_FLAG);
        super.dispatchDraw(canvas);

        paint.setXfermode(pdMode);
        path.reset();

        path.moveTo(0, 0);
        path.lineTo(getWidth(), 0);
        path.lineTo(0, TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50, getResources().getDisplayMetrics()));
        path.close();
        canvas.drawPath(path, paint);

        path.reset();

        path.moveTo(0, getHeight());
        path.lineTo(getWidth(), getHeight());
        path.lineTo(getWidth(), getHeight() - TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50, getResources().getDisplayMetrics()));
        path.close();
        canvas.drawPath(path, paint);

        canvas.restoreToCount(saveCount);
        paint.setXfermode(null);
    }
}
</code>```

Then all you have to do is to create an item decorator for your Recycler view that can accept a negative top margin

```<code>public class NegativeTopItemDecorator extends RecyclerView.ItemDecoration{
    private final int mTopMargin;

    public NegativeTopItemDecorator(int topMargin) {
        this.mTopMargin = topMargin;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        outRect.top = mTopMargin;
    }
}
</code>```

And add it to your RecyclerView

```<code>int topMargin = - (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50, getResources().getDisplayMetrics());
NegativeTopItemDecorator itemDecorator = new NegativeTopItemDecorator(topMargin);
mRecyclerView.addItemDecoration(itemDecorator);
</code>```

This will give you something like the following output

Title: how to make dynamic diagonal view list

Body:
i m adding diagonal cut layout to RecyclerView, but i m not getting expected result. my second view start with end of first view, and thats obvious. but what i want is that each view is join with each-other like this.

My Output:

and this is what i wanted:

CutLayout.class:

public class CutLayout extends FrameLayout {
    private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    private Xfermode pdMode = new PorterDuffXfermode(PorterDuff.Mode.CLEAR);
    private Path path = new Path();

    public CutLayout(Context context) {
        super(context);
    }

    public CutLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CutLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public CutLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        int saveCount = canvas.saveLayer(0, 0, getWidth(), getHeight(), null, Canvas.ALL_SAVE_FLAG);
        super.dispatchDraw(canvas);

        paint.setXfermode(pdMode);
        path.reset();
        path.moveTo(0, getHeight());
        path.lineTo(getWidth(), getHeight());
        path.lineTo(getWidth(), getHeight() - TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50, getResources().getDisplayMetrics()));
        path.close();
        canvas.drawPath(path, paint);

        canvas.restoreToCount(saveCount);
        paint.setXfermode(null);
    }
}

item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".SampleActivity">

    <com.yarolegovich.slidingrootnav.sample.helper.CutLayout
        android:layout_width="match_parent"
        android:layout_height="200dp">

        <ImageView
            android:scaleType="centerCrop"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:src="@drawable/homebulding" />
    </com.yarolegovich.slidingrootnav.sample.helper.CutLayout>
</LinearLayout>

Body:
Change your CutLayout to have the same path on top like so:

public class CutLayout extends FrameLayout {
    private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    private Xfermode pdMode = new PorterDuffXfermode(PorterDuff.Mode.CLEAR);
    private Path path = new Path();

    public CutLayout(Context context) {
        super(context);
    }

    public CutLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CutLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public CutLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        int saveCount = canvas.saveLayer(0, 0, getWidth(), getHeight(), null, Canvas.ALL_SAVE_FLAG);
        super.dispatchDraw(canvas);

        paint.setXfermode(pdMode);
        path.reset();

        path.moveTo(0, 0);
        path.lineTo(getWidth(), 0);
        path.lineTo(0, TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50, getResources().getDisplayMetrics()));
        path.close();
        canvas.drawPath(path, paint);

        path.reset();

        path.moveTo(0, getHeight());
        path.lineTo(getWidth(), getHeight());
        path.lineTo(getWidth(), getHeight() - TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50, getResources().getDisplayMetrics()));
        path.close();
        canvas.drawPath(path, paint);

        canvas.restoreToCount(saveCount);
        paint.setXfermode(null);
    }
}

Then all you have to do is to create an item decorator for your Recycler view that can accept a negative top margin

public class NegativeTopItemDecorator extends RecyclerView.ItemDecoration{
    private final int mTopMargin;

    public NegativeTopItemDecorator(int topMargin) {
        this.mTopMargin = topMargin;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        outRect.top = mTopMargin;
    }
}

And add it to your RecyclerView

int topMargin = - (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50, getResources().getDisplayMetrics());
NegativeTopItemDecorator itemDecorator = new NegativeTopItemDecorator(topMargin);
mRecyclerView.addItemDecoration(itemDecorator);

This will give you something like the following output


问:
ng-bind-html values to other html tags
I want to take data from ng-bind-html and bind it to some other html tags.Though i can directly use ng-bind-html for it. But is there any other way where we can use the binded html to other HTML tags?

JS:

```<code> $scope.left = '<span>Hello World</span><strong>New Testing<strong><br/>h1>Testing</h1>';
</code>```

HTML:

```<code><div ng-bind-html="left" ng-model="GetValues"></div>

<span>{{GetValues}}</span>
</code>```

答:
use trustAsHtml to compile the string into Dom

```<code>$scope.trustAsHtml = function(html){
   return $sce.trustAsHtml(html);
}
</code>```

now call the function in the html

```<code><div ng-bind-html="trustAsHtml(left)" ng-model="GetValues"></div>
</code>```

angular.module("app",[])
.controller("ctrl",function($scope,$sce){
 $scope.left = 'Hello WorldNew Testing

Testing
';

  $scope.trustAsHtml = function(html){
    return $sce.trustAsHtml(html);
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
  <div ng-bind-html="trustAsHtml(left)" ng-model="GetValues"></div>

<span>{{GetValues}}</span>
</div></code>```

Title: ng-bind-html values to other html tags

Body:
I want to take data from ng-bind-html and bind it to some other html tags.Though i can directly use ng-bind-html for it. But is there any other way where we can use the binded html to other HTML tags?

JS:

 $scope.left = 'Hello WorldNew Testing
h1>Testing
';

HTML:

{{GetValues}}

Body:
use trustAsHtml to compile the string into Dom

$scope.trustAsHtml = function(html){
   return $sce.trustAsHtml(html);
}

now call the function in the html

<div ng-bind-html="trustAsHtml(left)" ng-model="GetValues"></div>

angular.module("app",[])
.controller("ctrl",function($scope,$sce){
 $scope.left = '<span>Hello World</span><strong>New Testing<strong><br/><h1>Testing</h1>';

  $scope.trustAsHtml = function(html){
    return $sce.trustAsHtml(html);
  }
})

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
  <div ng-bind-html="trustAsHtml(left)" ng-model="GetValues"></div>

<span>{{GetValues}}</span>
</div>


问:
Unable to get values from the input fields using jquery
I have my handlebars file as

            <form class="form-horizontal well">

                    Username

                        <input type="text" class="form-control" placeholder="Username">

                    Password

                        <input type="password" class="form-control" placeholder="Password">

                        <button type="submit" class="btn btn-default" id="login">Sign in</button>

                    <button type="submit" class="btn btn-primary" id="register">Not a Member? Sign Up</button>

            </form>

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

<p>and my app.js as </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function(){

    /*Submit login form*/

    $("#login").on('click', function(){
        var user = $("form input[type=text]").val();
        var pass = $("form input[type=password]").val();

        var data = {
            username : user,
            password : pass
        };

        $.ajax({
            type : "POST",
            url : '/api/login',
            data : data
        });
    });
})</code>```

I am unable to use the values inside of the data object but when i try to do a simple alert using the user and pass values it alerts correct values but when doing a ajax call nothing is getting passed neither the user nor the pass inside the data object

答:
Also you try this </p>

```<code>  $.ajax({
        type : "POST",
        url : '/api/login',
        data : $('form').serialize(),
    });
</code>```

Body:
I have my handlebars file as

            <form class="form-horizontal well">

                    Username

                        <input type="text" class="form-control" placeholder="Username">

                    Password

                        <input type="password" class="form-control" placeholder="Password">

                        <button type="submit" class="btn btn-default" id="login">Sign in</button>

                    <button type="submit" class="btn btn-primary" id="register">Not a Member? Sign Up</button>

            </form>

and my app.js as

$(document).ready(function(){

    /*Submit login form*/

    $("#login").on('click', function(){
        var user = $("form input[type=text]").val();
        var pass = $("form input[type=password]").val();

        var data = {
            username : user,
            password : pass
        };

        $.ajax({
            type : "POST",
            url : '/api/login',
            data : data
        });
    });
})

I am unable to use the values inside of the data object but when i try to do a simple alert using the user and pass values it alerts correct values but when doing a ajax call nothing is getting passed neither the user nor the pass inside the data object

Body:
Also you try this

  $.ajax({
        type : "POST",
        url : '/api/login',
        data : $('form').serialize(),
    });


问:
Reports on .Net and SQL Server
My client wants a report with some bars/charts to analysis his data.

So how do I give him this type of reports as iam using .NET 1.1 and sql server 2008..

Is this requirement possible with BI, with .net1.1?

Or there is some other solution for this type of requirement?

Please send ur suggestions.

答: Why not use SQL Server Reporting Services? Although it does depend on which version of SQL Server your client has.</p>

Title: Reports on .Net and SQL Server


答:
Way 1 : Achieve with using $compile

html

```<code><div my-directive="left" ng-model="GetValues"></div>
</code>```

directive

```<code>var app = angular.module('myApp',[]);
app.controller('ctrlMain',function($scope){
    $scope.bindMe = {id:1,myvar:"test"};
});
app.directive('myDirective', function($compile){
  return{
    restrict: 'A',
    scope: {
        varToBind: '=myDirective'
    },
    link: function(scope, elm, attrs){
      outerList = '<span>Hello World</span><strong>New Testing<strong><br/>h1>Testing</h1>';
      outerList = $compile(outerList)(scope);
      elm.replaceWith(outerList);
    }
  }
});
</code>```

way 2: Achieve with using AngularJS ng-include

you can directly include a html file :)

```<code><div ng-include="'myFile.htm'"></div>//your DOM string code should be in myfile.htm file
</code>```

Title: ng-bind-html values to other html tags

Body:
Way 1 : Achieve with using $compile

html

<div my-directive="left" ng-model="GetValues"></div>

directive

var app = angular.module('myApp',[]);
app.controller('ctrlMain',function($scope){
    $scope.bindMe = {id:1,myvar:"test"};
});
app.directive('myDirective', function($compile){
  return{
    restrict: 'A',
    scope: {
        varToBind: '=myDirective'
    },
    link: function(scope, elm, attrs){
      outerList = '<span>Hello World</span><strong>New Testing<strong><br/>h1>Testing</h1>';
      outerList = $compile(outerList)(scope);
      elm.replaceWith(outerList);
    }
  }
});

way 2: Achieve with using AngularJS ng-include

you can directly include a html file :)

<div ng-include="'myFile.htm'"></div>//your DOM string code should be in myfile.htm file


问:
GKTurnBasedEventListener could not be set to delegate of my ViewController?
In objC the syntax written by Rawendrich for GKTurnBasedEventListener, which was GKTurnBasedEventHandler there at that time, now changed by Apple is as below.

```<code> if (!gameCenterAvailable) return;

void (^setGKEventHandlerDelegate)(NSError *) = ^ (NSError *error)
{
    GKTurnBasedEventHandler *ev =
      [GKTurnBasedEventHandler sharedTurnBasedEventHandler];
    ev.delegate = self;
};

NSLog(@"Authenticating local user...");
if ([GKLocalPlayer localPlayer].authenticated == NO) {
    [[GKLocalPlayer localPlayer]
     authenticateWithCompletionHandler:
      setGKEventHandlerDelegate];
} else {
    NSLog(@"Already authenticated!");
    setGKEventHandlerDelegate(nil);
}
</code>```

Now after converting this to swift, and with the composition of writing down GKTurnBasedEventListener instead of GKTurnBasedEventHandler, this comes the following way.

```<code>//  Converted with Swiftify v1.0.6381 - https://objectivec2swift.com/
if !gameCenterAvailable {
return
}
var setGKEventHandlerDelegate: ((_: Error) -> Void)? = {(_ error:   Error?) -> Void in
    var ev = GKTurnBasedEventHandler.shared()
    ev.delegate = self
}
print("Authenticating local user...")
if GKLocalPlayer.localPlayer().authenticated == false {
GKLocalPlayer.localPlayer().authenticate(withCompletionHandler:    setGKEventHandlerDelegate)
}
else {
print("Already authenticated!")
setGKEventHandlerDelegate(nil)

}
</code>```

Unfortunately this is not the right syntax to set delegate of GKTurnBasedEventListener for my ViewController.

Please if anyone of you could solve this for me, because without this I'm not able to read through event listener's default functions.

Cheers!

答:
Finally after just about harsh 10 hours, I figured out this problem from Here. Although this syntax is in objC, but there's no problem of converting it to swift from Swiftify.

Although a bit later than the real time, but I'm now able to understand that setting delegate of GKTunBasedEventListener is not like the one we do for UITableViewControllerDelegate.

Here, one must have to first authenticate local player, then after you have to register local player's listener to the ViewController's delegate GKLocalPlayerListener.

One other thing I found on Apple's Documentation:
Do not implement GKChallengeListener, GKInviteEventListener, GKSavedGameListener, and GKTurnBasedEventListener directly; implement GKLocalPlayerListener instead. You can listen for and handle multiple events using GKLocalPlayerListener.

So then on I've implemented in the following way.

```<code>import GameKit

class ViewController: UIViewController,   GKTurnBasedMatchmakerViewControllerDelegate,
GKLocalPlayerListener {

.....

func player(_ player: GKPlayer, receivedTurnEventFor match: GKTurnBasedMatch, didBecomeActive: Bool) {

    print("#1")
    print(player)
    print("#2")
    print(match)
    print("#3")
    print(didBecomeActive)

    if match.status == GKTurnBasedMatchStatus.open
    {
        if GKLocalPlayer.localPlayer() == match.currentParticipant
        {

        if didBecomeActive
        {
            // Active now
        }
        else
        {
            // Active already
        }

        }
        else
        {
            // It's someone's turn

            if match.matchData != myMatch?.matchData
            {
               // Match Data being Updated by Someone
                print(player.alias ?? "No Name:")
            }

        }

    }

    thirdTopLabel.text = match.matchID! + "\n" + didBecomeActive.description

}

....
</code>```

Now in ViewDidLoad() function put the following code.

```<code>// In the ViewDidLoad function
 if(!GKLocalPlayer.localPlayer().isAuthenticated)
    {
        authenticatePlayer { (auth) in

            weak var weakSelf = self
            weak var weakPlayer = GKLocalPlayer.localPlayer()

            if(auth){

                 weakPlayer?.register(weakSelf!)
                 self.suthentication = true;

            }
            else{
                print("failed in authentication")
                self.suthentication = false;
            }

        }

    }
    else
    {
        // Already Authenticated
        GKLocalPlayer.localPlayer().register(self)
        localPlayer = GKLocalPlayer.localPlayer()

    }
</code>```

And finally your Authentication function should be like this.

```<code>// authenticate local player :: Just Authentication
func authenticatePlayer(completionHandler: @escaping (_ resultedPlaces: Bool) -> Void) {

    localPlayer = GKLocalPlayer.localPlayer()

    localPlayer.authenticateHandler =
        { (viewController , error ) -> Void in
            if viewController != nil
            {
                self.present(viewController!, animated:true, completion: nil)
            }
            else
            {
                if self.localPlayer.isAuthenticated
                {

                    completionHandler(true);
                }
                else
                {
                    completionHandler(false);

                    print("not able to authenticate fail")
                    self.gameCenterEnabled = false

                    if (error != nil)
                    {
                        print("\(error.debugDescription)")
                    }
                    else
                    {
                        print(    "error is nil")
                    }
                }
            }

    }
}
</code>```

NOTE: GKLocalPlayerListener won't work on simulator.

Body:
In objC the syntax written by Rawendrich for GKTurnBasedEventListener, which was GKTurnBasedEventHandler there at that time, now changed by Apple is as below.

 if (!gameCenterAvailable) return;

void (^setGKEventHandlerDelegate)(NSError *) = ^ (NSError *error)
{
    GKTurnBasedEventHandler *ev =
      [GKTurnBasedEventHandler sharedTurnBasedEventHandler];
    ev.delegate = self;
};

NSLog(@"Authenticating local user...");
if ([GKLocalPlayer localPlayer].authenticated == NO) {
    [[GKLocalPlayer localPlayer]
     authenticateWithCompletionHandler:
      setGKEventHandlerDelegate];
} else {
    NSLog(@"Already authenticated!");
    setGKEventHandlerDelegate(nil);
}

Now after converting this to swift, and with the composition of writing down GKTurnBasedEventListener instead of GKTurnBasedEventHandler, this comes the following way.

//  Converted with Swiftify v1.0.6381 - https://objectivec2swift.com/
if !gameCenterAvailable {
return
}
var setGKEventHandlerDelegate: ((_: Error) -> Void)? = {(_ error:   Error?) -> Void in
    var ev = GKTurnBasedEventHandler.shared()
    ev.delegate = self
}
print("Authenticating local user...")
if GKLocalPlayer.localPlayer().authenticated == false {
GKLocalPlayer.localPlayer().authenticate(withCompletionHandler:    setGKEventHandlerDelegate)
}
else {
print("Already authenticated!")
setGKEventHandlerDelegate(nil)

}

Unfortunately this is not the right syntax to set delegate of GKTurnBasedEventListener for my ViewController.

Please if anyone of you could solve this for me, because without this I'm not able to read through event listener's default functions.

Cheers!

Body:
Finally after just about harsh 10 hours, I figured out this problem from Here. Although this syntax is in objC, but there's no problem of converting it to swift from Swiftify.

Although a bit later than the real time, but I'm now able to understand that setting delegate of GKTunBasedEventListener is not like the one we do for UITableViewControllerDelegate.

Here, one must have to first authenticate local player, then after you have to register local player's listener to the ViewController's delegate GKLocalPlayerListener.

One other thing I found on Apple's Documentation:
Do not implement GKChallengeListener, GKInviteEventListener, GKSavedGameListener, and GKTurnBasedEventListener directly; implement GKLocalPlayerListener instead. You can listen for and handle multiple events using GKLocalPlayerListener.

So then on I've implemented in the following way.

import GameKit

class ViewController: UIViewController,   GKTurnBasedMatchmakerViewControllerDelegate,
GKLocalPlayerListener {

.....

func player(_ player: GKPlayer, receivedTurnEventFor match: GKTurnBasedMatch, didBecomeActive: Bool) {

    print("#1")
    print(player)
    print("#2")
    print(match)
    print("#3")
    print(didBecomeActive)

    if match.status == GKTurnBasedMatchStatus.open
    {
        if GKLocalPlayer.localPlayer() == match.currentParticipant
        {

        if didBecomeActive
        {
            // Active now
        }
        else
        {
            // Active already
        }

        }
        else
        {
            // It's someone's turn

            if match.matchData != myMatch?.matchData
            {
               // Match Data being Updated by Someone
                print(player.alias ?? "No Name:")
            }

        }

    }

    thirdTopLabel.text = match.matchID! + "\n" + didBecomeActive.description

}

....

Now in ViewDidLoad() function put the following code.

// In the ViewDidLoad function
 if(!GKLocalPlayer.localPlayer().isAuthenticated)
    {
        authenticatePlayer { (auth) in

            weak var weakSelf = self
            weak var weakPlayer = GKLocalPlayer.localPlayer()

            if(auth){

                 weakPlayer?.register(weakSelf!)
                 self.suthentication = true;

            }
            else{
                print("failed in authentication")
                self.suthentication = false;
            }

        }

    }
    else
    {
        // Already Authenticated
        GKLocalPlayer.localPlayer().register(self)
        localPlayer = GKLocalPlayer.localPlayer()

    }

And finally your Authentication function should be like this.

// authenticate local player :: Just Authentication
func authenticatePlayer(completionHandler: @escaping (_ resultedPlaces: Bool) -> Void) {

    localPlayer = GKLocalPlayer.localPlayer()

    localPlayer.authenticateHandler =
        { (viewController , error ) -> Void in
            if viewController != nil
            {
                self.present(viewController!, animated:true, completion: nil)
            }
            else
            {
                if self.localPlayer.isAuthenticated
                {

                    completionHandler(true);
                }
                else
                {
                    completionHandler(false);

                    print("not able to authenticate fail")
                    self.gameCenterEnabled = false

                    if (error != nil)
                    {
                        print("\(error.debugDescription)")
                    }
                    else
                    {
                        print(    "error is nil")
                    }
                }
            }

    }
}

NOTE: GKLocalPlayerListener won't work on simulator.


问:
Java selenium show popup if exception occure
I am working on automation, using java selenium using chrome driver to get data from webpage.

I want to set like a popup message like joptionpane if exception occurs.

if chrome driver path is incorrect, it should show popup with message.

if internet disconnects while selenium running, also show popup.

I tried try catch block but not working perfectly. Can you guys show me a sample piece of code to achieve...

```<code>public static void main(String[] args) {
   try{
       System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
       throw new IllegalStateException("description of the exception");
  }catch(IllegalStateException e){
       JOptionPane.showMessageDialog(frame, "ChromeDriver Path incorrect","ErrorMsg",
                                            JOptionPane.ERROR_MESSAGE);
       System.exit(1);
   }
</code>```

答:
You can refer below code snippet , which I have used to handle similar problem while reading the test data. You can throw custom exceptions for your validations and at last catch statement show the popup box with the error message.    </p>

```<code> @DataProvider(name = "data")
        public String[][] getDataForTestCases()  {
            String[][] arrayExcelData = null;
            try {
                Log.info("Reading the Test Case.");

                // code to read the file and create data provider array

            } catch (Exception e) {
                Log.info("Problem while Reading Test Case   - " + e.getMessage());
                JOptionPane.showMessageDialog(new Frame(),
                        "Problem while Reading Test Case   - " + e.getMessage());
                System.exit(1);
             }
            Log.info("Done Reading Test Case Driver File.");
            return arrayExcelData;
        }
</code>```

Body:
I am working on automation, using java selenium using chrome driver to get data from webpage.

I want to set like a popup message like joptionpane if exception occurs.

if chrome driver path is incorrect, it should show popup with message.

if internet disconnects while selenium running, also show popup.

I tried try catch block but not working perfectly. Can you guys show me a sample piece of code to achieve...

public static void main(String[] args) {
   try{
       System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
       throw new IllegalStateException("description of the exception");
  }catch(IllegalStateException e){
       JOptionPane.showMessageDialog(frame, "ChromeDriver Path incorrect","ErrorMsg",
                                            JOptionPane.ERROR_MESSAGE);
       System.exit(1);
   }

Body:
You can refer below code snippet , which I have used to handle similar problem while reading the test data. You can throw custom exceptions for your validations and at last catch statement show the popup box with the error message.

 @DataProvider(name = "data")
        public String[][] getDataForTestCases()  {
            String[][] arrayExcelData = null;
            try {
                Log.info("Reading the Test Case.");

                // code to read the file and create data provider array

            } catch (Exception e) {
                Log.info("Problem while Reading Test Case   - " + e.getMessage());
                JOptionPane.showMessageDialog(new Frame(),
                        "Problem while Reading Test Case   - " + e.getMessage());
                System.exit(1);
             }
            Log.info("Done Reading Test Case Driver File.");
            return arrayExcelData;
        }


问:
Dynamics crm 365 get azure adal authorization code
I have a scenario is one where the user has signed into CRM and triggers some functionality that calls a third party API to retrieve data that is not in CRM.
This API is a registered application in the Same Azure Active Directory as where the CRM resides. CRM single sign on is enabled.

I am trying to find an example of C# code which retrieves the authorization code via a CRM plugin. So far, I have managed to retrieve the token using a client secret as described in this article:

Retrieving token without the ADAL client library

I have implemented a basic call with the parameters defined in this article:

Requesting an Authorization code

But I need to pass the user session to make it work. It currently throws an error

A silent sign-in request was sent but no user is signed in. The cookies used to represent the user's session were not sent in the request to Azure AD. This can happen if the user is using Internet Explorer or Edge, and the web app sending the silent sign-in request is in different IE security zone than the Azure AD endpoint (login.microsoftonline.com).

Any help appreciated.

答:
AFAIK, it is not suitable to interact with Azure AD using the Oauth code grant flow in the Microsoft Dynamics 365 plug-in since it required users interaction. And it is not able to send the session in the Microsoft Dynamics 365 plug-in to authenticate using ADAL library.

If you only want to access the Microsoft Dynamics 365 organization service in the CRM plug-in, there is no need to use the ADAL library to authenticate again.

It is only required that plug-in code create an instance of the service through the ServiceProvider.GetService method.

```<code>// Obtain the organization service reference.
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
</code>```

More detail about context of Microsoft Dynamics 365 Plug-in development, please refer the link below:

Understand the data context passed to a plug-in

Body:
AFAIK, it is not suitable to interact with Azure AD using the Oauth code grant flow in the Microsoft Dynamics 365 plug-in since it required users interaction. And it is not able to send the session in the Microsoft Dynamics 365 plug-in to authenticate using ADAL library.

If you only want to access the Microsoft Dynamics 365 organization service in the CRM plug-in, there is no need to use the ADAL library to authenticate again.

It is only required that plug-in code create an instance of the service through the ServiceProvider.GetService method.

// Obtain the organization service reference.
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

More detail about context of Microsoft Dynamics 365 Plug-in development, please refer the link below:

Understand the data context passed to a plug-in