问:
silhouette calculation in R for a large data
I want to calculate silhouette for cluster evaluation. There are some packages in R, for example cluster and clValid. Here is my code using cluster package:

```<code># load the data
# a data from the UCI website with 434874 obs. and  3 variables
data <- read.csv("./data/spatial_network.txt",sep="\t",header =  F)

# apply kmeans
km_res <- kmeans(data,20,iter.max = 1000,
               nstart=20,algorithm="MacQueen")

# calculate silhouette
library(cluster)
sil <- silhouette(km_res$cluster, dist(data))

# plot silhouette
library(factoextra)
fviz_silhouette(sil)
</code>```

The code works well for smaller data, say data with 50,000 obs, however I get an error like "Error: cannot allocate vector of size 704.5 Gb" when the data size is a bit large. This might be problem for Dunn index and other internal indices for large datasets.

I have 32GB RAM in my computer. The problem comes from calculating dist(data). I am wondering if it is possible to not calculating dist(data) in advance, and calculate corresponding distances when it is required in the silhouette formula.

I appreciate your help regarding this problem and how I can calculate silhouette for large and very large datasets.

答:
If it is possible to calculate the Silhouette index, without using the distance matrix, alternatively you can use the clues package, optimizing both the time and the memory used by the cluster package. Here is an example:

```<code>library(rbenchmark)
library(cluster)
library(clues)

set.seed(123)
x = c(rnorm(1000,0,0.9), rnorm(1000,4,1), rnorm(1000,-5,1))
y = c(rnorm(1000,0,0.9), rnorm(1000,6,1), rnorm(1000, 5,1))
cluster = rep(as.factor(1:3),each = 1000)

df <- cbind(x,y)
head(df)
               x           y
[1,] -0.50442808 -0.13527673
[2,] -0.20715974 -0.29498142
[3,]  1.40283748 -1.30334876
[4,]  0.06345755 -0.62755613
[5,]  0.11635896  2.33864121
[6,]  1.54355849 -0.03367351
</code>```

Runtime comparison between the two functions

```<code> benchmark(f1 = silhouette(as.integer(cluster), dist = dist(df)),
           f2 = get_Silhouette(y = df, mem = cluster))
  test replications elapsed relative user.self sys.self user.child sys.child
1   f1          100   15.16    1.902     13.00     1.64         NA        NA
2   f2          100    7.97    1.000      7.76     0.00         NA        NA
</code>```

Comparison in memory usage between the two functions

```<code>library(pryr)
object_size(silhouette(as.integer(cluster), dist = dist(df)))
73.9 kB
object_size(get_Silhouette(y = df, mem = cluster))
36.6 kB
</code>```

As a conclusion clues::get_Silhouette, it reduces the time and memory used to the same.

Body:
I want to calculate silhouette for cluster evaluation. There are some packages in R, for example cluster and clValid. Here is my code using cluster package:

# load the data
# a data from the UCI website with 434874 obs. and  3 variables
data <- read.csv("./data/spatial_network.txt",sep="\t",header =  F)

# apply kmeans
km_res <- kmeans(data,20,iter.max = 1000,
               nstart=20,algorithm="MacQueen")

# calculate silhouette
library(cluster)
sil <- silhouette(km_res$cluster, dist(data))

# plot silhouette
library(factoextra)
fviz_silhouette(sil)

The code works well for smaller data, say data with 50,000 obs, however I get an error like "Error: cannot allocate vector of size 704.5 Gb" when the data size is a bit large. This might be problem for Dunn index and other internal indices for large datasets.

I have 32GB RAM in my computer. The problem comes from calculating dist(data). I am wondering if it is possible to not calculating dist(data) in advance, and calculate corresponding distances when it is required in the silhouette formula.

I appreciate your help regarding this problem and how I can calculate silhouette for large and very large datasets.

Body:
If it is possible to calculate the Silhouette index, without using the distance matrix, alternatively you can use the clues package, optimizing both the time and the memory used by the cluster package. Here is an example:

library(rbenchmark)
library(cluster)
library(clues)

set.seed(123)
x = c(rnorm(1000,0,0.9), rnorm(1000,4,1), rnorm(1000,-5,1))
y = c(rnorm(1000,0,0.9), rnorm(1000,6,1), rnorm(1000, 5,1))
cluster = rep(as.factor(1:3),each = 1000)

df <- cbind(x,y)
head(df)
               x           y
[1,] -0.50442808 -0.13527673
[2,] -0.20715974 -0.29498142
[3,]  1.40283748 -1.30334876
[4,]  0.06345755 -0.62755613
[5,]  0.11635896  2.33864121
[6,]  1.54355849 -0.03367351

Runtime comparison between the two functions

 benchmark(f1 = silhouette(as.integer(cluster), dist = dist(df)),
           f2 = get_Silhouette(y = df, mem = cluster))
  test replications elapsed relative user.self sys.self user.child sys.child
1   f1          100   15.16    1.902     13.00     1.64         NA        NA
2   f2          100    7.97    1.000      7.76     0.00         NA        NA

Comparison in memory usage between the two functions

library(pryr)
object_size(silhouette(as.integer(cluster), dist = dist(df)))
73.9 kB
object_size(get_Silhouette(y = df, mem = cluster))
36.6 kB

As a conclusion clues::get_Silhouette, it reduces the time and memory used to the same.


来源: stackexchange

问:
Android: how to hide ActionBar on certain activities
I've developed a simple demo application with a splash screen a map and some regular screens.

I have an action bar at the top that contains a logo. It all looks fine on my phone (Galaxy s1 I9000 V2.3) but when i test it on Galaxy s2 v4 the action bar appears also in the splash screen and in the map screen.

The spalsh and map activity are not even inheriting from ActionBarActivity so how is that possible and how can i make it go away?

Manifest:

```<code><application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:theme="@style/Theme.AppCompat.Light" >
        <activity
            android:name=".HomeActivity"
            android:icon="@drawable/android_logo"
            android:label=""
            android:logo="@drawable/android_logo" >

            <!--
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            -->
        </activity>
        <activity
            android:name=".MapActivity"
            android:label="" >
        </activity>
        <activity
            android:name=".PackageActivity"
            android:icon="@drawable/android_logo"
            android:label=""
            android:logo="@drawable/android_logo" >
        </activity>
        <activity
            android:name=".SplashActivity"
            android:label="" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</code>```

MapActivity definition (it's a long one so i included just the definition):

```<code>public class MapActivity extends FragmentActivity implements LocationListener
</code>```

Splash Activity:

```<code>import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;

public class SplashActivity extends Activity{

    private static final long SPLASH_DISPLAY_LENGTH = 2000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);

        new Handler().postDelayed(new Runnable(){
            @Override
            public void run() {
                Intent mainIntent = new Intent(SplashActivity.this,HomeActivity.class);
                SplashActivity.this.startActivity(mainIntent);
                SplashActivity.this.finish();
            }
        }, SPLASH_DISPLAY_LENGTH);

    }

}
</code>```

答:
Replace AndroidManifest.xml

```<code>android:theme="@style/FullscreenTheme"
</code>```

to

```<code>android:theme="@style/Theme.Design.NoActionBar"
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've developed a simple demo application with a splash screen a map and some regular screens.

I have an action bar at the top that contains a logo. It all looks fine on my phone (Galaxy s1 I9000 V2.3) but when i test it on Galaxy s2 v4 the action bar appears also in the splash screen and in the map screen.

The spalsh and map activity are not even inheriting from ActionBarActivity so how is that possible and how can i make it go away?

Manifest:

<application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:theme="@style/Theme.AppCompat.Light" >
        <activity
            android:name=".HomeActivity"
            android:icon="@drawable/android_logo"
            android:label=""
            android:logo="@drawable/android_logo" >

        </activity>
        <activity
            android:name=".MapActivity"
            android:label="" >
        </activity>
        <activity
            android:name=".PackageActivity"
            android:icon="@drawable/android_logo"
            android:label=""
            android:logo="@drawable/android_logo" >
        </activity>
        <activity
            android:name=".SplashActivity"
            android:label="" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>

MapActivity definition (it's a long one so i included just the definition):

public class MapActivity extends FragmentActivity implements LocationListener

Splash Activity:

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;

public class SplashActivity extends Activity{

    private static final long SPLASH_DISPLAY_LENGTH = 2000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);

        new Handler().postDelayed(new Runnable(){
            @Override
            public void run() {
                Intent mainIntent = new Intent(SplashActivity.this,HomeActivity.class);
                SplashActivity.this.startActivity(mainIntent);
                SplashActivity.this.finish();
            }
        }, SPLASH_DISPLAY_LENGTH);

    }

}

Body:
Replace AndroidManifest.xml

android:theme="@style/FullscreenTheme"

to

android:theme="@style/Theme.Design.NoActionBar"

ContentLicense: CC BY-SA 4.0


问:
Flutter scoped model not updating all descendants"
My app is intended to consume live sensors data from an API using flutter scoped_model. The data is a JSON array like these:

```<code>[
  {
    "id": 4,
    "device_name": "fermentero2",
    "active_beer": 4,
    "active_beer_name": "Sourgobo",
    "controller_fridge_temp": "Fridge --.-   1.0 ░C",
    "controller_beer_temp": "Beer   28.6  10.0 ░C",
    "active_beer_temp": 28.63,
    "active_fridge_temp": null,
    "active_beer_set": 10,
    "active_fridge_set": 1,
    "controller_mode": "b"
  },
  {
    "id": 6,
    "device_name": "brewpi",
    "active_beer": 1,
    "active_beer_name": "Amber Ale",
    "controller_fridge_temp": null,
    "controller_beer_temp": null,
    "active_beer_temp": null,
    "active_fridge_temp": null,
    "active_beer_set": null,
    "active_fridge_set": null,
    "controller_mode": null
  }
]
</code>```

Those are devices. My Device model is as follow (json annotation):

```<code>@JsonSerializable(nullable: false)
class Device {
  int id;
  String device_name;
  @JsonKey(nullable: true) int active_beer;
  @JsonKey(nullable: true) String active_beer_name;
  @JsonKey(nullable: true) String controller_mode; // manual beer/fridge ou perfil
  @JsonKey(nullable: true) double active_beer_temp;
  @JsonKey(nullable: true) double active_fridge_temp;
  @JsonKey(nullable: true) double active_beer_set;
  @JsonKey(nullable: true) double active_fridge_set;

  Device({
    this.id,
    this.device_name,
    this.active_beer,
    this.active_beer_name,
    this.controller_mode,
    this.active_beer_temp,
    this.active_beer_set,
    this.active_fridge_set,
  });

  factory Device.fromJson(Map<String, dynamic> json) => _$DeviceFromJson(json);
  Map<String, dynamic> toJson() => _$DeviceToJson(this);

}
</code>```

My scoped model class for the Device is as follow:

```<code>class DeviceModel extends Model {

  Timer timer;

  List<dynamic> _deviceList = [];
  List<dynamic> get devices => _deviceList;

  set _devices(List<dynamic> value) {
    _deviceList = value;
    notifyListeners();
  }

  List _data;

  Future getDevices() async {
    loading = true;
    _data = await getDeviceInfo()
        .then((response) {
      print('Type of devices is ${response.runtimeType}');
      print("Array: $response");
      _devices = response.map((d) => Device.fromJson(d)).toList();
      loading = false;
      notifyListeners();
    });
  }

  bool _loading = false;

  bool get loading => _loading;

  set loading(bool value) {
    _loading = value;
    notifyListeners();
  }

    notifyListeners();
}
</code>```

My UI is intended to be a list of devices showing live data (rebuild ui as sensor data change) and a detail page of each Device, also showing live data. For that I'm using a timer. The page to list Devices is working as expected and "refreshing" every 30 seconds:

```<code>class DevicesPage extends StatefulWidget {
  @override
  State<DevicesPage> createState() => _DevicesPageState();
}

class _DevicesPageState extends State<DevicesPage> {
  DeviceModel model = DeviceModel();

  Timer timer;

  @override
  void initState() {
    model.getDevices();
    super.initState();
    timer = Timer.periodic(Duration(seconds: 30), (Timer t) => model.getDevices());
  }

  @override
  Widget build(BuildContext) {
    return Scaffold(
      appBar: new AppBar(
        title: new Text('Controladores'),
      ),
      drawer: AppDrawer(),
      body: ScopedModel<DeviceModel>(
        model: model,
        child: _buildListView(),
      ),
    );
  }

  _buildListView() {
    return ScopedModelDescendant<DeviceModel>(
      builder: (BuildContext context, Widget child, DeviceModel model) {
        if (model.loading) {
          return UiLoading();
        }
        final devicesList = model.devices;
        return ListView.builder(
          itemBuilder: (context, index) => InkWell(
            splashColor: Colors.blue[300],
            child: _buildListTile(devicesList[index]),
            onTap: () {
              Route route = MaterialPageRoute(
                builder: (context) => DevicePage(devicesList[index]),
              );
              Navigator.push(context, route);
            },
          ),
          itemCount: devicesList.length,
        );
      },
    );
  }

  _buildListTile(Device device) {
    return Card(
      child: ListTile(
        leading: Icon(Icons.devices),
        title: device.device_name == null
        ? null
            : Text(
        device.device_name.toString() ?? "",
        ),
        subtitle: device.active_beer_name == null
            ? null
            : Text(
          device.active_beer_temp.toString() ?? "",
        ),
      ),
    );
  }
}

class UiLoading extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          CircularProgressIndicator(),
          SizedBox(height: 12),
          Text(
            'Loading',
            style: TextStyle(
              fontWeight: FontWeight.bold,
            ),
          ),
        ],
      ),
    );
  }
}
</code>```

The problem happens with the detail page UI that is also supposed to show live Data but it behaves like a statelesswidget and do not rebuild itself after the Model gets updated:

```<code>class DevicePage extends StatefulWidget {

  Device device;
  DevicePage(this.device);

  @override
  //State<DevicePage> createState() => _DevicePageState(device);
  State<DevicePage> createState() => _DevicePageState();
}

class _DevicePageState extends State<DevicePage> {

  DeviceModel model = DeviceModel();

  Timer timer;

  @override
  void initState() {
    DeviceModel model = DeviceModel();
    super.initState();
    timer = Timer.periodic(Duration(seconds: 30), (Timer t) => model.updateDevice());

  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: new AppBar(
        title: new Text(widget.device.device_name),
      ),

      drawer: AppDrawer(),
      body: ScopedModel<DeviceModel>(
        model: model,
        child: _buildView(widget.device),
      ),
    );
  }

  _buildView(Device device) {
    return ScopedModelDescendant<DeviceModel>(
      builder: (BuildContext context, Widget child, DeviceModel model) {
        if (model.loading) {
          return UiLoading();
        }
        return Card(
          child: ListTile(
            leading: Icon(Icons.devices),
            title: device.device_name == null
                ? null
                : Text(
              device.device_name.toString() ?? "",
            ),
            subtitle: device.active_beer_name == null
                ? null
                : Text(
              device.active_beer_temp.toString() ?? "",
            ),
          ),
        );
      },
    );
  }
}

class UiLoading extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          CircularProgressIndicator(),
          SizedBox(height: 12),
          Text(
            'Loading',
            style: TextStyle(
              fontWeight: FontWeight.bold,
            ),
          ),
        ],
      ),
    );
  }
</code>```

What am I missing ?
many thanks in advance

答:
It looks like you're building a new DeviceModel for your DevicePage which means that model will be the one your ui would react to, not the one higher up the widget tree - your DevicesPage.

```<code>ScopedModel<DeviceModel>(
        model: model,
        child: _buildView(widget.device),
      )
</code>```

On your DevicePage where you add a the body to your Scaffold replace the ScopedModel with just:

```<code>_buildView(widget.device)
</code>```

That should solve your issue.

Body:
My app is intended to consume live sensors data from an API using flutter scoped_model. The data is a JSON array like these:

[
  {
    "id": 4,
    "device_name": "fermentero2",
    "active_beer": 4,
    "active_beer_name": "Sourgobo",
    "controller_fridge_temp": "Fridge --.-   1.0 ░C",
    "controller_beer_temp": "Beer   28.6  10.0 ░C",
    "active_beer_temp": 28.63,
    "active_fridge_temp": null,
    "active_beer_set": 10,
    "active_fridge_set": 1,
    "controller_mode": "b"
  },
  {
    "id": 6,
    "device_name": "brewpi",
    "active_beer": 1,
    "active_beer_name": "Amber Ale",
    "controller_fridge_temp": null,
    "controller_beer_temp": null,
    "active_beer_temp": null,
    "active_fridge_temp": null,
    "active_beer_set": null,
    "active_fridge_set": null,
    "controller_mode": null
  }
]

Those are devices. My Device model is as follow (json annotation):

@JsonSerializable(nullable: false)
class Device {
  int id;
  String device_name;
  @JsonKey(nullable: true) int active_beer;
  @JsonKey(nullable: true) String active_beer_name;
  @JsonKey(nullable: true) String controller_mode; // manual beer/fridge ou perfil
  @JsonKey(nullable: true) double active_beer_temp;
  @JsonKey(nullable: true) double active_fridge_temp;
  @JsonKey(nullable: true) double active_beer_set;
  @JsonKey(nullable: true) double active_fridge_set;

  Device({
    this.id,
    this.device_name,
    this.active_beer,
    this.active_beer_name,
    this.controller_mode,
    this.active_beer_temp,
    this.active_beer_set,
    this.active_fridge_set,
  });

  factory Device.fromJson(Map<String, dynamic> json) => _$DeviceFromJson(json);
  Map<String, dynamic> toJson() => _$DeviceToJson(this);

}

My scoped model class for the Device is as follow:

class DeviceModel extends Model {

  Timer timer;

  List<dynamic> _deviceList = [];
  List<dynamic> get devices => _deviceList;

  set _devices(List<dynamic> value) {
    _deviceList = value;
    notifyListeners();
  }

  List _data;

  Future getDevices() async {
    loading = true;
    _data = await getDeviceInfo()
        .then((response) {
      print('Type of devices is ${response.runtimeType}');
      print("Array: $response");
      _devices = response.map((d) => Device.fromJson(d)).toList();
      loading = false;
      notifyListeners();
    });
  }

  bool _loading = false;

  bool get loading => _loading;

  set loading(bool value) {
    _loading = value;
    notifyListeners();
  }

    notifyListeners();
}

My UI is intended to be a list of devices showing live data (rebuild ui as sensor data change) and a detail page of each Device, also showing live data. For that I'm using a timer. The page to list Devices is working as expected and "refreshing" every 30 seconds:

class DevicesPage extends StatefulWidget {
  @override
  State<DevicesPage> createState() => _DevicesPageState();
}

class _DevicesPageState extends State<DevicesPage> {
  DeviceModel model = DeviceModel();

  Timer timer;

  @override
  void initState() {
    model.getDevices();
    super.initState();
    timer = Timer.periodic(Duration(seconds: 30), (Timer t) => model.getDevices());
  }

  @override
  Widget build(BuildContext) {
    return Scaffold(
      appBar: new AppBar(
        title: new Text('Controladores'),
      ),
      drawer: AppDrawer(),
      body: ScopedModel<DeviceModel>(
        model: model,
        child: _buildListView(),
      ),
    );
  }

  _buildListView() {
    return ScopedModelDescendant<DeviceModel>(
      builder: (BuildContext context, Widget child, DeviceModel model) {
        if (model.loading) {
          return UiLoading();
        }
        final devicesList = model.devices;
        return ListView.builder(
          itemBuilder: (context, index) => InkWell(
            splashColor: Colors.blue[300],
            child: _buildListTile(devicesList[index]),
            onTap: () {
              Route route = MaterialPageRoute(
                builder: (context) => DevicePage(devicesList[index]),
              );
              Navigator.push(context, route);
            },
          ),
          itemCount: devicesList.length,
        );
      },
    );
  }

  _buildListTile(Device device) {
    return Card(
      child: ListTile(
        leading: Icon(Icons.devices),
        title: device.device_name == null
        ? null
            : Text(
        device.device_name.toString() ?? "",
        ),
        subtitle: device.active_beer_name == null
            ? null
            : Text(
          device.active_beer_temp.toString() ?? "",
        ),
      ),
    );
  }
}

class UiLoading extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          CircularProgressIndicator(),
          SizedBox(height: 12),
          Text(
            'Loading',
            style: TextStyle(
              fontWeight: FontWeight.bold,
            ),
          ),
        ],
      ),
    );
  }
}

The problem happens with the detail page UI that is also supposed to show live Data but it behaves like a statelesswidget and do not rebuild itself after the Model gets updated:

class DevicePage extends StatefulWidget {

  Device device;
  DevicePage(this.device);

  @override
  //State<DevicePage> createState() => _DevicePageState(device);
  State<DevicePage> createState() => _DevicePageState();
}

class _DevicePageState extends State<DevicePage> {

  DeviceModel model = DeviceModel();

  Timer timer;

  @override
  void initState() {
    DeviceModel model = DeviceModel();
    super.initState();
    timer = Timer.periodic(Duration(seconds: 30), (Timer t) => model.updateDevice());

  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: new AppBar(
        title: new Text(widget.device.device_name),
      ),

      drawer: AppDrawer(),
      body: ScopedModel<DeviceModel>(
        model: model,
        child: _buildView(widget.device),
      ),
    );
  }

  _buildView(Device device) {
    return ScopedModelDescendant<DeviceModel>(
      builder: (BuildContext context, Widget child, DeviceModel model) {
        if (model.loading) {
          return UiLoading();
        }
        return Card(
          child: ListTile(
            leading: Icon(Icons.devices),
            title: device.device_name == null
                ? null
                : Text(
              device.device_name.toString() ?? "",
            ),
            subtitle: device.active_beer_name == null
                ? null
                : Text(
              device.active_beer_temp.toString() ?? "",
            ),
          ),
        );
      },
    );
  }
}

class UiLoading extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          CircularProgressIndicator(),
          SizedBox(height: 12),
          Text(
            'Loading',
            style: TextStyle(
              fontWeight: FontWeight.bold,
            ),
          ),
        ],
      ),
    );
  }

What am I missing ?
many thanks in advance

Body:
It looks like you're building a new DeviceModel for your DevicePage which means that model will be the one your ui would react to, not the one higher up the widget tree - your DevicesPage.

ScopedModel<DeviceModel>(
        model: model,
        child: _buildView(widget.device),
      )

On your DevicePage where you add a the body to your Scaffold replace the ScopedModel with just:

_buildView(widget.device)

That should solve your issue.


答:
try

by the way if u want only latest row then u can search it by auto increment field (datalog_table.id)

```<code>SELECT dvc.deviceId,dvc.deviceName,dvc.deviceDescription,
       dtl.time_stamp,dtl.FuelLevel,dtl.Voltage
FROM  device_table dvc
INNER JOIN datalog_table dtl
ON dtl.DeviceId=dvc.deviceId
ORDER BY dtl.id  LIMIT 1
</code>```

Title: Joining one table to the latest row in another table using MySQL

Body:
I want to join two tables in a special way, first table is devices which has a list of devices.

The second table is datalog which is where abit of data is stored for everytime a device in devices gets polled.

Devices Table:

+----------+------------+----------------------------+---------------------+
| deviceId | deviceName | deviceDescription          | timeCreated         |
+----------+------------+----------------------------+---------------------+
|        1 | System 1   | Main System in Server Room | 2010-01-01 00:00:00 |
|        2 | System 2   | Outdoor System             | 2010-01-01 00:00:00 |
+----------+------------+----------------------------+---------------------+

DataLog Table:

+----+---------------------+----------+-----------+---------+
| id | time_stamp          | DeviceId | FuelLevel | Voltage |
+----+---------------------+----------+-----------+---------+
|  1 | 2010-01-01 00:00:00 |        1 |        60 |     220 |
|  2 | 2010-01-01 00:00:00 |        2 |        20 |     221 |
|  3 | 2010-01-02 00:00:00 |        1 |       100 |     219 |
|  4 | 2010-01-02 00:00:00 |        2 |       100 |     222 |
|  5 | 2010-01-03 00:00:00 |        1 |        80 |     219 |
|  6 | 2010-01-03 00:00:00 |        2 |        99 |     220 |
+----+---------------------+----------+-----------+---------+

Currently I am getting the latest data for each device using a query on the DataLog table with:

 Where DeviceId = 1 ORDER BY timestamp DESC LIMIT 1

What I would like is one query to return a list of all devices, with the columns joined with the latest data for each device like this:

+----------+------------+----------------------------+---------------------+-----------+---------+
| deviceId | deviceName | deviceDescription          | time_stamp          |FuelLevel  | Voltage |
+----------+------------+----------------------------+---------------------+-----------+---------+
|        1 | System 1   | Main System in Server Room | 2010-01-03 00:00:00 |        80 |     219 |
|        2 | System 2   | Outdoor System             | 2010-01-03 00:00:00 |       99  |     220 |
+----------+------------+----------------------------+---------------------+-----------+---------+

Body:
try

by the way if u want only latest row then u can search it by auto increment field (datalog_table.id)

SELECT dvc.deviceId,dvc.deviceName,dvc.deviceDescription,
       dtl.time_stamp,dtl.FuelLevel,dtl.Voltage
FROM  device_table dvc
INNER JOIN datalog_table dtl
ON dtl.DeviceId=dvc.deviceId
ORDER BY dtl.id  LIMIT 1


问:
How to select rows by range comparison in SQL Server?
I have following table named T in left as source table.

FINAL OUTPUT SHOULD BE AS FOLLOWING,

I want to take only those rows where Actual value is in between Basic, associated with the Model and Level columns.

For example if you take Model = HT65, the Actual value of 23.2 lies between Basic = 22 & 24, so that row should be selected where Basic = 24. i.e highlighted in yellow, same is true for JF97. Here you can refer right hand side table as reference result.

For the same model, if Actual is 21,  the first row should be chosen, with level = 1, like this:

If Actual column value is more than value in Basic Level should be marked as out highlighted in orange, as following,

I have not tried it as it seemed complex to me. your help would be appreciated.

答:
I think you want:

```<code>select t.*, t2.level
from t outer apply
     (select top (1) t2.*
      from t t2
      where t2.model = t.model and t2.basic >= t.actual
      order by t2.level asc
     ) t2;
</code>```

Note that this returns NULL rather than the string 'out'.  Mixing strings and numbers complicates the query because of the conversion logic.

Body:
I think you want:

select t.*, t2.level
from t outer apply
     (select top (1) t2.*
      from t t2
      where t2.model = t.model and t2.basic >= t.actual
      order by t2.level asc
     ) t2;

Note that this returns NULL rather than the string 'out'.  Mixing strings and numbers complicates the query because of the conversion logic.


问:
Core Data Creates A New Object When Updating An Old One
To start with, I don't believe this is a duplicate of: Updating object value in core data is also creating a new object (It's in Obj-C and they were calling insertNewObject every time they segued.)

Background Info: I learned how to use CoreData from the Ray Wenderlich book and referred to it when writing this code. I rolled my own custom stack as outlined in Chapter 3 if you have the book. I can show the code for this if needed.

Queue is the Entity I'm trying to update.

It has 1 property: name - String

And 1 to-many relationship: tasks: Task

My CoreData logic is in a Struct which contains the managedContext.

I have a basic find/create function to create a Queue object. This works. It creates 1 and only 1 object.

```<code>func findOrCreateMainQueue() -> Queue? {
    let queue = Queue(context: managedContext)
    queue.name = "Queue32"

    let queueFetch: NSFetchRequest<Queue> = Queue.fetchRequest()
    queueFetch.predicate = NSPredicate(format: "%K == %@", #keyPath(Queue.name), "Queue32" as CVarArg)
    do {
        let results = try managedContext.fetch(queueFetch)
        print(results.count)

        if results.count > 0 {
            return results.first!
        } else {
            try managedContext.save()
        }

    } catch let error as NSError {
        print("Fetch error: \(error) description: \(error.userInfo)")
    }

    return nil
}
</code>```

(As you can see by the queue.name suffix number I have tried a lot of different things.)

I have tried just about everything I can think of:

This code is basically copy/pasted from: How do you update a CoreData entry that has already been saved in Swift?

```<code>func addTaskToMainQueue2(task: Task) {
    let queueFetch: NSFetchRequest<Queue> = Queue.fetchRequest()
    queueFetch.predicate = NSPredicate(format: "%K == %@", #keyPath(Queue.name), "Queue32" as CVarArg)
    do {
        let results = try managedContext.fetch(queueFetch)
        print(results.count)

        if results.count > 0 {

            var tasks = results[0].tasks?.mutableCopy() as? NSMutableOrderedSet
            tasks?.add(task)
            results[0].setValue(tasks, forKey: "tasks")
        }

    } catch let error as NSError {
        print("Fetch error: \(error) description: \(error.userInfo)")
    }

        do {
            try managedContext.save()
        } catch let error as NSError {
            print("Save error: \(error),description: \(error.localizedDescription)")
        }

}
</code>```

Which causes a second Queue object to be created with the "Queue32" name.

Here is another thing I tried:

```<code>func addTaskToMainQueue(task: Task) {
    if var queue = findOrCreateMainQueue() {
        var tasks = queue.tasks?.mutableCopy() as? NSMutableOrderedSet
        tasks?.add(task)
        queue.tasks = tasks
        do {
            try managedContext.save()
        } catch let error as NSError {
            print("Save error: \(error),description: \(error.localizedDescription)")
        }

    }
}
</code>```

For the sake of space I won't add code for other things I've tried.

I've tried using the find/create function and updating in that method.

I've tried saving the queue as a local object and passing it to the addTask function which causes duplication as well.

It also doesn't matter if I pass in the Task or create one in the addTask function.

I am starting to believe my issue is something in my dataModel file causing this as I've tried a number of 'How to update a Core Data object' tutorials online and I get the same result each time.

awakeFromInsert() is called whenever I try to update an object. Not sure if this should be happening.

In other places in my app updating works. For example, if I add a Subtask to a Task. It works fine. However, if I want to change the name of another entity called Project the object duplicates. (Project has an id attribute which is fetched, then the name attribute is changed.)

Thank you in advance. I've been pulling my hair out for hours.

答:
I admit not having read all of your code but if you create a new managed object like this

```<code>let queue = Queue(context: managedContext)
</code>```

then it will be added to the managedContext and will be saved to disk at some point. So this code

```<code>if results.count > 0 {
    return results.first!
} else {
    try managedContext.save()
}
</code>```

is irrelevant in regard to the queue object created earlier because it will be saved even if results.count is > 0, although at a later point. So this means you will have to delete queue when the fetch is successful which feels unnecessary, better to wait with creating it

```<code>if results.count > 0 {
    return results.first!
} else {
    let queue = Queue(context: managedContext)
    queue.name = "Queue32"
    try managedContext.save()
}
</code>```

Off topic but I see you return nil if a new object was created rather than fetched, is this intended?

Body:
To start with, I don't believe this is a duplicate of: Updating object value in core data is also creating a new object (It's in Obj-C and they were calling insertNewObject every time they segued.)

Background Info: I learned how to use CoreData from the Ray Wenderlich book and referred to it when writing this code. I rolled my own custom stack as outlined in Chapter 3 if you have the book. I can show the code for this if needed.

Queue is the Entity I'm trying to update.

It has 1 property: name - String

And 1 to-many relationship: tasks: Task

My CoreData logic is in a Struct which contains the managedContext.

I have a basic find/create function to create a Queue object. This works. It creates 1 and only 1 object.

func findOrCreateMainQueue() -> Queue? {
    let queue = Queue(context: managedContext)
    queue.name = "Queue32"

    let queueFetch: NSFetchRequest<Queue> = Queue.fetchRequest()
    queueFetch.predicate = NSPredicate(format: "%K == %@", #keyPath(Queue.name), "Queue32" as CVarArg)
    do {
        let results = try managedContext.fetch(queueFetch)
        print(results.count)

        if results.count > 0 {
            return results.first!
        } else {
            try managedContext.save()
        }

    } catch let error as NSError {
        print("Fetch error: \(error) description: \(error.userInfo)")
    }

    return nil
}

(As you can see by the queue.name suffix number I have tried a lot of different things.)

I have tried just about everything I can think of:

This code is basically copy/pasted from: How do you update a CoreData entry that has already been saved in Swift?

func addTaskToMainQueue2(task: Task) {
    let queueFetch: NSFetchRequest<Queue> = Queue.fetchRequest()
    queueFetch.predicate = NSPredicate(format: "%K == %@", #keyPath(Queue.name), "Queue32" as CVarArg)
    do {
        let results = try managedContext.fetch(queueFetch)
        print(results.count)

        if results.count > 0 {

            var tasks = results[0].tasks?.mutableCopy() as? NSMutableOrderedSet
            tasks?.add(task)
            results[0].setValue(tasks, forKey: "tasks")
        }

    } catch let error as NSError {
        print("Fetch error: \(error) description: \(error.userInfo)")
    }

        do {
            try managedContext.save()
        } catch let error as NSError {
            print("Save error: \(error),description: \(error.localizedDescription)")
        }

}

Which causes a second Queue object to be created with the "Queue32" name.

Here is another thing I tried:

func addTaskToMainQueue(task: Task) {
    if var queue = findOrCreateMainQueue() {
        var tasks = queue.tasks?.mutableCopy() as? NSMutableOrderedSet
        tasks?.add(task)
        queue.tasks = tasks
        do {
            try managedContext.save()
        } catch let error as NSError {
            print("Save error: \(error),description: \(error.localizedDescription)")
        }

    }
}

For the sake of space I won't add code for other things I've tried.

I've tried using the find/create function and updating in that method.

I've tried saving the queue as a local object and passing it to the addTask function which causes duplication as well.

It also doesn't matter if I pass in the Task or create one in the addTask function.

I am starting to believe my issue is something in my dataModel file causing this as I've tried a number of 'How to update a Core Data object' tutorials online and I get the same result each time.

awakeFromInsert() is called whenever I try to update an object. Not sure if this should be happening.

In other places in my app updating works. For example, if I add a Subtask to a Task. It works fine. However, if I want to change the name of another entity called Project the object duplicates. (Project has an id attribute which is fetched, then the name attribute is changed.)

Thank you in advance. I've been pulling my hair out for hours.

Body:
I admit not having read all of your code but if you create a new managed object like this

let queue = Queue(context: managedContext)

then it will be added to the managedContext and will be saved to disk at some point. So this code

if results.count > 0 {
    return results.first!
} else {
    try managedContext.save()
}

is irrelevant in regard to the queue object created earlier because it will be saved even if results.count is > 0, although at a later point. So this means you will have to delete queue when the fetch is successful which feels unnecessary, better to wait with creating it

if results.count > 0 {
    return results.first!
} else {
    let queue = Queue(context: managedContext)
    queue.name = "Queue32"
    try managedContext.save()
}

Off topic but I see you return nil if a new object was created rather than fetched, is this intended?


问:
Generating random sparse matrix
I am dealing with large matrices - on the order of 10^8 columns and 10^3-10^4 rows. Since these matrices are only ones and zeros (over 99% zeros), I think the sparse construction in the Matrix package is appropriate. However, I don't see a way to generate a random matrix like in the example below. Note that non-zero entries are defined by the column probabilities col_prob.

```<code>set.seed(1) #For reproducibility
ncols <- 20
nrows <- 10
col_prob <- runif(ncols,0.1,0.2)
rmat <- matrix(rbinom(nrows*ncols,1,col_prob),
       ncol=ncols,byrow=T)
</code>```

Certainly I can convert rmat into a sparse matrix:

```<code>rmat_sparse <- Matrix(rmat, sparse=TRUE)
</code>```

However, I would like to generate the sparse matrix in one step. I'm not sure that the function Matrix::rsparsematrix can accomplish this.

答:
The following function will generate a sparse matrix of the type you are looking for, by manipulating the values of a blank dgCMatrix object.  It basically creates the rbinom rows one at a time and populates the @i and @p values accordingly.

```<code>library(Matrix)
randsparse <- function(nrows, ncols, col_prob) {
  mat <- Matrix(0, nrows, ncols, sparse = TRUE)  #blank matrix for template
  i <- vector(mode = "list", length = ncols)     #each element of i contains the '1' rows
  p <- rep(0, ncols)                             #p will be cumsum no of 1s by column
  for(r in 1:nrows){
    row <- rbinom(ncols, 1, col_prob)            #random row
    p <- p + row                                 #add to column identifier
    if(any(row == 1)){
      for (j in which(row == 1)){
        i[[j]] <- c(i[[j]], r-1)                 #append row identifier
      }
    }
  }
  p <- c(0, cumsum(p))                           #this is the format required
  i <- unlist(i)
  x <- rep(1, length(i))
  mat@i <- as.integer(i)
  mat@p <- as.integer(p)
  mat@x <- x
  return(mat)
}

set.seed(1)
randsparse(10, 20, runif(20, 0.1, 0.2))

10 x 20 sparse Matrix of class "dgCMatrix"

 [1,] 1 . . . . . . . 1 . . . . . 1 . . . . .
 [2,] . . . . . . . . . . . . . . . . . . . .
 [3,] 1 . . . . . . . . . . . . . . 1 1 . . 1
 [4,] . . . . . . . . . . . . . 1 . . . . . .
 [5,] . . . 1 . . . . 1 . 1 . . . . . . . . .
 [6,] 1 . . . . . . . . . . . . . 1 . . . 1 .
 [7,] . . . . . . . . . . . . . . . . . . . .
 [8,] . 1 . . 1 . . . . . . . 1 . . 1 . . . 1
 [9,] . . 1 . . . . . 1 . . . . 1 . . . 1 . .
[10,] . . . . . . . . . . 1 . . 1 . . . 1 1 .
</code>```

Title: Generating random sparse matrix

Body:
I am dealing with large matrices - on the order of 10^8 columns and 10^3-10^4 rows. Since these matrices are only ones and zeros (over 99% zeros), I think the sparse construction in the Matrix package is appropriate. However, I don't see a way to generate a random matrix like in the example below. Note that non-zero entries are defined by the column probabilities col_prob.

set.seed(1) #For reproducibility
ncols <- 20
nrows <- 10
col_prob <- runif(ncols,0.1,0.2)
rmat <- matrix(rbinom(nrows*ncols,1,col_prob),
       ncol=ncols,byrow=T)

Certainly I can convert rmat into a sparse matrix:

rmat_sparse <- Matrix(rmat, sparse=TRUE)

However, I would like to generate the sparse matrix in one step. I'm not sure that the function Matrix::rsparsematrix can accomplish this.

Body:
The following function will generate a sparse matrix of the type you are looking for, by manipulating the values of a blank dgCMatrix object.  It basically creates the rbinom rows one at a time and populates the @i and @p values accordingly.

library(Matrix)
randsparse <- function(nrows, ncols, col_prob) {
  mat <- Matrix(0, nrows, ncols, sparse = TRUE)  #blank matrix for template
  i <- vector(mode = "list", length = ncols)     #each element of i contains the '1' rows
  p <- rep(0, ncols)                             #p will be cumsum no of 1s by column
  for(r in 1:nrows){
    row <- rbinom(ncols, 1, col_prob)            #random row
    p <- p + row                                 #add to column identifier
    if(any(row == 1)){
      for (j in which(row == 1)){
        i[[j]] <- c(i[[j]], r-1)                 #append row identifier
      }
    }
  }
  p <- c(0, cumsum(p))                           #this is the format required
  i <- unlist(i)
  x <- rep(1, length(i))
  mat@i <- as.integer(i)
  mat@p <- as.integer(p)
  mat@x <- x
  return(mat)
}

set.seed(1)
randsparse(10, 20, runif(20, 0.1, 0.2))

10 x 20 sparse Matrix of class "dgCMatrix"

 [1,] 1 . . . . . . . 1 . . . . . 1 . . . . .
 [2,] . . . . . . . . . . . . . . . . . . . .
 [3,] 1 . . . . . . . . . . . . . . 1 1 . . 1
 [4,] . . . . . . . . . . . . . 1 . . . . . .
 [5,] . . . 1 . . . . 1 . 1 . . . . . . . . .
 [6,] 1 . . . . . . . . . . . . . 1 . . . 1 .
 [7,] . . . . . . . . . . . . . . . . . . . .
 [8,] . 1 . . 1 . . . . . . . 1 . . 1 . . . 1
 [9,] . . 1 . . . . . 1 . . . . 1 . . . 1 . .
[10,] . . . . . . . . . . 1 . . 1 . . . 1 1 .


问:
query result only returns one value
I want to see multiple values from my query but when I start this query, the result has only one value

```<code>function get_prove_associati($num) {
    $this->db->select("prove.*");
    $this->db->where("prove.numero",$num);
    return $this->db->get("prove")->row_array();
}
</code>```

In my db , there are four rows, not only one

答: According to the documentation, row_array() returns only the first row. Instead, result_array() is the correct method to return all found results.

Title: query result only returns one value

Body:
I want to see multiple values from my query but when I start this query, the result has only one value

function get_prove_associati($num) {
    $this->db->select("prove.*");
    $this->db->where("prove.numero",$num);
    return $this->db->get("prove")->row_array();
}

In my db , there are four rows, not only one


问:
DynamoDB Array of Array of strings schema
I'm looking for assistance on how I can achieve the schema below into my dynamodb database.

Example of my JSON

```<code>var users = [{
    userId: 123,
    userName: "John Smith",
    additionalInfomation: [
      ["favoriteColor", "blue"],
      ["hobbies", "ping-pong"]
    ]
}]
</code>```

This is what I have so far to achieve the userId and userName schema. I'm having trouble setting up additionalInfomation part.

```<code>  const params = {
    AttributeDefinitions: [
      {
        AttributeName: 'userId',
        AttributeType: 'N'
      },
      {
        AttributeName: 'userName',
        AttributeType: 'S'
      },
      {
        AttributeName: 'additionalInformation',
        AttributeType: <NEED HELP HERE> // <-------------------- ?????
      }
    ],
    KeySchema: [
      {
        AttributeName: 'userId',
        KeyType: 'HASH'
      },
      {
        AttributeName: 'userName',
        KeyType: 'RANGE'
      },
      {
        AttributeName: 'additionalInformation',
        KeyType: <NEED HELP HERE> // <-------------------- ?????
      }
    ],
    ProvisionedThroughput: {
      ReadCapacityUnits: 1,
      WriteCapacityUnits: 1
    },
    TableName: 'USERS',
    StreamSpecification: {
      StreamEnabled: false
    }
  };
  // Call DynamoDB to create the table
  ddb.createTable(params, function(err, data) {
    if (err) {
      console.log('Error', err);
    } else {
      console.log('Table Created', data);
    }
  });
</code>```

Need help setting the additionalInformation schema up. Please excuse my ignorance if this isn't the right approach. Still learning dynamoDB and the aws doc isn't quite helpful for a beginner.

答:
For this use case, I recommend that you choose either userId or userName as your HASH key (aka partition key) for your table, assuming that either of this attributes will uniquely identify the user. RANGE key (aka sort key) are beneficial when you have several items associated with one partition key, c.f. artists and song titles in the Primary Key paragraph of the DynamoDB user guide. Consequently, this means that you only need to specify one attribute in the AttributeDefinitions and KeySchema.

Furthermore, I recommend that you omit the additionalInformation from your schema based on the assumption that you will neither use that information as partition key nor a sort key.

Instead, you can add them as two separate attributes to individual items when calling putItem() or updateItem (or the corresponding put() and update() functions if you use the DynamoDB DocumentClient).

```<code>const params = {
  Item: {
   "userId": {
     N: "123"
    },
   "userName": {
     S: "dummy"
    },
   "favoriteColor": {
     S: "blue"
    },
   "hobbies": {
     SS: ["ping-pong", "another hobby"]
    }
  },
  TableName: "USERS"
 };
 const putItemPromise = dynamodb.putItem(params).promise()
</code>```

Note, in the example above I have specified favoriteColor as S, i.e. a single string, but the hobbies as SS meaning that it is a array of strings. This may or may not what you want, but since the attribute name is "hobbies" (and not "hobby"), I figured that it would make sense to allow more than one.

Body:
I'm looking for assistance on how I can achieve the schema below into my dynamodb database.

Example of my JSON

var users = [{
    userId: 123,
    userName: "John Smith",
    additionalInfomation: [
      ["favoriteColor", "blue"],
      ["hobbies", "ping-pong"]
    ]
}]

This is what I have so far to achieve the userId and userName schema. I'm having trouble setting up additionalInfomation part.

  const params = {
    AttributeDefinitions: [
      {
        AttributeName: 'userId',
        AttributeType: 'N'
      },
      {
        AttributeName: 'userName',
        AttributeType: 'S'
      },
      {
        AttributeName: 'additionalInformation',
        AttributeType: <NEED HELP HERE> // <-------------------- ?????
      }
    ],
    KeySchema: [
      {
        AttributeName: 'userId',
        KeyType: 'HASH'
      },
      {
        AttributeName: 'userName',
        KeyType: 'RANGE'
      },
      {
        AttributeName: 'additionalInformation',
        KeyType: <NEED HELP HERE> // <-------------------- ?????
      }
    ],
    ProvisionedThroughput: {
      ReadCapacityUnits: 1,
      WriteCapacityUnits: 1
    },
    TableName: 'USERS',
    StreamSpecification: {
      StreamEnabled: false
    }
  };
  // Call DynamoDB to create the table
  ddb.createTable(params, function(err, data) {
    if (err) {
      console.log('Error', err);
    } else {
      console.log('Table Created', data);
    }
  });

Need help setting the additionalInformation schema up. Please excuse my ignorance if this isn't the right approach. Still learning dynamoDB and the aws doc isn't quite helpful for a beginner.

Body:
For this use case, I recommend that you choose either userId or userName as your HASH key (aka partition key) for your table, assuming that either of this attributes will uniquely identify the user. RANGE key (aka sort key) are beneficial when you have several items associated with one partition key, c.f. artists and song titles in the Primary Key paragraph of the DynamoDB user guide. Consequently, this means that you only need to specify one attribute in the AttributeDefinitions and KeySchema.

Furthermore, I recommend that you omit the additionalInformation from your schema based on the assumption that you will neither use that information as partition key nor a sort key.

Instead, you can add them as two separate attributes to individual items when calling putItem() or updateItem (or the corresponding put() and update() functions if you use the DynamoDB DocumentClient).

const params = {
  Item: {
   "userId": {
     N: "123"
    },
   "userName": {
     S: "dummy"
    },
   "favoriteColor": {
     S: "blue"
    },
   "hobbies": {
     SS: ["ping-pong", "another hobby"]
    }
  },
  TableName: "USERS"
 };
 const putItemPromise = dynamodb.putItem(params).promise()

Note, in the example above I have specified favoriteColor as S, i.e. a single string, but the hobbies as SS meaning that it is a array of strings. This may or may not what you want, but since the attribute name is "hobbies" (and not "hobby"), I figured that it would make sense to allow more than one.


问:
call to php file via ajax not working
This seems like a relatively simple question, and I am pretty new to using ajax, but I saw a post about being able to call a PHP script when an OnClick event has been triggered. I am trying to destroy a session upon a user clicking the "Log Out" link, so I want to call the logout.php file when the OnClick event has occurred. My problem is that nothing happens when the link is clicked.

Here's my code:

```<code>$(document).ready(function() {

// Expand Panel
$("#open").click(function(){
    //when the user clicks the logout button
    $.ajax({
        url: "logout.php"
    )};
});
});

<div class="tab">
    <ul class="login">
        <li class="left"> </li>
        <li><?php if(isset($_SESSION['username'])){echo $_SESSION['username'];}else{echo 'Hello Guest!';}?></li>
        <li class="sep">|</li>
        <li id="toggle">
            <a id="open" class="open" href="#">Log Out</a>
        </li>
        <li class="right"> </li>
    </ul>
</div> <!-- / top -->
</code>```

答:
I suppose that you expect the output of the logout.php file to show. I think that your code might be working but that you forgot to tell the ajax where to put the data that it receives.

Try something like this:

```<code>$.ajax({
  url: 'logout.php',
  success: function(data) {
    $('.result').html(data);
    alert('Logout completed.');
  }
});
</code>```

Where "result" points to the div you want to load the response into.

Title: call to php file via ajax not working

Body:
This seems like a relatively simple question, and I am pretty new to using ajax, but I saw a post about being able to call a PHP script when an OnClick event has been triggered. I am trying to destroy a session upon a user clicking the "Log Out" link, so I want to call the logout.php file when the OnClick event has occurred. My problem is that nothing happens when the link is clicked.

Here's my code:

$(document).ready(function() {

// Expand Panel
$("#open").click(function(){
    //when the user clicks the logout button
    $.ajax({
        url: "logout.php"
    )};
});
});

<?php if(isset($_SESSION['username'])){echo $_SESSION['username'];}else{echo 'Hello Guest!';}?>

|

            Log Out

Body:
I suppose that you expect the output of the logout.php file to show. I think that your code might be working but that you forgot to tell the ajax where to put the data that it receives.

Try something like this:

$.ajax({
  url: 'logout.php',
  success: function(data) {
    $('.result').html(data);
    alert('Logout completed.');
  }
});

Where "result" points to the div you want to load the response into.


问:
Recursive xslt function for adding ul list hierarchy needs fixing
I'm trying a recursive function to nest flat elements by their outline level, but the function strips text from some of the elements. Otherwise I'm close to this working as the elements are being properly nested by outline level.

This is the source XML. The goal is to nest higher outline elements inside the lower.

```<code><article>
    <h3 class="icon component">
        <img src="images/component.png" alt="component" class="bullet"/>
    <span>Component: Forms</span>
    </h3>
    <p class="url details" data-outline="4">Sample: <a href="https://foo.com">foo.com</a></p>
    <p class="details" data-outline="4">Start line: 540</p>
    <p class="details" data-outline="4">End line: 700</p>
    <p class="details" data-outline="4">Foo</p>
    <li class="icon task" data-outline="4">
        <img src="images/task.png" alt="task" class="bullet"/>
        <p class="gist">Foo (Sev 3) (H48) </p>
    </li>
    <img src="images/image37.png" class="details" alt="Foo" data-outline="5"/>
    <p class="details" data-outline="5">Foo foo</p>
    <p class="details" data-outline="5">Foo foo</p>
    <li class="icon task" data-outline="4">
        <img src="images/task.png" alt="task" class="bullet"/>
        <p class="gist">Foo <code>foo</code> (Sev 3) (G83)</p>
    </li>
   <img src="images/image38.png" class="details" alt="" data-outline="5"/>
    <p class="caption details" data-outline="5">Screenshot: Foo foo</p>
    <li class="icon task" data-outline="5">
        <img src="images/task.png" alt="task" class="bullet"/>
        <p class="gist">foo foo (Sev 2) (2.4.6, G131)</p>
    </li>
    <p class="details" data-outline="6">Foo foo</p>
</article>
</code>```

This is the function:

```<code><xsl:function name="fpp:group" as="node()*">
    <xsl:param name="elements" as="element()*"/>
    <xsl:param name="outline" as="xs:integer"/>
    <xsl:for-each-group select="$elements" group-starting-with="*[@data-outline[.=$outline]]">
        <xsl:choose>
            <xsl:when test="self::*[@data-outline[.=$outline]]">
                <xsl:element name="{name()}">
                    <xsl:copy-of select="@*"/>
                    <xsl:apply-templates select="*" mode="copy"/>
                    <xsl:sequence select="fpp:group(current-group() except ., $outline + 1)"/>
                </xsl:element>
            </xsl:when>
            <xsl:otherwise>
                <xsl:apply-templates select="current-group()" mode="copy"/>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:for-each-group>
</xsl:function>
</code>```

Here's how I call it:

```<code><xsl:template match="article[li[matches(@class,'icon')]]" mode="step06">
    <xsl:copy>
        <xsl:variable name="hierarchy" select="fpp:group(*, 4)"/>
        <xsl:apply-templates select="$hierarchy" mode="copy"/>
    </xsl:copy>
</xsl:template>
</code>```

This is the current output, properly nested but note that the moved p.details elements are missing their text() string:

```<code><article>
    <h3 class="icon component">
        <img src="images/component.png" alt="component" class="bullet"/>
        <span>Component: Forms</span>
    </h3>
    <p class="url details" data-outline="4">
        <a href="https:foo.com">foo.com</a>
    </p>
    <p class="details" data-outline="4"/>
    <p class="details" data-outline="4"/>
    <p class="details" data-outline="4"/>
    <li class="icon task" data-outline="4">
        <img src="images/task.png" alt="task" class="bullet"/>
            <p class="gist">Foo (Sev 3) (H48) </p>
            <img src="images/image37.png" class="details" alt="Foo" data-outline="5"/>
            <p class="details" data-outline="5"/>
            <p class="details" data-outline="5"/>
    </li>
    <li class="icon task" data-outline="4">
        <img src="images/task.png" alt="task" class="bullet"/>
        <p class="gist">Foo <code>foo</code> (Sev 3) (G83)</p>
        <img src="images/image38.png" class="details" alt="" data-outline="5"/>
        <p class="caption details" data-outline="5"/>
        <li class="icon task" data-outline="5">
            <img src="images/task.png" alt="task" class="bullet"/>
            <p class="gist">Foo foo (Sev 2) (2.4.6, G131)</p>
            <p class="details" data-outline="6"/>
        </li>
    </li>
</article>
</code>```

What am I doing wrong? Thanks for you help!

答: I guess <xsl:apply-templates select="*" mode="copy"/> should be <xsl:apply-templates mode="copy"/> (or spelled out <xsl:apply-templates select="node()" mode="copy"/>).

Body:
I'm trying a recursive function to nest flat elements by their outline level, but the function strips text from some of the elements. Otherwise I'm close to this working as the elements are being properly nested by outline level.

This is the source XML. The goal is to nest higher outline elements inside the lower.

    Component: Forms

Sample: foo.com

Start line: 540

End line: 700

Foo

Foo (Sev 3) (H48)

Foo foo

Foo foo

Foo foo (Sev 3) (G83)

Screenshot: Foo foo

foo foo (Sev 2) (2.4.6, G131)

Foo foo

This is the function:

<xsl:function name="fpp:group" as="node()*">
    <xsl:param name="elements" as="element()*"/>
    <xsl:param name="outline" as="xs:integer"/>
    <xsl:for-each-group select="$elements" group-starting-with="*[@data-outline[.=$outline]]">
        <xsl:choose>
            <xsl:when test="self::*[@data-outline[.=$outline]]">
                <xsl:element name="{name()}">
                    <xsl:copy-of select="@*"/>
                    <xsl:apply-templates select="*" mode="copy"/>
                    <xsl:sequence select="fpp:group(current-group() except ., $outline + 1)"/>
                </xsl:element>
            </xsl:when>
            <xsl:otherwise>
                <xsl:apply-templates select="current-group()" mode="copy"/>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:for-each-group>
</xsl:function>

Here's how I call it:

<xsl:template match="article[li[matches(@class,'icon')]]" mode="step06">
    <xsl:copy>
        <xsl:variable name="hierarchy" select="fpp:group(*, 4)"/>
        <xsl:apply-templates select="$hierarchy" mode="copy"/>
    </xsl:copy>
</xsl:template>

This is the current output, properly nested but note that the moved p.details elements are missing their text() string:

        Component: Forms

        foo.com

Foo (Sev 3) (H48)

Foo foo (Sev 3) (G83)

Foo foo (Sev 2) (2.4.6, G131)

What am I doing wrong? Thanks for you help!


问:
Accepting args in $emit - Vue
A very simple alert implementation using $emit, but when passing arguments it behaves as if the event had never even occurred. On the event, I want to set the value of alert to the result.

I am listening on mount as:

```<code>this.$eventHub.$on('alert', data =>
  this.alert = data
})
</code>```

Will Work:

this.alert is undefined, but set.

```<code>this.$eventHub.$emit('alert')
</code>```

Won't Work:

this.alert is never set & event is never heard.

```<code>
this.$eventHub.$emit('alert', {'message':'Signal Test', 'color':'error'})
</code>```

What is occurring here?

答:
Not necessarily an answer, but more a user error. The issue is that I was signalling the event in the same component that I was listening for it on. I used all the same code, just simply moved the listener to a different component.

This may be as designed, but I didn't get any output to make this clear in console so I'm unsure if this behavior is expected or a bug.

Welcome any answers that may offer some context on why this occurs!

Title: Accepting args in $emit - Vue

Body:
A very simple alert implementation using $emit, but when passing arguments it behaves as if the event had never even occurred. On the event, I want to set the value of alert to the result.

I am listening on mount as:

this.$eventHub.$on('alert', data =>
  this.alert = data
})

Will Work:

this.alert is undefined, but set.

this.$eventHub.$emit('alert')

Won't Work:

this.alert is never set & event is never heard.

this.$eventHub.$emit('alert', {'message':'Signal Test', 'color':'error'})

What is occurring here?


问:
Typescript function return type relay
I have a simple class that implements the visitor pattern:

abstract class MyNode {};
class MyNodeA extends MyNode {};
class MyNodeB extends MyNode {};

abstract class NodeVisitor {
  abstract visitMyNodeA(node: MyNodeA): unknown;
  abstract visitMyNodeB(node: MyNodeB): unknown;

  public visit(node: MyNode) {
    if(node instanceof MyNodeA) {
      return this.visitMyNodeA(node);
    } else if(node instanceof MyNodeB) {
      return this.visitMyNodeB(node);
    } else {
      throw new Error('Unknown node type on visitor');
    }
  }
}
```

<p>and later, I want to have custom return types on each visit function when I implement <code>NodeVisitor</code></p>

<pre class="lang-js prettyprint-override"><code>class MyNodeVisitor extends NodeVisitor {
  visitMyNodeA(node: MyNodeA): number {
    return 1;
  }
  visitMyNodeB(node: MyNodeB): number {
    return this.visit(new MyNodeA()) + 1;
  }
}
</code>```

but this generates an error because the TypeScript compiler does not realize that a call on visit with a parameter of type MyNodeA redirects to the visitMyNodeA function which now returns a number.

How would I go about implementing such a solution?

答:
Yeah, the compiler can't figure that out by itself.  You can help it do so, at the expense of more complexity (and less type safety inside the visit() implementation).  My suggestion is to give visit() a generic signature whose return type is a conditional type based on the polymorphic this type of subclasses:

```<code>abstract class MyNode {myNode = "myNode"}
class MyNodeA extends MyNode {a = "a"}
class MyNodeB extends MyNode {b = "b"}

abstract class NodeVisitor {
  abstract visitMyNodeA(node: MyNodeA): unknown;
  abstract visitMyNodeB(node: MyNodeB): unknown;

  // call signature
  public visit<T extends MyNode>(
    node: T
  ): T extends MyNodeA ? ReturnType<this["visitMyNodeA"]> :
     T extends MyNodeB ? ReturnType<this["visitMyNodeB"]> :
    never;

  // implementation signature is wider
  public visit(node: MyNode): unknown {
    if (node instanceof MyNodeA) {
      return this.visitMyNodeA(node);
    } else if (node instanceof MyNodeB) {
      return this.visitMyNodeB(node);
    } else {
      throw new Error("Unknown node type on visitor");
    }
  }
}
class MyNodeVisitor extends NodeVisitor {
  visitMyNodeA(node: MyNodeA): number {
    return 1;
  }
  visitMyNodeB(node: MyNodeB): number {
    return this.visit(new MyNodeA()) + 1;
  }
}
</code>```

Does that work?  The idea is that you are leading the compiler through the analysis that if you pass in a MyNodeA that visit() will return the result of this.visitMyNodeA(node), and the same for MyNodeB.

Hope that helps; good luck!

Link to code

Title: Typescript function return type relay

Body:
I have a simple class that implements the visitor pattern:

abstract class MyNode {};
class MyNodeA extends MyNode {};
class MyNodeB extends MyNode {};

abstract class NodeVisitor {
  abstract visitMyNodeA(node: MyNodeA): unknown;
  abstract visitMyNodeB(node: MyNodeB): unknown;

  public visit(node: MyNode) {
    if(node instanceof MyNodeA) {
      return this.visitMyNodeA(node);
    } else if(node instanceof MyNodeB) {
      return this.visitMyNodeB(node);
    } else {
      throw new Error('Unknown node type on visitor');
    }
  }
}

and later, I want to have custom return types on each visit function when I implement NodeVisitor

class MyNodeVisitor extends NodeVisitor {
  visitMyNodeA(node: MyNodeA): number {
    return 1;
  }
  visitMyNodeB(node: MyNodeB): number {
    return this.visit(new MyNodeA()) + 1;
  }
}

but this generates an error because the TypeScript compiler does not realize that a call on visit with a parameter of type MyNodeA redirects to the visitMyNodeA function which now returns a number.

How would I go about implementing such a solution?

Body:
Yeah, the compiler can't figure that out by itself.  You can help it do so, at the expense of more complexity (and less type safety inside the visit() implementation).  My suggestion is to give visit() a generic signature whose return type is a conditional type based on the polymorphic this type of subclasses:

abstract class MyNode {myNode = "myNode"}
class MyNodeA extends MyNode {a = "a"}
class MyNodeB extends MyNode {b = "b"}

abstract class NodeVisitor {
  abstract visitMyNodeA(node: MyNodeA): unknown;
  abstract visitMyNodeB(node: MyNodeB): unknown;

  // call signature
  public visit<T extends MyNode>(
    node: T
  ): T extends MyNodeA ? ReturnType<this["visitMyNodeA"]> :
     T extends MyNodeB ? ReturnType<this["visitMyNodeB"]> :
    never;

  // implementation signature is wider
  public visit(node: MyNode): unknown {
    if (node instanceof MyNodeA) {
      return this.visitMyNodeA(node);
    } else if (node instanceof MyNodeB) {
      return this.visitMyNodeB(node);
    } else {
      throw new Error("Unknown node type on visitor");
    }
  }
}
class MyNodeVisitor extends NodeVisitor {
  visitMyNodeA(node: MyNodeA): number {
    return 1;
  }
  visitMyNodeB(node: MyNodeB): number {
    return this.visit(new MyNodeA()) + 1;
  }
}

Does that work?  The idea is that you are leading the compiler through the analysis that if you pass in a MyNodeA that visit() will return the result of this.visitMyNodeA(node), and the same for MyNodeB.

Hope that helps; good luck!

<a href="https://typescript-play.js.org/#code/IYIwzgLgTsDGEAJYBthjAgsgTwHIHsATAUwQG8BbPI0gXgQCIqCSGBfAKBTQxxeICCCYgA8IxAHaFe1EuWAJ6DYOy6p0WWcQBCwsZOmb+5EIsYhVHUJBjwk6jPwBqASzAuI+KOQ4IE16DhEADc3Dz4aAQAKCRoALiNIgEoEgFcJAGtYgHcJAG5ff3BAu1D3CAiSbRj4xKqUhHSs-FyCwoAHVJBkF1gEMo8AHgAVPXEpGX4APijCv1iSBOHChtHRccNKwQQAfgQAJWIIVKgJYex24kGIAAs3AG0GAYqtAQYAXSmEBLm-Nf0JnUdLsDkcTmcLldbg8nmEXvxtB8vj8-PNiMFiFACn5Ot1ev04TVFkCGk0chIfKiEC4AGYIImkFwSSDACSwYj4OlbARJSlUhBQMGnBDQsAAOme3IZSWxqLYwmQYEZdIZ1OZEFZ7M5QO0vLIvz8guOwtFErhW2qC2IMt+8uIitI+v5IpuUBaCAkxGyCAAolA3VAogwAKqZckemgiyEIfAU55eBg2qmcPycThqHhA1zlLxjAyOGjZjy5p0E8pSq0JbkNCSpCggTF8w1CikARllKbL4S0ltqFprdYb3lLzeNFNNzxiXqB0SSvIA1Ah24U0xwgA" rel="nofollow noreferrer">Link to code


问:
What tools do you use to develop C++ applications on Linux?
I develop C++ applications in a Linux environment.  The tools I use every day include Eclipse with the CDT plugin, gdb and valgrind.

What tools do other people use?  Is there anything out there for Linux that rivals the slickness of Microsoft Visual Studio?

答:
I use a bunch of terminal windows.  I have vim running on interesting source files, make and g++ output on another for compiler errors or a gdb session for runtime errors.  If I need help finding definitions I run cscope and use vim's cscope support to jump around.

Eclipse CDT is my second choice. It's nice but huge, ungainly and slow compared to vim.

Using terminal windows and vim is very flexible because I do not need to carry 400 MB of Java around with me   I can use SSH sessions from anywhere.

I use valgrind when I need to find a memory issue.

I use strace to watch what my software is doing on a system call level.  This lets me clean up really stupid code that calls time(0) four times in a row or makes too many calls to poll() or non-blocking read() or things like calling read() on a socket to read 1 byte at a time.  (That is super inefficient and lazy!)

I use objdump -d to inspect the machine code, especially for performance sensitive inner loops.  That is how I find things like the slowness of the array index operator on strings compared to using iterators.

I use oprofile to try to find hot spots in optimized code, I find that it often works a little better than gprof, and it can do things like look for data and instruction cache misses.  That can show you where to drop some helpful prefetch hints using GCC's __builtin_prefetch.  I tried to use it to find hot mis-predicted branches as well, but couldn't get that to work for me.

Update: I've found that perf works way better than oprofile. At least on Linux. Learn to use perf and love it as I do.

OwnerDisplayName: Clayton

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Zan Lynx


问:
iOS iPhone GKSession discovery in background
I know that the system can close Bonjour sockets while the application is suspended.
But ,will the system allow me while my application is in the background to only discover other devices not creating sockets to them and perhaps store those devices in a list or something like that ?</p>

答: Your app can only run in background for audio, voip or location. So there is no way other then the previous mentioned methods to run an app in the background. </p>


问:
How to modify different values with same tags in XML using Python?
I try to do this thing here :

BEFORE

        <c>
            <d>
                <name>VERSION</name>
                <description />
                <defaultValue>v1.0.0</defaultValue>
                <trim>false</trim>
            </d>
            <d>
                <name>LINK</name>
                <description />
                <defaultValue>current</defaultValue>
                <trim>false</trim>
            </d>
        </c>

```
<h1>AFTER</h1>
<pre class="lang-xml prettyprint-override"><code><a>
    <b>
        <c>
            <d>
                <name>VERSION</name>
                <description />
                <defaultValue>v2.0.0</defaultValue>
                <trim>false</trim>
            </d>
            <d>
                <name>LINK</name>
                <description />
                <defaultValue>I changed the link</defaultValue>
                <trim>false</trim>
            </d>
        </c>
    <b>
</a>
</code>```

I have an XML file and I want to change the default values.
I tried with this code but didn't work and idk how to handle it :

from xml.etree import ElementTree as ET
tab = ["V2.0.0, "I changed the link"]
i = 0
tree = ET.parse("myfile.xml")
for child in tree.findall(".//d"):
    tree.find(".//defaultValue").text = tab[i]
    i=+1
```

Thank you for your help !

答:
Try to change

```<code>tree.find(".//defaultValue").text = tab[i]
</code>```

with

```<code>child.find(".//defaultValue").text = tab[i]
</code>```

Add this line of code as the last line of your script in order to see the modified XML

```<code>ET.dump(tree)
</code>```

Body:
I try to do this thing here :

BEFORE

        <c>
            <d>
                <name>VERSION</name>
                <description />
                <defaultValue>v1.0.0</defaultValue>
                <trim>false</trim>
            </d>
            <d>
                <name>LINK</name>
                <description />
                <defaultValue>current</defaultValue>
                <trim>false</trim>
            </d>
        </c>

AFTER

        <c>
            <d>
                <name>VERSION</name>
                <description />
                <defaultValue>v2.0.0</defaultValue>
                <trim>false</trim>
            </d>
            <d>
                <name>LINK</name>
                <description />
                <defaultValue>I changed the link</defaultValue>
                <trim>false</trim>
            </d>
        </c>

I have an XML file and I want to change the default values.
I tried with this code but didn't work and idk how to handle it :

from xml.etree import ElementTree as ET
tab = ["V2.0.0, "I changed the link"]
i = 0
tree = ET.parse("myfile.xml")
for child in tree.findall(".//d"):
    tree.find(".//defaultValue").text = tab[i]
    i=+1

Thank you for your help !

Body:
Try to change

tree.find(".//defaultValue").text = tab[i]

with

child.find(".//defaultValue").text = tab[i]

Add this line of code as the last line of your script in order to see the modified XML

ET.dump(tree)


问:
Summation of each column by selected few specific rows - in R
I have started learning R recently. For one of my codes, I have been trying to debug this issue for quite a while.

I have the data which looks like this:

```<code>dd
    [,1]       [,2]   [,3]
[1,] "Category" "A"    "B"
[2,] "ONE"      "23"   "45"
[3,] "TWO"      "234"  "23"
[4,] "THREE"    "565"  "324"
[5,] "FOUR"     "676"  "343"
[6,] "FIVE"     "1231" "544"
</code>```

I want to add rows: ONE, THREE and FIVE (in Category) for each of the columns. Therefore, the output will look like:

```<code>sum  1819   913
</code>```

I have tried to use rowSums and sum. I get error every time I use this. One of the most common error is shown below.

```<code>sum = rowSums(subset(dd, CATEGORY == 'ONE', 'THREE', 'FIVE'))
Error in rowSums(subset(spread_DNT_TXN, CATEGORY == "Invoiced")) :
  'x' must be numeric
</code>```

I am looking for how I can perform this function. I am unable to find it anywhere.

Thanks in advance!

答:
To start, you can use the %in% operator and colSums:

```<code>colSums( dd[dd$Category %in% c("ONE", "THREE", "FIVE"), c("A", "B") )
</code>```

However, I recommend using data.table rather than data.frame or dplyr. I find slicing and grouping to be very clear with this package.

First, install and load data.table:

```<code>install.packages("data.table")
library(data.table)
</code>```

Then turn your old data.frame to a data.table:

```<code>dd <- as.data.table(dd)
</code>```

Now sum:

```<code>dd[Category %in% c("ONE", "THREE", "FIVE"), list(Sum_of_A = sum(A), Sum_of_B = sum(B))]
</code>```

Body:
I have started learning R recently. For one of my codes, I have been trying to debug this issue for quite a while.

I have the data which looks like this:

dd
    [,1]       [,2]   [,3]
[1,] "Category" "A"    "B"
[2,] "ONE"      "23"   "45"
[3,] "TWO"      "234"  "23"
[4,] "THREE"    "565"  "324"
[5,] "FOUR"     "676"  "343"
[6,] "FIVE"     "1231" "544"

I want to add rows: ONE, THREE and FIVE (in Category) for each of the columns. Therefore, the output will look like:

sum  1819   913

I have tried to use rowSums and sum. I get error every time I use this. One of the most common error is shown below.

sum = rowSums(subset(dd, CATEGORY == 'ONE', 'THREE', 'FIVE'))
Error in rowSums(subset(spread_DNT_TXN, CATEGORY == "Invoiced")) :
  'x' must be numeric

I am looking for how I can perform this function. I am unable to find it anywhere.

Thanks in advance!

Body:
To start, you can use the %in% operator and colSums:

colSums( dd[dd$Category %in% c("ONE", "THREE", "FIVE"), c("A", "B") )

However, I recommend using data.table rather than data.frame or dplyr. I find slicing and grouping to be very clear with this package.

First, install and load data.table:

install.packages("data.table")
library(data.table)

Then turn your old data.frame to a data.table:

dd <- as.data.table(dd)

Now sum:

dd[Category %in% c("ONE", "THREE", "FIVE"), list(Sum_of_A = sum(A), Sum_of_B = sum(B))]


问:
Object returned from onCreateLoader must not be a non-static inner member class: DumbLoader
I am trying to implement the Cursor Loader and Custom Cursor Adapter with the database(Sqlite local database) in
my android project. I actually want to feed my listview asynchronously with data from my local database with the help of the Cursor Loader and Adapter`. Below is are my class,subclass and methods

```<code>        // Home Activity class
        public class HomeActivity extends FragmentActivity implements LoaderCallbacks<Cursor> {
                DotCursorAdapter mAdapter;
                private ListView lv;
                private  final int LOADER_ID = 1932;

         DatabaseHandler dbHelper = new DatabaseHandler(this);

         @Override
         protected void onCreate(Bundle savedInstanceState) {
             super.onCreate(savedInstanceState);
                setContentView(R.layout.home_activity);
             lv = (ListView) findViewById(R.id.lists);

             mAdapter = new DotCursorAdapter(this, null,0);
             lv.setAdapter(mAdapter);

             getSupportLoaderManager().initLoader(LOADER_ID, null, this);
        }

         @Override
         public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
             return new DumbLoader(this);
         }
         @Override
         public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
             mAdapter.swapCursor(cursor);
         }
         @Override
         public void onLoaderReset(Loader<Cursor> cursorLoader) {
             mAdapter.swapCursor(null);
         }

        /**
         * DumbLoader sub class
         */
         public class DumbLoader extends CursorLoader {
             private static final String TAG = "DumbLoader";
             public DumbLoader(Context context) {
                 super(context);
             }
             @Override
             public Cursor loadInBackground() {
                 Cursor c = dbHelper.fetchAllCountries();

                 return c;

             }
        }

        /**
         * DotCursor Adapter sub class
         */
        public final class DotCursorAdapter extends CursorAdapter {

             public DotCursorAdapter(Context context, Cursor cursor, int flags) {
                  super(context, cursor, 0);
              }

             @Override
             public void bindView(View view, Context context, Cursor cursor) {

                  // Find fields to populate in inflated template
                  TextView tvBody = (TextView) view.findViewById(R.id.header_text);

                  String body = cursor.getString(cursor.getColumnIndexOrThrow("fname"));
                  // Populate fields with extracted properties
                  tvBody.setText(body);

             }
             @Override
              public View newView(Context context, Cursor cursor, ViewGroup parent) {
                  return LayoutInflater.from(context).inflate(R.layout.list_cardview_activity, parent, false);
              }
            }
    }
</code>```

Below also is my database handler method which fetches the data from the database.

```<code>public  Cursor fetchAllCountries() {
    SQLiteDatabase db = this.getReadableDatabase();

      Cursor mCursor = db.query(TABLE_LOGIN, new String[] {KEY_ID,KEY_FIRSTNAME},
        null, null, null, null, null);

      if (mCursor != null) {
       mCursor.moveToFirst();
      }
      return mCursor;
     }
</code>```

The Problem
On executing this codes above it gives a message error from the log cat and craches the app.

the main error

Object returned from onCreateLoader must not be a non-static inner
  member class

Below also is my log cat details

09-21 16:13:25.563: D/AbsListView(26541): Get MotionRecognitionManager
  09-21 16:13:25.568: D/AndroidRuntime(26541): Shutting down VM 09-21
  16:13:25.573: W/dalvikvm(26541): threadid=1: thread exiting with
  uncaught exception (group=0x411372a0) 09-21 16:13:25.573:
  E/AndroidRuntime(26541): FATAL EXCEPTION: main 09-21 16:13:25.573:
  E/AndroidRuntime(26541): java.lang.RuntimeException: Unable to start
  activity
  ComponentInfo{com.alliswell.alliswell/com.alliswell.alliswell.HomeActivity}:
  java.lang.IllegalArgumentException: Object returned from
  onCreateLoader must not be a non-static inner member class:
  DumbLoader{418dc668 id=0} 09-21 16:13:25.573: E/AndroidRuntime(26541):
    at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2110)
  09-21 16:13:25.573: E/AndroidRuntime(26541):  at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2135)
  09-21 16:13:25.573: E/AndroidRuntime(26541):  at
  android.app.ActivityThread.access$700(ActivityThread.java:140) 09-21
  16:13:25.573: E/AndroidRuntime(26541):    at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1237)
  09-21 16:13:25.573: E/AndroidRuntime(26541):  at
  android.os.Handler.dispatchMessage(Handler.java:99) 09-21
  16:13:25.573: E/AndroidRuntime(26541):    at
  android.os.Looper.loop(Looper.java:137) 09-21 16:13:25.573:
  E/AndroidRuntime(26541):  at
  android.app.ActivityThread.main(ActivityThread.java:4921) 09-21
  16:13:25.573: E/AndroidRuntime(26541):    at
  java.lang.reflect.Method.invokeNative(Native Method) 09-21
  16:13:25.573: E/AndroidRuntime(26541):    at
  java.lang.reflect.Method.invoke(Method.java:511) 09-21 16:13:25.573:
  E/AndroidRuntime(26541):  at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
  09-21 16:13:25.573: E/AndroidRuntime(26541):  at
  com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805) 09-21
  16:13:25.573: E/AndroidRuntime(26541):    at
  dalvik.system.NativeStart.main(Native Method) 09-21 16:13:25.573:
  E/AndroidRuntime(26541): Caused by:
  java.lang.IllegalArgumentException: Object returned from
  onCreateLoader must not be a non-static inner member class:
  DumbLoader{418dc668 id=0} 09-21 16:13:25.573: E/AndroidRuntime(26541):
    at
  android.support.v4.app.LoaderManagerImpl$LoaderInfo.start(LoaderManager.java:257)
  09-21 16:13:25.573: E/AndroidRuntime(26541):  at
  android.support.v4.app.LoaderManagerImpl.doStart(LoaderManager.java:714)
  09-21 16:13:25.573: E/AndroidRuntime(26541):  at
  android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:556)
  09-21 16:13:25.573: E/AndroidRuntime(26541):  at
  android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1178)
  09-21 16:13:25.573: E/AndroidRuntime(26541):  at
  android.app.Activity.performStart(Activity.java:5198) 09-21
  16:13:25.573: E/AndroidRuntime(26541):    at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2083)
  09-21 16:13:25.573: E/AndroidRuntime(26541):  ... 11 more

I think I am doing something wrong within my codes, I would be grateful if someone could help me solve this problem. Thank you.

答: LuksProg and BamsBamx suggestions are correct. Just to give more context to it, if you use a non-static inner class which extends AsyncTask or AsyncTaskLoader or if any kind of activity is happening in that class which is not on the main thread then the Runtime Exception is thrown. The reason is that if some background task is going on in a non-static inner class and at that time the parent activity is destroyed then there will be a memory leak as the inner classes always have a context stored of their parent classes. That's why to prevent the memory leak, any background operations have to be carried out in a static inner class or in a separate individual class. For more insights see this SO thread

Body:
I am trying to implement the Cursor Loader and Custom Cursor Adapter with the database(Sqlite local database) in
my android project. I actually want to feed my listview asynchronously with data from my local database with the help of the Cursor Loader and Adapter`. Below is are my class,subclass and methods

        // Home Activity class
        public class HomeActivity extends FragmentActivity implements LoaderCallbacks<Cursor> {
                DotCursorAdapter mAdapter;
                private ListView lv;
                private  final int LOADER_ID = 1932;

         DatabaseHandler dbHelper = new DatabaseHandler(this);

         @Override
         protected void onCreate(Bundle savedInstanceState) {
             super.onCreate(savedInstanceState);
                setContentView(R.layout.home_activity);
             lv = (ListView) findViewById(R.id.lists);

             mAdapter = new DotCursorAdapter(this, null,0);
             lv.setAdapter(mAdapter);

             getSupportLoaderManager().initLoader(LOADER_ID, null, this);
        }

         @Override
         public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
             return new DumbLoader(this);
         }
         @Override
         public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
             mAdapter.swapCursor(cursor);
         }
         @Override
         public void onLoaderReset(Loader<Cursor> cursorLoader) {
             mAdapter.swapCursor(null);
         }

        /**
         * DumbLoader sub class
         */
         public class DumbLoader extends CursorLoader {
             private static final String TAG = "DumbLoader";
             public DumbLoader(Context context) {
                 super(context);
             }
             @Override
             public Cursor loadInBackground() {
                 Cursor c = dbHelper.fetchAllCountries();

                 return c;

             }
        }

        /**
         * DotCursor Adapter sub class
         */
        public final class DotCursorAdapter extends CursorAdapter {

             public DotCursorAdapter(Context context, Cursor cursor, int flags) {
                  super(context, cursor, 0);
              }

             @Override
             public void bindView(View view, Context context, Cursor cursor) {

                  // Find fields to populate in inflated template
                  TextView tvBody = (TextView) view.findViewById(R.id.header_text);

                  String body = cursor.getString(cursor.getColumnIndexOrThrow("fname"));
                  // Populate fields with extracted properties
                  tvBody.setText(body);

             }
             @Override
              public View newView(Context context, Cursor cursor, ViewGroup parent) {
                  return LayoutInflater.from(context).inflate(R.layout.list_cardview_activity, parent, false);
              }
            }
    }

Below also is my database handler method which fetches the data from the database.

public  Cursor fetchAllCountries() {
    SQLiteDatabase db = this.getReadableDatabase();

      Cursor mCursor = db.query(TABLE_LOGIN, new String[] {KEY_ID,KEY_FIRSTNAME},
        null, null, null, null, null);

      if (mCursor != null) {
       mCursor.moveToFirst();
      }
      return mCursor;
     }

The Problem
On executing this codes above it gives a message error from the log cat and craches the app.

the main error

Object returned from onCreateLoader must not be a non-static inner
  member class

Below also is my log cat details

09-21 16:13:25.563: D/AbsListView(26541): Get MotionRecognitionManager
  09-21 16:13:25.568: D/AndroidRuntime(26541): Shutting down VM 09-21
  16:13:25.573: W/dalvikvm(26541): threadid=1: thread exiting with
  uncaught exception (group=0x411372a0) 09-21 16:13:25.573:
  E/AndroidRuntime(26541): FATAL EXCEPTION: main 09-21 16:13:25.573:
  E/AndroidRuntime(26541): java.lang.RuntimeException: Unable to start
  activity
  ComponentInfo{com.alliswell.alliswell/com.alliswell.alliswell.HomeActivity}:
  java.lang.IllegalArgumentException: Object returned from
  onCreateLoader must not be a non-static inner member class:
  DumbLoader{418dc668 id=0} 09-21 16:13:25.573: E/AndroidRuntime(26541):
    at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2110)
  09-21 16:13:25.573: E/AndroidRuntime(26541):  at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2135)
  09-21 16:13:25.573: E/AndroidRuntime(26541):  at
  android.app.ActivityThread.access$700(ActivityThread.java:140) 09-21
  16:13:25.573: E/AndroidRuntime(26541):    at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1237)
  09-21 16:13:25.573: E/AndroidRuntime(26541):  at
  android.os.Handler.dispatchMessage(Handler.java:99) 09-21
  16:13:25.573: E/AndroidRuntime(26541):    at
  android.os.Looper.loop(Looper.java:137) 09-21 16:13:25.573:
  E/AndroidRuntime(26541):  at
  android.app.ActivityThread.main(ActivityThread.java:4921) 09-21
  16:13:25.573: E/AndroidRuntime(26541):    at
  java.lang.reflect.Method.invokeNative(Native Method) 09-21
  16:13:25.573: E/AndroidRuntime(26541):    at
  java.lang.reflect.Method.invoke(Method.java:511) 09-21 16:13:25.573:
  E/AndroidRuntime(26541):  at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
  09-21 16:13:25.573: E/AndroidRuntime(26541):  at
  com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805) 09-21
  16:13:25.573: E/AndroidRuntime(26541):    at
  dalvik.system.NativeStart.main(Native Method) 09-21 16:13:25.573:
  E/AndroidRuntime(26541): Caused by:
  java.lang.IllegalArgumentException: Object returned from
  onCreateLoader must not be a non-static inner member class:
  DumbLoader{418dc668 id=0} 09-21 16:13:25.573: E/AndroidRuntime(26541):
    at
  android.support.v4.app.LoaderManagerImpl$LoaderInfo.start(LoaderManager.java:257)
  09-21 16:13:25.573: E/AndroidRuntime(26541):  at
  android.support.v4.app.LoaderManagerImpl.doStart(LoaderManager.java:714)
  09-21 16:13:25.573: E/AndroidRuntime(26541):  at
  android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:556)
  09-21 16:13:25.573: E/AndroidRuntime(26541):  at
  android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1178)
  09-21 16:13:25.573: E/AndroidRuntime(26541):  at
  android.app.Activity.performStart(Activity.java:5198) 09-21
  16:13:25.573: E/AndroidRuntime(26541):    at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2083)
  09-21 16:13:25.573: E/AndroidRuntime(26541):  ... 11 more

I think I am doing something wrong within my codes, I would be grateful if someone could help me solve this problem. Thank you.


问:
Getting comma separated values from PHP array
I have an array thusly

```<code>$main_array = [

    ["image" => "james.jpg", "name" => "james", "tag" => "spacey, wavy"],
    ["image" => "ned.jpg", "name" => "ned", "tag" => "bright"]
    ["image" => "helen.jpg", "name" => "helen", "tag" => "wavy, bright"]

]
</code>```

I use a foreach to echo some HTML based on the value of tag. Something like this

```<code>    foreach($main_array as $key => $array) {
        if ($array['tag'] == "bright") {
            echo '<p>'.$array['name'].' '.$array['image'].' '.$array['tag'].'</p>';
        }
    }
</code>```

This only outputs "ned" as matching the tag "bright". But it should output "helen" too. Similarly:

```<code>    foreach($main_array as $key => $array) {
        if ($array['tag'] == "wavy") {
            echo '<p>'.$array['name'].' '.$array['image'].' '.$array['tag'].'</p>';
        }
    }
</code>```

Should output "james" and "helen". What kind of function do I need to achieve the desired result?

答:
When checking an item in a list of items, you can use explode() to split it into parts (I've used split by ", " as each item seems to have a space as well) and then use in_array() to check if it is in the list...

```<code>if (in_array("bright", explode( ", ", $array['tag']))) {
</code>```

Body:
I have an array thusly

$main_array = [

    ["image" => "james.jpg", "name" => "james", "tag" => "spacey, wavy"],
    ["image" => "ned.jpg", "name" => "ned", "tag" => "bright"]
    ["image" => "helen.jpg", "name" => "helen", "tag" => "wavy, bright"]

]

I use a foreach to echo some HTML based on the value of tag. Something like this

    foreach($main_array as $key => $array) {
        if ($array['tag'] == "bright") {
            echo '
'.$array['name'].' '.$array['image'].' '.$array['tag'].'
';
        }
    }

This only outputs "ned" as matching the tag "bright". But it should output "helen" too. Similarly:

    foreach($main_array as $key => $array) {
        if ($array['tag'] == "wavy") {
            echo '
'.$array['name'].' '.$array['image'].' '.$array['tag'].'
';
        }
    }

Should output "james" and "helen". What kind of function do I need to achieve the desired result?

Body:
When checking an item in a list of items, you can use explode() to split it into parts (I've used split by ", " as each item seems to have a space as well) and then use in_array() to check if it is in the list...

if (in_array("bright", explode( ", ", $array['tag']))) {


问:
CollectionView sections
I have a collectionview and I want it to be of n section where each section has a ten of cells, my problem is: Maybe n equals thirty five, in this case I want to show 3 section with ten of cells and the last section with just five. </p>

答:
You can split the array into chunks using this extension

```<code>extension Array {
    func chunked(into size: Int) -> [[Element]] {
        return stride(from: 0, to: count, by: size).map {
            Array(self[$0 ..< Swift.min($0 + size, count)])
        }
    }
}
</code>```

If count is 35 -> [10,10,10,5]

If count is 30 -> [10,10,10]

If count is 29 -> [10,10,9]

Then use the two dimensional array in collectionview delegate methods

```<code>class ViewController: UIViewController, UICollectionViewDataSource {
    let array = Array(1...35)
    lazy var chunkedArray = array.chunked(into: 10)

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return chunkedArray.count
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return chunkedArray[section].count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
        print(chunkedArray[indexPath.section][indexPath.item])
        return cell
    }
}
</code>```

Title: CollectionView sections

Body:
You can split the array into chunks using this extension

extension Array {
    func chunked(into size: Int) -> [[Element]] {
        return stride(from: 0, to: count, by: size).map {
            Array(self[$0 ..< Swift.min($0 + size, count)])
        }
    }
}

If count is 35 -> [10,10,10,5]

If count is 30 -> [10,10,10]

If count is 29 -> [10,10,9]

Then use the two dimensional array in collectionview delegate methods

class ViewController: UIViewController, UICollectionViewDataSource {
    let array = Array(1...35)
    lazy var chunkedArray = array.chunked(into: 10)

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return chunkedArray.count
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return chunkedArray[section].count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
        print(chunkedArray[indexPath.section][indexPath.item])
        return cell
    }
}