问:
How to create range slider? (react-native)
This is my range slider

But for change values user need to click on this value. How to make, to be able to pull the slider? Thanks.

答:
If I were you, without any doubt, I'd search for a library to do the heavy lifting for me.

Assuming you need cross-platform (iOS and Android) range slider solution, based on my research by the time of writing this answer, the plugin which gave the best results in terms of performance on both platforms and customizability options is @ptomasroos/react-native-multi-slider.

It lacks good documentation, but there is example available. Here's the basic set-up:

```<code>import React from 'react';
import { View, Text } from 'react-native';
import MultiSlider from '@ptomasroos/react-native-multi-slider';

class RangeSlider extends React.Component {
    state = {
        values: [3, 7],
    };

    multiSliderValuesChange = (values) => {
        this.setState({
            values,
        });
    }

    render() {
        return (
            <View>
                <MultiSlider
                    values={[this.state.values[0], this.state.values[1]]}
                    sliderLength={280}
                    onValuesChange={this.multiSliderValuesChange}
                    min={0}
                    max={10}
                    step={1}
                />
                <Text style={styles.text}>Two Markers:</Text>
                <Text style={styles.text}>{this.state.values[0]}</Text>
                <Text style={styles.text}>{this.state.values[1]}</Text>
            </View>
        )
    }
}
</code>```

Body:
If I were you, without any doubt, I'd search for a library to do the heavy lifting for me.

Assuming you need cross-platform (iOS and Android) range slider solution, based on my research by the time of writing this answer, the plugin which gave the best results in terms of performance on both platforms and customizability options is @ptomasroos/react-native-multi-slider.

It lacks good documentation, but there is example available. Here's the basic set-up:

import React from 'react';
import { View, Text } from 'react-native';
import MultiSlider from '@ptomasroos/react-native-multi-slider';

class RangeSlider extends React.Component {
    state = {
        values: [3, 7],
    };

    multiSliderValuesChange = (values) => {
        this.setState({
            values,
        });
    }

    render() {
        return (
            <View>
                <MultiSlider
                    values={[this.state.values[0], this.state.values[1]]}
                    sliderLength={280}
                    onValuesChange={this.multiSliderValuesChange}
                    min={0}
                    max={10}
                    step={1}
                />
                <Text style={styles.text}>Two Markers:</Text>
                <Text style={styles.text}>{this.state.values[0]}</Text>
                <Text style={styles.text}>{this.state.values[1]}</Text>
            </View>
        )
    }
}


来源: stackexchange

问:
How things looks a like behind Ajax calls
I just started learning Ajax, and most people as I saw working with Ajax (making Get and Post requests) like this:

```<code>$.ajax({
         method: "GET",
         url: "Customers/GetCustomerById",
         data: { customerId: Id }
        })
.done(function (response) {
//Do something here
});
</code>```

I red behind Ajax is XMLHttpRequest object, so does that means when code above is used, something like this is happening "behind the scene" :

```<code>httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function someMyFunction(){
    // Process the server response here.
};
http.open("GET", url+"?"+customerId, true);
</code>```

Is this true?

And is this second approach avoided today? Or it's still being used?
I'm just learning web and I don't know so that's reason why I'm asking..

And I'm wondering also why people are using this "first" approach, maybe they are not but I acctually saw it on many places...

Thanks a lot guys and cheers!

答:
I red behind Ajax is XMLHttpRequest object

XHR is one browser API used to perform Ajax. There are several others. XHR is probably most commonly used.

Is this true?

jQuery does do something along those lines behind the scenes.

And is this second approach avoided today?

No.

Some people use jQuery because they find it more convenient than using the native browser APIs or another library. Other people do not use jQuery.

ContentLicense: CC BY-SA 3.0

Body:
I just started learning Ajax, and most people as I saw working with Ajax (making Get and Post requests) like this:

$.ajax({
         method: "GET",
         url: "Customers/GetCustomerById",
         data: { customerId: Id }
        })
.done(function (response) {
//Do something here
});

I red behind Ajax is XMLHttpRequest object, so does that means when code above is used, something like this is happening "behind the scene" :

httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function someMyFunction(){
    // Process the server response here.
};
http.open("GET", url+"?"+customerId, true);

Is this true?

And is this second approach avoided today? Or it's still being used?
I'm just learning web and I don't know so that's reason why I'm asking..

And I'm wondering also why people are using this "first" approach, maybe they are not but I acctually saw it on many places...

Thanks a lot guys and cheers!


问:
static list in Android Activity and memory leak
I have an ArrayList with more than 1000 string items in an Activity. Number of members of ArrayList does not change and no element update occurs. That Activity can be created and destroyed many times during application life time, but also it may be a few times. Also, ArrayList will be used to construct a ListView. Now I have two approaches in about ArrayList:

setting its variable as static to avoid creating objects and initializing ArrayList each time in onCreate() of Activity

creating and initializing ArrayList in onCreate() of Activity to avoid memory leak

I do not know which way is better or is there any other way?

答: If you don't need to display all 1000 elements at once, you can try to use SQLite database and Cursor, which will partially load strings that you need at the moment.</p>


问:
is this approach unidirectional or bidirectional
Consider following entities

UserDetails (with Vehicles)

```<code>@Entity
public class UserDetails {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int userId;
private String userName;

@OneToMany(mappedBy="user",cascade=CascadeType.ALL,orphanRemoval=true)
private List<Vehicle> vehicleList = new ArrayList<>();

//getter setters
}
</code>```

Vehicle

```<code>@Entity
public class Vehicle {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int vehicleId;
private String vehicleName;

@ManyToOne
@JoinColumn(name="user_id")
private UserDetails user;

//getter setters
}
</code>```

Why we should use the above @OneToMany code if we can achieve the same db tables using the code below? Is the use of @OneToMany here just giving a solution of accessing the vehicle from user side
and if i have no requirement of accessing the vehicle for any user , this is correct configuration?

And since it gives same table configuration as bi-directional, what
should we say it uni-directional or bi-directional approach? I think as per code we cannot access vehicle from user side but user from vehicle side so is it a kind of uni-directional?

UserDetails (without Vehicle)

```<code>@Entity
public class UserDetails {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int userId;
private String userName;

//getter setters
}
</code>```

Table UserDetails

```<code>mysql> select * from userdetails;
+--------+------------+
| userId | userName   |
+--------+------------+
|        | First User |
+--------+------------+
1 row in set (0.00 sec)
</code>```

Table Vehicle

```<code>mysql> select * from vehicle;
+-----------+-------------+---------+
| vehicleId | vehicleName | user_id |
+-----------+-------------+---------+
|         2 | karizma     |         |
|         3 | scooty-pep  |         |
+-----------+-------------+---------+
2 rows in set (0.00 sec)
</code>```

答:
The answer -afaik- is pretty much as you said

Is the use of @OneToMany here just giving a solution of accessing the
  vehicle from user side

So with this

and if i have no requirement of accessing the
  vehicle for any user , this is correct configuration?

it might not be the correct configuration. All I can think why not is that it affects on the performance: when populating the list of vehicles if there are many UserDetails with many Vehicles.

It is a possible to set the FetchType.LAZY for List<Vehicle> but depending how the JPA implementation does its internal optimization & caching that might not be always obeyed.

Body:
Consider following entities

UserDetails (with Vehicles)

@Entity
public class UserDetails {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int userId;
private String userName;

@OneToMany(mappedBy="user",cascade=CascadeType.ALL,orphanRemoval=true)
private List<Vehicle> vehicleList = new ArrayList<>();

//getter setters
}

Vehicle

@Entity
public class Vehicle {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int vehicleId;
private String vehicleName;

@ManyToOne
@JoinColumn(name="user_id")
private UserDetails user;

//getter setters
}

Why we should use the above @OneToMany code if we can achieve the same db tables using the code below? Is the use of @OneToMany here just giving a solution of accessing the vehicle from user side
and if i have no requirement of accessing the vehicle for any user , this is correct configuration?

And since it gives same table configuration as bi-directional, what
should we say it uni-directional or bi-directional approach? I think as per code we cannot access vehicle from user side but user from vehicle side so is it a kind of uni-directional?

UserDetails (without Vehicle)

@Entity
public class UserDetails {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int userId;
private String userName;

//getter setters
}

Table UserDetails

mysql> select * from userdetails;
+--------+------------+
| userId | userName   |
+--------+------------+
|        | First User |
+--------+------------+
1 row in set (0.00 sec)

Table Vehicle

mysql> select * from vehicle;
+-----------+-------------+---------+
| vehicleId | vehicleName | user_id |
+-----------+-------------+---------+
|         2 | karizma     |         |
|         3 | scooty-pep  |         |
+-----------+-------------+---------+
2 rows in set (0.00 sec)


问:
How to save Mobx state in sessionStorage
Trying to essentially accomplish this https://github.com/elgerlambert/redux-localstorage which is for Redux but do it for Mobx. And preferably would like to use sessionStorage. Is there an easy way to accomplish this with minimal boilerplate?</p>

答:
Here, you can use my code, although it only supports localStorage you should be able to modify it quite easily.

https://github.com/nightwolfz/mobx-storage


答:
1) Uni-directional is enough, even for the schema generation h2ddl tool. Keep in mind that you can also have a uni-directional mapping with only @OneToMany defined.

2) The biggest reason, apart from gaining access to the collection, in your case would be to be able to cascade the UserDetails operations onto the Vehicle entities, along with the removal of Vehicles when you clear them from the vehicleList collection.. which I guess you do not want to do logic-wise.

3) The only drawback with uni-directional would be the fact that you would need to write custom queries in order to get all vehicles for a user. With bidirectional you find a user and the vehicle collection is already there ready to be lazy loaded.

Personally I would keep that OneToMany but remove the cascading, orphanRemoval options.

Title: is this approach unidirectional or bidirectional


问:
Is it safe to use async/await inside akka.net actor
In the following code, I am using the syntactic sugar provided by .net, the async/await approach, but read that this is not a good way of handling asynchronous operations within akka, and I should rather use PipeTo().

```<code>public class AggregatorActor : ActorBase, IWithUnboundedStash
{
    #region Constructor
    public AggregatorActor(IActorSystemSettings settings, IAccountComponent component, LogSettings logSettings) : base(settings, logSettings)
    {
        _accountComponent = component;
        _settings = settings;
    }
    #endregion

    #region Public Methods

    public override void Listening()
    {

        ReceiveAsync<ProfilerMessages.ProfilerBase>(async x => await HandleMessage(x));
        ReceiveAsync<ProfilerMessages.TimeElasped>(async x => await HandleMessage(x));
    }
    public override async Task HandleMessage(object msg)
    {
        msg.Match().With<ProfilerMessages.GetSummary>(async x =>
        {
            _sender = Context.Sender;
            //Become busy. Stash
            Become(Busy);

            //Handle different request
            await HandleSummaryRequest(x.UserId, x.CasinoId, x.GamingServerId, x.AccountNumber, x.GroupName);
        });
        msg.Match().With<ProfilerMessages.RecurringCheck>(x =>
        {
            _logger.Info("Recurring Message");
            if (IsAllResponsesReceived())
            {
                BeginAggregate();
            }
        });
        msg.Match().With<ProfilerMessages.TimeElasped>(x =>
        {
            _logger.Info("Time Elapsed");
            BeginAggregate();
        });
    }
    private async Task HandleSummaryRequest(int userId, int casinoId, int gsid, string accountNumber, string groupName)
    {
        try
        {
            var accountMsg = new AccountMessages.GetAggregatedData(userId, accountNumber, casinoId, gsid);
            //AskPattern.AskAsync<AccountMessages.AccountResponseAll>(Context.Self, _accountActor, accountMsg, _settings.NumberOfMilliSecondsToWaitForResponse, (x) => { return x; });
            _accountActor.Tell(accountMsg);

            var contactMsg = new ContactMessages.GetAggregatedContactDetails(userId);
            //AskPattern.AskAsync<Messages.ContactMessages.ContactResponse>(Context.Self, _contactActor, contactMsg, _settings.NumberOfMilliSecondsToWaitForResponse, (x) => { return x; });
            _contactActor.Tell(contactMsg);

            var analyticMsg = new AnalyticsMessages.GetAggregatedAnalytics(userId, casinoId, gsid);
            //AskPattern.AskAsync<Messages.AnalyticsMessages.AnalyticsResponse>(Context.Self, _analyticsActor, analyticMsg, _settings.NumberOfMilliSecondsToWaitForResponse, (x) => { return x; });
            _analyticsActor.Tell(analyticMsg);

            var financialMsg = new FinancialMessages.GetAggregatedFinancialDetails(userId.ToString());
            //AskPattern.AskAsync<Messages.FinancialMessages.FinancialResponse>(Context.Self, _financialActor, financialMsg, _settings.NumberOfMilliSecondsToWaitForResponse, (x) => { return x; });
            _financialActor.Tell(financialMsg);

            var verificationMsg = VerificationMessages.GetAggregatedVerification.Instance(groupName, casinoId.ToString(), userId.ToString(), gsid);
            _verificationActor.Tell(verificationMsg);

            var riskMessage = RiskMessages.GeAggregatedRiskDetails.Instance(userId, accountNumber, groupName, casinoId, gsid);
            _riskActor.Tell(riskMessage);

            _cancelable = Context.System.Scheduler.ScheduleTellOnceCancelable(TimeSpan.FromMilliseconds(_settings.AggregatorTimeOut), Self, Messages.ProfilerMessages.TimeElasped.Instance(), Self);
            _cancelRecurring = Context.System.Scheduler.ScheduleTellRepeatedlyCancelable(_settings.RecurringResponseCheck, _settings.RecurringResponseCheck, Self, Messages.ProfilerMessages.RecurringCheck.Instance(), Self);
        }
        catch (Exception ex)
        {
            ExceptionHandler(ex);
        }
    }
    #endregion
}
</code>```

As you can see in the example code, I am making use of async/await, and using the ReceiveAsync() method procided by Akka.net.

What is the purpose of ReceiveAsync(), if we cannot use async/await within an actor?

答:
You can use async/await within an actor, however this requires a little bit of orchestration necessary to suspend/resume actor's mailbox until the the asynchronous task completes. This makes actor non-reentrant, which means that it will not pick any new messages, until the current task is finished. To make use of async/await within an actor you can either:

Use ReceiveAsync which can take async handlers.

Wrapping your async method call with ActorTaskScheduler.RunTask. This is usually useful in context of actor lifecycle methods (like PreStart/PostStop).

Keep in mind that this will work if a default actor message dispatcher is used, but it's not guaranteed to work, if an actor is configured to use different types of dispatchers.

Also there is a performance downside associated with using async/await inside actors, which is related to suspend/resume mechanics and lack of reentrancy of your actors. In many business cases it's not really a problem, but can sometimes be an issue in high-performance/low-latency workflows.

Body:
In the following code, I am using the syntactic sugar provided by .net, the async/await approach, but read that this is not a good way of handling asynchronous operations within akka, and I should rather use PipeTo().

public class AggregatorActor : ActorBase, IWithUnboundedStash
{
    #region Constructor
    public AggregatorActor(IActorSystemSettings settings, IAccountComponent component, LogSettings logSettings) : base(settings, logSettings)
    {
        _accountComponent = component;
        _settings = settings;
    }
    #endregion

    #region Public Methods

    public override void Listening()
    {

        ReceiveAsync<ProfilerMessages.ProfilerBase>(async x => await HandleMessage(x));
        ReceiveAsync<ProfilerMessages.TimeElasped>(async x => await HandleMessage(x));
    }
    public override async Task HandleMessage(object msg)
    {
        msg.Match().With<ProfilerMessages.GetSummary>(async x =>
        {
            _sender = Context.Sender;
            //Become busy. Stash
            Become(Busy);

            //Handle different request
            await HandleSummaryRequest(x.UserId, x.CasinoId, x.GamingServerId, x.AccountNumber, x.GroupName);
        });
        msg.Match().With<ProfilerMessages.RecurringCheck>(x =>
        {
            _logger.Info("Recurring Message");
            if (IsAllResponsesReceived())
            {
                BeginAggregate();
            }
        });
        msg.Match().With<ProfilerMessages.TimeElasped>(x =>
        {
            _logger.Info("Time Elapsed");
            BeginAggregate();
        });
    }
    private async Task HandleSummaryRequest(int userId, int casinoId, int gsid, string accountNumber, string groupName)
    {
        try
        {
            var accountMsg = new AccountMessages.GetAggregatedData(userId, accountNumber, casinoId, gsid);
            //AskPattern.AskAsync<AccountMessages.AccountResponseAll>(Context.Self, _accountActor, accountMsg, _settings.NumberOfMilliSecondsToWaitForResponse, (x) => { return x; });
            _accountActor.Tell(accountMsg);

            var contactMsg = new ContactMessages.GetAggregatedContactDetails(userId);
            //AskPattern.AskAsync<Messages.ContactMessages.ContactResponse>(Context.Self, _contactActor, contactMsg, _settings.NumberOfMilliSecondsToWaitForResponse, (x) => { return x; });
            _contactActor.Tell(contactMsg);

            var analyticMsg = new AnalyticsMessages.GetAggregatedAnalytics(userId, casinoId, gsid);
            //AskPattern.AskAsync<Messages.AnalyticsMessages.AnalyticsResponse>(Context.Self, _analyticsActor, analyticMsg, _settings.NumberOfMilliSecondsToWaitForResponse, (x) => { return x; });
            _analyticsActor.Tell(analyticMsg);

            var financialMsg = new FinancialMessages.GetAggregatedFinancialDetails(userId.ToString());
            //AskPattern.AskAsync<Messages.FinancialMessages.FinancialResponse>(Context.Self, _financialActor, financialMsg, _settings.NumberOfMilliSecondsToWaitForResponse, (x) => { return x; });
            _financialActor.Tell(financialMsg);

            var verificationMsg = VerificationMessages.GetAggregatedVerification.Instance(groupName, casinoId.ToString(), userId.ToString(), gsid);
            _verificationActor.Tell(verificationMsg);

            var riskMessage = RiskMessages.GeAggregatedRiskDetails.Instance(userId, accountNumber, groupName, casinoId, gsid);
            _riskActor.Tell(riskMessage);

            _cancelable = Context.System.Scheduler.ScheduleTellOnceCancelable(TimeSpan.FromMilliseconds(_settings.AggregatorTimeOut), Self, Messages.ProfilerMessages.TimeElasped.Instance(), Self);
            _cancelRecurring = Context.System.Scheduler.ScheduleTellRepeatedlyCancelable(_settings.RecurringResponseCheck, _settings.RecurringResponseCheck, Self, Messages.ProfilerMessages.RecurringCheck.Instance(), Self);
        }
        catch (Exception ex)
        {
            ExceptionHandler(ex);
        }
    }
    #endregion
}

As you can see in the example code, I am making use of async/await, and using the ReceiveAsync() method procided by Akka.net.

What is the purpose of ReceiveAsync(), if we cannot use async/await within an actor?

ContentLicense: CC BY-SA 4.0


问:
Use group by inside subquery
I am trying to display progressive_total and cumulative_sum group by the subincome field in house_details table using mysql. I built my schema in this link

working query:

```<code>SELECT *,
       COALESCE(
                  (SELECT SUM(x.rupees)
                   FROM house_details x
                   WHERE MONTH(x.date) < t1.month), '-') AS progressive_total,

  (SELECT SUM(x.rupees)
   FROM house_details x
   WHERE MONTH(x.date) <= t1.month) AS cumulative_sum
FROM
  (SELECT MONTHNAME(t.date) AS `monthname`,
          MONTH(t.date) `month`,
          YEAR(t.date) AS YEAR,
          t.income,
          t.subincome,
          t.ssubincome,
          SUM(rupees) AS amount,
          GROUP_CONCAT(receipt_id) AS receipt_ids
   FROM house_details t
   WHERE YEAR(t.date) = YEAR(CURRENT_DATE())
   GROUP BY month(t.date),
            t.subincome
   ORDER BY t.date) t1
</code>```

but this gives irrelevant cumulative_sum in the field.

I tried to use group by inside the subquery like this:

query:

```<code>SELECT *,
       COALESCE(
                  (SELECT SUM(x.rupees)
                   FROM house_details x
                   WHERE MONTH(x.date) < t1.month
                   GROUP BY x.subincome), '-') AS progressive_total,

  (SELECT SUM(x.rupees)
   FROM house_details x
   WHERE MONTH(x.date) <= t1.month
   GROUP BY x.subincome) AS cumulative_sum
FROM
  (SELECT MONTHNAME(t.date) AS `monthname`,
          MONTH(t.date) `month`,
          YEAR(t.date) AS YEAR,
          t.income,
          t.subincome,
          t.ssubincome,
          SUM(rupees) AS amount,
          GROUP_CONCAT(receipt_id) AS receipt_ids
   FROM house_details t
   WHERE YEAR(t.date) = YEAR(CURRENT_DATE())
   GROUP BY month(t.date),
            t.subincome
   ORDER BY t.date) t1;
</code>```

but it shows error sub query returns more than one row.

答:
You can use below query for your expected result set

```<code>SELECT *,
COALESCE(
    (SELECT SUM(pt.rupees) FROM (
        SELECT  MONTH(`date`) `month`,
        MAX(id) id,
        SUM(rupees) rupees
        FROM house_details
        GROUP BY `month`,subincome
    ) pt
    WHERE CASE WHEN pt.month = t1.month THEN pt.id < t1.id ELSE pt.month < t1.month END
), 0) AS progressive_total,
(SELECT SUM(rupees) FROM(
        SELECT  MONTH(`date`) `month`,
        MAX(id) id,
        SUM(rupees) rupees
        FROM house_details
        GROUP BY `month`,subincome
    ) cs
    WHERE  CASE WHEN cs.month = t1.month THEN cs.id <= t1.id ELSE cs.month <= t1.month END
) AS cumulative_sum
FROM (
    SELECT MONTHNAME(t.date) AS `monthname`,
    MAX(id) id,
    MONTH(t.date) `month`,
    YEAR(t.date) AS `year`,
    GROUP_CONCAT(t.income) income,
    t.subincome,
    GROUP_CONCAT(t.ssubincome) ssubincome,
    SUM(rupees) AS amount,
    GROUP_CONCAT(receipt_id) AS receipt_ids
    FROM house_details t
    WHERE YEAR(t.date) = YEAR(CURRENT_DATE())
    GROUP BY `monthname`,`month`, t.subincome
    ORDER BY `month`
) t1
</code>```

Demo

Title: Use group by inside subquery

Body:
I am trying to display progressive_total and cumulative_sum group by the subincome field in house_details table using mysql. I built my schema in this link

working query:

SELECT *,
       COALESCE(
                  (SELECT SUM(x.rupees)
                   FROM house_details x
                   WHERE MONTH(x.date) < t1.month), '-') AS progressive_total,

  (SELECT SUM(x.rupees)
   FROM house_details x
   WHERE MONTH(x.date) <= t1.month) AS cumulative_sum
FROM
  (SELECT MONTHNAME(t.date) AS `monthname`,
          MONTH(t.date) `month`,
          YEAR(t.date) AS YEAR,
          t.income,
          t.subincome,
          t.ssubincome,
          SUM(rupees) AS amount,
          GROUP_CONCAT(receipt_id) AS receipt_ids
   FROM house_details t
   WHERE YEAR(t.date) = YEAR(CURRENT_DATE())
   GROUP BY month(t.date),
            t.subincome
   ORDER BY t.date) t1

but this gives irrelevant cumulative_sum in the field.

I tried to use group by inside the subquery like this:

query:

SELECT *,
       COALESCE(
                  (SELECT SUM(x.rupees)
                   FROM house_details x
                   WHERE MONTH(x.date) < t1.month
                   GROUP BY x.subincome), '-') AS progressive_total,

  (SELECT SUM(x.rupees)
   FROM house_details x
   WHERE MONTH(x.date) <= t1.month
   GROUP BY x.subincome) AS cumulative_sum
FROM
  (SELECT MONTHNAME(t.date) AS `monthname`,
          MONTH(t.date) `month`,
          YEAR(t.date) AS YEAR,
          t.income,
          t.subincome,
          t.ssubincome,
          SUM(rupees) AS amount,
          GROUP_CONCAT(receipt_id) AS receipt_ids
   FROM house_details t
   WHERE YEAR(t.date) = YEAR(CURRENT_DATE())
   GROUP BY month(t.date),
            t.subincome
   ORDER BY t.date) t1;

but it shows error sub query returns more than one row.

Body:
You can use below query for your expected result set

SELECT *,
COALESCE(
    (SELECT SUM(pt.rupees) FROM (
        SELECT  MONTH(`date`) `month`,
        MAX(id) id,
        SUM(rupees) rupees
        FROM house_details
        GROUP BY `month`,subincome
    ) pt
    WHERE CASE WHEN pt.month = t1.month THEN pt.id < t1.id ELSE pt.month < t1.month END
), 0) AS progressive_total,
(SELECT SUM(rupees) FROM(
        SELECT  MONTH(`date`) `month`,
        MAX(id) id,
        SUM(rupees) rupees
        FROM house_details
        GROUP BY `month`,subincome
    ) cs
    WHERE  CASE WHEN cs.month = t1.month THEN cs.id <= t1.id ELSE cs.month <= t1.month END
) AS cumulative_sum
FROM (
    SELECT MONTHNAME(t.date) AS `monthname`,
    MAX(id) id,
    MONTH(t.date) `month`,
    YEAR(t.date) AS `year`,
    GROUP_CONCAT(t.income) income,
    t.subincome,
    GROUP_CONCAT(t.ssubincome) ssubincome,
    SUM(rupees) AS amount,
    GROUP_CONCAT(receipt_id) AS receipt_ids
    FROM house_details t
    WHERE YEAR(t.date) = YEAR(CURRENT_DATE())
    GROUP BY `monthname`,`month`, t.subincome
    ORDER BY `month`
) t1

Demo


问:
Registering ContentObserver for Android CallLog causes crash
Recently my app keeps crashing when registering a contentObserver for the Android CallLog (in onCreate of a Service). This is the way I register it:

```<code>getContentResolver().registerContentObserver(CallLog.Calls.CONTENT_URI, true, new MyObserver(new Handler()));
</code>```

Part of the stacktrace:

java.lang.RuntimeException: Unable to create service
  nl.xelion.restandroid.service.CallLogChanged:
  java.lang.SecurityException: Permission Denial: opening provider
  com.android.providers.contacts.CallLogProvider from
  ProcessRecord{f73a1ed 7949:nl.my.app.debug/u0a119}
  (pid=7949, uid=10119) requires android.permission.READ_CALL_LOG or
  android.permission.WRITE_CALL_LOG

...

Caused by: java.lang.SecurityException: Permission Denial: opening provider...etc

I used this tutorial, and it DID work for about a year:
http://www.adityathakker.com/android-content-observer-react-on-content-change

Approximately since Android O the crashes started to appear. The javadoc of registerContentObserver does say something along these lines: Starting in O, all content notifications must be backed by a valid ContentProvider. So I was wondering if this would be the problem, and if so, how to solve it?

<s>Anyway, why is it complaining about permissions for contacts, and </s>why didn't this happen before? This doesn't make sense to me.

<s>ps. I do use code which requires permission for contacts, which is called in the onChange of the ContentObserver, but even when I comment this piece of code the crash still occurs.</s>

答:
The problem lies with the update to Android O. Permissions are grouped together and since Android O permission behaviour was changed because of incorrect handling of permission requests.

In my example I had added the permissions READ_CALL_LOG/WRITE_CALL_LOG and CALL_PHONE to the manifest, but requested only CALL_PHONE at first startup of the app. This caused the permission group PHONE to be accepted, but neither of the call-log permissions. So when the registerContentObserver method was called, Android implicitly accepted it to be used because of accepting the group PHONE.

When my user upgraded from N to O, and registerContentObserver was called again, it would crash (justly). Solution: check for the READ_CALL_LOG/WRITE_CALL_LOG permisions before calling registerContentObserver.

Workaround for users on Android O who're still using the old - crashing- code: Manually turn off & on the specific permission in the Android settings of the app (so the PHONE permission group in this case). This causes all permissions in this group to be accepted (or at least those permissions in that group that are required by the app)

Body:
Recently my app keeps crashing when registering a contentObserver for the Android CallLog (in onCreate of a Service). This is the way I register it:

getContentResolver().registerContentObserver(CallLog.Calls.CONTENT_URI, true, new MyObserver(new Handler()));

Part of the stacktrace:

java.lang.RuntimeException: Unable to create service
  nl.xelion.restandroid.service.CallLogChanged:
  java.lang.SecurityException: Permission Denial: opening provider
  com.android.providers.contacts.CallLogProvider from
  ProcessRecord{f73a1ed 7949:nl.my.app.debug/u0a119}
  (pid=7949, uid=10119) requires android.permission.READ_CALL_LOG or
  android.permission.WRITE_CALL_LOG

...

Caused by: java.lang.SecurityException: Permission Denial: opening provider...etc

I used this tutorial, and it DID work for about a year:
http://www.adityathakker.com/android-content-observer-react-on-content-change

Approximately since Android O the crashes started to appear. The javadoc of registerContentObserver does say something along these lines: Starting in O, all content notifications must be backed by a valid ContentProvider. So I was wondering if this would be the problem, and if so, how to solve it?

<s>Anyway, why is it complaining about permissions for contacts, and </s>why didn't this happen before? This doesn't make sense to me.

<s>ps. I do use code which requires permission for contacts, which is called in the onChange of the ContentObserver, but even when I comment this piece of code the crash still occurs.</s>


答:
You can use singleton approach for avoiding memory leak.Below link help you to make singleton object.

ArrayList initialized/accessed using Singleton class

Title: static list in Android Activity and memory leak

Body:
I have an ArrayList with more than 1000 string items in an Activity. Number of members of ArrayList does not change and no element update occurs. That Activity can be created and destroyed many times during application life time, but also it may be a few times. Also, ArrayList will be used to construct a ListView. Now I have two approaches in about ArrayList:

setting its variable as static to avoid creating objects and initializing ArrayList each time in onCreate() of Activity

creating and initializing ArrayList in onCreate() of Activity to avoid memory leak

I do not know which way is better or is there any other way?


问:
how to filter data start date end date basis in array mongoose and nodejs
how to write query start date and end date basis,in outdoor_tracking there is column tracking_created_date , i want filter my all record start date  tracking_created_date   and end date tracking_created_date  filter all records in tracking column basis, please help me this. thanks

i want filter my data tracking_created_date

```<code>export function getdatewise(req, res) {

  return Campaign.find({$or: [{ "assets.outdoor_tracking.tracking_created_date" : {"$gte":new Date(), "$lte": new Date()} }]  }).exec()
    .then(handleEntityNotFound(res))
    .then(respondWithResult(res))
    .catch(handleError(res));
}
</code>```

Mongodb data

```<code> {
            "_id" : ObjectId("5a266f16663eb423d86937c9"),
            "company_id" : ObjectId("5a102c4b6b8d184b0897d4fc"),
            "brand_id" : ObjectId("5a102c726b8d184b0897d4ff"),
            "companyname" : "abc",
             "assets" : [
                {
                    "_id" : ObjectId("5a1ffdb68a624329a8196ec5"),
                    "city" : "abc",
                    "region" : "abc",
                    "location" : "abc",
                     "outdoor_tracking" : [
                        {
                          "latitude" : "1.192618",
                            "longitude" : "1.191406",
                             "_id" : ObjectId("5a266fadd5a1fe0dc053faee"),
                            "updated_date" : ISODate("2017-12-05T10:06:37.611Z"),
                            "tracking_created_date" : ISODate("2017-12-05T10:06:37.611Z"),
                            "comment" : "vfff"
                                   }
                    ]
                }
            ],"__v" : 1
        }
</code>```

答:
finally query created:</p>

```<code>export function getdatewise(req, res) {

  return Campaign.find({$or: [{ "assets.outdoor_tracking.tracking_created_date" :  {$gte:new Date("2015-04-14T23:59:59Z"),$lte: new Date("2017-12-15T23:59:59Z")} }]  }).exec()
    .then(handleEntityNotFound(res))
    .then(respondWithResult(res))
    .catch(handleError(res));
}
</code>```

Body:
how to write query start date and end date basis,in outdoor_tracking there is column tracking_created_date , i want filter my all record start date  tracking_created_date   and end date tracking_created_date  filter all records in tracking column basis, please help me this. thanks

i want filter my data tracking_created_date

export function getdatewise(req, res) {

  return Campaign.find({$or: [{ "assets.outdoor_tracking.tracking_created_date" : {"$gte":new Date(), "$lte": new Date()} }]  }).exec()
    .then(handleEntityNotFound(res))
    .then(respondWithResult(res))
    .catch(handleError(res));
}

Mongodb data

 {
            "_id" : ObjectId("5a266f16663eb423d86937c9"),
            "company_id" : ObjectId("5a102c4b6b8d184b0897d4fc"),
            "brand_id" : ObjectId("5a102c726b8d184b0897d4ff"),
            "companyname" : "abc",
             "assets" : [
                {
                    "_id" : ObjectId("5a1ffdb68a624329a8196ec5"),
                    "city" : "abc",
                    "region" : "abc",
                    "location" : "abc",
                     "outdoor_tracking" : [
                        {
                          "latitude" : "1.192618",
                            "longitude" : "1.191406",
                             "_id" : ObjectId("5a266fadd5a1fe0dc053faee"),
                            "updated_date" : ISODate("2017-12-05T10:06:37.611Z"),
                            "tracking_created_date" : ISODate("2017-12-05T10:06:37.611Z"),
                            "comment" : "vfff"
                                   }
                    ]
                }
            ],"__v" : 1
        }

Body:
finally query created:

export function getdatewise(req, res) {

  return Campaign.find({$or: [{ "assets.outdoor_tracking.tracking_created_date" :  {$gte:new Date("2015-04-14T23:59:59Z"),$lte: new Date("2017-12-15T23:59:59Z")} }]  }).exec()
    .then(handleEntityNotFound(res))
    .then(respondWithResult(res))
    .catch(handleError(res));
}


问:
Get two more values from Javascript object. it is possible?
My object is

```<code>objTest["CT_1^PS_1^OP01"] = "test1";
objTest["CT_1^PS_1^OP02"] = "test2";
objTest["CT_1^PS_1^OP03"] = "test3";
</code>```

and My stirng is

```<code>string sFindVal = "CT_1^PS_1";
</code>```

Is it possible to bring the "value" of the word beginning with "CT_1^PS_1"?

I want to get values ("test1", "test2", "test3")  only key is "CT_1^PS_1".

English is not my mother tongue.
Please understand.

答:
One way would be to use reduce over the Object.keys to return an array of all the values where the key includes the string

const objTest = {};

objTest["CT_1\\PS_1\\OP01"] = "test1";
objTest["CP_1\\PS_1\\OP01"] = "error";
objTest["CT_1\\PS_1\\OP02"] = "test2";
objTest["CT_1\\PS_1\\OP03"] = "test3";

const sFindVal = "CT_1\\PS_1";

const arr = Object.keys(objTest).reduce((arr, key) => {
  if (key.includes(sFindVal)) arr.push(objTest[key]);
  return arr;
}, []);

console.log(arr);```

Body:
My object is

objTest["CT_1^PS_1^OP01"] = "test1";
objTest["CT_1^PS_1^OP02"] = "test2";
objTest["CT_1^PS_1^OP03"] = "test3";

and My stirng is

string sFindVal = "CT_1^PS_1";

Is it possible to bring the "value" of the word beginning with "CT_1^PS_1"?

I want to get values ("test1", "test2", "test3")  only key is "CT_1^PS_1".

English is not my mother tongue.
Please understand.


问:
How to align/set/put/style two div next to each other
I have some problem with my CSS and HTML. I can't style the 2 footer items to be on the same line. Is there something wrong with how I have my divs and styles?

Suggestion to make better code is very welcome. I have tried float, inline-block.

/*footer*/
footer {
  color:white;
  background-color: #c2b180;
}
.button-social {
    background-color: #4CAF50;
    color: white;
    padding: 10px 20px 10px 20px;
    text-align: center;
    text-decoration: none;
    font-size: 16px;
    margin: 4px 2px;
    cursor: pointer;
}
a {
  text-decoration: none;
}
.sameline.block {
  float:left;
  width:50%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css"/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

<footer>
  <div class="sameline.block">
  <div class="about-this-page">
      <h3>About this page</h3>
      <p>Made by Duy Ta</p>
  </div>
    <div class="around-the-web">
      <h3>Around the Web</h3>
       <i class="fa fa-linkedin"></i>
       <i class="fa fa-github"></i>
       <i class="fa fa-twitter"></i>
  </div>
  </div>
  <div id="footer-below">qlip ©
    <script>document.write(new Date().getFullYear())</script>. All Rights Reversed
  </div>
</footer></code>```

答:
Try using below code in your css.

.samelineblock .about-this-page,.samelineblock .around-the-web {
  display: inline-block;
  padding:0 30px 0 0;
}

Body:
I have some problem with my CSS and HTML. I can't style the 2 footer items to be on the same line. Is there something wrong with how I have my divs and styles?

Suggestion to make better code is very welcome. I have tried float, inline-block.

/*footer*/
footer {
  color:white;
  background-color: #c2b180;
}
.button-social {
    background-color: #4CAF50;
    color: white;
    padding: 10px 20px 10px 20px;
    text-align: center;
    text-decoration: none;
    font-size: 16px;
    margin: 4px 2px;
    cursor: pointer;
}
a {
  text-decoration: none;
}
.sameline.block {
  float:left;
  width:50%;
}

 <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css"/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

About this page

Made by Duy Ta

Around the Web

qlip ©
    . All Rights Reversed


问:
Exclude a value for a path parameter in React Router by type
I'm a bit stuck with the route component. Imagine I have this two Routes with their own path:

```<code><Route path='/person/add' exact component={PersonForm}/>
<Route path='/person/:id' exact component={PersonView}/>
</code>```

/person/add should show a form where I can create a new Person
/person/:id should show a person with the given id.

The problem >> If I navigate to /person/add it will also show the component of /person/:id because the string "add" is valid for ":id".

Is there a way I can avoid this? For example by telling that :id should be a number?

答:
Found a possible solution: You can use Switch around the routes. Then it will only match on the first one that matches.

```<code><Switch>
  <Route path='/person/add' exact component={PersonForm}/>
  <Route path='/person/:id' exact component={PersonView}/>
</Switch>
</code>```

Body:
I'm a bit stuck with the route component. Imagine I have this two Routes with their own path:

<Route path='/person/add' exact component={PersonForm}/>
<Route path='/person/:id' exact component={PersonView}/>

/person/add should show a form where I can create a new Person
/person/:id should show a person with the given id.

The problem >> If I navigate to /person/add it will also show the component of /person/:id because the string "add" is valid for ":id".

Is there a way I can avoid this? For example by telling that :id should be a number?

Body:
Found a possible solution: You can use Switch around the routes. Then it will only match on the first one that matches.

<Switch>
  <Route path='/person/add' exact component={PersonForm}/>
  <Route path='/person/:id' exact component={PersonView}/>
</Switch>


问:
Extract Column(s) from text file having Multi Character Delimiter i.e. "%$%"
I have tried different solution for the problem given on the forum but doesn't work for the specified Delimiter %$%, I need to extract one specific column from the file containing 200+ columns.

I tried the following:

```<code>awk -F"%$%" '{print $1}' sample.txt > outfile.txt
awk 'gsub("%$%",":")' sample.txt > outfile.txt
</code>```

答:
no matter -F (FS) or gsub(), it expects a regex, you need either use character class or escape those chars with special meaning, like $ in your example.

```<code>kent$ awk -F'%[$]%' '{print $1}' <<<"foo%$%bar%$%blah"
foo
</code>```

If you just want to change the separator, you can do with gsub or using OFS:

```<code>kent$ awk -F'%[$]%' -v OFS=":" '$1=$1' <<<"foo%$%bar%$%blah"
foo:bar:blah
kent$ awk 'gsub(/%[$]%/,":")+1' <<<"foo%$%bar%$%blah"
foo:bar:blah
</code>```

Body:
I have tried different solution for the problem given on the forum but doesn't work for the specified Delimiter %$%, I need to extract one specific column from the file containing 200+ columns.

I tried the following:

awk -F"%$%" '{print $1}' sample.txt > outfile.txt
awk 'gsub("%$%",":")' sample.txt > outfile.txt

Body:
no matter -F (FS) or gsub(), it expects a regex, you need either use character class or escape those chars with special meaning, like $ in your example.

kent$ awk -F'%[$]%' '{print $1}' <<<"foo%$%bar%$%blah"
foo

If you just want to change the separator, you can do with gsub or using OFS:

kent$ awk -F'%[$]%' -v OFS=":" '$1=$1' <<<"foo%$%bar%$%blah"
foo:bar:blah
kent$ awk 'gsub(/%[$]%/,":")+1' <<<"foo%$%bar%$%blah"
foo:bar:blah


问:
Placing an imageview at the center of the layout regardless of screen size?
I am new to Android and so this is me experimenting with my layouts. I want to place an imageview at the center of the layout screen and it should be at the center regardless of device size or resolutions. Additionally, the imageview should automatically scale up in size depending on the device sizes. How should I go about it ?

This is what I tried so far.

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.inducesmile.androidcameraapi2.AndroidCameraApi">
    <TextureView
        android:id="@+id/texture"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/btn_takepicture"
        android:layout_alignParentTop="true"/>
    <Button
        android:id="@+id/btn_takepicture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="16dp"
        android:layout_marginTop="16dp"
        android:text="take_picture" />

    <ImageView
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:id="@+id/imageView"
        android:layout_alignParentTop="true"
        android:layout_alignEnd="@+id/btn_takepicture"
        android:layout_marginTop="140dp"
        android:src="@drawable/rectangle" />
</RelativeLayout>
</code>```

答:
you can try following code</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:src="@mipmap/ic_launcher"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>
</code>```

Body:
I am new to Android and so this is me experimenting with my layouts. I want to place an imageview at the center of the layout screen and it should be at the center regardless of device size or resolutions. Additionally, the imageview should automatically scale up in size depending on the device sizes. How should I go about it ?

This is what I tried so far.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.inducesmile.androidcameraapi2.AndroidCameraApi">
    <TextureView
        android:id="@+id/texture"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/btn_takepicture"
        android:layout_alignParentTop="true"/>
    <Button
        android:id="@+id/btn_takepicture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="16dp"
        android:layout_marginTop="16dp"
        android:text="take_picture" />

    <ImageView
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:id="@+id/imageView"
        android:layout_alignParentTop="true"
        android:layout_alignEnd="@+id/btn_takepicture"
        android:layout_marginTop="140dp"
        android:src="@drawable/rectangle" />
</RelativeLayout>

Body:
you can try following code

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:src="@mipmap/ic_launcher"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>


问:
Effect of an asterisk in a jQuery selector
In the DevTools console of Chrome (version 63), I typed the following:

Notice the extra asterisk in the second query.

Both queries find the same element, but the second one is clearly getting a slightly different result. Also I wouldn't have expected the asterisk to be legal.

Can someone explain what effect the asterisk is having?

Note that this is not just asking about the use of an asterisk in a query, but about its effect when immediately next to an identifier.

答:
Okay, thanks to the comments above, I understand what was happening.

#right means find the element with an id of 'right'. It will never return more than one element.

*#right means find any element with an id of 'right', in the same way as div#right means find any div with that id. It will return more than one element if there are more than one elements with that id. (There shouldn't be, but Chrome at least lets you do this.)

* #right means find the element with an id of 'right' that is also a descendant of another element. It will also return more than one element if there are more than one elements with that id.

Although the last case might seem redundant, it wouldn't match anything if the 'html' element was the only one that had an id of 'right'.


问:
Order by not work in cassandra
I'm a newbie in cassandra and I have an issue with "sort".

My table is very simple, It like that:

```<code>CREATE TABLE test.user_daily_report (
    stringdate bigint,
    m_date date,
    users int,
    PRIMARY KEY (stringdate, m_date)
) WITH CLUSTERING ORDER BY (m_date DESC)
   AND read_repair_chance = 0.0
   AND dclocal_read_repair_chance = 0.1
   AND gc_grace_seconds = 864000
   AND bloom_filter_fp_chance = 0.01
   AND caching = { 'keys' : 'ALL', 'rows_per_partition' : 'NONE' }
   AND comment = ''
   AND compaction = { 'class' : 'org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy', 'max_threshold' : 32, 'min_threshold' : 4 }
   AND compression = { 'chunk_length_in_kb' : 64, 'class' : 'org.apache.cassandra.io.compress.LZ4Compressor' }
   AND default_time_to_live = 0
   AND speculative_retry = '99PERCENTILE'
   AND min_index_interval = 128
   AND max_index_interval = 2048
   AND crc_check_chance = 1.0;
</code>```

But the result not have any effect of sort:

When I try to order by m_date i meet this issue:

Please help me, It makes me confuse a lot.

Thanks

答:
In contrast to traditional relational database, in Cassandra ORDER BY works only inside partition - when you specify the WHERE condition on partition key (stringdate in your example), i.e., select * from table where stringdate = 'something' order by m_date desc - in this case data related to particular stringdate will be sorted because they are in the same partition.

In your case, you're receiving all results from Cassandra because you added 'ALLOW FILTERING' - in this case, Cassandra performs scanning of the whole cluster using your condition, fetches data, and returns it to you - but it didn't perform any sorting.

I recommend to watch "DS220: Data Modeling" course from DataStax Academy - they provide a lot of useful information...

P.S. Can you describe what task do you want to solve? I believe that you need to change data model.

Title: Order by not work in cassandra

Body:
I'm a newbie in cassandra and I have an issue with "sort".

My table is very simple, It like that:

CREATE TABLE test.user_daily_report (
    stringdate bigint,
    m_date date,
    users int,
    PRIMARY KEY (stringdate, m_date)
) WITH CLUSTERING ORDER BY (m_date DESC)
   AND read_repair_chance = 0.0
   AND dclocal_read_repair_chance = 0.1
   AND gc_grace_seconds = 864000
   AND bloom_filter_fp_chance = 0.01
   AND caching = { 'keys' : 'ALL', 'rows_per_partition' : 'NONE' }
   AND comment = ''
   AND compaction = { 'class' : 'org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy', 'max_threshold' : 32, 'min_threshold' : 4 }
   AND compression = { 'chunk_length_in_kb' : 64, 'class' : 'org.apache.cassandra.io.compress.LZ4Compressor' }
   AND default_time_to_live = 0
   AND speculative_retry = '99PERCENTILE'
   AND min_index_interval = 128
   AND max_index_interval = 2048
   AND crc_check_chance = 1.0;

But the result not have any effect of sort:

When I try to order by m_date i meet this issue:

Please help me, It makes me confuse a lot.

Thanks


问:
Illegal attempt to associate a collection with two open sessions
I've got a j2ee web application and I'm using hibernate and struts2 framework.
the project works fine on local server but when I upload the application on the web and more users access it simultaneously, this error is thrown :

```<code>Illegal attempt to associate a collection with two open sessions
</code>```

all of a sudden the whole hibernate system crashes and I can't execute any queries.
here is the stacktrace:

```<code>'org.hibernate.HibernateException: Illegal attempt to associate a collection with two open sessions
    at org.hibernate.collection.AbstractPersistentCollection.setCurrentSession(AbstractPersistentCollection.java:432)
    at org.hibernate.event.def.WrapVisitor.processCollection(WrapVisitor.java:67)
    at org.hibernate.event.def.AbstractVisitor.processValue(AbstractVisitor.java:124)
    at org.hibernate.event.def.WrapVisitor.processValue(WrapVisitor.java:121)
    at org.hibernate.event.def.AbstractVisitor.processEntityPropertyValues(AbstractVisitor.java:78)
    at org.hibernate.event.def.DefaultFlushEntityEventListener.wrapCollections(DefaultFlushEntityEventListener.java:218)
    at org.hibernate.event.def.DefaultFlushEntityEventListener.onFlushEntity(DefaultFlushEntityEventListener.java:152)
    at org.hibernate.event.def.AbstractFlushingEventListener.flushEntities(AbstractFlushingEventListener.java:219)
    at org.hibernate.event.def.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:99)
    at org.hibernate.event.def.DefaultAutoFlushEventListener.onAutoFlush(DefaultAutoFlushEventListener.java:58)
    at org.hibernate.impl.SessionImpl.autoFlushIfRequired(SessionImpl.java:1175)
    at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1251)
    at org.hibernate.impl.QueryImpl.list(QueryImpl.java:102)
    at org.hibernate.impl.AbstractQueryImpl.uniqueResult(AbstractQueryImpl.java:859)
    at com.hposg.login.LoginFactory.doLogin(LoginFactory.java:31)
    at com.hposg.controller.struts.LoginAction.execute(LoginAction.java:50)
    at sun.reflect.GeneratedMethodAccessor489.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:616)
    at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:441)
    at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:280)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:243)
    at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:165)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:252)
    at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:122)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:179)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:94)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:235)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:89)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:130)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:126)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:138)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:165)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:179)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52)
    at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:488)
    at org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:395)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:857)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    at java.lang.Thread.run(Thread.java:636)
</code>```

here is the piece of code causing this:

```<code>public static Player doLogin(String ID, String pass) throws LoginException , BanedUser{

        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();

        Player player = (Player) session.createQuery(
                "from Player as player where player.loginName = " + "'" + ID
                        + "' and player.passWord ='" + pass + "'")
                .uniqueResult();

        if (player == null)
            throw new LoginException();
        else if (!player.getIsActive())
            throw new BanedUser();

        UserSession.getInstance();
        UserSession.addPlayer(player);

        session.beginTransaction().commit();

        return player;
    }
</code>```

the error happens irregularly(once a week, every other day, etc), any ideas what might cause this problem?

here is my hibernate.cfg.xml:

```<code><?xml version='1.0' encoding='utf-8'?>
</code>```

```<code>    <!-- Database connection settings -->
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">
        jdbc:mysql://localhost/hposg?characterEncoding=UTF-8
    </property>
    <property name="connection.username">root</property>
    <property name="connection.password"></property>

    <!-- JDBC connection pool (use the built-in) -->
    <property name="connection.pool_size">1</property>

    <!-- Echo all executed SQL to stdout -->
    <property name="show_sql">true</property>

    <!-- SQL dialect -->
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

    <!-- Enable Hibernate's automatic session context management -->
    <property name="current_session_context_class">thread</property>

    <!-- Disable the second-level cache -->
    <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

    <!-- Drop and re-create the database schema on startup -->
    <property name="hbm2ddl.auto">update</property>

  <!-- Mapping files -->

  <mapping resource="com/hposg/hibernate/resources/Player.hbm.xml"/>
  <mapping resource="com/hposg/hibernate/resources/Game.hbm.xml"/>
  <mapping resource="com/hposg/hibernate/resources/Portfolio.hbm.xml"/>
  <mapping resource="com/hposg/hibernate/resources/Purchase.hbm.xml"/>
  <mapping resource="com/hposg/hibernate/resources/Sale.hbm.xml"/>
  <mapping resource="com/hposg/hibernate/resources/Message.hbm.xml"/>
  <mapping resource="com/hposg/hibernate/resources/Admin.hbm.xml"/>
  <mapping resource="com/hposg/hibernate/resources/News.hbm.xml"/>
  <mapping resource="com/hposg/hibernate/resources/Invitation.hbm.xml"/>
  <mapping resource="com/hposg/hibernate/resources/CustomGameCreationRequest.hbm.xml"/>
  <mapping resource="com/hposg/hibernate/resources/Alert.hbm.xml"/>
  <mapping resource="com/hposg/hibernate/resources/AlertLimits.hbm.xml"/>
  <mapping resource="com/hposg/hibernate/resources/StockIndex.hbm.xml"/>
  <mapping resource="com/hposg/hibernate/resources/HPOSG.hbm.xml"/>
  <mapping resource="com/hposg/hibernate/resources/Tradeable.hbm.xml"/>
  <mapping resource="com/hposg/hibernate/resources/GlobalGameConfig.hbm.xml"/>
  <mapping resource="com/hposg/hibernate/resources/Announcement.hbm.xml"/>
  <mapping resource="com/hposg/hibernate/resources/AdviserMsg.hbm.xml"/>
  <mapping resource="com/hposg/hibernate/resources/SystemConfiguration.hbm.xml"/>
</session-factory>
</code>```

the following is my LoginAction as an example of my strategy to use hibernate :

```<code>try {
            Player player = LoginFactory.doLogin(username.toLowerCase(),
                    password);

            Session lSession = HibernateUtil.getSessionFactory()
                    .getCurrentSession();
            lSession.beginTransaction();

            lSession.lock(player, LockMode.NONE);
            player.getInbox().size();
            Collection<Message> unreadMsgs = lSession
                    .createQuery(
                            "FROM Message message WHERE Respondent.id='"
                                    + player.getId()
                                    + "' AND message.isRead=false").list();

            lSession.getTransaction().commit();

            UserSession.getInstance().addPlayer(player);
            Map session = (Map) ActionContext.getContext().get("session");
            session.put("UID", username.toLowerCase());
            session.put("TYPE", "PLAYER");
            session
                    .put("NAME", player.getName() + " "
                            + player.getFamily());
            session.put("UNREADMSGS", unreadMsgs.size());
            session.put("LAST_VIEWED_GAME_ID", 0);
            return SUCCESS;
        } catch (LoginException a) {
            addActionError(a.getMessage());
            return "error";
        } catch (Exception a) {
            addActionError(e.getMessage());
            return "error";
        }
</code>```

Am I missing sth?
Any Ideas?

答:
Your code shows you create 2 transactions.... try this:-</p>

```<code>public static Player doLogin(String ID, String pass) throws LoginException , BanedUser{

        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction tx = session.beginTransaction();

        ...

        tx.commit();

        return player;
    }
</code>```

Body:
I've got a j2ee web application and I'm using hibernate and struts2 framework.
the project works fine on local server but when I upload the application on the web and more users access it simultaneously, this error is thrown :

Illegal attempt to associate a collection with two open sessions

all of a sudden the whole hibernate system crashes and I can't execute any queries.
here is the stacktrace:

'org.hibernate.HibernateException: Illegal attempt to associate a collection with two open sessions
    at org.hibernate.collection.AbstractPersistentCollection.setCurrentSession(AbstractPersistentCollection.java:432)
    at org.hibernate.event.def.WrapVisitor.processCollection(WrapVisitor.java:67)
    at org.hibernate.event.def.AbstractVisitor.processValue(AbstractVisitor.java:124)
    at org.hibernate.event.def.WrapVisitor.processValue(WrapVisitor.java:121)
    at org.hibernate.event.def.AbstractVisitor.processEntityPropertyValues(AbstractVisitor.java:78)
    at org.hibernate.event.def.DefaultFlushEntityEventListener.wrapCollections(DefaultFlushEntityEventListener.java:218)
    at org.hibernate.event.def.DefaultFlushEntityEventListener.onFlushEntity(DefaultFlushEntityEventListener.java:152)
    at org.hibernate.event.def.AbstractFlushingEventListener.flushEntities(AbstractFlushingEventListener.java:219)
    at org.hibernate.event.def.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:99)
    at org.hibernate.event.def.DefaultAutoFlushEventListener.onAutoFlush(DefaultAutoFlushEventListener.java:58)
    at org.hibernate.impl.SessionImpl.autoFlushIfRequired(SessionImpl.java:1175)
    at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1251)
    at org.hibernate.impl.QueryImpl.list(QueryImpl.java:102)
    at org.hibernate.impl.AbstractQueryImpl.uniqueResult(AbstractQueryImpl.java:859)
    at com.hposg.login.LoginFactory.doLogin(LoginFactory.java:31)
    at com.hposg.controller.struts.LoginAction.execute(LoginAction.java:50)
    at sun.reflect.GeneratedMethodAccessor489.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:616)
    at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:441)
    at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:280)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:243)
    at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:165)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:252)
    at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:122)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:179)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:94)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:235)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:89)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:130)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:126)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:138)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:165)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:179)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52)
    at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:488)
    at org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:395)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:857)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    at java.lang.Thread.run(Thread.java:636)

here is the piece of code causing this:

public static Player doLogin(String ID, String pass) throws LoginException , BanedUser{

        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();

        Player player = (Player) session.createQuery(
                "from Player as player where player.loginName = " + "'" + ID
                        + "' and player.passWord ='" + pass + "'")
                .uniqueResult();

        if (player == null)
            throw new LoginException();
        else if (!player.getIsActive())
            throw new BanedUser();

        UserSession.getInstance();
        UserSession.addPlayer(player);

        session.beginTransaction().commit();

        return player;
    }

the error happens irregularly(once a week, every other day, etc), any ideas what might cause this problem?

here is my hibernate.cfg.xml:

<?xml version='1.0' encoding='utf-8'?>

    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">
        jdbc:mysql://localhost/hposg?characterEncoding=UTF-8
    </property>
    <property name="connection.username">root</property>
    <property name="connection.password"></property>

    <property name="connection.pool_size">1</property>

    <property name="show_sql">true</property>

    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

    <property name="current_session_context_class">thread</property>

    <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

    <property name="hbm2ddl.auto">update</property>

  <mapping resource="com/hposg/hibernate/resources/Player.hbm.xml"/>
  <mapping resource="com/hposg/hibernate/resources/Game.hbm.xml"/>
  <mapping resource="com/hposg/hibernate/resources/Portfolio.hbm.xml"/>
  <mapping resource="com/hposg/hibernate/resources/Purchase.hbm.xml"/>
  <mapping resource="com/hposg/hibernate/resources/Sale.hbm.xml"/>
  <mapping resource="com/hposg/hibernate/resources/Message.hbm.xml"/>
  <mapping resource="com/hposg/hibernate/resources/Admin.hbm.xml"/>
  <mapping resource="com/hposg/hibernate/resources/News.hbm.xml"/>
  <mapping resource="com/hposg/hibernate/resources/Invitation.hbm.xml"/>
  <mapping resource="com/hposg/hibernate/resources/CustomGameCreationRequest.hbm.xml"/>
  <mapping resource="com/hposg/hibernate/resources/Alert.hbm.xml"/>
  <mapping resource="com/hposg/hibernate/resources/AlertLimits.hbm.xml"/>
  <mapping resource="com/hposg/hibernate/resources/StockIndex.hbm.xml"/>
  <mapping resource="com/hposg/hibernate/resources/HPOSG.hbm.xml"/>
  <mapping resource="com/hposg/hibernate/resources/Tradeable.hbm.xml"/>
  <mapping resource="com/hposg/hibernate/resources/GlobalGameConfig.hbm.xml"/>
  <mapping resource="com/hposg/hibernate/resources/Announcement.hbm.xml"/>
  <mapping resource="com/hposg/hibernate/resources/AdviserMsg.hbm.xml"/>
  <mapping resource="com/hposg/hibernate/resources/SystemConfiguration.hbm.xml"/>
</session-factory>

the following is my LoginAction as an example of my strategy to use hibernate :

try {
            Player player = LoginFactory.doLogin(username.toLowerCase(),
                    password);

            Session lSession = HibernateUtil.getSessionFactory()
                    .getCurrentSession();
            lSession.beginTransaction();

            lSession.lock(player, LockMode.NONE);
            player.getInbox().size();
            Collection<Message> unreadMsgs = lSession
                    .createQuery(
                            "FROM Message message WHERE Respondent.id='"
                                    + player.getId()
                                    + "' AND message.isRead=false").list();

            lSession.getTransaction().commit();

            UserSession.getInstance().addPlayer(player);
            Map session = (Map) ActionContext.getContext().get("session");
            session.put("UID", username.toLowerCase());
            session.put("TYPE", "PLAYER");
            session
                    .put("NAME", player.getName() + " "
                            + player.getFamily());
            session.put("UNREADMSGS", unreadMsgs.size());
            session.put("LAST_VIEWED_GAME_ID", 0);
            return SUCCESS;
        } catch (LoginException a) {
            addActionError(a.getMessage());
            return "error";
        } catch (Exception a) {
            addActionError(e.getMessage());
            return "error";
        }

Am I missing sth?
Any Ideas?

Body:
Your code shows you create 2 transactions.... try this:-

public static Player doLogin(String ID, String pass) throws LoginException , BanedUser{

        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction tx = session.beginTransaction();

        ...

        tx.commit();

        return player;
    }

ContentLicense: CC BY-SA 2.5


问:
Adding the same image every time a button is clicked
I making a drawing pad for teachers, i want to include geometrical shapes in it, there is a button on click of which a shape is displayed.
What i am doing now is i created an image view already and set its visibility to gone, on button i am making it visible.

```<code><ImageView
        android:id="@+id/ivReact"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:background="@drawable/rectangle"
        android:visibility="gone"
        android:layout_centerInParent="true"

        />
</code>```

i want the previous image to be there, when a button is clicked the same image should be added twice in the layout and if the button clicked again it should be added again and go on.

is it possible to do that?

答: create a recycler view and put a image view there. Create a arraylist. Onclick add same image to the arraylist and apply adapter.notifyDataSetChanged().</p>

Body:
I making a drawing pad for teachers, i want to include geometrical shapes in it, there is a button on click of which a shape is displayed.
What i am doing now is i created an image view already and set its visibility to gone, on button i am making it visible.

<ImageView
        android:id="@+id/ivReact"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:background="@drawable/rectangle"
        android:visibility="gone"
        android:layout_centerInParent="true"

        />

i want the previous image to be there, when a button is clicked the same image should be added twice in the layout and if the button clicked again it should be added again and go on.

is it possible to do that?


问:
One to one relationship without reference property on one side
I have the following construct; a person with an address (ownsone, sub-entity) and an address with a country (hasone, one-to-one)

```<code>public class Person
{
     public Guid Id {get; set;}
     public string Name {get; set;}
     public Address Address {get; set;}
}

public class Address
{
     public Guid Id {get; set;}
     public Guid CountryId {get; set;}
     public Country Country {get; set;}
}

public class Country
{
     public Guid Id {get; set;}
     public string CountryCode {get; set;}
}

public class EntityConfiguration<Person> where Person : class
{
     public void Configure(EntityBuilder<Person> builder)
     {
         builder.OwnsOne(p => p.Address, addressBuilder =>
         addressBuilder.HasOne(address => address.Country).WithOne();
     }
}
</code>```

When I run Add-Migration I get a block of code for each entity which owns one address. With auto-generated keys and so on. But I want to specify the relation explicitly with HasForeignKey. How to do this?

答:
EF Core provides 2 fluent APIs for one-to-one relationships - HasForeignKey and HasPrincipalKey.

The main difference with one-to-many APIs is that you need to explicitly provide the generic type argument, because the principal and dependent end of the relationship cannot be determined by the HasOne / WithOne calls (for one-to-many the one is always the principal and many is the dependent). The navigation properties in this case doesn't matter:

```<code>addressBuilder.HasOne(address => address.Country)
   .WithOne()
   .HasForeignKey<Address>(address => address.CountryId)
</code>```

Reference: Relationships

Body:
I have the following construct; a person with an address (ownsone, sub-entity) and an address with a country (hasone, one-to-one)

public class Person
{
     public Guid Id {get; set;}
     public string Name {get; set;}
     public Address Address {get; set;}
}

public class Address
{
     public Guid Id {get; set;}
     public Guid CountryId {get; set;}
     public Country Country {get; set;}
}

public class Country
{
     public Guid Id {get; set;}
     public string CountryCode {get; set;}
}

public class EntityConfiguration<Person> where Person : class
{
     public void Configure(EntityBuilder<Person> builder)
     {
         builder.OwnsOne(p => p.Address, addressBuilder =>
         addressBuilder.HasOne(address => address.Country).WithOne();
     }
}

When I run Add-Migration I get a block of code for each entity which owns one address. With auto-generated keys and so on. But I want to specify the relation explicitly with HasForeignKey. How to do this?

Body:
EF Core provides 2 fluent APIs for one-to-one relationships - HasForeignKey and HasPrincipalKey.

The main difference with one-to-many APIs is that you need to explicitly provide the generic type argument, because the principal and dependent end of the relationship cannot be determined by the HasOne / WithOne calls (for one-to-many the one is always the principal and many is the dependent). The navigation properties in this case doesn't matter:

addressBuilder.HasOne(address => address.Country)
   .WithOne()
   .HasForeignKey<Address>(address => address.CountryId)

Reference: Relationships


答:
```<code> Use this code inside onclick

ImageView imageview = new ImageView(MainActivity.this);
     RelativeLayout relativelayout = (RelativeLayout)findViewById(R.id.relativeLayout);
     LinearLayout.LayoutParams params = new LinearLayout
     .LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);

     // Add image path from drawable folder.
     imageview.setImageResource(R.drawable.demo_new_image);
     imageview.setLayoutParams(params);
     relativelayout.addView(imageview);
</code>```

Title: Adding the same image every time a button is clicked


问:
Bootstrap grid place div next to div in a row
I want div 4 next to div 1 and below div 2 and 3 like the image below the code. How can I do that? Actual Code:

```<code>       <div class="container-fluid">
          <div class="row">
             <div class="col-md-4 col_trainings">1</div>
             <div class="col-md-3 col_downloads">2</div>
             <div class="col-md-3 col_project">3</div>
             <div class="col-sm-6 col_contact">4</div>
          </div>
       </div>
</code>```

答:
There is a library for this.
"Lightweight and independent Pinterest-like cascading grid layout library" http://bricklayer.js.org</p>

Body:
I want div 4 next to div 1 and below div 2 and 3 like the image below the code. How can I do that? Actual Code:

1

2

3

4


问:
cannot pass variable through callback nor can I put promise on function
So I have a data set hard coded that I need to loop through to check the distance from the user entered distance using googles web api for checking this works I just can't pass an id variable down through my code to where I need to be able to access it so that I can print depending on the answer I get from the api.

my code is like this:

```<code>checkDist(data) {
  this.setState({
    searching: true,
  });
  var self = this;
  data.forEach(item => {
    console.log('check');
    self.getDist(item.postcode, item.id);
  });
}

updateSearchResults(dist) {
  var output = [];
  var self = this;
  console.log('Here we will search the db using user data for suitable jobs');
  console.log("distFromLoc in Update: " + this.state.distFromLoc);
  window.setTimeout(function() {
    self.setState({
      dataToShow: output,
      searching: false,
      current: 1,
    });
    const dataLength = self.state.dataToShow.length
    self.setState({
      amountOfJobs: dataLength
    })}, 10000)
  }
getDist(dest, id){
  var self = this;
  const wrappedCallback = (id) => (...args) => this.callback(...args);
  var origin = this.state.location,
    destination = dest,
    service = new window.google.maps.DistanceMatrixService();

    service.getDistanceMatrix(
    {
      origins: [origin],
      destinations: [destination],
      travelMode: window.google.maps.TravelMode.DRIVING,
      avoidHighways: false,
      avoidTolls: false,
      unitSystem: window.google.maps.UnitSystem.IMPERIAL
    },
    wrappedCallback,
  );
}

callback(response, status, id) {
  const self = this;
  console.log("id in callback: " + id);
  if(status === "OK") {
    console.log(response);
    var dest = response.destinationAddresses[0];
    if (response.rows[0].elements[0].status === "ZERO_RESULTS"){

      } else if (response.rows[0].elements[0].status === "OK"){
        var dist = response.rows[0].elements[0].distance.text;
        this.setState({
          distFromLoc: dist
        }, function() {
          self.updateSearchResults(dist);
        })
      }
    } else {
      alert("Error: " + status);
    }
  }
</code>```

the ID gets passed through to the final function by changing const wrappedCallback = (...args) => this.callback(...args); to const wrappedCallback = (id) => (...args) => this.callback(...args); but this breaks the final function as it doesn't console log the response or the status anymore that it did when the const was the first way but the first way doesn't know what the id is.

Is there a way that I can make it know what the id, response, and status all mean as they are all required for stuff.

答:
Passing extra variables into another function can be done by a fairly simple pattern.

Say you have a function that says hi to a name

```<code>const hi = (name) => console.log(`hi ${name}`);
</code>```

And you want to pass this function to a setTimeout which accepts a function

```<code>setTimeout(hi, 1000);
</code>```

Well obviously cannot pass in the name now as is the case for your id, but if we wrap that function we can pass more arguments by passing an anonymous function.

```<code>setTimeout(() => hi('bill'), 1000);
</code>```

in the same way you can wrap your call to callback such as

```<code>(response, status) => callback(response, status, id)
</code>```

as long as id is in scope during this declaration.
The full function change would be:

```<code>getDist(dest, id){
  var self = this;
  var origin = this.state.location,
    destination = dest,
    service = new window.google.maps.DistanceMatrixService();

  service.getDistanceMatrix(
    {
      origins: [origin],
      destinations: [destination],
      travelMode: window.google.maps.TravelMode.DRIVING,
      avoidHighways: false,
      avoidTolls: false,
      unitSystem: window.google.maps.UnitSystem.IMPERIAL
    },
    (response, status) => callback(response, status, id),
  );
}
</code>```

Body:
So I have a data set hard coded that I need to loop through to check the distance from the user entered distance using googles web api for checking this works I just can't pass an id variable down through my code to where I need to be able to access it so that I can print depending on the answer I get from the api.

my code is like this:

checkDist(data) {
  this.setState({
    searching: true,
  });
  var self = this;
  data.forEach(item => {
    console.log('check');
    self.getDist(item.postcode, item.id);
  });
}

updateSearchResults(dist) {
  var output = [];
  var self = this;
  console.log('Here we will search the db using user data for suitable jobs');
  console.log("distFromLoc in Update: " + this.state.distFromLoc);
  window.setTimeout(function() {
    self.setState({
      dataToShow: output,
      searching: false,
      current: 1,
    });
    const dataLength = self.state.dataToShow.length
    self.setState({
      amountOfJobs: dataLength
    })}, 10000)
  }
getDist(dest, id){
  var self = this;
  const wrappedCallback = (id) => (...args) => this.callback(...args);
  var origin = this.state.location,
    destination = dest,
    service = new window.google.maps.DistanceMatrixService();

    service.getDistanceMatrix(
    {
      origins: [origin],
      destinations: [destination],
      travelMode: window.google.maps.TravelMode.DRIVING,
      avoidHighways: false,
      avoidTolls: false,
      unitSystem: window.google.maps.UnitSystem.IMPERIAL
    },
    wrappedCallback,
  );
}

callback(response, status, id) {
  const self = this;
  console.log("id in callback: " + id);
  if(status === "OK") {
    console.log(response);
    var dest = response.destinationAddresses[0];
    if (response.rows[0].elements[0].status === "ZERO_RESULTS"){

      } else if (response.rows[0].elements[0].status === "OK"){
        var dist = response.rows[0].elements[0].distance.text;
        this.setState({
          distFromLoc: dist
        }, function() {
          self.updateSearchResults(dist);
        })
      }
    } else {
      alert("Error: " + status);
    }
  }

the ID gets passed through to the final function by changing const wrappedCallback = (...args) => this.callback(...args); to const wrappedCallback = (id) => (...args) => this.callback(...args); but this breaks the final function as it doesn't console log the response or the status anymore that it did when the const was the first way but the first way doesn't know what the id is.

Is there a way that I can make it know what the id, response, and status all mean as they are all required for stuff.

Body:
Passing extra variables into another function can be done by a fairly simple pattern.

Say you have a function that says hi to a name

const hi = (name) => console.log(`hi ${name}`);

And you want to pass this function to a setTimeout which accepts a function

setTimeout(hi, 1000);

Well obviously cannot pass in the name now as is the case for your id, but if we wrap that function we can pass more arguments by passing an anonymous function.

setTimeout(() => hi('bill'), 1000);

in the same way you can wrap your call to callback such as

(response, status) => callback(response, status, id)

as long as id is in scope during this declaration.
The full function change would be:

getDist(dest, id){
  var self = this;
  var origin = this.state.location,
    destination = dest,
    service = new window.google.maps.DistanceMatrixService();

  service.getDistanceMatrix(
    {
      origins: [origin],
      destinations: [destination],
      travelMode: window.google.maps.TravelMode.DRIVING,
      avoidHighways: false,
      avoidTolls: false,
      unitSystem: window.google.maps.UnitSystem.IMPERIAL
    },
    (response, status) => callback(response, status, id),
  );
}


问:
Django - upload image file and store the image
In my custom user model, I need a field to store user's photo profile. So, I set a field photo_profile as an ImageField in the model.

```<code>class User(AbstractBaseUser):

    photo_profile = models.ImageField()

class RegisterForm(forms.ModelForm):

    class Meta:
        model = User
        fields = [#fields are going to be shown here
            'photo_profile',
        ]

def register_view(request):
    title = "Register"
    form = RegisterForm(request.POST or None)
    print("hello")
    if form.is_valid():
        user = form.save(commit=False)
        password = form.cleaned_data['password']
        user.set_password(password)
        user.is_active = True
        user.last_login = timezone.now()
        user.save()
        login(request, user)
        return render(request, 'index/index.html', {"user": user})

    context ={
        "form": form,
        "title": title,
    }
    return render(request, 'user/loginRegister.html', context)
</code>```

Now, if I go to my register page, there will be a button to upload image.

```<code>`<form method="post"action="" entype="multipart/form-data">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" class="btn btn-default" title="{{ title }}"/>
</form>`
</code>```

After I choose my image, the of image is shown. However, when I click submit button, the webpage is asking "the field (the one for photo) is required".

Is there an other way than using a FileUploadForm to solve this problem？Before I change the type of photo_profile to ImageField, a user can be created.

Thanks in advance！

答:
In order to handle files in a form, you'll need to pass them in too:</p>

```<code>form = RegisterForm(data=(request.POST or None), files=(request.FILES or None))
</code>```

Body:
In my custom user model, I need a field to store user's photo profile. So, I set a field photo_profile as an ImageField in the model.

class User(AbstractBaseUser):

    photo_profile = models.ImageField()

class RegisterForm(forms.ModelForm):

    class Meta:
        model = User
        fields = [#fields are going to be shown here
            'photo_profile',
        ]

def register_view(request):
    title = "Register"
    form = RegisterForm(request.POST or None)
    print("hello")
    if form.is_valid():
        user = form.save(commit=False)
        password = form.cleaned_data['password']
        user.set_password(password)
        user.is_active = True
        user.last_login = timezone.now()
        user.save()
        login(request, user)
        return render(request, 'index/index.html', {"user": user})

    context ={
        "form": form,
        "title": title,
    }
    return render(request, 'user/loginRegister.html', context)

Now, if I go to my register page, there will be a button to upload image.

`<form method="post"action="" entype="multipart/form-data">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" class="btn btn-default" title="{{ title }}"/>
</form>`

After I choose my image, the of image is shown. However, when I click submit button, the webpage is asking "the field (the one for photo) is required".

Is there an other way than using a FileUploadForm to solve this problem？Before I change the type of photo_profile to ImageField, a user can be created.

Thanks in advance！

Body:
In order to handle files in a form, you'll need to pass them in too:

form = RegisterForm(data=(request.POST or None), files=(request.FILES or None))