问:
How do I use the ngCordova sqlite service and the Cordova-SQLitePlugin with Ionic Framework?
I have been trying to incorperate sqlite into a simple Ionic app and this is the process I have been following:

```<code> ionic start myApp sidemenu
</code>```

Then I install the sqlite plugin:

```<code>ionic plugin add https://github.com/brodysoft/Cordova-SQLitePlugin
</code>```

and ngCordova

```<code>bower install ngCordova
</code>```

this gave me the following options:
Unable to find a suitable version for angular, please choose one:
    1) angular#1.2.0 which resolved to 1.2.0 and is required by ngCordova#0.1.4-alpha
    2) angular#>= 1.0.8 which resolved to 1.2.0 and is required by angular-ui-router#0.2.10
    3) angular#1.2.25 which resolved to 1.2.25 and is required by angular-animate#1.2.25, angular-sanitize#1.2.25
    4) angular#~1.2.17 which resolved to 1.2.25 and is required by ionic#1.0.0-beta.13Prefix the choice with ! to persist it to bower.json

I picked option 3)
 and I included the scripts in the file as follows:

```<code><script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="lib/ngCordova/dist/ng-cordova.js"></script>
<script src="cordova.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
</code>```

I then added a controller to the search view:

```<code>.controller('SearchCtrl', function ($scope, $cordovaSQLite){
  console.log('Test');
   var db = $cordovaSQLite.openDB({ name: "my.db" });

        // for opening a background db:
        var db = $cordovaSQLite.openDB({ name: "my.db", bgType: 1 });

        $scope.execute = function() {
          console.log('Test');
          var query = "INSERT INTO test_table (data, data_num) VALUES (?,?)";
          $cordovaSQLite.execute(db, query, ["test", 100]).then(function(res) {
            console.log("insertId: " + res.insertId);
          }, function (err) {
            console.error(err);
          });
     };
})
</code>```

This caused the error:

```<code>> TypeError: Cannot read property 'openDatabase' of undefined
>     at Object.openDB  (http://localhost:8100/lib/ngCordova/dist/ng-cordova.js:2467:36)
</code>```

Next I tried manually including the SQLitePlugin.js by:
copying from plugins/com.brodysoft.sqlitePlugin/www to main www/ and adding it to the index.html page

I tried including before everything:

```<code> <script src="SQLitePlugin.js"></script>
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="lib/ngCordova/dist/ng-cordova.js"></script>
<script src="cordova.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
</code>```

I get Error ReferenceError: cordova is not defined
so I then tried including it after the cordova.js script but still get the same error

would really appreciate the help
in case it is relevant, these are the current versions of Cordova and ionic I am using:

```<code>ionic --version  1.2.5
cordova --version 3.5.0-0.2.7
</code>```

and this is the generated bower.json

```<code>{
  "name": "myApp",
  "private": "true",
  "devDependencies": {
    "ionic": "driftyco/ionic-bower#1.0.0-beta.13"
  }
}
</code>```

and my package.json:

```<code>{
  "name": "myapp",
  "version": "1.0.0",
  "description": "myApp: An Ionic project",
  "dependencies": {
    "gulp": "^3.5.6",
    "gulp-sass": "^0.7.1",
    "gulp-concat": "^2.2.0",
    "gulp-minify-css": "^0.3.0",
    "gulp-rename": "^1.2.0"
  },
  "devDependencies": {
    "bower": "^1.3.3",
    "gulp-util": "^2.2.14",
    "shelljs": "^0.3.0"
  }
}
</code>```

答:
For later Ionic versions (Ionic 2+):

The best way to handle persistent storage with Ionic is using ionic-storage.

Ionic Storage is a package created and maintained by the ionic team to abstract development from the specifics of each browser or platform and automatically use the best storage solution available.

1. Installing Dependencies

In your case for SQLite you need to first install the dependencies for both Angular and Cordova:

npm install @ionic/storage --save

and

cordova plugin add cordova-sqlite-storage --save

Then edit your NgModule declaration in src/app/app.module.ts to add IonicStorageModule as an import:

import { IonicStorageModule } from '@ionic/storage';

@NgModule({
  declarations: [...],
  imports: [
    IonicModule.forRoot(MyApp),
    IonicStorageModule.forRoot({
      name: '__mydb',
      driverOrder: ['indexeddb', 'sqlite', 'websql'],
    })
  ],
  bootstrap: [...],
  entryComponents: [...],
  providers: [...],
})
export class AppModule { }
```
<br>
<h1>2. Inject Storage into your component </h1>
```import { Component } from '@angular/core';
import { Storage } from '@ionic/storage';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  constructor(public storage: Storage) {}
}
```
<br>
<h1>3. Storing data in SQLite</h1>
<p>Whenever you access storage, make sure to always wrap your code in the following:</p>
```storage.ready().then(() => { /* code here safely */});
```
<h3>3.1 Saving a key-value pair</h3>
```storage.ready().then(() => {
    storage.set('some key', 'some value');
});
```
<h3>3.2 Retrieving a value</h3>
```storage.ready().then(() => {
  storage.get('age').then((val: string) => {
      console.log('Your age is', val);
  });
});
```
<h3>3.3 Deleting a key-value pair</h3>
```storage.ready().then(() => {
    storage.remove('key').then((key: string) => { /* do something after deletion */})
});
```

Body:
I have been trying to incorperate sqlite into a simple Ionic app and this is the process I have been following:

 ionic start myApp sidemenu

Then I install the sqlite plugin:

ionic plugin add https://github.com/brodysoft/Cordova-SQLitePlugin

and ngCordova

bower install ngCordova

this gave me the following options:
Unable to find a suitable version for angular, please choose one:
    1) angular#1.2.0 which resolved to 1.2.0 and is required by ngCordova#0.1.4-alpha
    2) angular#>= 1.0.8 which resolved to 1.2.0 and is required by angular-ui-router#0.2.10
    3) angular#1.2.25 which resolved to 1.2.25 and is required by angular-animate#1.2.25, angular-sanitize#1.2.25
    4) angular#~1.2.17 which resolved to 1.2.25 and is required by ionic#1.0.0-beta.13Prefix the choice with ! to persist it to bower.json

I picked option 3)
 and I included the scripts in the file as follows:

I then added a controller to the search view:

.controller('SearchCtrl', function ($scope, $cordovaSQLite){
  console.log('Test');
   var db = $cordovaSQLite.openDB({ name: "my.db" });

        // for opening a background db:
        var db = $cordovaSQLite.openDB({ name: "my.db", bgType: 1 });

        $scope.execute = function() {
          console.log('Test');
          var query = "INSERT INTO test_table (data, data_num) VALUES (?,?)";
          $cordovaSQLite.execute(db, query, ["test", 100]).then(function(res) {
            console.log("insertId: " + res.insertId);
          }, function (err) {
            console.error(err);
          });
     };
})

This caused the error:

> TypeError: Cannot read property 'openDatabase' of undefined
>     at Object.openDB  (http://localhost:8100/lib/ngCordova/dist/ng-cordova.js:2467:36)

Next I tried manually including the SQLitePlugin.js by:
copying from plugins/com.brodysoft.sqlitePlugin/www to main www/ and adding it to the index.html page

I tried including before everything:

I get Error ReferenceError: cordova is not defined
so I then tried including it after the cordova.js script but still get the same error

would really appreciate the help
in case it is relevant, these are the current versions of Cordova and ionic I am using:

ionic --version  1.2.5
cordova --version 3.5.0-0.2.7

and this is the generated bower.json

{
  "name": "myApp",
  "private": "true",
  "devDependencies": {
    "ionic": "driftyco/ionic-bower#1.0.0-beta.13"
  }
}

and my package.json:

{
  "name": "myapp",
  "version": "1.0.0",
  "description": "myApp: An Ionic project",
  "dependencies": {
    "gulp": "^3.5.6",
    "gulp-sass": "^0.7.1",
    "gulp-concat": "^2.2.0",
    "gulp-minify-css": "^0.3.0",
    "gulp-rename": "^1.2.0"
  },
  "devDependencies": {
    "bower": "^1.3.3",
    "gulp-util": "^2.2.14",
    "shelljs": "^0.3.0"
  }
}

Body:
For later Ionic versions (Ionic 2+):

The best way to handle persistent storage with Ionic is using ionic-storage.

Ionic Storage is a package created and maintained by the ionic team to abstract development from the specifics of each browser or platform and automatically use the best storage solution available.

1. Installing Dependencies

In your case for SQLite you need to first install the dependencies for both Angular and Cordova:

npm install @ionic/storage --save

and

cordova plugin add cordova-sqlite-storage --save

Then edit your NgModule declaration in src/app/app.module.ts to add IonicStorageModule as an import:

import { IonicStorageModule } from '@ionic/storage';

@NgModule({
  declarations: [...],
  imports: [
    IonicModule.forRoot(MyApp),
    IonicStorageModule.forRoot({
      name: '__mydb',
      driverOrder: ['indexeddb', 'sqlite', 'websql'],
    })
  ],
  bootstrap: [...],
  entryComponents: [...],
  providers: [...],
})
export class AppModule { }

2. Inject Storage into your component

import { Component } from '@angular/core';
import { Storage } from '@ionic/storage';

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

3. Storing data in SQLite

Whenever you access storage, make sure to always wrap your code in the following:

storage.ready().then(() => { /* code here safely */});

3.1 Saving a key-value pair

storage.ready().then(() => {
    storage.set('some key', 'some value');
});

3.2 Retrieving a value

storage.ready().then(() => {
  storage.get('age').then((val: string) => {
      console.log('Your age is', val);
  });
});

3.3 Deleting a key-value pair

storage.ready().then(() => {
    storage.remove('key').then((key: string) => { /* do something after deletion */})
});


来源: stackexchange

问:
Gmail API forwardingAs
I'm curious if it's possible to gain access to the Gmail settings of all users within a domain once a user with Admin access authenticates. I know using the Admin SDK, you have access to user settings, however, I'd like to setup email forwarding and it doesn't seem like it's possible without each user authenticating. </p>

答: You may refer with this SO thread. Before you can call the Gmail API you need to use the service account "JWT flow" in your code to retrieve an OAuth2 credential for the Gmail user you want to access. Here is the documentation. You may also check this related post.</p>

ContentLicense: CC BY-SA 3.0

Title: Gmail API forwardingAs


问:
Chrome not showing "add to homescreen" in my PWA
I followed Google's first PWA tutorial and created my own project https://my-pwa-77d8a.firebaseapp.com. Everything looks fine:

The project has a manifest.json file

I'm using HTTPS on Firebase

The code has the <meta name="mobile-web-app-capable" content="yes"> tag

My manifest.json file contains: icons specs, name, short_name, start_url

I'm using Vue.js as my main framework and all the rest was built with vanilla JS

The service worker is set and running without errors

The console shows no erros

manifest.json

```<code>  {
    "short_name": "PizzaApp",
    "name": "My delicious PWA",
    "icons": [
      {
        "src": "img/launcher-icon-2x.png",
        "sizes": "96x96",
        "type": "image/png"
      },
      {
        "src": "img/launcher-icon-3x.png",
        "sizes": "144x144",
        "type": "image/png"
      },
      {
        "src": "img/launcher-icon-4x.png",
        "sizes": "192x192",
        "type": "image/png"
      }
    ],
    "start_url": "/index.html",
    "display": "standalone",
    "orientation": "portrait"
  }
</code>```

I can manually add to homescreen both from mobile and desktop. But Chrome never shows the add to homescreen banner. What is wrong?

SOLVED

As pointed bellow, my service worker was trying to cache a missing offline.html file. I created the file, cleared the phone's cache and everything worked fine.

答: The problem is that your offline.html file (https://my-pwa-77d8a.firebaseapp.com/offline.html) is returning 404.

Body:
I followed Google's first PWA tutorial and created my own project https://my-pwa-77d8a.firebaseapp.com. Everything looks fine:

The project has a manifest.json file

I'm using HTTPS on Firebase

The code has the <meta name="mobile-web-app-capable" content="yes"> tag

My manifest.json file contains: icons specs, name, short_name, start_url

I'm using Vue.js as my main framework and all the rest was built with vanilla JS

The service worker is set and running without errors

The console shows no erros

manifest.json

  {
    "short_name": "PizzaApp",
    "name": "My delicious PWA",
    "icons": [
      {
        "src": "img/launcher-icon-2x.png",
        "sizes": "96x96",
        "type": "image/png"
      },
      {
        "src": "img/launcher-icon-3x.png",
        "sizes": "144x144",
        "type": "image/png"
      },
      {
        "src": "img/launcher-icon-4x.png",
        "sizes": "192x192",
        "type": "image/png"
      }
    ],
    "start_url": "/index.html",
    "display": "standalone",
    "orientation": "portrait"
  }

I can manually add to homescreen both from mobile and desktop. But Chrome never shows the add to homescreen banner. What is wrong?

SOLVED

As pointed bellow, my service worker was trying to cache a missing offline.html file. I created the file, cleared the phone's cache and everything worked fine.


问:
How can I view network requests (for debugging) in React Native?
I'd like to view my network requests in React Native to help me debug - ideally in the 'Network' tab of Chrome's devtools.

There are some closed issues about this on GitHub (https://github.com/facebook/react-native/issues/4122 and https://github.com/facebook/react-native/issues/934) but I don't entirely understand them. It sounds like I need to undo some of React Native's polyfills and then run some commands with extra debugging flags, and maybe modify some Chrome security settings? And apparently there are some security issues involved in doing this that might make it a terrible idea, but nobody involved in the thread has explicitly stated what they are.

Could somebody provide a step-by-step guide to getting the Network tab working with React Native, as well as an explanation of the security issues involved in doing so?

答:
I know this is an old question, but there's a much safer way to do this now that does not require disabling CORS or altering the React Native source code. You can use a third party library called Reactotron that not only tracks API calls (using the network plugin), but also can track your Redux store, and Sagas with additional setup:

https://github.com/infinitered/reactotron
https://github.com/infinitered/reactotron/blob/master/docs/plugin-networking.md


问:
ASP.NET MVC 5 concurrent requests are queued even with disabled Session
Before thinking about downvoting or telling me "google it", please read the problem more carefully. This is old/classic problem but old/classic solution is no longer working. Here is very simple scenario to reproduce in Visual Studio 2013/2015:

1) Create ASP.NET Web application using MVC template:

2) Open Controllers\HomeController.cs and add attribute to controller and "Sleep" action:

```<code>[SessionState( System.Web.SessionState.SessionStateBehavior.Disabled)]
public class HomeController : Controller
{
    public ActionResult Sleep(int? time)
    {
        System.Threading.Thread.Sleep(time ?? 3000);
        return Content("OK");
    }

    public ActionResult Index()
    {
...
</code>```

3) Open file: Views\Home\Index.cshtml and add/replace content html with the following :

<button type="button" onclick="ReqClick();">
    Request
</button>

    <textarea id="log" style="width:640px; height:480px"></textarea>

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

<p>4) Run it (does not matter if you're using IIS or IIS Express or Vs Dev Server) - Open Home/Index. Click F12 to open dev tool, open network tab. On the Home page click "Request" button twice fast. You can see that second request takes almost 6 seconds:</p>

<p><img src="https://i.stack.imgur.com/8YWV3.png" alt="enter image description here"></p>

<p><img src="https://i.stack.imgur.com/PeSIX.png" alt="enter image description here"></p>

<p>In Debug mode in controller you can see that Session is null:</p>

<p><img src="https://i.stack.imgur.com/VxtbS.png" alt="enter image description here"></p>

<p>Cookies are totally empty (ASP.NET Session Id is absent)
<img src="https://i.stack.imgur.com/Z7PQI.png" alt="enter image description here"></p>

<p>Please let me know what I'm missing?</p>

<p>Adding the setting below to web.config does not help either:</p>

<blockquote>
```<sessionState mode="Off"/>
<pages enableSessionState="ReadOnly"/>
```

答:
Concurrent parallel requests worked for me when I decorated my controller with this attribute

```<code>[SessionState(System.Web.SessionState.SessionStateBehavior.ReadOnly)]
</code>```

It works better than the above disabling session state and was added back in MVC 3.  More info here

Body:
Before thinking about downvoting or telling me "google it", please read the problem more carefully. This is old/classic problem but old/classic solution is no longer working. Here is very simple scenario to reproduce in Visual Studio 2013/2015:

1) Create ASP.NET Web application using MVC template:

2) Open Controllers\HomeController.cs and add attribute to controller and "Sleep" action:

[SessionState( System.Web.SessionState.SessionStateBehavior.Disabled)]
public class HomeController : Controller
{
    public ActionResult Sleep(int? time)
    {
        System.Threading.Thread.Sleep(time ?? 3000);
        return Content("OK");
    }

    public ActionResult Index()
    {
...

3) Open file: Views\Home\Index.cshtml and add/replace content html with the following :

<button type="button" onclick="ReqClick();">
    Request
</button>

    <textarea id="log" style="width:640px; height:480px"></textarea>

4) Run it (does not matter if you're using IIS or IIS Express or Vs Dev Server) - Open Home/Index. Click F12 to open dev tool, open network tab. On the Home page click "Request" button twice fast. You can see that second request takes almost 6 seconds:

In Debug mode in controller you can see that Session is null:

Cookies are totally empty (ASP.NET Session Id is absent)

Please let me know what I'm missing?

Adding the setting below to web.config does not help either:

<sessionState mode="Off"/>
<pages enableSessionState="ReadOnly"/>

Body:
Concurrent parallel requests worked for me when I decorated my controller with this attribute

[SessionState(System.Web.SessionState.SessionStateBehavior.ReadOnly)]

It works better than the above disabling session state and was added back in MVC 3.  More info here


问:
Make Kingswaysoft truncate input data that is too long
I have an SSIS project that I'm using to automate pulling CRM data into a SQL Server Database using Kingswaysoft. These SSIS packages are autogenerated, so my solution to this issue needs to be compatible with that.

The description field on Contact in CRM is a nvarchar(2000), but this CRM org still has old data, and some of those old contact records have a description longer than 2000 characters. When I try to pull those using Kingsway, I get this error:

Error: 0xC002F304 at Stage Data for contact, Export contact Data [2]: An error occurred with the following error message: "The input value for 'description' field (or one of its related fields) does not fit into the output buffer, please consider increasing the output column's Length property or changing its data type to one that can accommodate more data such as ntext (DT_NTEXT). This change can be done using the component's Advanced Editor window.".

This makes sense, since I'm pulling a column longer than specified in the metadata, but the problem is that I want to ignore this error, truncate the column, and continue the data load. Obviously I could set the column to DT_NTEXT and not worry about it, but since these packages are autogenerated I have no way of knowing beforehand which columns have old data and which don't, so I won't know which should be DT_NTEXT.

So is there a way to make Kingswaysoft truncate input data which is longer than what's specified in the metadata?

答:
Thank you for choosing KingswaySoft as your integration solution. For this situation, unfortunately there is no way to make that work without making those changes in the component’s Advanced Editor.

If the source component just simply ignores the error and truncates the value, you will lose some of your data and thus affect the data integrity during the integration. Therefore, you may need to change the data type to DT_NTEXT or increase the length of this field in order to handle this situation properly. Alternatively, you can try to change the field length on your CRM side so that the SSIS package can be generated correctly.


问:
When to use header('Content-Type: application/json') in PHP
I've been trying to figure out what's really the usage of header('Content-Type: application/json') in php scripts and I've found different questions and answers on stackoverflow about this subject but I still don't completely get it...

So here's the question : I've seen in some php projects this line of code, and I'm trying to understand

if this is used when another web page is calling this actual script (with ajax for example) so that the calling page can get a json from the php page

OR

if this script means that the php page is going to deal with json sent from another web page. Or maybe something else ???

Another thing that could help me if answered, lately I've been retrieving json from a resource (external url) with cURL and I had to put this header (Content-type:application/json) in the request. Did I send this header to the exertnal resource or was this MY header so that I can deal with the returned json ?

thanks

答:
Ok for those who are interested, I finally figured out that header('Content-Type: application/json') is used when another page is calling the php script, so that the other page can automatically parse the result as json.

For instance i have in my test.php :

```<code>header('Content-type: application/json; charset=utf-8');
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr); // {"a":1,"b":2,"c":3,"d":4,"e":5}
</code>```

and in my main.js

```<code>function test() {
    $.ajax({
        url: 'test.php',
        type: 'GET',
        //dataType: 'html',
        success: function (response) {
            alert(response);
        }
    });
};
</code>```

When I dont have dataType set to "json" or when I don't have the header in my test.php, the alert gives {"a":1,"b":2,"c":3,"d":4,"e":5} which is a string (tried with typeof(response), and when I have this header, or dataType:"json", I get [object Object] from the alert. So this header function is there to indicate to the calling pages which type of data it gives back, so that you can know how to deal with it. In my script, if I didn't have header('Content-Type: application/json'), I would have to parse the response in the javascript like this : JSON.parse(response) in order to make it a json, but with that header, I already have a json object, and I can parse it to html with jSON.stringify(response).

Body:
Ok for those who are interested, I finally figured out that header('Content-Type: application/json') is used when another page is calling the php script, so that the other page can automatically parse the result as json.

For instance i have in my test.php :

header('Content-type: application/json; charset=utf-8');
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr); // {"a":1,"b":2,"c":3,"d":4,"e":5}

and in my main.js

function test() {
    $.ajax({
        url: 'test.php',
        type: 'GET',
        //dataType: 'html',
        success: function (response) {
            alert(response);
        }
    });
};

When I dont have dataType set to "json" or when I don't have the header in my test.php, the alert gives {"a":1,"b":2,"c":3,"d":4,"e":5} which is a string (tried with typeof(response), and when I have this header, or dataType:"json", I get [object Object] from the alert. So this header function is there to indicate to the calling pages which type of data it gives back, so that you can know how to deal with it. In my script, if I didn't have header('Content-Type: application/json'), I would have to parse the response in the javascript like this : JSON.parse(response) in order to make it a json, but with that header, I already have a json object, and I can parse it to html with jSON.stringify(response).

ContentLicense: CC BY-SA 4.0


问:
Angular Service function not returning anything, trying to do multiple http requests and return single observable
Unfortunately, the way the site is setup that I need to retrieve data from, is that this data is spread across multiple sites (the exact same type of data and JSON return format) but they are at different URLs.  They are classified by the URLs, so I do need to retain the URLs in order to further classify it throughout the app.  I have the following service function where I am trying to pass a set of topics (which are then passed to the URL), retrieve the data and return a single observable.  However, this is returning nothing:

```<code>getDataTopicItems(topicArray) {
    return this.items = topicArray.forEach((topic, i, topicArray) => {
        return this.http.get(this.baseUrl + topic + "/_api/Web/Lists/GetByTitle('What''s New')/items", this.options)
            .map(res => res.json())
            .map(items => items.d.results)
            .do(data => console.log(data))
            .concatMap(data => data)
      }
    )
}
</code>```

I am subscribing to it in the template of the component where I am calling this function through an *ngFor plus an async pipe.  What am I doing wrong?

Update:  I also tried the following:

```<code>return this.http.get(this.baseUrl + topicArray[0] + this.policyOptions, this.options)
            .map(res => res.json())
            .map(items => this.policies = items.d.results)
            .do(data => console.log(data))
            .flatMap((policies) => topicArray.forEach((topic, i, topicArray) => {
                if (i < 0) {
                    this.http.get(this.baseUrl + topic + this.policyOptions)
                        .map(res => res.json())
                        .map(items => this.policies = items.d.results)
                        .do(data => console.log(data))
                }
            }))
</code>```

答: Array.prototype.forEach returns undefined. See MDN for documentation. Use Array.prototype.map instead, and this.items will be an array of observables that you can then do whatever you want with.

Body:
Unfortunately, the way the site is setup that I need to retrieve data from, is that this data is spread across multiple sites (the exact same type of data and JSON return format) but they are at different URLs.  They are classified by the URLs, so I do need to retain the URLs in order to further classify it throughout the app.  I have the following service function where I am trying to pass a set of topics (which are then passed to the URL), retrieve the data and return a single observable.  However, this is returning nothing:

getDataTopicItems(topicArray) {
    return this.items = topicArray.forEach((topic, i, topicArray) => {
        return this.http.get(this.baseUrl + topic + "/_api/Web/Lists/GetByTitle('What''s New')/items", this.options)
            .map(res => res.json())
            .map(items => items.d.results)
            .do(data => console.log(data))
            .concatMap(data => data)
      }
    )
}

I am subscribing to it in the template of the component where I am calling this function through an *ngFor plus an async pipe.  What am I doing wrong?

Update:  I also tried the following:

return this.http.get(this.baseUrl + topicArray[0] + this.policyOptions, this.options)
            .map(res => res.json())
            .map(items => this.policies = items.d.results)
            .do(data => console.log(data))
            .flatMap((policies) => topicArray.forEach((topic, i, topicArray) => {
                if (i < 0) {
                    this.http.get(this.baseUrl + topic + this.policyOptions)
                        .map(res => res.json())
                        .map(items => this.policies = items.d.results)
                        .do(data => console.log(data))
                }
            }))


问:
Export a GridView to Excel
I'm trying to export a GridView into a xls file, I insert the GridView into a Modal and I'm supposing that because of that it can't be exported.

This is my BackEnd of the action from the Button:

```<code>protected void Btn_download_Click(object sender, EventArgs e)
        {
            Response.ClearContent();
            Response.AppendHeader("content-disposition", "attachment; flename=MainReport.xls");
            Response.ContentType = "application/excel";

            StringWriter stringWriter = new StringWriter();
            HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);

            Grv_main.RenderControl(htmlTextWriter);
            Response.Write(stringWriter.ToString());
            Response.End();
        }
</code>```

and this is the HTML:

```<code><form id="form1" runat="server">

        <div class="container">
            <div class="modal fade" id="History-Maint" role="dialog">
                <div class="modal-dialog modal-lg">
                    <div class="modal-content">
                        <div class="modal-header" style="padding: 35px 50px;">
                            <button type="button" class="close" data-dismiss="modal">×</button>
                            <h3><span class="glyphicon glyphicon-list-alt"></span>&nbsp Maintenance Report</h3>
                        </div>
                        <div class="modal-body">
                            <asp:GridView ID="Grv_main"
                                CssClass="table table-striped table-bordered table-hover"
                                runat="server"
                                AutoGenerateColumns="False"
                                Width="940px"
                                HorizontalAlign="Center"
                                DataKeyNames="id"
                                AllowPaging="True" OnRowEditing="GridView1_RowEditing">
                                <Columns>
                                    <asp:TemplateField HeaderText="id" Visible="false">
                                        <ItemTemplate>
                                            <asp:Label ID="Lbl_id" runat="server" Text='<%# Bind("id") %>'></asp:Label>
                                        </ItemTemplate>
                                        <ItemStyle HorizontalAlign="Center" />
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="status">
                                        <ItemTemplate>
                                            <asp:Label ID="Lbl_stats" runat="server" Text='<%# Bind("STATUS") %>'></asp:Label>
                                        </ItemTemplate>
                                        <HeaderStyle HorizontalAlign="Center" />
                                        <ItemStyle HorizontalAlign="Center" />
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="tool">
                                        <ItemTemplate>
                                            <asp:Label ID="Lbl_tool" runat="server" Text='<%# Bind("TOOL") %>'></asp:Label>
                                        </ItemTemplate>
                                        <HeaderStyle HorizontalAlign="Center" />
                                        <ItemStyle HorizontalAlign="Center" />
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="Area Change">
                                        <ItemTemplate>
                                            <asp:Label ID="Lbl_areach" runat="server" Text='<%# Bind("AREA") %>'></asp:Label>
                                        </ItemTemplate>
                                        <HeaderStyle HorizontalAlign="Center" />
                                        <ItemStyle HorizontalAlign="Center" />
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="responsable">
                                        <ItemTemplate>
                                            <asp:Label ID="Lbl_resp" runat="server" Text='<%# Bind("RESPONSABLE") %>'></asp:Label>
                                        </ItemTemplate>
                                        <HeaderStyle HorizontalAlign="Center" />
                                        <ItemStyle HorizontalAlign="Center" />
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="nota">
                                        <ItemTemplate>
                                            <asp:Label ID="Lbl_note" runat="server" Text='<%# Bind("NOTA") %>'></asp:Label>
                                        </ItemTemplate>
                                        <HeaderStyle HorizontalAlign="Center" />
                                        <ItemStyle HorizontalAlign="Center" />
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="fecha de modificacion">
                                        <ItemTemplate>
                                            <asp:Label ID="Lbl_mod" runat="server" Text='<%# Bind("MODIFY") %>'></asp:Label>
                                        </ItemTemplate>
                                        <HeaderStyle HorizontalAlign="Center" />
                                        <ItemStyle HorizontalAlign="Center" />
                                    </asp:TemplateField>
                                </Columns>
                            </asp:GridView>
                        </div>
                        <div class="modal-footer">
                            <asp:Button ID="Btn_download" runat="server" CssClass="btn btn-success" Text='Guardar' OnClick="Btn_download_Click" />
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <asp:ContentPlaceHolder ID="ContentPlaceHolder2" runat="server">
        </asp:ContentPlaceHolder>
    </form>
</code>```

all of this, is on a MasterPage and into a form with the runat="server"

答:
The best for me has been to use ClosedXML

https://github.com/closedxml/closedxml

It's very easy and you can add sorting, and filtering built in.

Here's an example from the documentation:

```<code>var workbook = new XLWorkbook();
var worksheet = workbook.Worksheets.Add("Sample Sheet");
worksheet.Cell("A1").Value = "Hello World!";
workbook.SaveAs("HelloWorld.xlsx");
</code>```

Title: Export a GridView to Excel

Body:
I'm trying to export a GridView into a xls file, I insert the GridView into a Modal and I'm supposing that because of that it can't be exported.

This is my BackEnd of the action from the Button:

protected void Btn_download_Click(object sender, EventArgs e)
        {
            Response.ClearContent();
            Response.AppendHeader("content-disposition", "attachment; flename=MainReport.xls");
            Response.ContentType = "application/excel";

            StringWriter stringWriter = new StringWriter();
            HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);

            Grv_main.RenderControl(htmlTextWriter);
            Response.Write(stringWriter.ToString());
            Response.End();
        }

and this is the HTML:

<form id="form1" runat="server">

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

&nbsp Maintenance Report

                            <asp:GridView ID="Grv_main"
                                CssClass="table table-striped table-bordered table-hover"
                                runat="server"
                                AutoGenerateColumns="False"
                                Width="940px"
                                HorizontalAlign="Center"
                                DataKeyNames="id"
                                AllowPaging="True" OnRowEditing="GridView1_RowEditing">
                                <Columns>
                                    <asp:TemplateField HeaderText="id" Visible="false">
                                        <ItemTemplate>
                                            <asp:Label ID="Lbl_id" runat="server" Text='<%# Bind("id") %>'></asp:Label>
                                        </ItemTemplate>
                                        <ItemStyle HorizontalAlign="Center" />
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="status">
                                        <ItemTemplate>
                                            <asp:Label ID="Lbl_stats" runat="server" Text='<%# Bind("STATUS") %>'></asp:Label>
                                        </ItemTemplate>
                                        <HeaderStyle HorizontalAlign="Center" />
                                        <ItemStyle HorizontalAlign="Center" />
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="tool">
                                        <ItemTemplate>
                                            <asp:Label ID="Lbl_tool" runat="server" Text='<%# Bind("TOOL") %>'></asp:Label>
                                        </ItemTemplate>
                                        <HeaderStyle HorizontalAlign="Center" />
                                        <ItemStyle HorizontalAlign="Center" />
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="Area Change">
                                        <ItemTemplate>
                                            <asp:Label ID="Lbl_areach" runat="server" Text='<%# Bind("AREA") %>'></asp:Label>
                                        </ItemTemplate>
                                        <HeaderStyle HorizontalAlign="Center" />
                                        <ItemStyle HorizontalAlign="Center" />
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="responsable">
                                        <ItemTemplate>
                                            <asp:Label ID="Lbl_resp" runat="server" Text='<%# Bind("RESPONSABLE") %>'></asp:Label>
                                        </ItemTemplate>
                                        <HeaderStyle HorizontalAlign="Center" />
                                        <ItemStyle HorizontalAlign="Center" />
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="nota">
                                        <ItemTemplate>
                                            <asp:Label ID="Lbl_note" runat="server" Text='<%# Bind("NOTA") %>'></asp:Label>
                                        </ItemTemplate>
                                        <HeaderStyle HorizontalAlign="Center" />
                                        <ItemStyle HorizontalAlign="Center" />
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="fecha de modificacion">
                                        <ItemTemplate>
                                            <asp:Label ID="Lbl_mod" runat="server" Text='<%# Bind("MODIFY") %>'></asp:Label>
                                        </ItemTemplate>
                                        <HeaderStyle HorizontalAlign="Center" />
                                        <ItemStyle HorizontalAlign="Center" />
                                    </asp:TemplateField>
                                </Columns>
                            </asp:GridView>

                            <asp:Button ID="Btn_download" runat="server" CssClass="btn btn-success" Text='Guardar' OnClick="Btn_download_Click" />

        <asp:ContentPlaceHolder ID="ContentPlaceHolder2" runat="server">
        </asp:ContentPlaceHolder>
    </form>

all of this, is on a MasterPage and into a form with the runat="server"

Body:
The best for me has been to use ClosedXML

https://github.com/closedxml/closedxml

It's very easy and you can add sorting, and filtering built in.

Here's an example from the documentation:

var workbook = new XLWorkbook();
var worksheet = workbook.Worksheets.Add("Sample Sheet");
worksheet.Cell("A1").Value = "Hello World!";
workbook.SaveAs("HelloWorld.xlsx");


问:
How to use Hibernate Validator Annotations with Spring MVC 4
I have searched the internet for days now with no luck of finding anything relevant or up to date on this topic. I'm trying to do some simple form validation using annotations using Hibernate Validator 5.4.1 Final and Validation-api 1.1.0 Final. Without even adding any annotations to my code I get the error shown below from just adding these two jars to my lib folder. Please please please any help or guidance on this would be greatly appreciated!</p>

```<code>org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean#0': Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: Could not initialize class org.hibernate.validator.internal.engine.ConfigurationImpl
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1553)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:700)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:658)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:624)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:672)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:543)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:484)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
javax.servlet.GenericServlet.init(GenericServlet.java:158)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:314)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Thread.java:745)
</code>```

答:
Are you using "Hibernate Validator" dependency or "validator-api"?
validator-api dont have implementation for validation.
You should use this dependency </p>

Body:
I have searched the internet for days now with no luck of finding anything relevant or up to date on this topic. I'm trying to do some simple form validation using annotations using Hibernate Validator 5.4.1 Final and Validation-api 1.1.0 Final. Without even adding any annotations to my code I get the error shown below from just adding these two jars to my lib folder. Please please please any help or guidance on this would be greatly appreciated!

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean#0': Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: Could not initialize class org.hibernate.validator.internal.engine.ConfigurationImpl
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1553)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:700)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:658)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:624)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:672)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:543)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:484)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
javax.servlet.GenericServlet.init(GenericServlet.java:158)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:314)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Thread.java:745)


问:
How to get start date and end date of the current month (Swift 3)
I'm trying to get the start and end dates of the current month in dd/MM/yyyy format. I tried using extension as answered in this SO Question.But it seems like it's not what I want(the format is different and also it's giving me last month's last date and current month last but one date ). Can some one help me.

Extension Class:

```<code>extension Date {
    func startOfMonth() -> Date? {
        let comp: DateComponents = Calendar.current.dateComponents([.year, .month, .hour], from: Calendar.current.startOfDay(for: self))
        return Calendar.current.date(from: comp)!
    }

    func endOfMonth() -> Date? {
        var comp: DateComponents = Calendar.current.dateComponents([.month, .day, .hour], from: Calendar.current.startOfDay(for: self))
        comp.month = 1
        comp.day = -1
        return Calendar.current.date(byAdding: comp, to: self.startOfMonth()!)
    }
}
</code>```

My Struct:

```<code>struct Constants{

    // keys required for making a Login call (POST Method)
    struct LoginKeys {
       .....
    }

    struct RankingKeys {

        static let DateFrom = String(describing: Date().startOfMonth()) //giving me 2016-11-30 16:00:00 +0000
        static let DateTo  = String(describing: Date().endOfMonth())
//2016-12-30 16:00:00 +0000
    }
}
</code>```

Expected Result:

```<code>DateFrom  = "01/12/2016"
DateTo = "31/12/2016"
</code>```

答:
This is what I'm using. Pretty simple but it works.

```<code>extension Calendar {

func dayOfWeek(_ date: Date) -> Int {
    var dayOfWeek = self.component(.weekday, from: date) + 1 - self.firstWeekday

    if dayOfWeek <= 0 {
        dayOfWeek += 7
    }

    return dayOfWeek
}

func startOfWeek(_ date: Date) -> Date {
    return self.date(byAdding: DateComponents(day: -self.dayOfWeek(date) + 1), to: date)!
}

func endOfWeek(_ date: Date) -> Date {
    return self.date(byAdding: DateComponents(day: 6), to: self.startOfWeek(date))!
}

func startOfMonth(_ date: Date) -> Date {
    return self.date(from: self.dateComponents([.year, .month], from: date))!
}

func endOfMonth(_ date: Date) -> Date {
    return self.date(byAdding: DateComponents(month: 1, day: -1), to: self.startOfMonth(date))!
}

func startOfQuarter(_ date: Date) -> Date {
    let quarter = (self.component(.month, from: date) - 1) / 3 + 1
    return self.date(from: DateComponents(year: self.component(.year, from: date), month: (quarter - 1) * 3 + 1))!
}

func endOfQuarter(_ date: Date) -> Date {
    return self.date(byAdding: DateComponents(month: 3, day: -1), to: self.startOfQuarter(date))!
}

func startOfYear(_ date: Date) -> Date {
    return self.date(from: self.dateComponents([.year], from: date))!
}

func endOfYear(_ date: Date) -> Date {
    return self.date(from: DateComponents(year: self.component(.year, from: date), month: 12, day: 31))!
}
}
</code>```

How to use

```<code>let calendar: Calendar = Calendar.current
let startDate = calendar.startOfMonth(Date())
print("startDate :: \(startDate)")
</code>```

Body:
I'm trying to get the start and end dates of the current month in dd/MM/yyyy format. I tried using extension as answered in this SO Question.But it seems like it's not what I want(the format is different and also it's giving me last month's last date and current month last but one date ). Can some one help me.

Extension Class:

extension Date {
    func startOfMonth() -> Date? {
        let comp: DateComponents = Calendar.current.dateComponents([.year, .month, .hour], from: Calendar.current.startOfDay(for: self))
        return Calendar.current.date(from: comp)!
    }

    func endOfMonth() -> Date? {
        var comp: DateComponents = Calendar.current.dateComponents([.month, .day, .hour], from: Calendar.current.startOfDay(for: self))
        comp.month = 1
        comp.day = -1
        return Calendar.current.date(byAdding: comp, to: self.startOfMonth()!)
    }
}

My Struct:

struct Constants{

    // keys required for making a Login call (POST Method)
    struct LoginKeys {
       .....
    }

    struct RankingKeys {

        static let DateFrom = String(describing: Date().startOfMonth()) //giving me 2016-11-30 16:00:00 +0000
        static let DateTo  = String(describing: Date().endOfMonth())
//2016-12-30 16:00:00 +0000
    }
}

Expected Result:

DateFrom  = "01/12/2016"
DateTo = "31/12/2016"

Body:
This is what I'm using. Pretty simple but it works.

extension Calendar {

func dayOfWeek(_ date: Date) -> Int {
    var dayOfWeek = self.component(.weekday, from: date) + 1 - self.firstWeekday

    if dayOfWeek <= 0 {
        dayOfWeek += 7
    }

    return dayOfWeek
}

func startOfWeek(_ date: Date) -> Date {
    return self.date(byAdding: DateComponents(day: -self.dayOfWeek(date) + 1), to: date)!
}

func endOfWeek(_ date: Date) -> Date {
    return self.date(byAdding: DateComponents(day: 6), to: self.startOfWeek(date))!
}

func startOfMonth(_ date: Date) -> Date {
    return self.date(from: self.dateComponents([.year, .month], from: date))!
}

func endOfMonth(_ date: Date) -> Date {
    return self.date(byAdding: DateComponents(month: 1, day: -1), to: self.startOfMonth(date))!
}

func startOfQuarter(_ date: Date) -> Date {
    let quarter = (self.component(.month, from: date) - 1) / 3 + 1
    return self.date(from: DateComponents(year: self.component(.year, from: date), month: (quarter - 1) * 3 + 1))!
}

func endOfQuarter(_ date: Date) -> Date {
    return self.date(byAdding: DateComponents(month: 3, day: -1), to: self.startOfQuarter(date))!
}

func startOfYear(_ date: Date) -> Date {
    return self.date(from: self.dateComponents([.year], from: date))!
}

func endOfYear(_ date: Date) -> Date {
    return self.date(from: DateComponents(year: self.component(.year, from: date), month: 12, day: 31))!
}
}

How to use

let calendar: Calendar = Calendar.current
let startDate = calendar.startOfMonth(Date())
print("startDate :: \(startDate)")


问:
reversing an array using pointer c
I am trying to write a code that receives the number of input numbers and integers, then reverses those order and prints them out. When I run this code it freezes from the for loop in input_integer function. What am I doing wrong?</p>

```<code># include <stdio.h>
# include <stdlib.h>

void input_integer (int *arr, int *arrSize);
void inverse_reorder (int *arr, int *arrSize);

int main (void){
    int* arrSize;
    int* arr;
    int i;

    input_integer(arr, arrSize);
    printf("inputted data : ");
    for ( i = 0; i < *arrSize ; i++ ){
        printf("%d, ", *(arr + i));
    }
    inverse_reorder(arr, arrSize);
    printf("reversed data : ");
    for ( i = 0; i < *arrSize ; i++ ){
        printf("%d, ", *(arr + i));
    }

    return 0;
}

void input_integer (int* arr, int *arrSize){
    printf("Array size = ? ");
    scanf("%d", arrSize);
    int i;
    for( i = 0; i < *arrSize ; i++ ){
        scanf("%d", *(arr + i));
    }
}

void inverse_reorder (int * arr, int *arrSize){
    int i;
    int temp = 0;
    for ( i = 0; i < *arrSize ; i++ ){
        temp = *(arr+i);
        *(arr+i) = *(arr + *arrSize - i);
        *(arr + *arrSize - i) = temp;
    }
}
</code>```

答:
Use gcc -Wall to compile your programs.</p>

```<code>reversing.c: In function ‘input_integer’:
reversing.c:31:13: warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘int’ [-Wformat=]
     scanf("%d", *(arr + i));
            ~^   ~~~~~~~~~~
reversing.c: In function ‘main’:
reversing.c:12:3: warning: ‘arr’ is used uninitialized in this function [-Wuninitialized]
   input_integer(arr, arrSize);
   ^~~~~~~~~~~~~~~~~~~~~~~~~~~
reversing.c:12:3: warning: ‘arrSize’ is used uninitialized in this function [-Wuninitialized]
</code>```

Title: reversing an array using pointer c

Body:
I am trying to write a code that receives the number of input numbers and integers, then reverses those order and prints them out. When I run this code it freezes from the for loop in input_integer function. What am I doing wrong?

# include <stdio.h>
# include <stdlib.h>

void input_integer (int *arr, int *arrSize);
void inverse_reorder (int *arr, int *arrSize);

int main (void){
    int* arrSize;
    int* arr;
    int i;

    input_integer(arr, arrSize);
    printf("inputted data : ");
    for ( i = 0; i < *arrSize ; i++ ){
        printf("%d, ", *(arr + i));
    }
    inverse_reorder(arr, arrSize);
    printf("reversed data : ");
    for ( i = 0; i < *arrSize ; i++ ){
        printf("%d, ", *(arr + i));
    }

    return 0;
}

void input_integer (int* arr, int *arrSize){
    printf("Array size = ? ");
    scanf("%d", arrSize);
    int i;
    for( i = 0; i < *arrSize ; i++ ){
        scanf("%d", *(arr + i));
    }
}

void inverse_reorder (int * arr, int *arrSize){
    int i;
    int temp = 0;
    for ( i = 0; i < *arrSize ; i++ ){
        temp = *(arr+i);
        *(arr+i) = *(arr + *arrSize - i);
        *(arr + *arrSize - i) = temp;
    }
}

Body:
Use gcc -Wall to compile your programs.

reversing.c: In function ‘input_integer’:
reversing.c:31:13: warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘int’ [-Wformat=]
     scanf("%d", *(arr + i));
            ~^   ~~~~~~~~~~
reversing.c: In function ‘main’:
reversing.c:12:3: warning: ‘arr’ is used uninitialized in this function [-Wuninitialized]
   input_integer(arr, arrSize);
   ^~~~~~~~~~~~~~~~~~~~~~~~~~~
reversing.c:12:3: warning: ‘arrSize’ is used uninitialized in this function [-Wuninitialized]


问:
Git local repository for remote directory
I cannot find the answer to this anywhere. Is it possible to set up a local git repository for files on a webserver? I do not want to put the repo on the webserver because of a lack of space. </p>

答:
It sounds like you want a repo stored locally, but you want its work tree to coincide with a tree of content served by your web server.

There is not native support for this, but if you can map the underlying drive/directory that contains the content tree to a local path (i.e. treat it as a network shared drive) then you could make it work with git worktree

The details of setting the server up to share the content directory, and mapping that share locally, depend on OS (and maybe on your web daemon and how it's set up, though if it's just serving files from a local content directory then it shouldn't be an issue).

Note that when you add a worktree, git wants to see an empty directory to check out into.  So you'll need a brief "outage window" during which the content tree can be empty. The procedure might then look like this

```<code># First, map the content tree to ./web-content
# ...

# Now initialize a repo
mkdir repo-init
cd repo-init
git init

# Import the web content into the repo; must be in outage window
mv ../web-content/* .
git add .
git commit

# Re-make the repo as a "mirror" to remove the default work tree
cd ..
git clone --mirror repo-init repo
rm -rf repo-init
cd repo
git remote remove origin

# Now check the content back out to the server
git worktree add ../web-content master

# outage window can now end
</code>```

You now have a local repo that is tracking the files on the web server.  If you want to be able to pull (or push) to update the server, you'll have to configure appropriately (as you would if the repo were on the server).

Body:
It sounds like you want a repo stored locally, but you want its work tree to coincide with a tree of content served by your web server.

There is not native support for this, but if you can map the underlying drive/directory that contains the content tree to a local path (i.e. treat it as a network shared drive) then you could make it work with git worktree

The details of setting the server up to share the content directory, and mapping that share locally, depend on OS (and maybe on your web daemon and how it's set up, though if it's just serving files from a local content directory then it shouldn't be an issue).

Note that when you add a worktree, git wants to see an empty directory to check out into.  So you'll need a brief "outage window" during which the content tree can be empty. The procedure might then look like this

# First, map the content tree to ./web-content
# ...

# Now initialize a repo
mkdir repo-init
cd repo-init
git init

# Import the web content into the repo; must be in outage window
mv ../web-content/* .
git add .
git commit

# Re-make the repo as a "mirror" to remove the default work tree
cd ..
git clone --mirror repo-init repo
rm -rf repo-init
cd repo
git remote remove origin

# Now check the content back out to the server
git worktree add ../web-content master

# outage window can now end

You now have a local repo that is tracking the files on the web server.  If you want to be able to pull (or push) to update the server, you'll have to configure appropriately (as you would if the repo were on the server).


问:
Rescue Phoenix.MissingParamError and return json for user
I have the following action in one of controllers in my Phoenix app:

```<code>      plug :scrub_params, "account"
      plug :scrub_params, "studio"

      def create(conn, %{"account" => account_params, "studio" => studio_params}) do
      end
</code>```

When somebody do not send proper params app is returning Phoenix.MissingParamError error. How can I rescue it and return nice message to user in json?

答:
Perhaps you can use the Plug.ErrorHandler. something like this.</p>

```<code>defmodule AppRouter do
  use Plug.Router
  use Plug.ErrorHandler

  ...

  def handle_errors(conn, %{kind: _kind, reason: _reason, stack: _stack}) do
    send_resp(conn, conn.status, "Something went wrong")
  end
end
</code>```

Body:
I have the following action in one of controllers in my Phoenix app:

      plug :scrub_params, "account"
      plug :scrub_params, "studio"

      def create(conn, %{"account" => account_params, "studio" => studio_params}) do
      end

When somebody do not send proper params app is returning Phoenix.MissingParamError error. How can I rescue it and return nice message to user in json?

Body:
Perhaps you can use the Plug.ErrorHandler. something like this.

defmodule AppRouter do
  use Plug.Router
  use Plug.ErrorHandler

  ...

  def handle_errors(conn, %{kind: _kind, reason: _reason, stack: _stack}) do
    send_resp(conn, conn.status, "Something went wrong")
  end
end


问:
Add control dependency after operations are created?
Is it possible to create a control dependency between two ops after they've both been created? I realize that with tf.control_dependencies it's possible to make one op wait on another before executing, but the dependent op has to be created within the tf.control_dependencies context. I'd like to construct the two ops independently first and then add the dependency.

答:
While not possible in general, you can slightly modify an existing op to enforce dependencies. For example, you can add zero to a tensor:

def first_before_second_num(op_first, op_second):
   with tf.control_dependencies([op_first]):
       op_second += 0
   return op_second

If you have a NoOp like a train_step, then you might want to group it with another NoOp:

def first_before_second_noop(op_first, op_second):
   with tf.control_dependencies([op_first]):
       op_second tf.group(op_second, tf.no_op())
   return op_second


问:
Index of hovered element in QGraphicsPathItem
I have a QGraphicsPathItem which is drawn from a list of cartesian x,y points.

What would be the best (performance wise) method of determining when the cursor is hovered over one of these points I presently iterate through the source list and compare each point with the cursor position.

Regards

答: I usually use the QGraphicScene's itemAt() method to check for graphic items under the cursor.


问:
uiwebview reload/append data if scrolling occurs at the top or at the bottom
i am using uiwebview to render data as html in my iphone application. i want to refresh the data if user is scrolling at the top of the view and i want to append  the next page to the current page if the user is scrolling at the bottom of of the view.

and also during reload or fetching data i would like to freeze the screen and show a loading animation in the space between scroll layer and data render layer.

i am using TapDetectingWindow to handle the scroll position but never i get negative value for top scrolling and nor bigger value for bottom scrolling.

http://mithin.in/2009/08/26/detecting-taps-and-events-on-uiwebview-the-right-way

thanks...

答:
did you try - (void)scrollViewDidScroll:(UIScrollView *)scrollView

in UIScrollViewDelegate and then get the currentOffset of the scrollview?

ContentLicense: CC BY-SA 2.5


问:
JavaScript test failing - checking for similar items, true if one item or less needs to be switched
Working on this code for a test, passing some but failing others.

Problem:

Two arrays are called similar if one can be obtained from another by swapping at most one pair of elements in one of the arrays.

Given two arrays a and b, check whether they are similar.

Example:

For a = [1, 2, 3] and b = [1, 2, 3], the output should be
  areSimilar(a, b) = true.

The arrays are equal, no need to swap any elements.

For a = [1, 2, 3] and b = [2, 1, 3], the output should be
  areSimilar(a, b) = true.

My Solution:

function areSimilar(a, b) {
    var error = 0;
    for(var i = 0; i  1){
            return false;
        } else{
            return true;
        }
}```

Example of Test Passed:

Input:

a: [1, 2, 2]
  b: [2, 1, 1]

Output:

false

Expected Output:

false

Example of Test Failed:

Input:

a: [2, 3, 9]
  b: [10, 3, 2]

Output:

true

Expected Output:

false

答:
If i understand right your problem, i think something like this should works

EDIT

```<code>function areSimilar(a, b) {

   var isSimilar = true
   var isAlreadySwap = false

   a.forEach(function(item, index){
      if(item !== b[index] && item === b[index+1] && !isAlreadySwap){
         var temp = b[index]
         b[index] = b[index+1]
         b[index+1] = temp
         isAlreadySwap = true
      }else if(item !== b[index]){
         isSimilar = false;
         return;
      }
   })

   return isSimilar
}
</code>```

Body:
Working on this code for a test, passing some but failing others.

Problem:

Two arrays are called similar if one can be obtained from another by swapping at most one pair of elements in one of the arrays.

Given two arrays a and b, check whether they are similar.

Example:

For a = [1, 2, 3] and b = [1, 2, 3], the output should be
  areSimilar(a, b) = true.

The arrays are equal, no need to swap any elements.

For a = [1, 2, 3] and b = [2, 1, 3], the output should be
  areSimilar(a, b) = true.

My Solution:

function areSimilar(a, b) {
    var error = 0;
    for(var i = 0; i  1){
            return false;
        } else{
            return true;
        }
}

Example of Test Passed:

Input:

a: [1, 2, 2]
  b: [2, 1, 1]

Output:

false

Expected Output:

false

Example of Test Failed:

Input:

a: [2, 3, 9]
  b: [10, 3, 2]

Output:

true

Expected Output:

false

Body:
If i understand right your problem, i think something like this should works

EDIT

function areSimilar(a, b) {

   var isSimilar = true
   var isAlreadySwap = false

   a.forEach(function(item, index){
      if(item !== b[index] && item === b[index+1] && !isAlreadySwap){
         var temp = b[index]
         b[index] = b[index+1]
         b[index+1] = temp
         isAlreadySwap = true
      }else if(item !== b[index]){
         isSimilar = false;
         return;
      }
   })

   return isSimilar
}


问:
Ruby Array#select with an options hash to match on
I have an array of hashes that I would like to search on, and I would like to write a method that takes an options hash as an argument and return all elements in the array that match against all key/value pairs dynamically, and I'm having trouble figuring it out.

```<code>my_array = [
  {
    foo: 'a',
    bar: 'b',
    baz: 'c'
  },
  {
    foo: 1,
    bar: 2,
    baz: 3
  },
  {
    foo: 'A',
    bar: 'B',
    baz: 'C'
  },
  {
    foo: 11,
    bar: 12,
    baz: 13
  }
]

# takes an opts hash and returns all elements for which all
# all key/value pairs match
def search_by(opts)
  opts.each do |k, v|
    self.select { |f| f[k] == f[v] }
  end
end

my_array.search_by(foo: 'a', bar: 'b')
# should return { foo: 'a', bar: 'b', baz: 'c' }
</code>```

I've tried a couple different ways to dynamically compose a block to pass to #select based on similar questions on SO, but I haven't had much luck and haven't been able to find this exact use case.  What's the best way to dynamically #select with multiple conditions while only having to execute #select once?

答:
You may be trying to over complicate this. How about this

```<code>my_array = [
  {foo: 'a', bar: 'b', baz: 'c'},
  {foo: 1, bar: 2, baz: 3},
  {foo: 'A', bar: 'B', baz: 'C'},
  {foo: 11, bar: 12, baz: 13}
]
finder = {foo: 'a', bar: 'b'}
my_array.select {|h| h.values_at(*finder.keys) == finder.values }
#=> [{:foo=>"a", :bar=>"b", :baz=>"c"}]
</code>```

Hash#values_at uses the given keys to return the appropriate values which in your case should match the values for those keys in the "finder" Hash.

To make it work explicitly the way you explained we can define a singleton method for my_array as such:

```<code>my_array.define_singleton_method(:search_by) do |opts|
  self.select {|h| h.values_at(*opts.keys) == opts.values}
end

my_array.search_by(foo: 'a', bar: 'b')
#=> [{:foo=>"a", :bar=>"b", :baz=>"c"}]
my_array.search_by(foobar: 'n')
#=> []
my_array << {foo: 11,bar: 15,baz: 'c'}
my_array.search_by(foo: 11)
#=>[{:foo=>11, :bar=>12, :baz=>13}, {:foo=>11, :bar=>15, :baz=>"c"}]
</code>```

Body:
I have an array of hashes that I would like to search on, and I would like to write a method that takes an options hash as an argument and return all elements in the array that match against all key/value pairs dynamically, and I'm having trouble figuring it out.

my_array = [
  {
    foo: 'a',
    bar: 'b',
    baz: 'c'
  },
  {
    foo: 1,
    bar: 2,
    baz: 3
  },
  {
    foo: 'A',
    bar: 'B',
    baz: 'C'
  },
  {
    foo: 11,
    bar: 12,
    baz: 13
  }
]

# takes an opts hash and returns all elements for which all
# all key/value pairs match
def search_by(opts)
  opts.each do |k, v|
    self.select { |f| f[k] == f[v] }
  end
end

my_array.search_by(foo: 'a', bar: 'b')
# should return { foo: 'a', bar: 'b', baz: 'c' }

I've tried a couple different ways to dynamically compose a block to pass to #select based on similar questions on SO, but I haven't had much luck and haven't been able to find this exact use case.  What's the best way to dynamically #select with multiple conditions while only having to execute #select once?

Body:
You may be trying to over complicate this. How about this

my_array = [
  {foo: 'a', bar: 'b', baz: 'c'},
  {foo: 1, bar: 2, baz: 3},
  {foo: 'A', bar: 'B', baz: 'C'},
  {foo: 11, bar: 12, baz: 13}
]
finder = {foo: 'a', bar: 'b'}
my_array.select {|h| h.values_at(*finder.keys) == finder.values }
#=> [{:foo=>"a", :bar=>"b", :baz=>"c"}]

Hash#values_at uses the given keys to return the appropriate values which in your case should match the values for those keys in the "finder" Hash.

To make it work explicitly the way you explained we can define a singleton method for my_array as such:

my_array.define_singleton_method(:search_by) do |opts|
  self.select {|h| h.values_at(*opts.keys) == opts.values}
end

my_array.search_by(foo: 'a', bar: 'b')
#=> [{:foo=>"a", :bar=>"b", :baz=>"c"}]
my_array.search_by(foobar: 'n')
#=> []
my_array << {foo: 11,bar: 15,baz: 'c'}
my_array.search_by(foo: 11)
#=>[{:foo=>11, :bar=>12, :baz=>13}, {:foo=>11, :bar=>15, :baz=>"c"}]


问:
iOS 11 Core NFC - any sample code?
I just installed the first iOS 11 beta to an iPhone 7 and am interested in trying the NFC. There's nothing about it in settings.  I am wondering if there's any sample code out there showing how to read a tag. Can anyone show how to use the Core NFC SDK, in a code snippet?</p>

答:
You need to make sure the usage description is in place and also add the capability to the app inside of the Apple Developer Center.
I have a tutorial based on my experience (Swift 4-based). It's available here: Core NFC Tutorial</p>

Title: iOS 11 Core NFC - any sample code?


问:
Pandas merge two df
I have two DataFrames

df1 has following form

```<code>    ID    col1    col2
0   1     2       10
1   3     1       21
</code>```

and df2 looks like this

```<code>    ID    field1    field2
0   1     4         1
1   1     3         3
2   3     5         4
3   3     9         5
4   1     2         0
</code>```

I want to concatenate both DataFrames but so that I have only one line per each ID, so it'd look like this:

```<code>    ID   col1    col2   field1_1    field2_1    field1_2    field2_2    field1_3    field2_3
0   1    2       10     4           1           3           3           2           0
1   3    1       21     5           4           9           5
</code>```

I have tried merging and pivoting the data df.pivot(index=df1.index, columns='ID')
But because the length is variable, I become a ValueError.

ValueError: all arrays must be same length

答:
Without over formatting, we want to merge and add a level of a multi index that counts the 'ID's.

```<code>df = df1.merge(df2)
cc = df.groupby('ID').cumcount()
df.set_index(['ID', 'col1', 'col2', cc]).unstack()

             field1           field2
                  0    1    2      0    1    2
ID col1 col2
1  2    10      4.0  3.0  2.0    1.0  3.0  0.0
3  1    21      5.0  9.0  NaN    4.0  5.0  NaN
</code>```

We can nail down the formatting with:

```<code>df = df1.merge(df2)
cc = df.groupby('ID').cumcount() + 1
d1 = df.set_index(['ID', 'col1', 'col2', cc]).unstack().sort_index(axis=1, level=1)
d1.columns = d1.columns.to_series().map('{0[0]}_{0[1]}'.format)
d1.reset_index()

   ID  col1  col2  field1_1  field2_1  field1_2  field2_2  field1_3  field2_3
0   1     2    10       4.0       1.0       3.0       3.0       2.0       0.0
1   3     1    21       5.0       4.0       9.0       5.0       NaN       NaN
</code>```

Title: Pandas merge two df

Body:
I have two DataFrames

df1 has following form

    ID    col1    col2
0   1     2       10
1   3     1       21

and df2 looks like this

    ID    field1    field2
0   1     4         1
1   1     3         3
2   3     5         4
3   3     9         5
4   1     2         0

I want to concatenate both DataFrames but so that I have only one line per each ID, so it'd look like this:

    ID   col1    col2   field1_1    field2_1    field1_2    field2_2    field1_3    field2_3
0   1    2       10     4           1           3           3           2           0
1   3    1       21     5           4           9           5

I have tried merging and pivoting the data df.pivot(index=df1.index, columns='ID')
But because the length is variable, I become a ValueError.

ValueError: all arrays must be same length

Body:
Without over formatting, we want to merge and add a level of a multi index that counts the 'ID's.

df = df1.merge(df2)
cc = df.groupby('ID').cumcount()
df.set_index(['ID', 'col1', 'col2', cc]).unstack()

             field1           field2
                  0    1    2      0    1    2
ID col1 col2
1  2    10      4.0  3.0  2.0    1.0  3.0  0.0
3  1    21      5.0  9.0  NaN    4.0  5.0  NaN

We can nail down the formatting with:

df = df1.merge(df2)
cc = df.groupby('ID').cumcount() + 1
d1 = df.set_index(['ID', 'col1', 'col2', cc]).unstack().sort_index(axis=1, level=1)
d1.columns = d1.columns.to_series().map('{0[0]}_{0[1]}'.format)
d1.reset_index()

   ID  col1  col2  field1_1  field2_1  field1_2  field2_2  field1_3  field2_3
0   1     2    10       4.0       1.0       3.0       3.0       2.0       0.0
1   3     1    21       5.0       4.0       9.0       5.0       NaN       NaN


问:
How does includeEmptyRows work? - PHP Google Analytics API
I can't retrieve empty rows from GA response. I already set IncludeEmptyRows to true. Am I doing something wrong?

Here is my code where I initialize request:

```<code>$dateRange = new \Google_Service_AnalyticsReporting_DateRange();
  $dateRange->setStartDate('2016-05-10');
  $dateRange->setEndDate('2016-06-20');

  $sessions = new \Google_Service_AnalyticsReporting_Metric();
  $sessions->setExpression("ga:sessions");
  $sessions->setAlias("sessions");

  $dimension = new \Google_Service_AnalyticsReporting_Dimension();
  $dimension->setName("ga:userType");

  $request = new \Google_Service_AnalyticsReporting_ReportRequest();
  $request->setViewId($VIEW_ID);
  $request->setDateRanges( $dateRange );
  $request->setMetrics( array($sessions) );
  $request->setDimensions( array($dimension) );
  $request->setIncludeEmptyRows( true );
</code>```

As you see, I set includeEmptyRows to true, but still can't get empty row

```<code>["data"]=>
    array(6) {
      ["rows"]=>
      array(1) {
        [0]=>
        array(2) {
          ["dimensions"]=>
          array(1) {
            [0]=>
            string(11) "New Visitor"
          }
          ["metrics"]=>
          array(1) {
            [0]=>
            array(1) {
              ["values"]=>
              array(1) {
                [0]=>
                string(2) "63"
              }
            }
          }
        }
      }
</code>```

there should be "Returning Visitor" dimension all the time, not only when it is > 0 ( i used different dates here )

```<code>["data"]=>
    array(6) {
      ["rows"]=>
      array(2) {
        [0]=>
        array(2) {
          ["dimensions"]=>
          array(1) {
            [0]=>
            string(11) "New Visitor"
          }
          ["metrics"]=>
          array(1) {
            [0]=>
            array(1) {
              ["values"]=>
              array(1) {
                [0]=>
                string(3) "159"
              }
            }
          }
        }
        [1]=>
        array(2) {
          ["dimensions"]=>
          array(1) {
            [0]=>
            string(17) "Returning Visitor"
          }
          ["metrics"]=>
          array(1) {
            [0]=>
            array(1) {
              ["values"]=>
              array(1) {
                [0]=>
                string(1) "5"
              }
            }
          }
        }
      }
</code>```

Any help? Thank you so much.

答:
I answered a similar question here.

In short, this only works when you're using just a date dimension.  The result for you follow a similar set of steps as the answer linked above, only you would summarize on just the userType dimension after the last step.

Body:
I can't retrieve empty rows from GA response. I already set IncludeEmptyRows to true. Am I doing something wrong?

Here is my code where I initialize request:

$dateRange = new \Google_Service_AnalyticsReporting_DateRange();
  $dateRange->setStartDate('2016-05-10');
  $dateRange->setEndDate('2016-06-20');

  $sessions = new \Google_Service_AnalyticsReporting_Metric();
  $sessions->setExpression("ga:sessions");
  $sessions->setAlias("sessions");

  $dimension = new \Google_Service_AnalyticsReporting_Dimension();
  $dimension->setName("ga:userType");

  $request = new \Google_Service_AnalyticsReporting_ReportRequest();
  $request->setViewId($VIEW_ID);
  $request->setDateRanges( $dateRange );
  $request->setMetrics( array($sessions) );
  $request->setDimensions( array($dimension) );
  $request->setIncludeEmptyRows( true );

As you see, I set includeEmptyRows to true, but still can't get empty row

["data"]=>
    array(6) {
      ["rows"]=>
      array(1) {
        [0]=>
        array(2) {
          ["dimensions"]=>
          array(1) {
            [0]=>
            string(11) "New Visitor"
          }
          ["metrics"]=>
          array(1) {
            [0]=>
            array(1) {
              ["values"]=>
              array(1) {
                [0]=>
                string(2) "63"
              }
            }
          }
        }
      }

there should be "Returning Visitor" dimension all the time, not only when it is > 0 ( i used different dates here )

["data"]=>
    array(6) {
      ["rows"]=>
      array(2) {
        [0]=>
        array(2) {
          ["dimensions"]=>
          array(1) {
            [0]=>
            string(11) "New Visitor"
          }
          ["metrics"]=>
          array(1) {
            [0]=>
            array(1) {
              ["values"]=>
              array(1) {
                [0]=>
                string(3) "159"
              }
            }
          }
        }
        [1]=>
        array(2) {
          ["dimensions"]=>
          array(1) {
            [0]=>
            string(17) "Returning Visitor"
          }
          ["metrics"]=>
          array(1) {
            [0]=>
            array(1) {
              ["values"]=>
              array(1) {
                [0]=>
                string(1) "5"
              }
            }
          }
        }
      }

Any help? Thank you so much.


问:
Regex to match BIN ranges
I'm trying to write a regex that matches the numbers 456725 to 456744 (Last 2 digits, 25-44), but can't seem to figure out a correct regex format. I've tried ^(4567[2-4][0-9]) but using this also matches 456745 which it shouldn't.

答:
If you do it like ^(4567[2-4][0-9]), you are allowing any number in the range between [2-4] together with any number in the range between [0-9], which is obviously not what you wanted.

So you need to change for something like:
^4567(?:2[5-9]|3[0-9]|4[0-4])

Explanation

^ asserts position at start of the string

4567 matches the characters 4567 literally

Non-capturing group (?:2[5-9]|3[0-9]|4[0-4])

1st Alternative 2[5-9]

2 matches the character 2 literally

Match a single character present in the list [5-9]

2nd Alternative 3[0-9]

3 matches the character 3 literally

Match a single character present in the list [0-9]

3rd Alternative 4[0-4]

4 matches the character 4 literally

Match a single character present in the list [0-4]

You could use the page regex101 to learn more and read good explanations on the subject. Hope it helps.

Title: Regex to match BIN ranges


问:
JS/Lodash - Group values which occur more than once?
I have an array something like:

```<code>const arr = [
  { id: 123, parent: [345] },
  { id: 811, parent: [456] },
  { id: 987, parent: [876] },
  { id: 811, parent: [137] },
  { id: 811, parent: [825] }
]
</code>```

An object with id 811 occurs 3 times.

I need to transform it into:

```<code>const newArr = [
  { id: 123, parent: [345] },
  { id: 811, parent: [456, 137, 825] },
  { id: 987, parent: [876] }
]
</code>```

That is, I need to find the objects that have an id which occurs more than once, then merge those objects into one object which has a parent array of the parent values from all the objects.

What's the best way to do this using lodash methods..?

答:
Using lodash, groupBy the id, merge each group, and concat the arrays:

const arr = [{"id":123,"parent":[345]},{"id":811,"parent":[456]},{"id":987,"parent":[876]},{"id":811,"parent":[137]},{"id":811,"parent":[825]}];

const result = _(arr)
  .groupBy('id')
  .map((group) => _.mergeWith({}, ...group, (o1, o2) =>
    Array.isArray(o1) ? o1.concat(o2) : undefined
  ))
  .value();

console.log(result);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script></code>```

Or using ES6 you do the same thing with Array#reduce and Map:

const arr = [{"id":123,"parent":[345]},{"id":811,"parent":[456]},{"id":987,"parent":[876]},{"id":811,"parent":[137]},{"id":811,"parent":[825]}];

const result = [...arr.reduce((map, obj) => {
  const group = map.get(obj.id) || { id: obj.id, parent: [] };

  group.parent.push(...obj.parent);

  return map.set(obj.id, group);
}, new Map()).values()];

console.log(result);```

Body:
I have an array something like:

const arr = [
  { id: 123, parent: [345] },
  { id: 811, parent: [456] },
  { id: 987, parent: [876] },
  { id: 811, parent: [137] },
  { id: 811, parent: [825] }
]

An object with id 811 occurs 3 times.

I need to transform it into:

const newArr = [
  { id: 123, parent: [345] },
  { id: 811, parent: [456, 137, 825] },
  { id: 987, parent: [876] }
]

That is, I need to find the objects that have an id which occurs more than once, then merge those objects into one object which has a parent array of the parent values from all the objects.

What's the best way to do this using lodash methods..?

Body:
Using lodash, groupBy the id, merge each group, and concat the arrays:

const arr = [{"id":123,"parent":[345]},{"id":811,"parent":[456]},{"id":987,"parent":[876]},{"id":811,"parent":[137]},{"id":811,"parent":[825]}];

const result = _(arr)
  .groupBy('id')
  .map((group) => _.mergeWith({}, ...group, (o1, o2) =>
    Array.isArray(o1) ? o1.concat(o2) : undefined
  ))
  .value();

console.log(result);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

Or using ES6 you do the same thing with Array#reduce and Map:

const arr = [{"id":123,"parent":[345]},{"id":811,"parent":[456]},{"id":987,"parent":[876]},{"id":811,"parent":[137]},{"id":811,"parent":[825]}];

const result = [...arr.reduce((map, obj) => {
  const group = map.get(obj.id) || { id: obj.id, parent: [] };

  group.parent.push(...obj.parent);

  return map.set(obj.id, group);
}, new Map()).values()];

console.log(result);


问:
cf push vs git push on Bluemix
I'm under the impression that a cf push deploys my app to bluemix. Whereas a git push only pushes the sources to the project's git repository and does not redeploy the app. Is that correct?</p>

答:
git commands prepare and send files from your local system to your git repository. If you have a DevOps toolchain or pipeline set up, then that toolchain could monitor your repository and execute a series of steps (build, test, blue-green deploy, etc) to get your app up and running on Bluemix. However, that has nothing to do with git push, other than Bluemix is monitoring the repository to which you have sent your updated code.

cf (and bx) commands interact directly with Bluemix. cf (Cloud Foundry) push takes the contents of your current folder structure and uploads it to Bluemix.

Both cf and git allow you to ignore files and folders. This keeps you from accidentally storing things like credentials for your cloud apps in a public git repository; so you might have an entry in your .gitignore file which specifies that your env.json file is not to be stored in your git repo. However, that file is required for the app to run; cf uses a different file, .cfignore, to tell it what to ignore. local test files, local, or git oriented documentation which is not used by the running application shouldn't be uploaded to the cloud app space, so, for example, you might tell cf to ignore all files in your "Documentation" folder so that all of those presentations, pdfs, images, etc in the documentation folder don't get sent up to your cloud - Bluemix - environment.

Title: cf push vs git push on Bluemix


答:
If your variable is just an integer it is best to just compare it as such...

For the regex though..the ^(4567 is correct your issue is the [2-4] and [0-9] those are independent of each other. You need to put the pieces together so only 25-29 and 40-44 are allowed.

This should get you on the right track:

```<code>^(4567(?:2[5-9]|3[0-9]|4[0-4]))$
</code>```

Title: Regex to match BIN ranges

Body: I'm trying to write a regex that matches the numbers 456725 to 456744 (Last 2 digits, 25-44), but can't seem to figure out a correct regex format. I've tried ^(4567[2-4][0-9]) but using this also matches 456745 which it shouldn't.

Body:
If your variable is just an integer it is best to just compare it as such...

For the regex though..the ^(4567 is correct your issue is the [2-4] and [0-9] those are independent of each other. You need to put the pieces together so only 25-29 and 40-44 are allowed.

This should get you on the right track:

^(4567(?:2[5-9]|3[0-9]|4[0-4]))$


问:
How to get a value from controller to view in laravel?
I have a simple input form with a text input field and a submit button. I am trying to get the value from the input field to be displayed again on the same page after the submit button is clicked. So far laravel always throws an error that the variable is undefined.

Route:

```<code>Route::get('/find/names', "FindController@get_name")->name('names');
</code>```

Controller

```<code> public function get_name(){
         $name = Input::get('name_by_user');
         return $name;
    }
</code>```

view

```<code>        <form role="form" method="GET">
                    <div class="row">
                        <div class="form-group">
                            <div class="input-group">
                                <input type="text" name="name_by_user"/>
                                <span class="input-group-btn">
                                    <button class="btn search-button" type="submit">
                                    <span aria-hidden="true">
                                    <span>Search</span>
                                    </button>
                                </span>
                                </span>
                            </div>
                        </div>
                    </div>
                </form>

  display name after submitting:  {{$name}}
</code>```

答:
I would do something like this

Route

```<code>Route::name('names')->get('/find/names', "FindController@get_name");
</code>```

Controller

```<code>public function get_name(){
   $collection = Input::all();
   $name = $collection->pluck('name_by_user');
   return view('view_file_in_resources', compact('name'));
}
</code>```

Now you will have a $names collection in your view.

But if you only want to fetch result from one row, you controller should look like this:

```<code>public function get_name($name){
   $name = Input::where('name_by_user', $name)->get();
   return view('view_file_in_resources', compact('name'));
}
</code>```

And your routes file

```<code>Route::name('names')->get('/find/names/{name}', "FindController@get_name");
</code>```

Body:
I have a simple input form with a text input field and a submit button. I am trying to get the value from the input field to be displayed again on the same page after the submit button is clicked. So far laravel always throws an error that the variable is undefined.

Route:

Route::get('/find/names', "FindController@get_name")->name('names');

Controller

 public function get_name(){
         $name = Input::get('name_by_user');
         return $name;
    }

view

        <form role="form" method="GET">

                                <input type="text" name="name_by_user"/>

                                    <button class="btn search-button" type="submit">

                                    Search
                                    </button>

                </form>

  display name after submitting:  {{$name}}

Body:
I would do something like this

Route

Route::name('names')->get('/find/names', "FindController@get_name");

Controller

public function get_name(){
   $collection = Input::all();
   $name = $collection->pluck('name_by_user');
   return view('view_file_in_resources', compact('name'));
}

Now you will have a $names collection in your view.

But if you only want to fetch result from one row, you controller should look like this:

public function get_name($name){
   $name = Input::where('name_by_user', $name)->get();
   return view('view_file_in_resources', compact('name'));
}

And your routes file

Route::name('names')->get('/find/names/{name}', "FindController@get_name");


问:
Property 'Server' does not exist on type 'typeof "http"'
I know that var someModule = require('someModule') is generally replaced by import * as someModule from 'someModule' but I can't figure out how to use Typescript/ES6 syntax to express the following Node.js code:

```<code>var server = require('http').Server(app);
</code>```

After reading import and call a function with es6
I have tried the following:

```<code>import * as httpModule from 'http';
const server = httpModule.Server(app);
</code>```

and the code does compile and run properly but I still get this TS error:

[ts] Property 'Server' does not exist on type 'typeof "http"'.

I have @types/node and @types/express installed. Am I missing something?

答:
Try this:

```<code>import { Server, createServer } from 'http';
const server = createServer(app);
</code>```

This might help.

Clarification: You are using default import instead named import.

Body:
I know that var someModule = require('someModule') is generally replaced by import * as someModule from 'someModule' but I can't figure out how to use Typescript/ES6 syntax to express the following Node.js code:

var server = require('http').Server(app);

After reading import and call a function with es6
I have tried the following:

import * as httpModule from 'http';
const server = httpModule.Server(app);

and the code does compile and run properly but I still get this TS error:

[ts] Property 'Server' does not exist on type 'typeof "http"'.

I have @types/node and @types/express installed. Am I missing something?

Body:
Try this:

import { Server, createServer } from 'http';
const server = createServer(app);

This might help.

Clarification: You are using default import instead named import.


答:
Just use distinct</p>

```<code> select distinct team_id,opponents_id
   from your_table
</code>```

Title: Distinct on two columns

Body:
How to select unique results from both columns:

+---------+--------------+
| team_id | opponents_id |
+---------+--------------+
|       1 |            2 |
|       1 |            3 |
|       1 |            4 |
|       1 |            5 |
|       1 |            6 |
|       2 |            1 |
|       2 |            3 |
|       2 |            4 |
|       2 |            5 |
|       2 |            6 |
|       3 |            1 |
|       3 |            2 |
|       3 |            4 |
|       3 |            5 |
|       3 |            6 |
|       4 |            1 |
|       4 |            2 |
|       4 |            3 |
|       4 |            5 |
|       4 |            6 |
|       5 |            1 |
|       5 |            2 |
|       5 |            3 |
|       5 |            4 |
|       5 |            6 |
|       6 |            1 |
|       6 |            2 |
|       6 |            3 |
|       6 |            4 |
|       6 |            5 |
+---------+--------------+

Body:
Just use distinct

 select distinct team_id,opponents_id
   from your_table


答:
If you want to suppress duplicate based on the two column then you should group your value with composite index column1, column2

```<code>SELECT column1, column2
FROM MA_TABLE
GROUP BY column1, column2
</code>```

It should return you a list of unique resultset

Title: Distinct on two columns

Body:
If you want to suppress duplicate based on the two column then you should group your value with composite index column1, column2

SELECT column1, column2
FROM MA_TABLE
GROUP BY column1, column2

It should return you a list of unique resultset