问:
Restrict users to their own entities
How can we restrict users to their own entities within the Framework? I know that we can check the session Id or include the currentSession in the LINQ query but I kind of wonder if the framework provides a better and efficient way to overcome this?</p>

答:
I gave an example on the old forums of how to manually create an interface called IMustOwnEntity which you add to your entities, and an extension method for IRepository which uses the interface to control access.

Create an empty interface for your domain entities to inherit. Then create an extension method and overload the Update to take the entity and a user Id (which you pass from AbpSession or whatever). The method must check if the entity implements your interface, then check if the passed user is the entity's creator before updating otherwise it just updates the entity as normal. You must decide what to do if the user is not the owner; in my example below I just throw an exception.

Interface

```<code>public interface IMustOwnEntity
{
}
</code>```

Extension Class

```<code>public static class RepositoryExtensions
{
  public static TEntity Update<TEntity>(this IRepository<TEntity> repository, TEntity entity, long userId) where TEntity : class, IEntity<int>, ICreationAudited
  {
    if (entity is IMustOwnEntity)
    {
      var exists = repository.FirstOrDefaultAsync((record) => record.Id == entity.Id && record.CreatorUserId == userId);

      if (exists != null)
      {
          return repository.Update(entity);
      }
      else
      {
          throw new Exception("Record does not belong to user");
      }
    }
    else
    {
      return repository.Update(entity);
    }
  }
}
</code>```

Title: Restrict users to their own entities

Body:
I gave an example on the old forums of how to manually create an interface called IMustOwnEntity which you add to your entities, and an extension method for IRepository which uses the interface to control access.

Create an empty interface for your domain entities to inherit. Then create an extension method and overload the Update to take the entity and a user Id (which you pass from AbpSession or whatever). The method must check if the entity implements your interface, then check if the passed user is the entity's creator before updating otherwise it just updates the entity as normal. You must decide what to do if the user is not the owner; in my example below I just throw an exception.

Interface

public interface IMustOwnEntity
{
}

Extension Class

public static class RepositoryExtensions
{
  public static TEntity Update<TEntity>(this IRepository<TEntity> repository, TEntity entity, long userId) where TEntity : class, IEntity<int>, ICreationAudited
  {
    if (entity is IMustOwnEntity)
    {
      var exists = repository.FirstOrDefaultAsync((record) => record.Id == entity.Id && record.CreatorUserId == userId);

      if (exists != null)
      {
          return repository.Update(entity);
      }
      else
      {
          throw new Exception("Record does not belong to user");
      }
    }
    else
    {
      return repository.Update(entity);
    }
  }
}


来源: stackexchange

问:
Laravel whereIn with with()
I want to pass in array of ids and get all the category of that ids with all the banners of that category

I have defined relationship in ProductMainCategory.php Model

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class ProductMainCategory extends Model
{
    protected $hidden = ['created_at','updated_at'];

    public function banners()
    {
        return $this->hasMany('App\ProductCategoryBanner', 'category_id');
    }
}
</code>```

The ProductCategoryBanner.php Model

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class ProductCategoryBanner extends Model
{
    protected $hidden = ['created_at','updated_at'];
}
</code>```

And in My controller

```<code>   //get distinct main_categories by id
    $main_category_ids = Product::whereIn('id', $product_ids)
                                ->select('main_category_id')
                                ->distinct()
                                ->pluck('main_category_id')
                                ->toArray();

    //get main_category with banners (error query)
    $main_categories_with_images = ProductMainCategory::whereIn('id', $main_category_ids)
                                                      ->with(array('banners'=>function($query){
                                                            $query->select('id','image');
                                                       }))
                                                      ->get();

    //this query works, but it'll give all the categories but i want only passed id's categories
    $main_categories_with_images = ProductMainCategory::with('banners')
                                                  ->get();
</code>```

I'm getting the data but banners are empty

```<code>    [
        {
            "id": 1,
            "name": "Grocery & Staples",
            "admin_id": 1,
            "banners": [] //getting empty array
        },
        {
            "id": 2,
            "name": "Fruits & Vegetables",
            "admin_id": 1,
            "banners": [] //getting empty array
        }
    ]

//actual result without $query->select('id','image'); is
 [
    {
        "id": 1,
        "name": "Grocery & Staples",
        "admin_id": 1,
        "banners": [
            {
                "id": 1,
                "category_id": "1",
                "image": "link 1",
                "admin_id": 2
            },
            {
                "id": 2,
                "category_id": "1",
                "image": "link 2",
                "admin_id": 1
            }
        ]
    },
    {
        "id": 2,
        "name": "Fruits & Vegetables",
        "admin_id": 1,
        "banners": [
            {
                "id": 3,
                "category_id": "2",
                "image": "link 3",
                "admin_id": 1
            },
            {
                "id": 4,
                "category_id": "2",
                "image": "link 4",
                "admin_id": 1
            }
        ]
    }
]
</code>```

答:
```<code> $main_categories_with_images = ProductMainCategory::whereIn('id', $main_category_ids)
                                                  ->with(array('banners'=>function($query){
                                                        $query->select('id','image');
                                                   }))
                                                  ->get();
</code>```

Change WareIn to WhereIn

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class ProductCategoryBanner extends Model
  {
  protected $hidden = ['created_at','updated_at'];

  public function mainCategory() { return $this->belongsTo('ProductMainCategory')->select(['id','image']); }
 }
</code>```

ContentLicense: CC BY-SA 3.0

Title: Laravel whereIn with with()

Body:
I want to pass in array of ids and get all the category of that ids with all the banners of that category

I have defined relationship in ProductMainCategory.php Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class ProductMainCategory extends Model
{
    protected $hidden = ['created_at','updated_at'];

    public function banners()
    {
        return $this->hasMany('App\ProductCategoryBanner', 'category_id');
    }
}

The ProductCategoryBanner.php Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class ProductCategoryBanner extends Model
{
    protected $hidden = ['created_at','updated_at'];
}

And in My controller

   //get distinct main_categories by id
    $main_category_ids = Product::whereIn('id', $product_ids)
                                ->select('main_category_id')
                                ->distinct()
                                ->pluck('main_category_id')
                                ->toArray();

    //get main_category with banners (error query)
    $main_categories_with_images = ProductMainCategory::whereIn('id', $main_category_ids)
                                                      ->with(array('banners'=>function($query){
                                                            $query->select('id','image');
                                                       }))
                                                      ->get();

    //this query works, but it'll give all the categories but i want only passed id's categories
    $main_categories_with_images = ProductMainCategory::with('banners')
                                                  ->get();

I'm getting the data but banners are empty

    [
        {
            "id": 1,
            "name": "Grocery & Staples",
            "admin_id": 1,
            "banners": [] //getting empty array
        },
        {
            "id": 2,
            "name": "Fruits & Vegetables",
            "admin_id": 1,
            "banners": [] //getting empty array
        }
    ]

//actual result without $query->select('id','image'); is
 [
    {
        "id": 1,
        "name": "Grocery & Staples",
        "admin_id": 1,
        "banners": [
            {
                "id": 1,
                "category_id": "1",
                "image": "link 1",
                "admin_id": 2
            },
            {
                "id": 2,
                "category_id": "1",
                "image": "link 2",
                "admin_id": 1
            }
        ]
    },
    {
        "id": 2,
        "name": "Fruits & Vegetables",
        "admin_id": 1,
        "banners": [
            {
                "id": 3,
                "category_id": "2",
                "image": "link 3",
                "admin_id": 1
            },
            {
                "id": 4,
                "category_id": "2",
                "image": "link 4",
                "admin_id": 1
            }
        ]
    }
]

Body:
 $main_categories_with_images = ProductMainCategory::whereIn('id', $main_category_ids)
                                                  ->with(array('banners'=>function($query){
                                                        $query->select('id','image');
                                                   }))
                                                  ->get();

Change WareIn to WhereIn

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class ProductCategoryBanner extends Model
  {
  protected $hidden = ['created_at','updated_at'];

  public function mainCategory() { return $this->belongsTo('ProductMainCategory')->select(['id','image']); }
 }


问:
How to export excel in PHP and compatible for all devices
I am trying to export an export file in PHP. I am using Codeigniter Framework.

I exported Excel in this way:

```<code>header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename={$filename}.xls");
</code>```

It is showing data in Windows in right format. But prompt a message when I initially open it. But When I open it in MAC OS, it is not working.

How can I export Excel in right format that works in Google Drive as well? I have tried so many ways as above and as follows. All not working properly in Mac and Google Drive spreadsheets:

```<code>header('Content-Disposition: attachment; filename='.$filename.'.xlsx');
header('Content-type:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');

header('Content-Disposition: attachment; filename='.$filename.'.xls');
header('Content-type: application/vnd.ms-excel');

header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename=$filename.xls");
</code>```

答:
header("Content-Type: application/xls");

header("Content-Disposition: attachement; filename=export_test.xls");

ContentLicense: CC BY-SA 4.0

Body:
I am trying to export an export file in PHP. I am using Codeigniter Framework.

I exported Excel in this way:

header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename={$filename}.xls");

It is showing data in Windows in right format. But prompt a message when I initially open it. But When I open it in MAC OS, it is not working.

How can I export Excel in right format that works in Google Drive as well? I have tried so many ways as above and as follows. All not working properly in Mac and Google Drive spreadsheets:

header('Content-Disposition: attachment; filename='.$filename.'.xlsx');
header('Content-type:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');

header('Content-Disposition: attachment; filename='.$filename.'.xls');
header('Content-type: application/vnd.ms-excel');

header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename=$filename.xls");


答: You have typo after ProductMainCategory : wareIn(), It should be whereIn()

Title: Laravel whereIn with with()


问:
Input from file in C, data types
thanks in advance for taking the time to read through my question...

```<code>/* Binary search for use with Gen_window.comp */
#include <stdio.h>

int main()
{
  char line[1000];
  double sig, E;

  FILE *fp, *fopen();
  fp = fopen("sig_data", "r");

  if (fp==NULL){
        printf("Error opening file!");
  }
  else {
        printf("Processing file...");
  }

  while( (fgets(line, 25, fp) != NULL) ){
        fscanf(fp, "%lf\t%lf", &E, &sig);
        printf("\nThe energy is: %lf eV\nThe corresponding cross section is: %lf barns\n",E, sig);
  }

}
</code>```

Numbers in the file are of the format X.XXXXXX+X or X.XXXXXX-X accordingly.  Does C have a way to specify this as input?  Is it a bother that there is no 'e'.  I cannot find any documentation that tells about inputing exponential, only returning exponential...

I do not need it to print that exact format, any other exponential format would be fine.

I realize there should be some specifiers and precision in my %lf, or maybe it should be %e, but I have tried everything that makes sense to me, so I am basically leaving it blank.

Thanks for your help.

答:
Jester and plinth's answers are broadly correct, but flawed.  There is indeed no way to make the stock number-parsing routines (*scanf, atof, strtod) process a number in the format you have.  However, the suggested workarounds are bad.  First off, it is my personal opinion that *scanf and ato* should never be used, due to their horrifically bad handling of malformed input. More seriously, decimal-to-float conversion requires extended-precision arithmetic to avoid loss of accuracy.  strtod (which is the routine that should be used for this problem) can be relied on to do this correctly, but processing the mantissa and exponent separately and then combining them in the obvious fashion does not.  You need an intermediate type bigger than double and you need powers of 10 that are accurately computed all the way to the last bit, which pow doesn't reliably give you.

So my recommendation is to rewrite each line on the fly to make it acceptable to strtod.

Read each line into a pair of string buffers, splitting at \t.  I would do this by hand, but you can probably get away with using fscanf as long as you only use %s formats.  Make sure that each buffer has at least two extra bytes of space available.

Scan each buffer for the + or -.  Use memmove to shift that and all subsequent bytes of the string down one.  Poke an e into the buffer at the original position of the sign.  (If you do step 1 by hand you can combine this step with the loop for that step.)

You now have the number in a format that strtod can process.

ContentLicense: CC BY-SA 2.5

Title: Input from file in C, data types

Body:
thanks in advance for taking the time to read through my question...

/* Binary search for use with Gen_window.comp */
#include <stdio.h>

int main()
{
  char line[1000];
  double sig, E;

  FILE *fp, *fopen();
  fp = fopen("sig_data", "r");

  if (fp==NULL){
        printf("Error opening file!");
  }
  else {
        printf("Processing file...");
  }

  while( (fgets(line, 25, fp) != NULL) ){
        fscanf(fp, "%lf\t%lf", &E, &sig);
        printf("\nThe energy is: %lf eV\nThe corresponding cross section is: %lf barns\n",E, sig);
  }

}

Numbers in the file are of the format X.XXXXXX+X or X.XXXXXX-X accordingly.  Does C have a way to specify this as input?  Is it a bother that there is no 'e'.  I cannot find any documentation that tells about inputing exponential, only returning exponential...

I do not need it to print that exact format, any other exponential format would be fine.

I realize there should be some specifiers and precision in my %lf, or maybe it should be %e, but I have tried everything that makes sense to me, so I am basically leaving it blank.

Thanks for your help.


问:
jQuery gathering inputs without submit
I'm trying to get values from inputs without any action from user and then save it via php to txt file.

This is what I got so far:

```<code>var x = setInterval(function() {
var email = $("#test").val();
if(email != '' && email != newemail) {

     $('#display').append(email)

   $.ajax({
      type: "POST",
      url: 'inputs-saving.php',
      data: ({usremail:email}),
      success: function(data) {
      }
    });

}
var newemail = $("#test").val();
}, 1000);
</code>```

it works almost fine, but I need to check if value changed, because if I input some text it will be constantly writen in file every second.

I have also tried to add something like "var newemail = email", but can't make it work corectly.

答:
```<code>$("input").blur(function(){
    //place your logic
});
</code>```

blur will not trigger every time you change the text, only when you remove focus from that box

Title: jQuery gathering inputs without submit

Body:
I'm trying to get values from inputs without any action from user and then save it via php to txt file.

This is what I got so far:

var x = setInterval(function() {
var email = $("#test").val();
if(email != '' && email != newemail) {

     $('#display').append(email)

   $.ajax({
      type: "POST",
      url: 'inputs-saving.php',
      data: ({usremail:email}),
      success: function(data) {
      }
    });

}
var newemail = $("#test").val();
}, 1000);

it works almost fine, but I need to check if value changed, because if I input some text it will be constantly writen in file every second.

I have also tried to add something like "var newemail = email", but can't make it work corectly.

Body:
$("input").blur(function(){
    //place your logic
});

blur will not trigger every time you change the text, only when you remove focus from that box


问:
Mass local notifications swift 3
I have an array of dictionaries.  The dictionaries contain names/longitude/and latitude for different bars.

I want to create location based notifications for each bar in my app.

Here is the function I'm using, but for some reason it only creates a notification for the first bar in the list. The rest do not work.

Any idea what is wrong with this? I'm not sure what content.badge is for.

```<code>// Register location based notifications for all bars
func setupNotifications(){
    if(CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedAlways || CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedWhenInUse){

        for i in 0...(allBars.count - 1){
            let lat = (allBars[i])["Latitude"] as? Double
            let long = (allBars[i])["Longitude"] as? Double
            let name = (allBars[i])["Name"] as! String

            let region = CLCircularRegion(center: CLLocationCoordinate2D(latitude: lat!, longitude: long!), radius: 60, identifier: "\(name)")

            region.notifyOnEntry = true
            region.notifyOnExit = false

            let trigger = UNLocationNotificationTrigger(region: region, repeats: true)
            let content = UNMutableNotificationContent()
            content.title = "Rate \(name) in the app!"
            content.badge = 1
            content.sound = UNNotificationSound.default()

            let request = UNNotificationRequest(identifier: "LN\(name)", content: content, trigger: trigger)
            UNUserNotificationCenter.current().add(request) {(error) in
                if let error = error{
                    print("Need notification permissions... \(error)")
                }
                else{
                    //success
                }
            }
        }
    }
}
</code>```

答:
```<code>import UserNotifications

class ViewController: UIViewController,UNUserNotificationCenterDelegate {

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

    print("UNUserNotificationCenter")

    UNUserNotificationCenter.current().requestAuthorization(options: [.sound,.alert,.badge], completionHandler: { didallow, error in

     })
}

@IBAction func btn(_ sender: UIButton) {
    let content = UNMutableNotificationContent()

    content.title = "the 5 sec are up"
    content.subtitle = "they are up now"
    content.body = "the 5 sec are realy up now"
    content.badge = 1

    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5.0, repeats: false)

    let request = UNNotificationRequest(identifier: "time done", content: content, trigger: trigger)

    UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    print("Handle push for foreground")

    print("\(notification.request.content.userInfo)")
}

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    print("Handle push for background or close")

    print("\(response.notification.request.content.userInfo)")

    completionHandler()
}
</code>```

Title: Mass local notifications swift 3

Body:
I have an array of dictionaries.  The dictionaries contain names/longitude/and latitude for different bars.

I want to create location based notifications for each bar in my app.

Here is the function I'm using, but for some reason it only creates a notification for the first bar in the list. The rest do not work.

Any idea what is wrong with this? I'm not sure what content.badge is for.

// Register location based notifications for all bars
func setupNotifications(){
    if(CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedAlways || CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedWhenInUse){

        for i in 0...(allBars.count - 1){
            let lat = (allBars[i])["Latitude"] as? Double
            let long = (allBars[i])["Longitude"] as? Double
            let name = (allBars[i])["Name"] as! String

            let region = CLCircularRegion(center: CLLocationCoordinate2D(latitude: lat!, longitude: long!), radius: 60, identifier: "\(name)")

            region.notifyOnEntry = true
            region.notifyOnExit = false

            let trigger = UNLocationNotificationTrigger(region: region, repeats: true)
            let content = UNMutableNotificationContent()
            content.title = "Rate \(name) in the app!"
            content.badge = 1
            content.sound = UNNotificationSound.default()

            let request = UNNotificationRequest(identifier: "LN\(name)", content: content, trigger: trigger)
            UNUserNotificationCenter.current().add(request) {(error) in
                if let error = error{
                    print("Need notification permissions... \(error)")
                }
                else{
                    //success
                }
            }
        }
    }
}


问:
How to add devices from storyboard View as

This is my storyboard screen.

As you see, There are 4 iPhone type in my Xcode.

I want to add an iPad here. But, I don't know how to add other devices.

答: The first check, might be your app is iPhone only.Select universal app first.


问:
Uncaught TypeError: Cannot read property 'history' of undefined !! React router
Hi I have installed react-router-dom and I want to use <Link> from it.
Below is my code

```<code>   import { BrowserRouter, Route, Link } from 'react-router-dom'

    class UserList extends Component {

     renderList() {
        return this.props.users.map((user) => {
        return (
            <li
                key={user.id}
                onClick={() => this.props.selectUser(user)}
            >
                {user.first} {user.last}
            </li>
        );
    });
   }

   render() {
     return (
      <div>
        <Link to="/admin/"> Click Me </Link>
        <ul>
            {this.renderList()}
        </ul>
      </div>
    );
  }
}

   function mapStateToProps(state) {
     return {
       users: state.users
     };
   }

  function matchDispatchToProps(dispatch){
    return bindActionCreators({selectUser: selectUser}, dispatch);
   }

  export default connect(mapStateToProps, matchDispatchToProps)(UserList);
</code>```

But getting this error

Warning: Failed context type: The context router is marked as   required in Link, but its value is undefined.

Uncaught TypeError: Cannot read property 'history' of undefined

any idea !!!

答:
Suppose you have some root component called App.  You need to make its root node to be a router (say BrowserRouter) that will react on url changes and provide Link with correct router implementation via context.

```<code>// app.js
import { BrowserRouter, Route, } from 'react-router-dom'
import UserList from './path/to/UserListComponent'

class App extends Component {
  ...

  render() {
    return (
      <BrowserRouter>
        ...
        <Route path="/users" component={UserList}/>
        ...
      </BrowserRouter>
    )
  }
}
</code>```

Body:
Hi I have installed react-router-dom and I want to use <Link> from it.
Below is my code

   import { BrowserRouter, Route, Link } from 'react-router-dom'

    class UserList extends Component {

     renderList() {
        return this.props.users.map((user) => {
        return (

 this.props.selectUser(user)}
            >
                {user.first} {user.last}

        );
    });
   }

   render() {
     return (

        <Link to="/admin/"> Click Me </Link>

            {this.renderList()}

    );
  }
}

   function mapStateToProps(state) {
     return {
       users: state.users
     };
   }

  function matchDispatchToProps(dispatch){
    return bindActionCreators({selectUser: selectUser}, dispatch);
   }

  export default connect(mapStateToProps, matchDispatchToProps)(UserList);

But getting this error

Warning: Failed context type: The context router is marked as   required in Link, but its value is undefined.

Uncaught TypeError: Cannot read property 'history' of undefined

any idea !!!

Body:
Suppose you have some root component called App.  You need to make its root node to be a router (say BrowserRouter) that will react on url changes and provide Link with correct router implementation via context.

// app.js
import { BrowserRouter, Route, } from 'react-router-dom'
import UserList from './path/to/UserListComponent'

class App extends Component {
  ...

  render() {
    return (
      <BrowserRouter>
        ...
        <Route path="/users" component={UserList}/>
        ...
      </BrowserRouter>
    )
  }
}


答:
change this :</p>

```<code> //get main_category with banners (error query)
    $main_categories_with_images = ProductMainCategory::whereIn('id', $main_category_ids)
                                                      ->with(array('banners'=>function($query){
                                                            $query->select('id','image');
                                                       }))
                                                      ->get();
</code>```

Title: Laravel whereIn with with()

Body:
change this :

 //get main_category with banners (error query)
    $main_categories_with_images = ProductMainCategory::whereIn('id', $main_category_ids)
                                                      ->with(array('banners'=>function($query){
                                                            $query->select('id','image');
                                                       }))
                                                      ->get();


问:
How to remove Web Essentials from Chrome after disabling browser link
I have set "enable browser link menu" to false the Web Essentials options in Visual Studio, however, I still see this error message in Chrome console.

```<code>[09:21:58 GMT+1000 (AUS Eastern Standard Time)] Browser Link: Exception thrown when trying to invoke Browser Link extension callback "madskristensen.editorextensions.browserlink.unusedcss.unusedcssextensionfactory.GetIgnoreList":
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.NullReferenceException: Object reference not set to an instance of an object.
   at MadsKristensen.EditorExtensions.BrowserLink.UnusedCss.UnusedCssExtension.GetIgnoreList()
   --- End of inner exception stack trace ---
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at Microsoft.VisualStudio.Web.BrowserLink.ClientMessaging.DispatchMessage(BrowserLinkConnection connection, MessageArgs obj)
</code>```

This is my only gripe after disabling browser link is seeing this message in my console nearly everytime I open the Developer Tools on the console log view.

I have tried finding the extension (chrome://extensions/) or plugin (chrome://plugins/) but it is not listed.

答:
Simply Go to Tools >> Extensions and Updates

Look at the installed programs.

Disable Web Essentials 2013, 5 Update

Voila !! Your problem is solved

Body:
I have set "enable browser link menu" to false the Web Essentials options in Visual Studio, however, I still see this error message in Chrome console.

[09:21:58 GMT+1000 (AUS Eastern Standard Time)] Browser Link: Exception thrown when trying to invoke Browser Link extension callback "madskristensen.editorextensions.browserlink.unusedcss.unusedcssextensionfactory.GetIgnoreList":
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.NullReferenceException: Object reference not set to an instance of an object.
   at MadsKristensen.EditorExtensions.BrowserLink.UnusedCss.UnusedCssExtension.GetIgnoreList()
   --- End of inner exception stack trace ---
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at Microsoft.VisualStudio.Web.BrowserLink.ClientMessaging.DispatchMessage(BrowserLinkConnection connection, MessageArgs obj)

This is my only gripe after disabling browser link is seeing this message in my console nearly everytime I open the Developer Tools on the console log view.

I have tried finding the extension (chrome://extensions/) or plugin (chrome://plugins/) but it is not listed.


问:
how do I navigate and grab infos from an Array like this
Im trying to navigate and fetch info from this array but im not having much success any tips? This is an decoded JSON from Twitter API

I tryed echo $array->statuses[0]->created_at; and it did not work, am i doing something wrong here?

```<code>Array
    (
        [statuses] => Array
            (
                [0] => stdClass Object
                    (
                        [created_at] => Thu Jul 06 04:05:06 +0000 2017
                        [id] => 882812623959584768
                        [id_str] => 882812623959584768
                        [text] => RT @blackdragonsBR: [R6] GG!! Fechamos o mapa Banco por 5x2 e conquistamos a liderança no #ALIENWARENOIGN #GOBD #Acer #Predator https://t.c…
                        [truncated] =>
                        [entities] => stdClass Object
                            (
                                [hashtags] => Array
                                    (
                                        [0] => stdClass Object
                                            (
                                                [text] => ALIENWARENOIGN
                                                [indices] => Array
                                                    (
                                                        [0] => 90
                                                        [1] => 105
                                                }

                                        )
                                }
                        }
                }
        }
}
</code>```

答:
You can use json_encode and json_decode at time then it make the variable to array only then you can get the data easily.

Just like this

```<code>$array=json_decode(json_encode($array,true),true);
$array[statuses][0]['created_at'];
</code>```

It will work for you

Body:
Im trying to navigate and fetch info from this array but im not having much success any tips? This is an decoded JSON from Twitter API

I tryed echo $array->statuses[0]->created_at; and it did not work, am i doing something wrong here?

Array
    (
        [statuses] => Array
            (
                [0] => stdClass Object
                    (
                        [created_at] => Thu Jul 06 04:05:06 +0000 2017
                        [id] => 882812623959584768
                        [id_str] => 882812623959584768
                        [text] => RT @blackdragonsBR: [R6] GG!! Fechamos o mapa Banco por 5x2 e conquistamos a liderança no #ALIENWARENOIGN #GOBD #Acer #Predator https://t.c…
                        [truncated] =>
                        [entities] => stdClass Object
                            (
                                [hashtags] => Array
                                    (
                                        [0] => stdClass Object
                                            (
                                                [text] => ALIENWARENOIGN
                                                [indices] => Array
                                                    (
                                                        [0] => 90
                                                        [1] => 105
                                                }

                                        )
                                }
                        }
                }
        }
}

Body:
You can use json_encode and json_decode at time then it make the variable to array only then you can get the data easily.

Just like this

$array=json_decode(json_encode($array,true),true);
$array[statuses][0]['created_at'];

It will work for you


问:
find the same elements count of two sorted array using functional programming style
Example:
Given nums1 = [1, 2, 3, 4], nums2 = [2, 3], return 2

I have the imperative style solution using python, the algorithm complexity is O(m+n) :

```<code>def sameElementsCount(nums1, nums2):
    count = 0
    len1 = len(nums1)
    len2 = len(nums2)
    i = 0
    j = 0
    while i < len1 and j < len2:
        if nums1[i] == nums2[j]:
            count += 1
            i += 1
            j += 1
        elif nums1[i] < nums2[j]:
            i += 1
        else:
            j += 1
    return count

print sameElementsCount([1,2,3,4], [2,3])
</code>```

how to do it using functional programming  higher order functions like (map/filter/reduce). make sure the
algorithm complexity is O(m+n)

答: You can use set intersection: len(set(num1) & set(num2))

Body:
Example:
Given nums1 = [1, 2, 3, 4], nums2 = [2, 3], return 2

I have the imperative style solution using python, the algorithm complexity is O(m+n) :

def sameElementsCount(nums1, nums2):
    count = 0
    len1 = len(nums1)
    len2 = len(nums2)
    i = 0
    j = 0
    while i < len1 and j < len2:
        if nums1[i] == nums2[j]:
            count += 1
            i += 1
            j += 1
        elif nums1[i] < nums2[j]:
            i += 1
        else:
            j += 1
    return count

print sameElementsCount([1,2,3,4], [2,3])

how to do it using functional programming  higher order functions like (map/filter/reduce). make sure the
algorithm complexity is O(m+n)


问:
Google Form Script to Add Pre-Filled Text
I have a Form that my staff uses to send me data through out the day.

One of the sections is a " long answer text" box for any comments.

Usually there are no comments so it is left blank.

My question is -

is there a way to automatically pre fill text in a google form and how?

I have used the pre filled link but if the user decides to submit another form (which they always do), it will take them back to the original form link and not the pre fill link.

This data is sent to a spreadsheet with a custom dashboard with the most recent data.

If there is a blank in the comment column, it will grab the last non blank cell in the column section and give off the wrong comment for that data.

I havent found a way to fill all the blank cells with "no comment" in google sheets without filling all the cells that have not been used for google form submissions. Figured it might be easier to start with any script magic from google form instead of google sheets.

Thank you in advance

答:
Yes this is possible, and you can use a separate spreadsheet as input for your pre-filled form that you don't have to change.

There is already an answer for a question that has a lot of commonality with yours here.

Have a try with that first. If you tried to script it and cannot go further you can submit your tried code here and we can help you further. Always try it yourself first before asking the question here at SO.


问:
View to Show Third Party Licenses in Android App
I'm new to Android App Development and was studying about various views. There was a particular view which caught my attention and is used in Google Play Music Android App

I think it is a PopUpWindow but not fully sure. How can we achieve this kind of View and customize the text inside it?

答:
It is a custom dialog my friend. Follow these steps to create your own custom dailog:

step 1 :-> create a layout file custom_layout in res/layout folder like this

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<TextView
    android:id="@+id/tv"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:padding="10dp"
    android:text="hello world" />

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:padding="10dp"
    android:text="hello world" />

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:padding="10dp"
    android:text="hello world" />

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:src="@mipmap/ic_launcher" />
</code>```

step :-> 2 create a dialog like this in your activity java file

```<code> Dialog custoDialog = new Dialog(MainActivity.this);
    custoDialog.setContentView(R.layout.custom_layout);

    Window window = custoDialog.getWindow();
    window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
    window.setGravity(Gravity.CENTER);

    // acces you custom dialog controlss like this
    TextView tv = (TextView) custoDialog.findViewById(R.id.tv);
    tv.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //perfom actions here
        }
    });
    custoDialog.show();
</code>```

ask me in case of any query

Body:
It is a custom dialog my friend. Follow these steps to create your own custom dailog:

step 1 :-> create a layout file custom_layout in res/layout folder like this

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<TextView
    android:id="@+id/tv"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:padding="10dp"
    android:text="hello world" />

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:padding="10dp"
    android:text="hello world" />

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:padding="10dp"
    android:text="hello world" />

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:src="@mipmap/ic_launcher" />

step :-> 2 create a dialog like this in your activity java file

 Dialog custoDialog = new Dialog(MainActivity.this);
    custoDialog.setContentView(R.layout.custom_layout);

    Window window = custoDialog.getWindow();
    window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
    window.setGravity(Gravity.CENTER);

    // acces you custom dialog controlss like this
    TextView tv = (TextView) custoDialog.findViewById(R.id.tv);
    tv.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //perfom actions here
        }
    });
    custoDialog.show();

ask me in case of any query


问:
Creating a list using data from MySQL database
I'm trying to create a basic product list that takes data from the MySQL database and display on screen of the website.

I currently have the following code but still needs some work, it currently only displays the name and category with an error message saying:Warning: printf(): Too few arguments in C:\xampp\htdocs\ICTDBS504\list items.php on line 41
() ()

I also need to add a photo in but I am unsure on how and where that goes in the code. Should the photo be apart of the html or saved on the database? and if on the database how does that get written into the php code

```<code><?php
    $mysqli = new mysqli("localhost", "root", "", "etrading");

    /* check connection */
    if ($mysqli->connect_errno) {
        printf("Connect failed: %s\n", $mysqli->connect_error);
        exit();
    }

    $query = "SELECT Name, Category, Price, Duration, Photo FROM item ORDER by ItemID LIMIT 3";
    $result = $mysqli->query($query);

    /* numeric array */
    $row = $result->fetch_array(MYSQLI_NUM);
    printf ("%s (%s)\n", $row[0], $row[1]);

    /* associative array */
    $row = $result->fetch_array(MYSQLI_ASSOC);
    printf ("%s (%s) (%s)\n", $row["Name"], $row["Category"]);

    /* associative and numeric array */
    $row = $result->fetch_array(MYSQLI_BOTH);
    printf ("%s (%s) (%s)\n", $row[0], $row["Price"], $row["Duration"]);

    /* free result set */
    $result->free();

    /* close connection */
    $mysqli->close();
?>
</code>```

答:
In this part of your code you have type more arguments in printf():

```<code>    /* associative array */
    $row = $result->fetch_array(MYSQLI_ASSOC);
    printf ("%s (%s) (%s)\n", $row["Name"], $row["Category"]);
</code>```

Printf have 3 arguments but you only have put 2: $row["Name"] and $row["Category"].

To solve the error you have to fix the arguments or add 1 more datas.

Body:
I'm trying to create a basic product list that takes data from the MySQL database and display on screen of the website.

I currently have the following code but still needs some work, it currently only displays the name and category with an error message saying:Warning: printf(): Too few arguments in C:\xampp\htdocs\ICTDBS504\list items.php on line 41
() ()

I also need to add a photo in but I am unsure on how and where that goes in the code. Should the photo be apart of the html or saved on the database? and if on the database how does that get written into the php code

<?php
    $mysqli = new mysqli("localhost", "root", "", "etrading");

    /* check connection */
    if ($mysqli->connect_errno) {
        printf("Connect failed: %s\n", $mysqli->connect_error);
        exit();
    }

    $query = "SELECT Name, Category, Price, Duration, Photo FROM item ORDER by ItemID LIMIT 3";
    $result = $mysqli->query($query);

    /* numeric array */
    $row = $result->fetch_array(MYSQLI_NUM);
    printf ("%s (%s)\n", $row[0], $row[1]);

    /* associative array */
    $row = $result->fetch_array(MYSQLI_ASSOC);
    printf ("%s (%s) (%s)\n", $row["Name"], $row["Category"]);

    /* associative and numeric array */
    $row = $result->fetch_array(MYSQLI_BOTH);
    printf ("%s (%s) (%s)\n", $row[0], $row["Price"], $row["Duration"]);

    /* free result set */
    $result->free();

    /* close connection */
    $mysqli->close();
?>

Body:
In this part of your code you have type more arguments in printf():

    /* associative array */
    $row = $result->fetch_array(MYSQLI_ASSOC);
    printf ("%s (%s) (%s)\n", $row["Name"], $row["Category"]);

Printf have 3 arguments but you only have put 2: $row["Name"] and $row["Category"].

To solve the error you have to fix the arguments or add 1 more datas.


问:
AWS Cpanel & Phpmyadmin
Can any please help me in below issue.
I am planning to host more than one site on single AWS ec-2 Instance, now I want every site have its own cpanel and phpmyadmin.

Confusion
should I need to install Cpanel and PHPMyAdmin for every site or what?

Maybe it a silly question but currently, I am stuck.

答: No .. the right thing is adding from "addon domain" menu on cpanel and then u have seperate root folder for your files and you can add extra database and user in "mysql databases" menu section on cpanel</p>

Title: AWS Cpanel & Phpmyadmin


问:
DoModal main application returning -1 code randomly
I have a vc++ program that calls another large exe written in MFC vc++ over and over with create process threads.
sometimes the exe fails to start because the DoModal in the exe fails, but not always. out of 6 calls, 2 may not start.

is there some sort of resource limit? or something else that can identify the problem rather than a -1 return code?
It seems to be mainly when I run as a service under localsystem account, not sure why - might be a red herring.

In the main application startup main window:-

```<code> CTestDlg dlg;
 int ret = dlg.DoModal();
</code>```

return code is sometimes -1.

答:
the solution was in article: How to increase the maximum number of child processes that can be spawned by a windows service -- desktop heap limits

worked for me, but had to reboot after making changes for it to take effect.

Body:
I have a vc++ program that calls another large exe written in MFC vc++ over and over with create process threads.
sometimes the exe fails to start because the DoModal in the exe fails, but not always. out of 6 calls, 2 may not start.

is there some sort of resource limit? or something else that can identify the problem rather than a -1 return code?
It seems to be mainly when I run as a service under localsystem account, not sure why - might be a red herring.

In the main application startup main window:-

 CTestDlg dlg;
 int ret = dlg.DoModal();

return code is sometimes -1.


问:
pandas.read_csv FileNotFoundError: File b'\xe2\x80\xaa<etc>' despite correct path
I'm trying to load a .csv file using the pd.read_csv() function when I get an error despite the file path being correct and using raw strings.

```<code>import pandas as pd
df = pd.read_csv('C:\\Users\\user\\Desktop\\datafile.csv')
df = pd.read_csv(r'C:\Users\user\Desktop\datafile.csv')
df = pd.read_csv('C:/Users/user/Desktop/datafile.csv')
</code>```

all gives the error below:

FileNotFoundError: File b'\xe2\x80\xaaC:/Users/user/Desktop/tutorial.csv' (or the relevant path) does not exist.

Only when i copy the file into the working directory will it load correct.

Is anyone aware of what might be causing the error?

I had previously loaded other datasets with full filepaths without any problems and I'm currently only encountering issues since I've re-installed my python (via Anaconda package installer).

Edit:

I've found the issue that was causing the problem.

When I was copying the filepath over from the file properties window, I unwittingly copied another character that seems invisible.

Assigning that copied string also gives an unicode error.

Deleting that invisible character made any of above code work.

答:
Try this and see if it works. This is independent of the path you provide.

```<code>pd.read_csv(r'C:\Users\aiLab\Desktop\example.csv')
</code>```

Here r  is a special character and means raw string. So prefix it to your string literal.

https://www.journaldev.com/23598/python-raw-string:

Python raw string is created by prefixing a string literal with ‘r’
  or ‘R’. Python raw string treats backslash () as a literal character.
  This is useful when we want to have a string that contains backslash
  and don’t want it to be treated as an escape character.

Body:
I'm trying to load a .csv file using the pd.read_csv() function when I get an error despite the file path being correct and using raw strings.

import pandas as pd
df = pd.read_csv('C:\\Users\\user\\Desktop\\datafile.csv')
df = pd.read_csv(r'C:\Users\user\Desktop\datafile.csv')
df = pd.read_csv('C:/Users/user/Desktop/datafile.csv')

all gives the error below:

FileNotFoundError: File b'\xe2\x80\xaaC:/Users/user/Desktop/tutorial.csv' (or the relevant path) does not exist.

Only when i copy the file into the working directory will it load correct.

Is anyone aware of what might be causing the error?

I had previously loaded other datasets with full filepaths without any problems and I'm currently only encountering issues since I've re-installed my python (via Anaconda package installer).

Edit:

I've found the issue that was causing the problem.

When I was copying the filepath over from the file properties window, I unwittingly copied another character that seems invisible.

Assigning that copied string also gives an unicode error.

Deleting that invisible character made any of above code work.

Body:
Try this and see if it works. This is independent of the path you provide.

pd.read_csv(r'C:\Users\aiLab\Desktop\example.csv')

Here r  is a special character and means raw string. So prefix it to your string literal.

https://www.journaldev.com/23598/python-raw-string:

Python raw string is created by prefixing a string literal with ‘r’
  or ‘R’. Python raw string treats backslash () as a literal character.
  This is useful when we want to have a string that contains backslash
  and don’t want it to be treated as an escape character.


问:
How to trigger a change event manually - angular2
Given the following components:

```<code>@Component({
    selector: 'compA',
    template:  template: `<compB [item]=item></compB>`
})
export class CompA {
    item:any;
    updateItem():void {
        item[name] = "updated name";
    }
}

@Component({
    selector: 'compB',
    template:  template: `<p>{{item[name]}}</p>`
})
export class CompB implements OnInit{
    @Input() item: any;
    someArray: any[];

    ngOnInit():void {
        someArray.push("something");
    }
}
</code>```

As far as I understood that unless the complete item object is changed, angular2 does not recognize the changes on item. Therefore, I'd like to emit a change event manually for item when the updateItem method is called. And afterwards, make the child component i.e. CompB re-rendered as if angular detected a change in the regular way.

Currently, what I have done is to implement the ngOnInit method of for CompB and call that method inside updateItem method through a ViewChild link. Another part of the story is that my actual source has objects like someArray which I'd like to be reset in each render. I'm not sure re-rendering resets someArray though. Currently, I'm resetting them in the ngOnInit method.

So, my question is: how do I trigger re-rendering for changes on deeper elements of a parent object?

Thanks

答:
As far as I understood that unless the complete item object is
  changed, angular2 does not recognize the changes on item.

It's not all that straightforward. You have to distinguish between triggering ngOnChanges when object is mutated and DOM update of the child component. Angular doesn't recognize that item is changed and doesn't trigger a ngOnChanges lifecycle hook, but the DOM will still be updated if you reference particular property of the item in the template. It's because the reference to the object is preserved. Therefore to have this behavior:

And afterwards, make the child component i.e. CompB re-rendered as if
  angular detected a change in the regular way.

You don't have to do anything in particular because you will still have update in the DOM.

Manual change detection

You can insert a change detector and trigger it like this:

```<code>@Component({
    selector: 'compA',
    template:  template: `<compB [item]=item></compB>`
})
export class CompA {
    item:any;
    constructor(cd: ChangeDetectorRef) {}

    updateItem():void {
        item[name] = "updated name";
        this.cd.detectChanges();
    }
}
</code>```

This triggers change detection for the current component and all its children.

But, it won't have any effect in your case because even though Angular doesn't detect change in item it still runs change detection for the child B component and updates the DOM.

Unless you use ChangeDetectionStrategy.OnPush. In this case a way to go for you would be to do a manual check in the ngDoCheck hook of the CompB:

```<code>import { ChangeDetectorRef } from '@angular/core';

export class CompB implements OnInit{
    @Input() item: any;
    someArray: any[];
    previous;

    constructor(cd: ChangeDetectorRef) {}

    ngOnInit():void {
        this.previous = this.item.name;
        someArray.push("something");
    }

    ngDoCheck() {
      if (this.previous !== this.item.name) {
        this.cd.detectChanges();
      }
    }
}
</code>```

You can find more information in the following articles:

Everything you need to know about change detection in Angular article.

The mechanics of DOM updates in Angular

The mechanics of property bindings update in Angular

Body:
Given the following components:

@Component({
    selector: 'compA',
    template:  template: `<compB [item]=item></compB>`
})
export class CompA {
    item:any;
    updateItem():void {
        item[name] = "updated name";
    }
}

@Component({
    selector: 'compB',
    template:  template: `<p>{{item[name]}}</p>`
})
export class CompB implements OnInit{
    @Input() item: any;
    someArray: any[];

    ngOnInit():void {
        someArray.push("something");
    }
}

As far as I understood that unless the complete item object is changed, angular2 does not recognize the changes on item. Therefore, I'd like to emit a change event manually for item when the updateItem method is called. And afterwards, make the child component i.e. CompB re-rendered as if angular detected a change in the regular way.

Currently, what I have done is to implement the ngOnInit method of for CompB and call that method inside updateItem method through a ViewChild link. Another part of the story is that my actual source has objects like someArray which I'd like to be reset in each render. I'm not sure re-rendering resets someArray though. Currently, I'm resetting them in the ngOnInit method.

So, my question is: how do I trigger re-rendering for changes on deeper elements of a parent object?

Thanks

Body:
As far as I understood that unless the complete item object is
  changed, angular2 does not recognize the changes on item.

It's not all that straightforward. You have to distinguish between triggering ngOnChanges when object is mutated and DOM update of the child component. Angular doesn't recognize that item is changed and doesn't trigger a ngOnChanges lifecycle hook, but the DOM will still be updated if you reference particular property of the item in the template. It's because the reference to the object is preserved. Therefore to have this behavior:

And afterwards, make the child component i.e. CompB re-rendered as if
  angular detected a change in the regular way.

You don't have to do anything in particular because you will still have update in the DOM.

Manual change detection

You can insert a change detector and trigger it like this:

@Component({
    selector: 'compA',
    template:  template: `<compB [item]=item></compB>`
})
export class CompA {
    item:any;
    constructor(cd: ChangeDetectorRef) {}

    updateItem():void {
        item[name] = "updated name";
        this.cd.detectChanges();
    }
}

This triggers change detection for the current component and all its children.

But, it won't have any effect in your case because even though Angular doesn't detect change in item it still runs change detection for the child B component and updates the DOM.

Unless you use ChangeDetectionStrategy.OnPush. In this case a way to go for you would be to do a manual check in the ngDoCheck hook of the CompB:

import { ChangeDetectorRef } from '@angular/core';

export class CompB implements OnInit{
    @Input() item: any;
    someArray: any[];
    previous;

    constructor(cd: ChangeDetectorRef) {}

    ngOnInit():void {
        this.previous = this.item.name;
        someArray.push("something");
    }

    ngDoCheck() {
      if (this.previous !== this.item.name) {
        this.cd.detectChanges();
      }
    }
}

You can find more information in the following articles:

Everything you need to know about change detection in Angular article.

The mechanics of DOM updates in Angular

The mechanics of property bindings update in Angular


问:
cursor.forEach is not a function Node.js
Here I am trying to use forEach method to iterate through each document of the cursor and pushing it into the result array but i am getting an error at
forEach

here is my code :

```<code>    var fetch = function(callback) {
    // mongoose.connect('mongodb://localhost/registration');
    mongoose.connect('mongodb://localhost/questiondb');
    var cursor = user.find();
   cursor.forEach(function (doc,err) {
         if(!err)
             resultArray.push(doc);
         else
         {
              callback(false);
         }
   },
     function () {
          callback(resultArray);
     });
};
</code>```

error is :
TypeError: cursor.forEach is not a function

答: Because the cursor is not an array.forEach function must be used on an array.

Body:
Here I am trying to use forEach method to iterate through each document of the cursor and pushing it into the result array but i am getting an error at
forEach

here is my code :

    var fetch = function(callback) {
    // mongoose.connect('mongodb://localhost/registration');
    mongoose.connect('mongodb://localhost/questiondb');
    var cursor = user.find();
   cursor.forEach(function (doc,err) {
         if(!err)
             resultArray.push(doc);
         else
         {
              callback(false);
         }
   },
     function () {
          callback(resultArray);
     });
};

error is :
TypeError: cursor.forEach is not a function


答:
There is variable scope problem , Try this:

var newemail = '';
var x = setInterval(function() {
  var email = $("#test").val();
  if (email != '' && email != newemail) {

    $('#display').append(email)

    $.ajax({
      type: "POST",
      url: 'inputs-saving.php',
      data: ({
        usremail: email
      }),
      success: function(data) {
         currentemail = email;
      }
    });
  }
}, 1000);```

Title: jQuery gathering inputs without submit

Body:
I'm trying to get values from inputs without any action from user and then save it via php to txt file.

This is what I got so far:

var x = setInterval(function() {
var email = $("#test").val();
if(email != '' && email != newemail) {

     $('#display').append(email)

   $.ajax({
      type: "POST",
      url: 'inputs-saving.php',
      data: ({usremail:email}),
      success: function(data) {
      }
    });

}
var newemail = $("#test").val();
}, 1000);

it works almost fine, but I need to check if value changed, because if I input some text it will be constantly writen in file every second.

I have also tried to add something like "var newemail = email", but can't make it work corectly.


问:
How to write a user-defined aggregate function?
I am trying to understand the Java Spark documentation. There is a section called Untyped User Defined Aggregate Functions which has some sample code that I am not able to understand. Here is the code:

```<code>package org.apache.spark.examples.sql;

// $example on:untyped_custom_aggregation$
import java.util.ArrayList;
import java.util.List;

import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.SparkSession;
import org.apache.spark.sql.expressions.MutableAggregationBuffer;
import org.apache.spark.sql.expressions.UserDefinedAggregateFunction;
import org.apache.spark.sql.types.DataType;
import org.apache.spark.sql.types.DataTypes;
import org.apache.spark.sql.types.StructField;
import org.apache.spark.sql.types.StructType;
// $example off:untyped_custom_aggregation$

public class JavaUserDefinedUntypedAggregation {

  // $example on:untyped_custom_aggregation$
  public static class MyAverage extends UserDefinedAggregateFunction {

    private StructType inputSchema;
    private StructType bufferSchema;

    public MyAverage() {
      List<StructField> inputFields = new ArrayList<>();
      inputFields.add(DataTypes.createStructField("inputColumn", DataTypes.LongType, true));
      inputSchema = DataTypes.createStructType(inputFields);

      List<StructField> bufferFields = new ArrayList<>();
      bufferFields.add(DataTypes.createStructField("sum", DataTypes.LongType, true));
      bufferFields.add(DataTypes.createStructField("count", DataTypes.LongType, true));
      bufferSchema = DataTypes.createStructType(bufferFields);
    }
    // Data types of input arguments of this aggregate function
    public StructType inputSchema() {
      return inputSchema;
    }
    // Data types of values in the aggregation buffer
    public StructType bufferSchema() {
      return bufferSchema;
    }
    // The data type of the returned value
    public DataType dataType() {
      return DataTypes.DoubleType;
    }
    // Whether this function always returns the same output on the identical input
    public boolean deterministic() {
      return true;
    }
    // Initializes the given aggregation buffer. The buffer itself is a `Row` that in addition to
    // standard methods like retrieving a value at an index (e.g., get(), getBoolean()), provides
    // the opportunity to update its values. Note that arrays and maps inside the buffer are still
    // immutable.
    public void initialize(MutableAggregationBuffer buffer) {
      buffer.update(0, 0L);
      buffer.update(1, 0L);
    }
    // Updates the given aggregation buffer `buffer` with new input data from `input`
    public void update(MutableAggregationBuffer buffer, Row input) {
      if (!input.isNullAt(0)) {
        long updatedSum = buffer.getLong(0) + input.getLong(0);
        long updatedCount = buffer.getLong(1) + 1;
        buffer.update(0, updatedSum);
        buffer.update(1, updatedCount);
      }
    }
    // Merges two aggregation buffers and stores the updated buffer values back to `buffer1`
    public void merge(MutableAggregationBuffer buffer1, Row buffer2) {
      long mergedSum = buffer1.getLong(0) + buffer2.getLong(0);
      long mergedCount = buffer1.getLong(1) + buffer2.getLong(1);
      buffer1.update(0, mergedSum);
      buffer1.update(1, mergedCount);
    }
    // Calculates the final result
    public Double evaluate(Row buffer) {
      return ((double) buffer.getLong(0)) / buffer.getLong(1);
    }
  }
  // $example off:untyped_custom_aggregation$

  public static void main(String[] args) {
    SparkSession spark = SparkSession
      .builder()
      .appName("Java Spark SQL user-defined DataFrames aggregation example")
      .getOrCreate();

    // $example on:untyped_custom_aggregation$
    // Register the function to access it
    spark.udf().register("myAverage", new MyAverage());

    Dataset<Row> df = spark.read().json("examples/src/main/resources/employees.json");
    df.createOrReplaceTempView("employees");
    df.show();
    // +-------+------+
    // |   name|salary|
    // +-------+------+
    // |Michael|  3000|
    // |   Andy|  4500|
    // | Justin|  3500|
    // |  Berta|  4000|
    // +-------+------+

    Dataset<Row> result = spark.sql("SELECT myAverage(salary) as average_salary FROM employees");
    result.show();
    // +--------------+
    // |average_salary|
    // +--------------+
    // |        3750.0|
    // +--------------+
    // $example off:untyped_custom_aggregation$

    spark.stop();
  }
}
</code>```

My doubts related to the above code are:

Whenever I want to create a UDF, should I have the functions initialize, update and merge?

What is the significance of the variables inputSchema and bufferSchema? I'm surprised they exist because they are never used to create any DataFrames at all. Are they supposed to be present in every UDF? If yes, then are they supposed to be the exact same name?

Why are the getters of inputSchema and bufferSchema not named getInputSchema() and getBufferSchema()? Why are there no setters of these variables?

What is the significance of the function called deterministic() here? Please give a scenario when it would be useful to call this function.

In general I want to know how to how to write a user defined aggregate function in Spark.

答:
Whenever I want to create a UDF, should I have the functions initialize, update and merge

UDF stands for user-defined function while the methods initialize, update, and merge are for user-defined aggregate functions (aka UDAF).

A UDF is a function that works with a single row to (usually) produce one row (e.g. upper function).

A UDAF is a function that works with zero or many rows to produce one row (e.g. count aggregate function).

You certainly don't have to (and won't be able to) have the functions initialize, update and merge for user-defined functions (UDFs).

Use any of the udf functions to define and register a UDF.

```<code>val myUpper = udf { (s: String) => s.toUpperCase }
</code>```

How to how to write a user defined aggregate function in Spark.

What is the significance of the variables inputSchema and bufferSchema?

(Shameless plug: I've been describing UDAFs in Mastering Spark SQL book in UserDefinedAggregateFunction — Contract for User-Defined Untyped Aggregate Functions (UDAFs))

Quoting Untyped User-Defined Aggregate Functions:

```<code>// Data types of input arguments of this aggregate function
def inputSchema: StructType = StructType(StructField("inputColumn", LongType) :: Nil)

// Data types of values in the aggregation buffer
def bufferSchema: StructType = {
  StructType(StructField("sum", LongType) :: StructField("count", LongType) :: Nil)
}
</code>```

In other words, inputSchema is what you expect from the input while bufferSchema is what you keep temporarily while doing aggregation.

Why are there no setters of these variables?

They are extension points that are managed by Spark.

What is the significance of the function called deterministic() here?

Quoting Untyped User-Defined Aggregate Functions:

```<code>// Whether this function always returns the same output on the identical input
def deterministic: Boolean = true
</code>```

Please give a scenario when it would be useful to call this function.

That's something I'm still working on and so can't answer today.

Body:
I am trying to understand the Java Spark documentation. There is a section called Untyped User Defined Aggregate Functions which has some sample code that I am not able to understand. Here is the code:

package org.apache.spark.examples.sql;

// $example on:untyped_custom_aggregation$
import java.util.ArrayList;
import java.util.List;

import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.SparkSession;
import org.apache.spark.sql.expressions.MutableAggregationBuffer;
import org.apache.spark.sql.expressions.UserDefinedAggregateFunction;
import org.apache.spark.sql.types.DataType;
import org.apache.spark.sql.types.DataTypes;
import org.apache.spark.sql.types.StructField;
import org.apache.spark.sql.types.StructType;
// $example off:untyped_custom_aggregation$

public class JavaUserDefinedUntypedAggregation {

  // $example on:untyped_custom_aggregation$
  public static class MyAverage extends UserDefinedAggregateFunction {

    private StructType inputSchema;
    private StructType bufferSchema;

    public MyAverage() {
      List<StructField> inputFields = new ArrayList<>();
      inputFields.add(DataTypes.createStructField("inputColumn", DataTypes.LongType, true));
      inputSchema = DataTypes.createStructType(inputFields);

      List<StructField> bufferFields = new ArrayList<>();
      bufferFields.add(DataTypes.createStructField("sum", DataTypes.LongType, true));
      bufferFields.add(DataTypes.createStructField("count", DataTypes.LongType, true));
      bufferSchema = DataTypes.createStructType(bufferFields);
    }
    // Data types of input arguments of this aggregate function
    public StructType inputSchema() {
      return inputSchema;
    }
    // Data types of values in the aggregation buffer
    public StructType bufferSchema() {
      return bufferSchema;
    }
    // The data type of the returned value
    public DataType dataType() {
      return DataTypes.DoubleType;
    }
    // Whether this function always returns the same output on the identical input
    public boolean deterministic() {
      return true;
    }
    // Initializes the given aggregation buffer. The buffer itself is a `Row` that in addition to
    // standard methods like retrieving a value at an index (e.g., get(), getBoolean()), provides
    // the opportunity to update its values. Note that arrays and maps inside the buffer are still
    // immutable.
    public void initialize(MutableAggregationBuffer buffer) {
      buffer.update(0, 0L);
      buffer.update(1, 0L);
    }
    // Updates the given aggregation buffer `buffer` with new input data from `input`
    public void update(MutableAggregationBuffer buffer, Row input) {
      if (!input.isNullAt(0)) {
        long updatedSum = buffer.getLong(0) + input.getLong(0);
        long updatedCount = buffer.getLong(1) + 1;
        buffer.update(0, updatedSum);
        buffer.update(1, updatedCount);
      }
    }
    // Merges two aggregation buffers and stores the updated buffer values back to `buffer1`
    public void merge(MutableAggregationBuffer buffer1, Row buffer2) {
      long mergedSum = buffer1.getLong(0) + buffer2.getLong(0);
      long mergedCount = buffer1.getLong(1) + buffer2.getLong(1);
      buffer1.update(0, mergedSum);
      buffer1.update(1, mergedCount);
    }
    // Calculates the final result
    public Double evaluate(Row buffer) {
      return ((double) buffer.getLong(0)) / buffer.getLong(1);
    }
  }
  // $example off:untyped_custom_aggregation$

  public static void main(String[] args) {
    SparkSession spark = SparkSession
      .builder()
      .appName("Java Spark SQL user-defined DataFrames aggregation example")
      .getOrCreate();

    // $example on:untyped_custom_aggregation$
    // Register the function to access it
    spark.udf().register("myAverage", new MyAverage());

    Dataset<Row> df = spark.read().json("examples/src/main/resources/employees.json");
    df.createOrReplaceTempView("employees");
    df.show();
    // +-------+------+
    // |   name|salary|
    // +-------+------+
    // |Michael|  3000|
    // |   Andy|  4500|
    // | Justin|  3500|
    // |  Berta|  4000|
    // +-------+------+

    Dataset<Row> result = spark.sql("SELECT myAverage(salary) as average_salary FROM employees");
    result.show();
    // +--------------+
    // |average_salary|
    // +--------------+
    // |        3750.0|
    // +--------------+
    // $example off:untyped_custom_aggregation$

    spark.stop();
  }
}

My doubts related to the above code are:

Whenever I want to create a UDF, should I have the functions initialize, update and merge?

What is the significance of the variables inputSchema and bufferSchema? I'm surprised they exist because they are never used to create any DataFrames at all. Are they supposed to be present in every UDF? If yes, then are they supposed to be the exact same name?

Why are the getters of inputSchema and bufferSchema not named getInputSchema() and getBufferSchema()? Why are there no setters of these variables?

What is the significance of the function called deterministic() here? Please give a scenario when it would be useful to call this function.

In general I want to know how to how to write a user defined aggregate function in Spark.

Body:
Whenever I want to create a UDF, should I have the functions initialize, update and merge

UDF stands for user-defined function while the methods initialize, update, and merge are for user-defined aggregate functions (aka UDAF).

A UDF is a function that works with a single row to (usually) produce one row (e.g. upper function).

A UDAF is a function that works with zero or many rows to produce one row (e.g. count aggregate function).

You certainly don't have to (and won't be able to) have the functions initialize, update and merge for user-defined functions (UDFs).

Use any of the udf functions to define and register a UDF.

val myUpper = udf { (s: String) => s.toUpperCase }

How to how to write a user defined aggregate function in Spark.

What is the significance of the variables inputSchema and bufferSchema?

(Shameless plug: I've been describing UDAFs in Mastering Spark SQL book in UserDefinedAggregateFunction — Contract for User-Defined Untyped Aggregate Functions (UDAFs))

Quoting Untyped User-Defined Aggregate Functions:

// Data types of input arguments of this aggregate function
def inputSchema: StructType = StructType(StructField("inputColumn", LongType) :: Nil)

// Data types of values in the aggregation buffer
def bufferSchema: StructType = {
  StructType(StructField("sum", LongType) :: StructField("count", LongType) :: Nil)
}

In other words, inputSchema is what you expect from the input while bufferSchema is what you keep temporarily while doing aggregation.

Why are there no setters of these variables?

They are extension points that are managed by Spark.

What is the significance of the function called deterministic() here?

Quoting Untyped User-Defined Aggregate Functions:

// Whether this function always returns the same output on the identical input
def deterministic: Boolean = true

Please give a scenario when it would be useful to call this function.

That's something I'm still working on and so can't answer today.


问:
Programmatically binding List to ListBox
Let's say, for instance, I have the following extremely simple window:

```<code><Window x:Class="CalendarGenerator.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1"
        Height="300"
        Width="447">
  <Grid>
    <ListBox Margin="12,40,0,12"
             Name="eventList"
             HorizontalAlignment="Left"
             Width="134" />
  </Grid>
</Window>
</code>```

And a simple list defined as:

```<code>List<String> ListOfNames = new List<String>();
</code>```

And let's assume that the list has several names in it. How would I go about binding the List to the ListBox using as much code-behind as possible?

答:
First you'd need to give your ListBox a name so that it's accessible from your code behind (edit I note you've already done this, so I'll change my example ListBox's name to reflect yours):

```<code><ListBox x:Name="eventList" ... />
</code>```

Then it's as simple as setting the ListBox's ItemsSource property to your list:

```<code>eventList.ItemsSource = ListOfNames;
</code>```

Since you've defined your "ListOfNames" object as a List<String>, the ListBox won't automatically reflect changes made to the list. To get WPF's databinding to react to changes within the list, define it as an ObservableCollection<String> instead.

OwnerDisplayName: Jason Miesionczek

Body:
Let's say, for instance, I have the following extremely simple window:

<Window x:Class="CalendarGenerator.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1"
        Height="300"
        Width="447">
  <Grid>
    <ListBox Margin="12,40,0,12"
             Name="eventList"
             HorizontalAlignment="Left"
             Width="134" />
  </Grid>
</Window>

And a simple list defined as:

List<String> ListOfNames = new List<String>();

And let's assume that the list has several names in it. How would I go about binding the List to the ListBox using as much code-behind as possible?

Body:
First you'd need to give your ListBox a name so that it's accessible from your code behind (edit I note you've already done this, so I'll change my example ListBox's name to reflect yours):

<ListBox x:Name="eventList" ... />

Then it's as simple as setting the ListBox's ItemsSource property to your list:

eventList.ItemsSource = ListOfNames;

Since you've defined your "ListOfNames" object as a List<String>, the ListBox won't automatically reflect changes made to the list. To get WPF's databinding to react to changes within the list, define it as an ObservableCollection<String> instead.

OwnerDisplayName: Matt Hamilton

LastEditorDisplayName: Matt Hamilton


问:
How to use the same name classes but in separate styles
see the example to understand:

```<code>    <!--Standard Bootstrap -->
    <link href="/build/css/site/bootstrap.min.css" rel="stylesheet">

    <!-- Material Design Bootstrap -->
    <link href="/build/css/site/mdb.min.css" rel="stylesheet">
</code>```

so i want a thing like it:

```<code>    <div class="btn btn-danger" >Standard Bootstrap Button</div>
    <div class="btn btn-danger" >Material Design Bootstrap Button</div>
</code>```

The name of the classes are the same. But they are in two separate styles.
How can I use the two styles as I said?

Forgive me for the bad English.

Body:
see the example to understand:

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

    <link href="/build/css/site/mdb.min.css" rel="stylesheet">

so i want a thing like it:

Standard Bootstrap Button

Material Design Bootstrap Button

The name of the classes are the same. But they are in two separate styles.
How can I use the two styles as I said?

Forgive me for the bad English.

Body:
Browser's stylesheet

Included by <link> tag

Nested in <head><style> tag

Inline, e.g. <a style="display: none">

That's the order of loading cascading stylesheets in your document. You can extend style of any class in any further place, but cannot define two classes with same name with different styles. It will override in given order.


问:
Chef server - permissions to specific cookbook
Does chef-server have any way to allow/disallow downloading specific cookbook? Let us say, organization has few projects and there are cookbooks installing environment for them. I would like to set client A permission to download only A cookbook and B - only B.

Maybe this could be achieved by creating multpiple organizations, for example per project?

答: https://docs.chef.io/auth.html has a full overview of the Chef Server ACL system. Setting up what you describe would be incredibly complex but is theoretically possible. Why do you think you want to do this?</p>


问:
Keeping table first row and first column fixed remaining table cell should scroll horizontal scroll bar
Hi everyone please me i'm facing an issue in css
I have created one table in html keeping table first row and first column fixed remaining table cell should scroll horizontal scroll bar
For table first row and first column i have wrote style:"position:absolute" after that table first column going out of the table i cant able to give height and fit inside the tableI have sent image which i'm facing issue for that Please help me!</p>

答:
```<code>Try this code. (dont forget to include bootstrap files)
**HTML**

<div class="container">
  <table class="table table-fixed">
    <thead>
      <tr>
        <th class="col-xs-3">First Name</th>
        <th class="col-xs-3">Last Name</th>
        <th class="col-xs-6">E-mail</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td class="col-xs-3">John</td>
        <td class="col-xs-3">Doe</td>
        <td class="col-xs-6">johndoe@email.com</td>
      </tr>

      <tr>
        <td class="col-xs-3">John</td>
        <td class="col-xs-3">Doe</td>
        <td class="col-xs-6">johndoe@email.com</td>
      </tr>
      <tr>
        <td class="col-xs-3">John</td>
        <td class="col-xs-3">Doe</td>
        <td class="col-xs-6">johndoe@email.com</td>
      </tr>
      <tr>
        <td class="col-xs-3">John</td>
        <td class="col-xs-3">Doe</td>
        <td class="col-xs-6">johndoe@email.com</td>
      </tr>
      <tr>
        <td class="col-xs-3">John</td>
        <td class="col-xs-3">Doe</td>
        <td class="col-xs-6">johndoe@email.com</td>
      </tr>
      <tr>
        <td class="col-xs-3">John</td>
        <td class="col-xs-3">Doe</td>
        <td class="col-xs-6">johndoe@email.com</td>
      </tr>
      <tr>
        <td class="col-xs-3">John</td>
        <td class="col-xs-3">Doe</td>
        <td class="col-xs-6">johndoe@email.com</td>
      </tr>
      <tr>
        <td class="col-xs-3">John</td>
        <td class="col-xs-3">Doe</td>
        <td class="col-xs-6">johndoe@email.com</td>
      </tr>
      <tr>
        <td class="col-xs-3">John</td>
        <td class="col-xs-3">Doe</td>
        <td class="col-xs-6">johndoe@email.com</td>
      </tr>
      <tr>
        <td class="col-xs-3">John</td>
        <td class="col-xs-3">Doe</td>
        <td class="col-xs-6">johndoe@email.com</td>
      </tr>
      <tr>
        <td class="col-xs-3">John</td>
        <td class="col-xs-3">Doe</td>
        <td class="col-xs-6">johndoe@email.com</td>
      </tr>
      <tr>
        <td class="col-xs-3">John</td>
        <td class="col-xs-3">Doe</td>
        <td class="col-xs-6">johndoe@email.com</td>
      </tr>
      <tr>
        <td class="col-xs-3">John</td>
        <td class="col-xs-3">Doe</td>
        <td class="col-xs-6">johndoe@email.com</td>
      </tr>
      <tr>
        <td class="col-xs-3">John</td>
        <td class="col-xs-3">Doe</td>
        <td class="col-xs-6">johndoe@email.com</td>
      </tr>
      <tr>
        <td class="col-xs-3">John</td>
        <td class="col-xs-3">Doe</td>
        <td class="col-xs-6">johndoe@email.com</td>
      </tr>
      <tr>
        <td class="col-xs-3">John</td>
        <td class="col-xs-3">Doe</td>
        <td class="col-xs-6">johndoe@email.com</td>
      </tr>
      <tr>
        <td class="col-xs-3">John</td>
        <td class="col-xs-3">Doe</td>
        <td class="col-xs-6">johndoe@email.com</td>
      </tr>
      <tr>
        <td class="col-xs-3">John</td>
        <td class="col-xs-3">Doe</td>
        <td class="col-xs-6">johndoe@email.com</td>
      </tr>
      <tr>
        <td class="col-xs-3">John</td>
        <td class="col-xs-3">Doe</td>
        <td class="col-xs-6">johndoe@email.com</td>
      </tr>
      <tr>
        <td class="col-xs-3">John</td>
        <td class="col-xs-3">Doe</td>
        <td class="col-xs-6">johndoe@email.com</td>
      </tr>
    </tbody>
  </table>
</div>

**CSS**

body{
  background-color: #bdc3c7;
}
.table-fixed{
  width: 100%;
  background-color: #f3f3f3;
  tbody{
    height:200px;
    overflow-y:auto;
    width: 100%;
    }
  thead,tbody,tr,td,th{
    display:block;
  }
  tbody{
    td{
      float:left;
    }
  }
  thead {
    tr{
      th{
        float:left;
       background-color: #f39c12;
       border-color:#e67e22;
      }
    }
  }
}
</code>```


问:
ViewModel and Data Binding
Android has recently introduced Architecture Components and in particular a ViewModel, which is

designed to store and manage UI-related data so that the data survives configuration changes such as screen rotations

In example provided by Google, ViewModel is used like this:

```<code>public class MyActivity extends AppCompatActivity {
    public void onCreate(Bundle savedInstanceState) {
        MyViewModel model = ViewModelProviders.of(this).get(MyViewModel.class);
        model.getUsers().observe(this, users -> {
            // update UI
        });
    }
}
</code>```

Question: How does ViewModel suppose to correlate with the Data Binding?

I mean, in case of data binding there is going to be a binding which provides data for the UI.

Is it going to look like this:

```<code>...
model.getUsers().observe(this, users -> {
  // update binding, that will auto-update the UI?
});
...
</code>```

答:
Your layout_name.xml file would look like

```<code><layout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools">

   <data>
       <import type="android.view.View"/>
       <variable
           name="model"
           type="com.yourpackage.ViewModelName"/>
   </data>

   <RelativeLayout
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:background="@color/white"
       android:visibility="@{model.someVariable == true ? View.VISIBLE : View.GONE}">

   </RelativeLayout>
</layout>
</code>```

Your Activity class would look like

```<code>public class YourActivityName extends BaseActivity
{
    private ViewModelName viewModelVariable;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ViewModelName viewModelVariable = new ViewModelName();
        ViewDataBinding viewDataBinding = DataBindingUtil.setContentView(this, R.layout.layout_name);
        viewDataBinding.setVariable(BR.model, viewModelVariable);

    }
}
</code>```

ViewModel class would look like

```<code>public class ViewModelName extends BaseObservable{
    //Logic and variables for view model
    public boolean someVariable;
}
</code>```

Title: ViewModel and Data Binding

Body:
Android has recently introduced Architecture Components and in particular a ViewModel, which is

designed to store and manage UI-related data so that the data survives configuration changes such as screen rotations

In example provided by Google, ViewModel is used like this:

public class MyActivity extends AppCompatActivity {
    public void onCreate(Bundle savedInstanceState) {
        MyViewModel model = ViewModelProviders.of(this).get(MyViewModel.class);
        model.getUsers().observe(this, users -> {
            // update UI
        });
    }
}

Question: How does ViewModel suppose to correlate with the Data Binding?

I mean, in case of data binding there is going to be a binding which provides data for the UI.

Is it going to look like this:

...
model.getUsers().observe(this, users -> {
  // update binding, that will auto-update the UI?
});
...

Body:
Your layout_name.xml file would look like

<layout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools">

   <data>
       <import type="android.view.View"/>
       <variable
           name="model"
           type="com.yourpackage.ViewModelName"/>
   </data>

   <RelativeLayout
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:background="@color/white"
       android:visibility="@{model.someVariable == true ? View.VISIBLE : View.GONE}">

   </RelativeLayout>
</layout>

Your Activity class would look like

public class YourActivityName extends BaseActivity
{
    private ViewModelName viewModelVariable;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ViewModelName viewModelVariable = new ViewModelName();
        ViewDataBinding viewDataBinding = DataBindingUtil.setContentView(this, R.layout.layout_name);
        viewDataBinding.setVariable(BR.model, viewModelVariable);

    }
}

ViewModel class would look like

public class ViewModelName extends BaseObservable{
    //Logic and variables for view model
    public boolean someVariable;
}


问:
python numpy: iterate for different conditions without using a loop
I am trying to iterate over numpy arrays and generate an output, which has conditions similar to that described below:

```<code>min1 = 3
max1 = 1
a1 = np.array([1, 2, 5, 3, 4])
a2 = np.array([5, 2, 6, 2, 1])
output = np.zeros(5)
for i in range(0, 5):
  if((a1[i] - a2[i]) > min1):
    output[i] = 3 * (a1[i] - a2[i])

  if((a1[i] - a2[i]) < max1):
    output = 5 * (a1[i] - a2[i])
</code>```

I need to optimize the above code, so that I utilize the numpy functionalities as the best and also avoid using a loop. How should I do it?

答:
The operation a1[i]-a2[i] is done 4 times in a single iteration
Save it as a variable to save 3*5 = 15 computations</p>

Body:
I am trying to iterate over numpy arrays and generate an output, which has conditions similar to that described below:

min1 = 3
max1 = 1
a1 = np.array([1, 2, 5, 3, 4])
a2 = np.array([5, 2, 6, 2, 1])
output = np.zeros(5)
for i in range(0, 5):
  if((a1[i] - a2[i]) > min1):
    output[i] = 3 * (a1[i] - a2[i])

  if((a1[i] - a2[i]) < max1):
    output = 5 * (a1[i] - a2[i])

I need to optimize the above code, so that I utilize the numpy functionalities as the best and also avoid using a loop. How should I do it?


问:
Date time error while creating table in mysql
I am getting an date/time  error while creating table in my sql ? how can i fix this?

```<code>create table ibi.stpl_toll_day_fare_fy_ex as
select
cast(date_time as date) as calendar_date,
</code>```

I get this error

Error code :1292.incorrect datatime value.

答: Please check if the value in the date_time field of the existing table has the right data (if may have non relevant value to date)</p>

Body:
I am getting an date/time  error while creating table in my sql ? how can i fix this?

create table ibi.stpl_toll_day_fare_fy_ex as
select
cast(date_time as date) as calendar_date,

I get this error

Error code :1292.incorrect datatime value.


问:
How is this strict aliasing undefined behaviour?
I know, I saw it already but I couldn't find any good explanation why is this undefined behaviour:

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

//Common union for both types
union float_int {
    float f;
    uint32_t i;
};

int main(void) {
    union float_int fi;
    //This should be problematic
    uint32_t* i_ptr = (uint32_t *)&fi.f;

    fi.f = 10.0f;
    printf("%f : %u\r\n", fi.f, fi.i); //Prints: 10.000000 : 1092616192 which is OK
    printf("%u\r\n", *i_ptr); //Prints: 1092616192 which is also OK

    return 0;
}
</code>```

If we check memory representation, both are 4-bytes long so there is no memory overflow in pointing or similar.

How is this undefined behaviour?

```<code>int main() {
    union float_int fi;
    void* v_ptr = &fi.f;
    uint32_t* i_ptr = (uint32_t *)v_ptr;
}
</code>```

Is this code still undefined behaviour? I want to read float number as unsigned integer 32-bits.

Why is using memcpy the only available way of doing it?

答:
This is not strict aliasing, it is a violation of strict aliasing.

First, you are doing

```<code> uint32_t* i_ptr = (uint32_t *)&fi.f;   //converting to a non-character type pointer
</code>```

and then, you try to access that by

```<code>  printf("%u\r\n", *i_ptr);   //access value via incompatible lvalue expr.
</code>```

which causes the issue. float and uint32_t are not compatible types.

Quoting C11, chapter §6.5/P7

An object shall have its stored value accessed only by an lvalue expression that has one of
  the following types: 88)

— a type compatible with the effective type of the object,

— a qualified version of a type compatible with the effective type of the object,

— a type that is the signed or unsigned type corresponding to the effective type of the
  object,

— a type that is the signed or unsigned type corresponding to a qualified version of the
  effective type of the object,

— an aggregate or union type that includes one of the aforementioned types among its
  members (including, recursively, a member of a subaggregate or contained union), or

— a character type.

In reply to the comment, let's see C11, chapter §6.2.6.1

Values stored in non-bit-field objects of any other object type consist of n × CHAR_BIT
  bits, where n is the size of an object of that type, in bytes. The value may be copied into
  an object of type unsigned char [n] (e.g., by memcpy); the resulting set of bytes is
  called the object representation of the value.

and

Certain object representations need not represent a value of the object type. If the stored
  value of an object has such a representation and is read by an lvalue expression that does
  not have character type, the behavior is undefined. [...] Such a representation is called
  a trap representation.

Body:
I know, I saw it already but I couldn't find any good explanation why is this undefined behaviour:

#include <stdio.h>
#include <stdint.h>

//Common union for both types
union float_int {
    float f;
    uint32_t i;
};

int main(void) {
    union float_int fi;
    //This should be problematic
    uint32_t* i_ptr = (uint32_t *)&fi.f;

    fi.f = 10.0f;
    printf("%f : %u\r\n", fi.f, fi.i); //Prints: 10.000000 : 1092616192 which is OK
    printf("%u\r\n", *i_ptr); //Prints: 1092616192 which is also OK

    return 0;
}

If we check memory representation, both are 4-bytes long so there is no memory overflow in pointing or similar.

How is this undefined behaviour?

int main() {
    union float_int fi;
    void* v_ptr = &fi.f;
    uint32_t* i_ptr = (uint32_t *)v_ptr;
}

Is this code still undefined behaviour? I want to read float number as unsigned integer 32-bits.

Why is using memcpy the only available way of doing it?

Body:
This is not strict aliasing, it is a violation of strict aliasing.

First, you are doing

 uint32_t* i_ptr = (uint32_t *)&fi.f;   //converting to a non-character type pointer

and then, you try to access that by

  printf("%u\r\n", *i_ptr);   //access value via incompatible lvalue expr.

which causes the issue. float and uint32_t are not compatible types.

Quoting C11, chapter §6.5/P7

An object shall have its stored value accessed only by an lvalue expression that has one of
  the following types: 88)

— a type compatible with the effective type of the object,

— a qualified version of a type compatible with the effective type of the object,

— a type that is the signed or unsigned type corresponding to the effective type of the
  object,

— a type that is the signed or unsigned type corresponding to a qualified version of the
  effective type of the object,

— an aggregate or union type that includes one of the aforementioned types among its
  members (including, recursively, a member of a subaggregate or contained union), or

— a character type.

In reply to the comment, let's see C11, chapter §6.2.6.1

Values stored in non-bit-field objects of any other object type consist of n × CHAR_BIT
  bits, where n is the size of an object of that type, in bytes. The value may be copied into
  an object of type unsigned char [n] (e.g., by memcpy); the resulting set of bytes is
  called the object representation of the value.

and

Certain object representations need not represent a value of the object type. If the stored
  value of an object has such a representation and is read by an lvalue expression that does
  not have character type, the behavior is undefined. [...] Such a representation is called
  a trap representation.


问:
Aggregating DataTable Without LINQ
I want to aggregate a datatables rows based on some distinct values. I have to use Select and Compute methods or other non-linq approaches.
My question is: how can I aggregate (sum, count, min and ...) and grouping fields, and get results just like the sql server tables. Consider I have a table with four columns a, b, c, d. When I want to aggregate 'a' based on 'b, I can write:

```<code>Select sum(a) as 'a', b
from myTable
group by b
</code>```

And the sql sever make a table with two columns, 'a' and 'b', so how can i do this in C# and using DataTables?
I saw the examples of DataTable.Compute() in MSDN and the other related sources for aggregating and grouping the data in a datatable, but it return just an object value and it doesn't useful for grouping rows in datatable. in my problem, the user deiced to using of sum, min, max, or ... at run time, and  I trying to find a solution  for creating some dynamic queries.

答: You should use Dynamic LINQ. It allows you to execute LINQ based on string inputs.

Title: Aggregating DataTable Without LINQ

Body:
I want to aggregate a datatables rows based on some distinct values. I have to use Select and Compute methods or other non-linq approaches.
My question is: how can I aggregate (sum, count, min and ...) and grouping fields, and get results just like the sql server tables. Consider I have a table with four columns a, b, c, d. When I want to aggregate 'a' based on 'b, I can write:

Select sum(a) as 'a', b
from myTable
group by b

And the sql sever make a table with two columns, 'a' and 'b', so how can i do this in C# and using DataTables?
I saw the examples of DataTable.Compute() in MSDN and the other related sources for aggregating and grouping the data in a datatable, but it return just an object value and it doesn't useful for grouping rows in datatable. in my problem, the user deiced to using of sum, min, max, or ... at run time, and  I trying to find a solution  for creating some dynamic queries.