问:
Check if record exist in the database android
I want to check if records exist in the SQLite database, here's what I have done so far. when I search for a already existing records im getting value from EditText in list.

```<code>    //code from activity class

    public View.OnClickListener searchStation = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        arrayAdapterList=new ArrayAdapter<String>(SearchAndReview.this,
                android.R.layout.simple_list_item_1,
                list);
        String searchTextFinal=searchText.getText().toString();
        dbms.searchStation(searchTextFinal);
        Cursor cursor= dbms.searchStation(searchTextFinal);

       list.add(searchTextFinal);
        arrayAdapterList= new ArrayAdapter<String>(SearchAndReview.this,
                android.R.layout.simple_list_item_1, list);
        listView.setAdapter(arrayAdapterList);

    }
};
</code>```

// code from databasehelper class

```<code>   public Cursor searchStation(String name){
    SQLiteDatabase database = this.getWritableDatabase();
    String searchStationQuery = "SELECT stationName FROM review WHERE stationId='"+ name+"'";
    Cursor c =database.rawQuery(searchStationQuery,null);
    if (c != null && c.moveToFirst()) {
    }
    return c;
}
</code>```

答:
DatabaseManager.java

```<code>public Cursor checkFavourites()
{

    String query="select * from "+DATABASE_TABLE;
    Cursor cursor=db.rawQuery(query,null);

    return cursor;
}
</code>```

MainActivity.java

```<code>public void favourite_Click(View view){
    Cursor cursor=dbManager.checkFavourites();
    if (cursor.getCount()>0)
    {
        Toast.makeText(MainActivity.this, "Favourites", Toast.LENGTH_SHORT).show();
    }
    else
    {
        Toast.makeText(MainActivity.this,"Nothing in favourites yet", Toast.LENGTH_SHORT).show();
    }
}
</code>```

Body:
I want to check if records exist in the SQLite database, here's what I have done so far. when I search for a already existing records im getting value from EditText in list.

    //code from activity class

    public View.OnClickListener searchStation = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        arrayAdapterList=new ArrayAdapter<String>(SearchAndReview.this,
                android.R.layout.simple_list_item_1,
                list);
        String searchTextFinal=searchText.getText().toString();
        dbms.searchStation(searchTextFinal);
        Cursor cursor= dbms.searchStation(searchTextFinal);

       list.add(searchTextFinal);
        arrayAdapterList= new ArrayAdapter<String>(SearchAndReview.this,
                android.R.layout.simple_list_item_1, list);
        listView.setAdapter(arrayAdapterList);

    }
};

// code from databasehelper class

   public Cursor searchStation(String name){
    SQLiteDatabase database = this.getWritableDatabase();
    String searchStationQuery = "SELECT stationName FROM review WHERE stationId='"+ name+"'";
    Cursor c =database.rawQuery(searchStationQuery,null);
    if (c != null && c.moveToFirst()) {
    }
    return c;
}

Body:
DatabaseManager.java

public Cursor checkFavourites()
{

    String query="select * from "+DATABASE_TABLE;
    Cursor cursor=db.rawQuery(query,null);

    return cursor;
}

MainActivity.java

public void favourite_Click(View view){
    Cursor cursor=dbManager.checkFavourites();
    if (cursor.getCount()>0)
    {
        Toast.makeText(MainActivity.this, "Favourites", Toast.LENGTH_SHORT).show();
    }
    else
    {
        Toast.makeText(MainActivity.this,"Nothing in favourites yet", Toast.LENGTH_SHORT).show();
    }
}


来源: stackexchange

问:
MQL4 multi-timeframe indicator
I would like to write out an indicator that can take in input the int shift of an assigned timeframe, and turns out a value related to another timeframe.

As an example, I would like to write an MACD indicator over a 100 periods of M15, that can return out its value 1,2,3,4,5,6,7... minutes before the current candle.

Since in the current candle this indicator "changes" its value, tick by tick, I think that should be possible to write out such an indicator, but I can not figure out how to do it.

答:
MQL4 language principally has tools for this:

However, as noted above, your experimentation will need thorough quant validations, as the earlier Builds did not support this in [MT4-Strategy Tester] code-execution environment ( and more recent shifts into New-MQL4.56789 have devastated performance constraints for all [CustomIndicators], the all [MT4-graph]-GUI-s together plus the all [Expert Advisor]-s use, since all these suddenly share one ( yes, ONE and THE ONLY ) computing thread.

Ok, you have been warned :o)

So,

if indeed keen to equip your [CustomIndicator] so as to be independent of the GUI-native-TimeFrame, all your calculations inside such [CustomIndicator]-code must use indirect access-tools to source the PriceDOMAIN data - so never use any { Open[] | High[] | Low[] | Close[] }-TimeSeries data directly, but only using { iOpen() | iHigh() | iLow() | iClose() }

All these access tools conceptually have a common signature:

```<code>double  iLow( string   symbol,          // symbol
              int      timeframe,       // timeframe
              int      shift            // shift
              );
</code>```

and

if your code

obeys this duty,

your [CustomIndicator]( iff the StrategyTester will not finally spoil the game -- due quant testing will show this )

will be working with data from timeframe & shift of your wish.

Implementation remarks:

Your [CustomIndicator]-code has to implement a "non-GUI-shift" independently from the GUI-native-TimeFrame shift-counting. See an iCustom() signature template for inspiration. The GUI-TimeFrame-shift is like moving the line-graph on GUI-screen, i.e. in GUI-native-TimeFrame steps, not taking into account your [CustomIndicator] "internal"-"non-GUI-shift" values, so your code has to be smarter, so as to process this "internal"-"non-GUI-shift" during a value generation. If in doubts, during prototyping, validate the proper "mechanics" on Time[aShiftINTENDED] vs iTime( _Symbol, PERIOD_INTENDED, aShiftINTENDED )

Due to quite a lot of points, where an iCustom() call-interface may be a bit misleading, or a revision-change-management error-prone, we got used to use a formal template for each [Custom Indicator] code, helping to maintain referential integrity with a iCustom() use in the actual [ExpertAdvisor] code. It might seem a bit dumb, but those, who have spent man*hours in search for a bug in { un- | ill- }-propagated call-interface changes, this may become a life-saver.

We formalise the call-interface in such a way, that this section, maintained in the [CustomIndicator]-code, can always be copied into the [ExpertAdviser] code, so that the iCustom() signature-match can be inspected.

```<code>//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//!!!!
//---- indicator parameters -------------------------------------------------
//                          POSITIONAL ORDINAL-NUMBERED CALLING INTERFACE
//                      all iCustom() calls MUST BE REVISED ON REVISION
//!!!!
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
#define          XEMA_CUSTOM_INDICATOR_NAME    "EMA_DEMA_TEMA_XEMA_wShift"   // this.
//--- input parameters ------------------------------------------------------   iCustom( ) CALL INTERFACE
input  int                 nBARs_period      = 8;
extern double              MUL_SIGMA         = 2.5;
sinput ENUM_APPLIED_PRICE  aPriceTYPE        = PRICE_CLOSE;
extern int                 ShiftBARs         = 0;
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
/*      = iCustom( _Symbol,
                   PERIOD_CURRENT, XEMA_CUSTOM_INDICATOR_NAME,  // |-> iCustom INDICATOR NAME
                                   XEMA_nBARs_period,           // |->                         input    nBARs_period
                                   XEMA_MUL_SIGMA,              // |->                         input    MUL_SIGMA
                                   XEMA_PRICE_TYPE,             // |->                         input    aPriceTYPE       from: ENUM_APPLIED_PRICE
                                   XEMA_ShiftBARs,              // |->                         input    ShiftBARs
                                   XEMA_<_VALUE_>_BUFFER_ID,    // |-> line# --------------------------------------------from: { #define'd (e)nums ... }
                                   0                            // |-> [0]-aTimeDOMAIN-offset
                                   );                           //
*/
#define                            XEMA_Main_AXIS_BUFFER_ID  0  // <----xEMA<maxEMAtoCOMPUTE>[]
#define                            XEMA_UpperBAND_BUFFER_ID  1
#define                            XEMA_LowerBAND_BUFFER_ID  2
#define                            XEMA_StdDEV____BUFFER_ID  3
#define                            XEMA_SimpleEMA_BUFFER_ID  4  // sEMA
#define                            XEMA_DoubleEMA_BUFFER_ID 10  // dEMA
#define                            XEMA_TripleEMA_BUFFER_ID 11  // tEMA

//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//!!!!
//---- indicator parameters -------------------------------------------------
//                          POSITIONAL ORDINAL-NUMBERED CALLING INTERFACE
//                      all iCustom() calls MUST BE REVISED ON REVISION
//!!!!
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
</code>```

ContentLicense: CC BY-SA 3.0

Title: MQL4 multi-timeframe indicator

Body:
MQL4 language principally has tools for this:

However, as noted above, your experimentation will need thorough quant validations, as the earlier Builds did not support this in [MT4-Strategy Tester] code-execution environment ( and more recent shifts into New-MQL4.56789 have devastated performance constraints for all [CustomIndicators], the all [MT4-graph]-GUI-s together plus the all [Expert Advisor]-s use, since all these suddenly share one ( yes, ONE and THE ONLY ) computing thread.

Ok, you have been warned :o)

So,

if indeed keen to equip your [CustomIndicator] so as to be independent of the GUI-native-TimeFrame, all your calculations inside such [CustomIndicator]-code must use indirect access-tools to source the PriceDOMAIN data - so never use any { Open[] | High[] | Low[] | Close[] }-TimeSeries data directly, but only using { iOpen() | iHigh() | iLow() | iClose() }

All these access tools conceptually have a common signature:

double  iLow( string   symbol,          // symbol
              int      timeframe,       // timeframe
              int      shift            // shift
              );

and

if your code

obeys this duty,

your [CustomIndicator]( iff the StrategyTester will not finally spoil the game -- due quant testing will show this )

will be working with data from timeframe & shift of your wish.

Implementation remarks:

Your [CustomIndicator]-code has to implement a "non-GUI-shift" independently from the GUI-native-TimeFrame shift-counting. See an iCustom() signature template for inspiration. The GUI-TimeFrame-shift is like moving the line-graph on GUI-screen, i.e. in GUI-native-TimeFrame steps, not taking into account your [CustomIndicator] "internal"-"non-GUI-shift" values, so your code has to be smarter, so as to process this "internal"-"non-GUI-shift" during a value generation. If in doubts, during prototyping, validate the proper "mechanics" on Time[aShiftINTENDED] vs iTime( _Symbol, PERIOD_INTENDED, aShiftINTENDED )

Due to quite a lot of points, where an iCustom() call-interface may be a bit misleading, or a revision-change-management error-prone, we got used to use a formal template for each [Custom Indicator] code, helping to maintain referential integrity with a iCustom() use in the actual [ExpertAdvisor] code. It might seem a bit dumb, but those, who have spent man*hours in search for a bug in { un- | ill- }-propagated call-interface changes, this may become a life-saver.

We formalise the call-interface in such a way, that this section, maintained in the [CustomIndicator]-code, can always be copied into the [ExpertAdviser] code, so that the iCustom() signature-match can be inspected.

//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//!!!!
//---- indicator parameters -------------------------------------------------
//                          POSITIONAL ORDINAL-NUMBERED CALLING INTERFACE
//                      all iCustom() calls MUST BE REVISED ON REVISION
//!!!!
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
#define          XEMA_CUSTOM_INDICATOR_NAME    "EMA_DEMA_TEMA_XEMA_wShift"   // this.
//--- input parameters ------------------------------------------------------   iCustom( ) CALL INTERFACE
input  int                 nBARs_period      = 8;
extern double              MUL_SIGMA         = 2.5;
sinput ENUM_APPLIED_PRICE  aPriceTYPE        = PRICE_CLOSE;
extern int                 ShiftBARs         = 0;
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
/*      = iCustom( _Symbol,
                   PERIOD_CURRENT, XEMA_CUSTOM_INDICATOR_NAME,  // |-> iCustom INDICATOR NAME
                                   XEMA_nBARs_period,           // |->                         input    nBARs_period
                                   XEMA_MUL_SIGMA,              // |->                         input    MUL_SIGMA
                                   XEMA_PRICE_TYPE,             // |->                         input    aPriceTYPE       from: ENUM_APPLIED_PRICE
                                   XEMA_ShiftBARs,              // |->                         input    ShiftBARs
                                   XEMA_<_VALUE_>_BUFFER_ID,    // |-> line# --------------------------------------------from: { #define'd (e)nums ... }
                                   0                            // |-> [0]-aTimeDOMAIN-offset
                                   );                           //
*/
#define                            XEMA_Main_AXIS_BUFFER_ID  0  // <----xEMA<maxEMAtoCOMPUTE>[]
#define                            XEMA_UpperBAND_BUFFER_ID  1
#define                            XEMA_LowerBAND_BUFFER_ID  2
#define                            XEMA_StdDEV____BUFFER_ID  3
#define                            XEMA_SimpleEMA_BUFFER_ID  4  // sEMA
#define                            XEMA_DoubleEMA_BUFFER_ID 10  // dEMA
#define                            XEMA_TripleEMA_BUFFER_ID 11  // tEMA

//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//!!!!
//---- indicator parameters -------------------------------------------------
//                          POSITIONAL ORDINAL-NUMBERED CALLING INTERFACE
//                      all iCustom() calls MUST BE REVISED ON REVISION
//!!!!
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^


问:
How do I gracefully avoid dependencies on infrastructure services from domain entities using DDD?

Background

Suppose I am tasked with building a system in the domain of notification sending using Domain Driven Design (DDD). One of the key requirements of this system is that it needs to support various "types" of notifications, such as SMS, email, etc.

After several iterations on developing the domain model, I continue to land on having a Notification base class as an entity, with subclasses SMSNotification, EmailNotification, etc. as child classes (each being an entity as well).

Notification

public abstract class Notification extends Entity<UUID> {
    //...fields...

    public abstract void send();
}
```

<p><code>SMSNotification</code></p>

<pre class="lang-java prettyprint-override"><code>public class SMSNotification extends Notification {

    public void send(){
         //logic for sending the SMS notification using an infrastructure service.
    }
}
</code>```

EmailNotification

public class EmailNotification extends Notification {

    public void send(){
        //logic for sending the email notification using an infrastructure service.
    }
}
```

<h2>Problem(s)</h2>

<ul>
<li>With this current design approach, each subclass of <code>Notification</code> is interacting with an infrastructure service, where the infrastructure is tasked with interfacing with some external system. </li>
</ul>

<p>Eric Evans dedicates a little page space about this on page 107 in his book Domain-Driven Design when introducing the concept of <code>domain services</code>:</p>

<blockquote>
  <p>..., in most development systems, it is awkward to make a direct interface between a domain object and external resources. We can dress up such external services with a facade that takes inputs in terms of the model, ... but whatever intermediaries we may have, and even though they don't belong to us, those services are carrying out the domain responsibility...</p>
</blockquote>

<ul>
<li>If instead, I procure a <code>SendNotificationService</code> in my domain model using Evans' advice instead of having a <code>send</code> method on each subclass of <code>Notification</code>, I am not sure how I can avoid the need for knowing <em>what type</em> of notification was provided, so that the appropriate infrastructure action can be taken:</li>
</ul>

<p><code>SendNotificationService</code> (Domain Service)</p>

<pre class="lang-java prettyprint-override"><code>public class SendNotificationService {
    public void send(Notification notification){
        //if notification is an SMS notification...
        //    utilize infrastructure services for SMS sending.
        //if notification is an email notification...
        //    utilize infrastructure services for email sending.
        //
        //(╯°□°）╯︵ ┻━┻)
    }
}
</code>```

What am I missing here?

Object oriented design principles are pushing me in favor of having the model first suggested, with the Notification, SMSNotification, and EmailNotification classes. Implementing the send method on each subclass of Notification makes sense, as all notifications need to be sent (justifies its placement in Notification) and each "type" or subclass of Notification will have specialized behavior in how the notification is sent (justifies making send abstract in Notification). This approach also honors Open/Closed Principle (OCP), since the Notification class will be closed to modification, and as new notification types are supported, a new subclass of Notification can be created to extend functionality. Regardless, there seems to be consensus on not having entities interface with external services, as well as not having subclasses of entities at all in DDD.

If the behavior of sending notifications is removed from Notification, then where it is placed must be aware of the "type" of notification, and act accordingly, which I can only conceptualize as chain of if...else... statements, which directly contradicts OCP.

答:
TLDR: If you need some infrastructure logic to be executed against your domain and you need some input to it from domain - don't build it in, just declare intentions with appropriate data/markers. You'll then process this declared intentions later, in infrastructure layer.

Do notifications of various kind differ in any way other that delivery mechanism? If not - there could be enough to use a Notification value object (or Entity, if your domain model requires so) with additional field (Enum, if the list is known, or some kind of marker) to store a delivery method name. Maybe, there could be numerous such methods per single notification instance.

Then you have a business logic - a domain service - to fire a notification. A domain service should only depend on domain vocabulary. E.g NotificationDeliveryMethodProvider.

In your adapters layer you can implement various delivery method providers to interact with infrastructure. And a factory to get providers according to a value in DeliveryMethod enum (or marker).

Basically, it's not an aggregate's responsibility to "send" itself of manipulate in any way. Its responsibility should be to maintain its state, execute state transitions in a consistent way and coordinate states of its enclosed entities/values. And fire events about its state changes.

In one of my projects I used the following subpackages under my domain package:

provides - interfaces of domain services provided to clients

cousumes - interfaces of upstream dependencies

businesslogic - implementation of domain services

values - value objects with code to enforce their invariants

...

Besides domain package there were also:

adapters package dealing with infrastructure

App object, where all interfaces were bound to implementations.

[There could also be] config package, but in my case it was very light.

These domain, adapters, App and config could be deployed as different jar-files with clear dependency structure, if you need to enforce it for somebody other.

Body:
Background

Suppose I am tasked with building a system in the domain of notification sending using Domain Driven Design (DDD). One of the key requirements of this system is that it needs to support various "types" of notifications, such as SMS, email, etc.

After several iterations on developing the domain model, I continue to land on having a Notification base class as an entity, with subclasses SMSNotification, EmailNotification, etc. as child classes (each being an entity as well).

Notification

public abstract class Notification extends Entity<UUID> {
    //...fields...

    public abstract void send();
}

SMSNotification

public class SMSNotification extends Notification {

    public void send(){
         //logic for sending the SMS notification using an infrastructure service.
    }
}

EmailNotification

public class EmailNotification extends Notification {

    public void send(){
        //logic for sending the email notification using an infrastructure service.
    }
}

Problem(s)

With this current design approach, each subclass of Notification is interacting with an infrastructure service, where the infrastructure is tasked with interfacing with some external system.

Eric Evans dedicates a little page space about this on page 107 in his book Domain-Driven Design when introducing the concept of domain services:

..., in most development systems, it is awkward to make a direct interface between a domain object and external resources. We can dress up such external services with a facade that takes inputs in terms of the model, ... but whatever intermediaries we may have, and even though they don't belong to us, those services are carrying out the domain responsibility...

If instead, I procure a SendNotificationService in my domain model using Evans' advice instead of having a send method on each subclass of Notification, I am not sure how I can avoid the need for knowing what type of notification was provided, so that the appropriate infrastructure action can be taken:

SendNotificationService (Domain Service)

public class SendNotificationService {
    public void send(Notification notification){
        //if notification is an SMS notification...
        //    utilize infrastructure services for SMS sending.
        //if notification is an email notification...
        //    utilize infrastructure services for email sending.
        //
        //(╯°□°）╯︵ ┻━┻)
    }
}

What am I missing here?

Object oriented design principles are pushing me in favor of having the model first suggested, with the Notification, SMSNotification, and EmailNotification classes. Implementing the send method on each subclass of Notification makes sense, as all notifications need to be sent (justifies its placement in Notification) and each "type" or subclass of Notification will have specialized behavior in how the notification is sent (justifies making send abstract in Notification). This approach also honors Open/Closed Principle (OCP), since the Notification class will be closed to modification, and as new notification types are supported, a new subclass of Notification can be created to extend functionality. Regardless, there seems to be consensus on not having entities interface with external services, as well as not having subclasses of entities at all in DDD.

If the behavior of sending notifications is removed from Notification, then where it is placed must be aware of the "type" of notification, and act accordingly, which I can only conceptualize as chain of if...else... statements, which directly contradicts OCP.


问:
Taking sum From a table and trying to update that rows in another
here is everything i tried yet !

```<code>UPDATE DailyBooking
SET RecievedAmount =
(
    SELECT DailyBooking.ID,
        (SELECT  SUM(RecipientDetails.Amount) FROM RecipientDetails
         WHERE RecipientDetails.DBID = DailyBooking.ID)
    FROM DailyBooking
    INNER JOIN RecipientDetails
        ON RecipientDetails.DBID = DailyBooking.ID
 )
</code>```

this query is throwing error

Only one expression can be specified in the select list when the
  subquery is not introduced with EXISTS.

and when i try that with where clause like :

```<code> UPDATE DailyBooking SET RecievedAmount=(
    SELECT DailyBooking.ID,
    (SELECT  SUM(RecipientDetails.Amount) FROM RecipientDetails
    WHERE RecipientDetails.DBID = DailyBooking.ID) FROM DailyBooking INNER JOIN RecipientDetails ON
    RecipientDetails.DBID =DailyBooking.ID
     ) where DailyBooking.ID = RecipientDetails.DBID
</code>```

it is throwing error like :

Msg 4104, Level 16, State 1, Line 6 The multi-part identifier
  "RecipientDetails.DBID" could not be bound.

Tables !
1 Table Providing Sum :
RecipientDetails

Table having RecievedAmount Column:

DailyBooking

Thanks in Advance..

答:
Hope this helps.</p>

```<code>UPDATE DailyBooking
SET RecievedAmount =
 (SELECT  SUM(RecipientDetails.Amount) FROM RecipientDetails
     WHERE RecipientDetails.DBID = DailyBooking.ID)
FROM DailyBooking
INNER JOIN RecipientDetails
    ON RecipientDetails.DBID = DailyBooking.ID
</code>```

Body:
here is everything i tried yet !

UPDATE DailyBooking
SET RecievedAmount =
(
    SELECT DailyBooking.ID,
        (SELECT  SUM(RecipientDetails.Amount) FROM RecipientDetails
         WHERE RecipientDetails.DBID = DailyBooking.ID)
    FROM DailyBooking
    INNER JOIN RecipientDetails
        ON RecipientDetails.DBID = DailyBooking.ID
 )

this query is throwing error

Only one expression can be specified in the select list when the
  subquery is not introduced with EXISTS.

and when i try that with where clause like :

 UPDATE DailyBooking SET RecievedAmount=(
    SELECT DailyBooking.ID,
    (SELECT  SUM(RecipientDetails.Amount) FROM RecipientDetails
    WHERE RecipientDetails.DBID = DailyBooking.ID) FROM DailyBooking INNER JOIN RecipientDetails ON
    RecipientDetails.DBID =DailyBooking.ID
     ) where DailyBooking.ID = RecipientDetails.DBID

it is throwing error like :

Msg 4104, Level 16, State 1, Line 6 The multi-part identifier
  "RecipientDetails.DBID" could not be bound.

Tables !
1 Table Providing Sum :
RecipientDetails

Table having RecievedAmount Column:

DailyBooking

Thanks in Advance..

Body:
Hope this helps.

UPDATE DailyBooking
SET RecievedAmount =
 (SELECT  SUM(RecipientDetails.Amount) FROM RecipientDetails
     WHERE RecipientDetails.DBID = DailyBooking.ID)
FROM DailyBooking
INNER JOIN RecipientDetails
    ON RecipientDetails.DBID = DailyBooking.ID


问:
How to reload by resetting pagination, total rows in DataTable plugin?
I am not sure on how to reload a new table with the correct pagination and etc when every time i insert a new Data or select a different dropdown option.

What my usual code does is, when i select a value from my dropdown, my table will refresh and display a new set of data inside the table body tag. When i use this plugin, it displays everything perfectly fine but when i select a different value from my dropdown, it displays a new set but my sorting, pagination and others will still function based on the first set of data i selected.

Here is my code. It will really be helpful if someone can point out my mistake. Thank you !

```<code>var loadClassType = function(eventID){
    $("#loadClassTypeTableBody").empty();

    var formData = {
        'perform'     : "getClassTypeList",
        'event_id'    : eventID,
    };

    $.ajax({
        type        : 'POST',
        url         : './competition.php',
        data        : formData,
        dataType    : 'json',
        encode      : true
    })
    .done(function(data) {

        if (data.success) {
            var htmlBlock="";
            var i = 1;
            $.each(data.data, function(id,errMsg){
                htmlBlock += '<tr>';
                htmlBlock +=    '<td>'+i+'</td>';
                htmlBlock +=    '<td>'+errMsg['class_type_name']+'</td>';

                if (errMsg['status'] == 1 ) {
                      htmlBlock +=    '<td class="text-success">Active</td>';
                }else{
                      htmlBlock +=    '<td class="text-danger">Disabled</td>';
                }

                if (errMsg['status'] == 1 ) {
                      htmlBlock +=    '<td><i class="material-icons" rel="tooltip" title data-original-title="Click to \'Disable\'" onClick="ctrlClassType(2,'+errMsg['id']+','+eventID+')">lock_open</i></td>';
                }else{
                      htmlBlock +=    '<td><i class="material-icons" rel="tooltip" title data-original-title="Click to \'Enable\' " onClick="ctrlClassType(1,'+errMsg['id']+','+eventID+')">lock</i></td>';
                }
                htmlBlock +=  '</tr>';
                i++;
        });

            $("#loadClassTypeTableBody").append(htmlBlock);
            $("#loadClassTypeTable").DataTable().clear();
        }else{
            console.log(data);

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

And my HTML Code :

```<code><table class="table table-hover" id="loadClassTypeTable">
    <thead>
        <tr>
            <th>#</th>
            <th>Class Type Name</th>

            <th>Status</th>
            <th>Options</th>
        </tr>
    </thead>

    <tbody id="loadClassTypeTableBody">
      <!-- Depends on JS -->
    </tbody>
</table>
</code>```

What i have tried so far is,

```<code>$("#loadClassTypeTable").DataTable().clear().draw();
// returns "No data available in table" and following with my blocks of html code
$("#loadClassTypeTable").DataTable().ajax.reload(); // doesnt work because i am not passing a jason value
</code>```

答:
Okay, after spending sometime, i found a fix by playing around with the codes and doing some research. This method worked for me. Hopefully it might help someone who encountered the same problem as mine.

First thing to take note :

```<code>//clear and destroy the table first
$('#viewEntriesTable').DataTable().clear();
$('#viewEntriesTable').DataTable().destroy();

//in my case,i will use the append method to insert my HTML Blocks of code first
$("#load_total_joined_entries").append(htmlBlocks);

//and finally
 $('#viewEntriesTable').DataTable();
</code>```

Second thing to take note: I have to avoid appending my html blocks if there is no rows detected by using "colspan" ... this was referred from the discussion here after getting an error which says Uncaught TypeError: Cannot set property '_DT_CellIndex' of undefined datatable

Body:
I am not sure on how to reload a new table with the correct pagination and etc when every time i insert a new Data or select a different dropdown option.

What my usual code does is, when i select a value from my dropdown, my table will refresh and display a new set of data inside the table body tag. When i use this plugin, it displays everything perfectly fine but when i select a different value from my dropdown, it displays a new set but my sorting, pagination and others will still function based on the first set of data i selected.

Here is my code. It will really be helpful if someone can point out my mistake. Thank you !

var loadClassType = function(eventID){
    $("#loadClassTypeTableBody").empty();

    var formData = {
        'perform'     : "getClassTypeList",
        'event_id'    : eventID,
    };

    $.ajax({
        type        : 'POST',
        url         : './competition.php',
        data        : formData,
        dataType    : 'json',
        encode      : true
    })
    .done(function(data) {

        if (data.success) {
            var htmlBlock="";
            var i = 1;
            $.each(data.data, function(id,errMsg){
                htmlBlock += '
';
                htmlBlock +=    ''+i+'	';
                htmlBlock +=    ''+errMsg['class_type_name']+'	';

                if (errMsg['status'] == 1 ) {
                      htmlBlock +=    'Active	';
                }else{
                      htmlBlock +=    'Disabled	';
                }

                if (errMsg['status'] == 1 ) {
                      htmlBlock +=    'lock_open	';
                }else{
                      htmlBlock +=    'lock	';
                }
                htmlBlock +=  '
';
                i++;
        });

            $("#loadClassTypeTableBody").append(htmlBlock);
            $("#loadClassTypeTable").DataTable().clear();
        }else{
            console.log(data);

        }
    });
}

And my HTML Code :

            #
            Class Type Name

            Status
            Options

What i have tried so far is,

$("#loadClassTypeTable").DataTable().clear().draw();
// returns "No data available in table" and following with my blocks of html code
$("#loadClassTypeTable").DataTable().ajax.reload(); // doesnt work because i am not passing a jason value

Body:
Okay, after spending sometime, i found a fix by playing around with the codes and doing some research. This method worked for me. Hopefully it might help someone who encountered the same problem as mine.

First thing to take note :

//clear and destroy the table first
$('#viewEntriesTable').DataTable().clear();
$('#viewEntriesTable').DataTable().destroy();

//in my case,i will use the append method to insert my HTML Blocks of code first
$("#load_total_joined_entries").append(htmlBlocks);

//and finally
 $('#viewEntriesTable').DataTable();

Second thing to take note: I have to avoid appending my html blocks if there is no rows detected by using "colspan" ... this was referred from the discussion here after getting an error which says Uncaught TypeError: Cannot set property '_DT_CellIndex' of undefined datatable


问:
How to make an input have more than one event?
I have a button and a select in my form. The button has onclick event while the select has onchange event. How to make the select has both onclick and onchange event?

This is the script:

```<code>$('#i_btn').on('click', function(){
     alert('Event 1');
});

$('#i_sel').on('change', function(){
     alert('Event 2');
});
</code>```

When the select is changed, it should do alert('Event 1'); alert('Event 2');. I do not want to rewrite the onclick code in onchange

答:
You can use trigger inside the on change of the select make sure you have defined buttons on click before on change

$('#btn1').on('click', function(){
     alert('Clicked');
});

$('#select1').on('change', function(){
     alert('Changed');
     $("#btn1").trigger("click");
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<select id="select1">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>
<button id="btn1">click</button></code>```

Body:
I have a button and a select in my form. The button has onclick event while the select has onchange event. How to make the select has both onclick and onchange event?

This is the script:

$('#i_btn').on('click', function(){
     alert('Event 1');
});

$('#i_sel').on('change', function(){
     alert('Event 2');
});

When the select is changed, it should do alert('Event 1'); alert('Event 2');. I do not want to rewrite the onclick code in onchange

Body:
You can use trigger inside the on change of the select make sure you have defined buttons on click before on change

$('#btn1').on('click', function(){
     alert('Clicked');
});

$('#select1').on('change', function(){
     alert('Changed');
     $("#btn1").trigger("click");
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<select id="select1">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>
<button id="btn1">click</button>


问:
How do I install a font on a user's machine in VB.NET so applications like Word can use it?
Need to install a font on all user's machines that will use the application I am writing which creates custom documents in Word.  It's a barcode font.

I've successfully added the font to my solution and set its build action to Embedded Resource and have also successfully written code to check if the font is already installed on the user's system.

Now I just need to figure out how to extract the font from my solution and install it onto the user's machine as if they installed the font themselves for use in Office applications, etc.

Most of the examples I've found out there are for using the font within the VB.NET application instead of outside it and the one's I have found which seem to fit my purpose aren't working for me.

答:
First, you need to copy the font to the Windows\Fonts directory (you'll want to make sure to use the Environment.GetFolderPath method provided by the .NET Framework instead of hard-coding the typical path to the Windows directory, just in case something is different in one of your users' environments).

Then, you need to call the AddFontResource function to add the font to the system font table. Since AddFontResource is provided by the Windows API, you'll need to P/Invoke to call it from VB.NET code. The declaration looks something like this (the lpszFilename parameter is the path to the font file that you want to add):

```<code><DllImport("gdi32.dll"), CharSet := CharSet.Auto> _
Public Shared Function AddFontResource(ByVal lpszFilename As String) As Integer
</code>```

Finally, if Word (or whatever application you intend to use the font in) is running at the time you call the AddFontResource function from your code, you need to inform it that the available fonts have changed. You do this by sending a WM_FONTCHANGE message to all top-level windows using the SendMessage function and setting the hWnd parameter toHWND_BROADCAST. Again, you'll need to P/Invoke; the declarations look like this:

```<code>Public Const HWND_BROADCAST As Integer = &HFFFF
Public Const WM_FONTCHANGE As Integer = &H1D

<DllImport("user32.dll"), CharSet := CharSet.Auto> _
Public Shared Function SendMessage(ByVal hWnd As IntPtr, ByVal wMsg As Integer, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As Integer
</code>```

And you would call it to send the broadcast message like this:

```<code>SendMessage(New IntPtr(HWND_BROADCAST), WM_FONTCHANGE, IntPtr.Zero, IntPtr.Zero)
</code>```

NOTE: The above steps only install the font for the current Windows session. If you need the font to be available on subsequent restarts, you need to add it to the registry. The key to modify is this one:

```<code>HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts
</code>```

ContentLicense: CC BY-SA 2.5

Body:
First, you need to copy the font to the Windows\Fonts directory (you'll want to make sure to use the Environment.GetFolderPath method provided by the .NET Framework instead of hard-coding the typical path to the Windows directory, just in case something is different in one of your users' environments).

Then, you need to call the AddFontResource function to add the font to the system font table. Since AddFontResource is provided by the Windows API, you'll need to P/Invoke to call it from VB.NET code. The declaration looks something like this (the lpszFilename parameter is the path to the font file that you want to add):

<DllImport("gdi32.dll"), CharSet := CharSet.Auto> _
Public Shared Function AddFontResource(ByVal lpszFilename As String) As Integer

Finally, if Word (or whatever application you intend to use the font in) is running at the time you call the AddFontResource function from your code, you need to inform it that the available fonts have changed. You do this by sending a WM_FONTCHANGE message to all top-level windows using the SendMessage function and setting the hWnd parameter toHWND_BROADCAST. Again, you'll need to P/Invoke; the declarations look like this:

Public Const HWND_BROADCAST As Integer = &HFFFF
Public Const WM_FONTCHANGE As Integer = &H1D

<DllImport("user32.dll"), CharSet := CharSet.Auto> _
Public Shared Function SendMessage(ByVal hWnd As IntPtr, ByVal wMsg As Integer, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As Integer

And you would call it to send the broadcast message like this:

SendMessage(New IntPtr(HWND_BROADCAST), WM_FONTCHANGE, IntPtr.Zero, IntPtr.Zero)

NOTE: The above steps only install the font for the current Windows session. If you need the font to be available on subsequent restarts, you need to add it to the registry. The key to modify is this one:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts


问:
React setState - Add array to nested object with multiple arrays
I'm currently working on a new application in React. This is the first time I'm creating something in React. The application will display our own promotions.

My initial state is as follows:

```<code>{
  "promotion": {
    "name": "",
    "campaign": "",
    "url": "https://",
    "position": 0,
    "periods": [
      {
        "startDateTimeStamp": 1510558814960,
        "endDateTimeStamp": 1510558814960,
        "variants": [
          {
            "title": "",
            "text": "",
            "image": ""
          }
        ]
      }
    ]
  }
}
</code>```

This is created from my defaultPromotion constant. This constant is stored in a separate file, which I call api.js

```<code>export const defaultPromotion = {
  name: '',
  campaign: '',
  url: 'https://',
  position: 0,
  periods: [
    {
      startDateTimeStamp: Date.now(),
      endDateTimeStamp: Date.now(),
      variants: [
        {
          title: '',
          text: '',
          image: '',
        },
      ]
    },
  ]
}
</code>```

In my createPromotion component it's created as followed

```<code>let promotionState = api.promotions.defaultPromotion;

this.state = {
  promotion: promotionState
};
</code>```

I can add a new period with the following:

```<code>addPromotion() {
    let promotion = this.state.promotion;
    promotion.periods.push( api.promotions.defaultPromotion.periods[0] );
    this.forceUpdate();
}
</code>```

After that, a new period is added as expected. Suggestions to do this with setState() are very welcome! So, my new state is now:

```<code>{
  "promotion": {
    "name": "",
    "campaign": "",
    "url": "https://",
    "position": 0,
    "periods": [
      {
        "startDateTimeStamp": 1510559984421,
        "endDateTimeStamp": 1510559984421,
        "variants": [
          {
            "title": "",
            "text": "",
            "image": ""
          }
        ]
      },
      {
        "startDateTimeStamp": 1510559984421,
        "endDateTimeStamp": 1510559984421,
        "variants": [
          {
            "title": "",
            "text": "",
            "image": ""
          }
        ]
      }
    ]
  }
}
</code>```

Now, I want to add a new variant for this promotion period, this is where I'm stuck for 2 days now.

I'm adding a new period as follows:

```<code>addVariant( periodKey ) {
  const promotion = this.state.promotion;
  promotion.periods[periodKey].variants.push(api.promotions.defaultPromotion.periods[0].variants[0]);
  this.setState({ promotion: promotion });
}
</code>```

periodKey is here "1", so, I'm expecting that there will be added a new variant for periods[1], but, it's added to both periods. State is now as follows:

```<code>{
  "promotion": {
    "name": "",
    "campaign": "",
    "url": "https://",
    "position": 0,
    "periods": [
      {
        "startDateTimeStamp": 1510559984421,
        "endDateTimeStamp": 1510559984421,
        "variants": [
          {
            "title": "",
            "text": "",
            "image": ""
          },
          {
            "title": "",
            "text": "",
            "image": ""
          }
        ]
      },
      {
        "startDateTimeStamp": 1510559984421,
        "endDateTimeStamp": 1510559984421,
        "variants": [
          {
            "title": "",
            "text": "",
            "image": ""
          },
          {
            "title": "",
            "text": "",
            "image": ""
          }
        ]
      }
    ]
  }
}
</code>```

Can someone explain me why this is happening and how I can add a new variant the right way?

Many, many thanks in advance!

UPDATE 1

Based on the answers from bennygenel and Patrick Hübl-Neschkudla, my implementation is now as follows:

Setting the initial state:

```<code>constructor(props) {
      super(props);

      let promotionState = api.promotions.defaultPromotion;
      this.state = { ...promotionState };

}
</code>```

Method:

```<code>addVariant( periodKey ) {
  this.setState((prevState) => {
    const { periods } = prevState;

    periods[periodKey].variants.push(
      Object.assign({}, { ...periods[periodKey].variants, api.promotions.defaultPromotion.periods[0].variants[0]})
    );

    return { periods };
  });
}
</code>```

But this still is setting the new variant in all the periods. I've also tried the exact code from Benny, but with the same results. The method is called as

```<code>this.props.addVariant( this.props.periodKey );
</code>```

Even when I call it as:

```<code>this.props.addVariant(2);
</code>```

The same behaviour is happening.

UPDATE 2

I now have rewritten everything to redux, this is so I have access to my promotion in every component the easy way, instead off passing them through certain components. Based on the answer of @mersocarlin, I now have the following reducer cases:

Add period

```<code>case PROMOTION_ADD_PERIOD:
    const { periods } = { ...state };
    periods.push(api.promotions.defaultPromotion.periods[0]);

    state = {
        ...state,
        periods: periods
    };
    break;
</code>```

Add a period variant

```<code>case PROMOTION_ADD_PERIOD_VARIANT :

  state = {
    ...state,
    periods: [
      ...state.periods[action.payload.period],
      {
        variants: [
          ...state.periods[action.payload.period].variants,
          api.promotions.defaultPromotion.periods[0].variants[0]
        ]
      }
    ]
  };

  break;
</code>```

The following case:
Add a new variant, works, state:

```<code>{
  "name": "",
  "campaign": "",
  "url": "https://",
  "position": 0,
  "periods": [
    {
      "startDateTimeStamp": 1510599968588,
      "endDateTimeStamp": 1510599968588,
      "variants": [
        {
          "title": "",
          "text": "",
          "image": ""
        }
      ]
    },
    {
      "startDateTimeStamp": 1510599968594,
      "endDateTimeStamp": 1510599968594,
      "variants": [
        {
          "title": "",
          "text": "",
          "image": ""
        }
      ]
    }
  ]
}
</code>```

After that, adding a new variant, kinda works, well, the variant is added, but I'm losing my 2nd period. State:

```<code>{
  "name": "",
  "campaign": "",
  "url": "https://",
  "position": 0,
  "periods": [
    {
      "variants": [
        {
          "title": "",
          "text": "",
          "image": ""
        },
        {
          "title": "",
          "text": "",
          "image": ""
        }
      ]
    }
  ]
}
</code>```

I think this is a small thing I'm not see'ing. Does someone have the solution for the "PROMOTION_ADD_PERIOD_VARIANT" case?

Update 3
Changed the "PROMOTION_ADD_PERIOD" case as follows:

```<code>case PROMOTION_ADD_PERIOD:
    state = {
        ...state,
        periods: [
            ...state.periods,
            initialState.periods[0]
        ]
    };

    break;
</code>```

Update 4
Finaly found the solution. See the final code for PROMOTION_ADD_PERIOD_VARIANT below:

```<code>state = {
  ...state,
  periods: [
    ...state.periods.map((item, index) => {
      if ( index !== action.payload.period ) {
        return item;
      }

      return {
        ...item,
        variants: [
          ...item.variants,
          initialState.periods[0].variants[0]
        ]
      }
    })
  ]
};
</code>```

Thank you all so much for your help!!

答:
First suggestion, if you are going to have only one promotion object in your state and not an array, lose the promotion level. this will reduce the complexity of your state. You can use spread syntax to easily set your initial state.

Example

```<code>let promotionState = api.promotions.defaultPromotion;

this.state = { ...promotionState };
</code>```

Above code would end up creating a state like below;

```<code>{
  "name": "",
  "campaign": "",
  "url": "https://",
  "position": 0,
  "periods": [{
    "startDateTimeStamp": 1510559984421,
    "endDateTimeStamp": 1510559984421,
    "variants": [{
      "title": "",
      "text": "",
      "image": ""
    }]
  }, {
    "startDateTimeStamp": 1510559984421,
    "endDateTimeStamp": 1510559984421,
    "variants": [{
      "title": "",
      "text": "",
      "image": ""
    }]
  }]
}
</code>```

Another suggestion I can make is to use functional setState to reduce possibility to mutate.

Example

```<code>addPromotion() {
  this.setState((prevState) => {
    const { periods } = prevState;
    periods.push(api.promotions.defaultPromotion.periods[0]);
    return { periods };
  });
}
</code>```

```<code>addVariant( periodKey ) {
  this.setState((prevState) => {
    const { periods } = prevState;
    periods[periodKey].variants.push(api.promotions.defaultPromotion.periods[0].variants[0]);
    return { periods };
  });
}
</code>```

Body:
I'm currently working on a new application in React. This is the first time I'm creating something in React. The application will display our own promotions.

My initial state is as follows:

{
  "promotion": {
    "name": "",
    "campaign": "",
    "url": "https://",
    "position": 0,
    "periods": [
      {
        "startDateTimeStamp": 1510558814960,
        "endDateTimeStamp": 1510558814960,
        "variants": [
          {
            "title": "",
            "text": "",
            "image": ""
          }
        ]
      }
    ]
  }
}

This is created from my defaultPromotion constant. This constant is stored in a separate file, which I call api.js

export const defaultPromotion = {
  name: '',
  campaign: '',
  url: 'https://',
  position: 0,
  periods: [
    {
      startDateTimeStamp: Date.now(),
      endDateTimeStamp: Date.now(),
      variants: [
        {
          title: '',
          text: '',
          image: '',
        },
      ]
    },
  ]
}

In my createPromotion component it's created as followed

let promotionState = api.promotions.defaultPromotion;

this.state = {
  promotion: promotionState
};

I can add a new period with the following:

addPromotion() {
    let promotion = this.state.promotion;
    promotion.periods.push( api.promotions.defaultPromotion.periods[0] );
    this.forceUpdate();
}

After that, a new period is added as expected. Suggestions to do this with setState() are very welcome! So, my new state is now:

{
  "promotion": {
    "name": "",
    "campaign": "",
    "url": "https://",
    "position": 0,
    "periods": [
      {
        "startDateTimeStamp": 1510559984421,
        "endDateTimeStamp": 1510559984421,
        "variants": [
          {
            "title": "",
            "text": "",
            "image": ""
          }
        ]
      },
      {
        "startDateTimeStamp": 1510559984421,
        "endDateTimeStamp": 1510559984421,
        "variants": [
          {
            "title": "",
            "text": "",
            "image": ""
          }
        ]
      }
    ]
  }
}

Now, I want to add a new variant for this promotion period, this is where I'm stuck for 2 days now.

I'm adding a new period as follows:

addVariant( periodKey ) {
  const promotion = this.state.promotion;
  promotion.periods[periodKey].variants.push(api.promotions.defaultPromotion.periods[0].variants[0]);
  this.setState({ promotion: promotion });
}

periodKey is here "1", so, I'm expecting that there will be added a new variant for periods[1], but, it's added to both periods. State is now as follows:

{
  "promotion": {
    "name": "",
    "campaign": "",
    "url": "https://",
    "position": 0,
    "periods": [
      {
        "startDateTimeStamp": 1510559984421,
        "endDateTimeStamp": 1510559984421,
        "variants": [
          {
            "title": "",
            "text": "",
            "image": ""
          },
          {
            "title": "",
            "text": "",
            "image": ""
          }
        ]
      },
      {
        "startDateTimeStamp": 1510559984421,
        "endDateTimeStamp": 1510559984421,
        "variants": [
          {
            "title": "",
            "text": "",
            "image": ""
          },
          {
            "title": "",
            "text": "",
            "image": ""
          }
        ]
      }
    ]
  }
}

Can someone explain me why this is happening and how I can add a new variant the right way?

Many, many thanks in advance!

UPDATE 1

Based on the answers from bennygenel and Patrick Hübl-Neschkudla, my implementation is now as follows:

Setting the initial state:

constructor(props) {
      super(props);

      let promotionState = api.promotions.defaultPromotion;
      this.state = { ...promotionState };

}

Method:

addVariant( periodKey ) {
  this.setState((prevState) => {
    const { periods } = prevState;

    periods[periodKey].variants.push(
      Object.assign({}, { ...periods[periodKey].variants, api.promotions.defaultPromotion.periods[0].variants[0]})
    );

    return { periods };
  });
}

But this still is setting the new variant in all the periods. I've also tried the exact code from Benny, but with the same results. The method is called as

this.props.addVariant( this.props.periodKey );

Even when I call it as:

this.props.addVariant(2);

The same behaviour is happening.

UPDATE 2

I now have rewritten everything to redux, this is so I have access to my promotion in every component the easy way, instead off passing them through certain components. Based on the answer of @mersocarlin, I now have the following reducer cases:

Add period

case PROMOTION_ADD_PERIOD:
    const { periods } = { ...state };
    periods.push(api.promotions.defaultPromotion.periods[0]);

    state = {
        ...state,
        periods: periods
    };
    break;

Add a period variant

case PROMOTION_ADD_PERIOD_VARIANT :

  state = {
    ...state,
    periods: [
      ...state.periods[action.payload.period],
      {
        variants: [
          ...state.periods[action.payload.period].variants,
          api.promotions.defaultPromotion.periods[0].variants[0]
        ]
      }
    ]
  };

  break;

The following case:
Add a new variant, works, state:

{
  "name": "",
  "campaign": "",
  "url": "https://",
  "position": 0,
  "periods": [
    {
      "startDateTimeStamp": 1510599968588,
      "endDateTimeStamp": 1510599968588,
      "variants": [
        {
          "title": "",
          "text": "",
          "image": ""
        }
      ]
    },
    {
      "startDateTimeStamp": 1510599968594,
      "endDateTimeStamp": 1510599968594,
      "variants": [
        {
          "title": "",
          "text": "",
          "image": ""
        }
      ]
    }
  ]
}

After that, adding a new variant, kinda works, well, the variant is added, but I'm losing my 2nd period. State:

{
  "name": "",
  "campaign": "",
  "url": "https://",
  "position": 0,
  "periods": [
    {
      "variants": [
        {
          "title": "",
          "text": "",
          "image": ""
        },
        {
          "title": "",
          "text": "",
          "image": ""
        }
      ]
    }
  ]
}

I think this is a small thing I'm not see'ing. Does someone have the solution for the "PROMOTION_ADD_PERIOD_VARIANT" case?

Update 3
Changed the "PROMOTION_ADD_PERIOD" case as follows:

case PROMOTION_ADD_PERIOD:
    state = {
        ...state,
        periods: [
            ...state.periods,
            initialState.periods[0]
        ]
    };

    break;

Update 4
Finaly found the solution. See the final code for PROMOTION_ADD_PERIOD_VARIANT below:

state = {
  ...state,
  periods: [
    ...state.periods.map((item, index) => {
      if ( index !== action.payload.period ) {
        return item;
      }

      return {
        ...item,
        variants: [
          ...item.variants,
          initialState.periods[0].variants[0]
        ]
      }
    })
  ]
};

Thank you all so much for your help!!

Body:
First suggestion, if you are going to have only one promotion object in your state and not an array, lose the promotion level. this will reduce the complexity of your state. You can use spread syntax to easily set your initial state.

Example

let promotionState = api.promotions.defaultPromotion;

this.state = { ...promotionState };

Above code would end up creating a state like below;

{
  "name": "",
  "campaign": "",
  "url": "https://",
  "position": 0,
  "periods": [{
    "startDateTimeStamp": 1510559984421,
    "endDateTimeStamp": 1510559984421,
    "variants": [{
      "title": "",
      "text": "",
      "image": ""
    }]
  }, {
    "startDateTimeStamp": 1510559984421,
    "endDateTimeStamp": 1510559984421,
    "variants": [{
      "title": "",
      "text": "",
      "image": ""
    }]
  }]
}

Another suggestion I can make is to use functional setState to reduce possibility to mutate.

Example

addPromotion() {
  this.setState((prevState) => {
    const { periods } = prevState;
    periods.push(api.promotions.defaultPromotion.periods[0]);
    return { periods };
  });
}

addVariant( periodKey ) {
  this.setState((prevState) => {
    const { periods } = prevState;
    periods[periodKey].variants.push(api.promotions.defaultPromotion.periods[0].variants[0]);
    return { periods };
  });
}


问:
Vertically center parent div on page
I know vertical alignment is tricky and there are plenty of questions about it on stackoverflow... I have been trying to figure this out for a few hours, with no success, so decided to ask it (apologies if it is a duplicate)

I have created a login page for my website.

There are 2 main divs in the body, one for logo and one for login content. The login content, has 2 sections, one for email and password and one for social media login.

```<code><body>
 <div>
 My Logo goes here
 <div>
 <div>
  <section id="loginForm"></section>
  <section id="SocialLoginForm"></section>
 </div>
</body>
</code>```

Is there a way to always vertically center the login div? I want the logo to stay on the top, but the login div be vertically centered. I know I can assign a height to the div and center it's content, but I don't know how to determine the height as the screen size will change...

this is how it looks like, as you see there is a big gap at the bottom.

答:
body, html{
    display:table;
    height:100%;
    width:100%;
}
.my-container{
    display:table-cell;
    vertical-align:middle;
}
.my-container .your-div{
    width:150px;
    height:150px;
    border:1px solid #e3e3e3;
    margin:0 auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<body>
<div class="my-container">

<div class="your-div">

 <div>My Logo goes here<div>
 <div>
  <section id="loginForm">loginForm</section>
  <section id="SocialLoginForm">SocialLoginForm</section>
 </div>
 </div>

 </div>
</body>
</html></code>```

Title: Vertically center parent div on page

Body:
I know vertical alignment is tricky and there are plenty of questions about it on stackoverflow... I have been trying to figure this out for a few hours, with no success, so decided to ask it (apologies if it is a duplicate)

I have created a login page for my website.

There are 2 main divs in the body, one for logo and one for login content. The login content, has 2 sections, one for email and password and one for social media login.

 My Logo goes here

Is there a way to always vertically center the login div? I want the logo to stay on the top, but the login div be vertically centered. I know I can assign a height to the div and center it's content, but I don't know how to determine the height as the screen size will change...

this is how it looks like, as you see there is a big gap at the bottom.

Body:
body, html{
    display:table;
    height:100%;
    width:100%;
}
.my-container{
    display:table-cell;
    vertical-align:middle;
}
.my-container .your-div{
    width:150px;
    height:150px;
    border:1px solid #e3e3e3;
    margin:0 auto;
}

<html>
<body>
<div class="my-container">

<div class="your-div">

 <div>My Logo goes here<div>
 <div>
  <section id="loginForm">loginForm</section>
  <section id="SocialLoginForm">SocialLoginForm</section>
 </div>
 </div>

 </div>
</body>
</html>


答:
You could also simply add the event handler to the element...

```<code>$('#i_btn, #i_sel').on('click', function(){
     alert('Event 1');
});

$('#i_sel').on('change', function(){
     alert('Event 2');
});
</code>```

Unless you really need the click to trigger on the button...

Title: How to make an input have more than one event?

Body:
You could also simply add the event handler to the element...

$('#i_btn, #i_sel').on('click', function(){
     alert('Event 1');
});

$('#i_sel').on('change', function(){
     alert('Event 2');
});

Unless you really need the click to trigger on the button...


问:
Hyperledger composer allows TLS enabled docker network or not?
In hyperledger examples such as balance-transfer I see that the certificates of all peers are required to build a client and channel object on basis of which transactions are done. In composer I don't see the application taking into consideration those certificates for peers. Is it just because the TLS is not enabled in the docker-compose file. Is it even possible to have TLS enabled docker network yet??</p>

答:
Composer can work with a TLS enabled hyperledger fabric network, you just need to create the appropriate connection profile.
see https://hyperledger.github.io/composer/reference/connectionprofile.html for more information</p>


问:
How to pass event and other arguments in grid's context menu item handler?
I'm using Dojo 1.5, and I'm trying to create a context menu that can invocate a function myFunction passing the event and other arguments. So far I've the following code:

```<code>    <div dojoType="dijit.Menu" id="bankerMenu" style="display: none;">
        <div dojoType="dijit.MenuItem" onclick="copyDocuments('bankerFolder');" iconClass="dijitEditorIcon dijitEditorIconCopy">Copy to Client</div>
            <div dojoType="dijit.PopupMenuItem" onclick="doNothing()" iconClass="dijitEditorIcon dijitEditorIconCopy">
                <span><s:text name="CopyTo.label"/></span>
                <div dojoType="dijit.Menu" id="bigsubmenu">
var="distributionList">
                        <div dojoType="dijit.MenuItem" onclick="myFunction(event,'bankerFolder',1)"><s:property value='distributionListName'/></div>
                </div>
            </div>
    </div>
</code>```

But it is not recognizing the 'event' that I want to pass to the function. I know I can susbtitute the call using this:

```<code>            <div dojoType="dijit.MenuItem" label="Some menu item 2">
                <script type="dojo/method" event="onClick" args="evt">
                    myFunction(evt,'bankerFolder',1);
                </script>
            </div>
</code>```

but I would like to simplify it and used the first syntax. How can I do that?

答:
Passing event literally would likely end up leaving you at the mercy of cross-browser inconsistencies.  However, since events connected through Dojo worry about this for you, and since onClick is a widget event that already receives the event object as an argument, you should be able to get away with the following:

```<code><div dojoType="dijit.MenuItem" onClick="myFunction(arguments[0],'bankerFolder',1)"><s:property value='distributionListName'/></div>
</code>```

Also note the capital C in onClick - widget events always use camel case; they are not actual DOM events, though they are often mapped to analogous DOM events.  I get the impression you were testing with capital C though, based on the problem you described encountering.

Here's a simplified example of the idea working (initially provided/suggested by Dustin Machi in the Dojo IRC channel): http://jsfiddle.net/xwFC5/5/

Body:
I'm using Dojo 1.5, and I'm trying to create a context menu that can invocate a function myFunction passing the event and other arguments. So far I've the following code:

Copy to Client

                <s:text name="CopyTo.label"/>

var="distributionList">

<s:property value='distributionListName'/>

But it is not recognizing the 'event' that I want to pass to the function. I know I can susbtitute the call using this:

but I would like to simplify it and used the first syntax. How can I do that?

Body:
Passing event literally would likely end up leaving you at the mercy of cross-browser inconsistencies.  However, since events connected through Dojo worry about this for you, and since onClick is a widget event that already receives the event object as an argument, you should be able to get away with the following:

<div dojoType="dijit.MenuItem" onClick="myFunction(arguments[0],'bankerFolder',1)"><s:property value='distributionListName'/></div>

Also note the capital C in onClick - widget events always use camel case; they are not actual DOM events, though they are often mapped to analogous DOM events.  I get the impression you were testing with capital C though, based on the problem you described encountering.

Here's a simplified example of the idea working (initially provided/suggested by Dustin Machi in the Dojo IRC channel): http://jsfiddle.net/xwFC5/5/


问:
Insert a string before a matching string or at the end using regex
I have a requirement where the string has to contain _exact. I am using Java.

If the string has a locale (_en or _ja) at the end, add _exact before the locale.

If _exact is already present, don't add it again.

If no locale at the end, and no exact, add _exact at the end of the string.

E.g.:

something -> something_exact

something_en -> something_exact_en

something_ja -> something_exact_ja

something_exact_en -> something_exact_en

something_exact -> something_exact

I spent some time and came up with 2 regex that, if ran in succession on the same string, make it possible. I am not sure if they cover all the possible cases though.

^(.*)(?<!_exact)(_(?:en|ja))$

^(.*)(?<!_exact)(?<!_(?:en|ja))$

If anybody could help me come up with just 1 regex that does the job, it would be great! Thank you!

答:
You can use this regex:

```<code>str = str.replaceAll("^(?!.*_exact(?:_en|_ja)?$)(.+?)(_en|_ja)?$", "$1_exact$2");
</code>```

RegEx Demo

(?!.*_exact(?:_en|_ja)?$) is a negative lookahead that skips inputs that ends with _exact or _exact_en or _exact_ja.

Body:
You can use this regex:

str = str.replaceAll("^(?!.*_exact(?:_en|_ja)?$)(.+?)(_en|_ja)?$", "$1_exact$2");

RegEx Demo

(?!.*_exact(?:_en|_ja)?$) is a negative lookahead that skips inputs that ends with _exact or _exact_en or _exact_ja.


问:
Type geometry does not exist after CREATE EXTENSION postgis
After creating new postgres db and loading necessary postgis extension

```<code>$ createdb  demodb
$ psql demodb
> CREATE EXTENSION postgis;
> CREATE EXTENSION postgis_topology;
</code>```

I get django.db.utils.ProgrammingError: type "geometry" does not exist exception thrown while running django manage.py migrate

After this I tried running the failed query in pgadmin and it said the same: type "geometry" does not exist

Although appending CREATE EXTENSION postgis; before the query seems to fix this and query returned ok. But running manage.py migrate again throwed the same exception.

Isn't loading new extension permanent? And if so, how can I load it permanently, so it is loaded when running migrate?

答:
For me grant usage on schema <postgis-install-schema> to <myschema> solved it (<postgis-install-schema> was public in my case).

(grant all privileges as suggested from TechnoConserve may be too much for security reasons)

Body:
After creating new postgres db and loading necessary postgis extension

$ createdb  demodb
$ psql demodb
> CREATE EXTENSION postgis;
> CREATE EXTENSION postgis_topology;

I get django.db.utils.ProgrammingError: type "geometry" does not exist exception thrown while running django manage.py migrate

After this I tried running the failed query in pgadmin and it said the same: type "geometry" does not exist

Although appending CREATE EXTENSION postgis; before the query seems to fix this and query returned ok. But running manage.py migrate again throwed the same exception.

Isn't loading new extension permanent? And if so, how can I load it permanently, so it is loaded when running migrate?


问:
DDL scripts in a transaction block takes effect even when there are errors
I have some sql script files where i am making some DDL changes as part of commit block

```<code>BEGIN TRANSACTION

-- CREATE/ALTER TABLE, COLUMNS, CONTRAINTS etc etc
COMMIT
</code>```

Sometime when script fail, i still see the changes in DDL applied in database although this whole thing is in transaction block. What am I missing here?

答: DDL statment internally uses commit. DDL statment can not be rollback using rollback command.

Body:
I have some sql script files where i am making some DDL changes as part of commit block

BEGIN TRANSACTION

-- CREATE/ALTER TABLE, COLUMNS, CONTRAINTS etc etc
COMMIT

Sometime when script fail, i still see the changes in DDL applied in database although this whole thing is in transaction block. What am I missing here?


问:
canvas background turns black after rerender fabric.js
I have the following situation: I draw the canvas with a background image and this works:

```<code>var canvasSection = new fabric.Canvas('buildSection', {
  selectionColor: 'rgba(94,213,94,0.2)',
  width: widthS,
  height: heightS,
  hoverCursor: 'pointer',
  backgroundColor: ({
    source: 'image/bordenconfigurator/background/background1.png',
    repeat: 'repeat'
  })

});
</code>```

But then I need to clear canvas and to redraw it. at this point when I try to set background, instead of an image I see a black screen. In console I can see that the background image is set however. This is the code I'm trying:

```<code>$('#cForm').on('change', function() {

  if ($(this).val() == 'rectLandsc') {
    widthS = 600;
    heightS = 400;

  } else if ($(this).val() == 'rectPortr') {
    ....

  }
  canvasSection.clear();

  canvasSection.set({
    fill: 'rgba(0,0,0,0)',
    //  backgroundColor: ({source: 'image/bordenconfigurator/background/background1.png', repeat: 'repeat'})
  });
  //canvasSection.backgroundColor({source: 'image/bordenconfigurator/background/background.png', repeat:'repeat'});
  canvasSection.setBackgroundColor({
      source: 'image/bordenconfigurator/background/background.png'
    }),
    canvasSection.renderAll.bind(canvas);
  drawBaseForm();
  canvasSection.renderAll();

  console.log(canvasSection);
});
</code>```

Is it a kind of a bug? Or am I doing something wrong? Could anyone help me out here?

答:
```<code>canvas.setBackgroundColor({
  source: 'image/bordenconfigurator/background/background1.png',
  repeat: 'repeat'
}, canvas.renderAll.bind(canvas));
</code>```

setBackgroundColor first parameter is color/pattern and second parameter is callback function.

DEMO

var canvas = new fabric.Canvas('c');
canvas.setBackgroundColor({
  source: 'http://fabricjs.com/assets/pug_small.jpg'
}, canvas.renderAll.bind(canvas));

function clearCanvas(){
 var background = canvas.backgroundColor;
 canvas.clear();
 setTimeout(function(){
  canvas.setBackgroundColor(background,canvas.renderAll.bind(canvas));
 },2000)
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>canvas{
 border: 2px dotted black;
}</code>```

<button onclick='clearCanvas()'>clear</button>
<canvas id="c" width="500" height="500"></canvas>```

Body:
I have the following situation: I draw the canvas with a background image and this works:

var canvasSection = new fabric.Canvas('buildSection', {
  selectionColor: 'rgba(94,213,94,0.2)',
  width: widthS,
  height: heightS,
  hoverCursor: 'pointer',
  backgroundColor: ({
    source: 'image/bordenconfigurator/background/background1.png',
    repeat: 'repeat'
  })

});

But then I need to clear canvas and to redraw it. at this point when I try to set background, instead of an image I see a black screen. In console I can see that the background image is set however. This is the code I'm trying:

$('#cForm').on('change', function() {

  if ($(this).val() == 'rectLandsc') {
    widthS = 600;
    heightS = 400;

  } else if ($(this).val() == 'rectPortr') {
    ....

  }
  canvasSection.clear();

  canvasSection.set({
    fill: 'rgba(0,0,0,0)',
    //  backgroundColor: ({source: 'image/bordenconfigurator/background/background1.png', repeat: 'repeat'})
  });
  //canvasSection.backgroundColor({source: 'image/bordenconfigurator/background/background.png', repeat:'repeat'});
  canvasSection.setBackgroundColor({
      source: 'image/bordenconfigurator/background/background.png'
    }),
    canvasSection.renderAll.bind(canvas);
  drawBaseForm();
  canvasSection.renderAll();

  console.log(canvasSection);
});

Is it a kind of a bug? Or am I doing something wrong? Could anyone help me out here?

Body:
canvas.setBackgroundColor({
  source: 'image/bordenconfigurator/background/background1.png',
  repeat: 'repeat'
}, canvas.renderAll.bind(canvas));

setBackgroundColor first parameter is color/pattern and second parameter is callback function.

DEMO

var canvas = new fabric.Canvas('c');
canvas.setBackgroundColor({
  source: 'http://fabricjs.com/assets/pug_small.jpg'
}, canvas.renderAll.bind(canvas));

function clearCanvas(){
 var background = canvas.backgroundColor;
 canvas.clear();
 setTimeout(function(){
  canvas.setBackgroundColor(background,canvas.renderAll.bind(canvas));
 },2000)
}

canvas{
 border: 2px dotted black;
}

<script src="https://rawgithub.com/kangax/fabric.js/master/dist/fabric.js"></script>
<button onclick='clearCanvas()'>clear</button>
<canvas id="c" width="500" height="500"></canvas>


问:
How do I prepopulate form fileds in APEX
I'm using apex to create an application that has a database backend.
The application allows the users to search for institutions according to specific criteria, once the criteria are specified, a report is displayed to the user including the institution name and the logo of the institution. The name column is linked to a page that displays the details of a chosen institution.

I want to create a link from the details page that takes the user to the 'Contact US' page which should have some prepopulated form fields like the institution name and email etc. However, I'm not sure how to pass the institution id so that the fields can be prepopulated.

答: In your report, have the institution id as a column of type link next to name and logo.  Make the target page your contact us page and populate the institution id page item with #INSTITUTION_ID# (or whatever your institution_id column is called.


问:
ssl error in the hostname
Hi I am making a connection to my MQTT server with SSL .I am getting the following exception.

```<code>curl: (51) SSL: certificate subject name (*.xyz.com) does not match target host name '192.168.2.10'
</code>```

I am using a domain certificate for the ssl. Any help will be appreciated.

答:
Seems like HostName verification is enabled while you are trying to make a MQTT connection.
If your HostName verification is enabled, then the Subject DN present in the certificate should be same as the Server Hostname. Here, server is the MQTT broker I guess.

In your case, the system where the broker is running has the HostName '192.168.2.10', whereas the certificate that has been issued to the broker contains some different hostname present in the DN.

Now there can be two solutions to this:

You can try the same by disabling the hostname verification on the MQTT client end.

You can issue a new certificate to the broker that contains the Hostname of machine in the Subject DN of the certificate.

Hope it addresses your concern.

Title: ssl error in the hostname

Body:
Hi I am making a connection to my MQTT server with SSL .I am getting the following exception.

curl: (51) SSL: certificate subject name (*.xyz.com) does not match target host name '192.168.2.10'

I am using a domain certificate for the ssl. Any help will be appreciated.


问:
How to insert double quotes into String with interpolation in scala
Having trouble escaping all the quotes in my function

(basic usage of it -> if i find a string do nothing, if its not a string add " in the begin and end)

code snippet :

```<code>  def putTheDoubleQuotes(value: Any): Any = {
    value match {
      case s: String => s //do something ...
      case _  => s"\"$value\"" //not working
    }
  }
</code>```

only thing that worked was :

case _ => s"""\"$value\""""

is there a better syntax for this ?

it looks terrible and the IDE (IntelliJ) marks it in red (but lets you run it which really pisses me!!!!!)

答:
Simple way:- </p>

```<code>val str="abc"
println(s"$str") //without double quotes
println(s"""\"$str\"""") // with double quotes
</code>```

Body:
Having trouble escaping all the quotes in my function

(basic usage of it -> if i find a string do nothing, if its not a string add " in the begin and end)

code snippet :

  def putTheDoubleQuotes(value: Any): Any = {
    value match {
      case s: String => s //do something ...
      case _  => s"\"$value\"" //not working
    }
  }

only thing that worked was :

case _ => s"""\"$value\""""

is there a better syntax for this ?

it looks terrible and the IDE (IntelliJ) marks it in red (but lets you run it which really pisses me!!!!!)

Body:
Simple way:-

val str="abc"
println(s"$str") //without double quotes
println(s"""\"$str\"""") // with double quotes


问:
Data-attribute list to array
I have:

```<code><img id="img" data-list="['image2.jpg', 'image3.jpg', 'image4.jpg']" src="image1.jpg">
</code>```

How can i get images listed in data-list to array varible?

答:
Get the data from the img, format it as a JSON, and use JSON#parse to convert it to an array:

var img = document.querySelector('#img');
var array = JSON.parse(img.dataset.list.replace(/'/g, '"'));

console.log(array);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img id="img" data-list="['image2.jpg', 'image3.jpg', 'image4.jpg']" src="image1.jpg"></code>```

Title: Data-attribute list to array

Body:
I have:

How can i get images listed in data-list to array varible?

Body:
Get the data from the img, format it as a JSON, and use JSON#parse to convert it to an array:

var img = document.querySelector('#img');
var array = JSON.parse(img.dataset.list.replace(/'/g, '"'));

console.log(array);

<img id="img" data-list="['image2.jpg', 'image3.jpg', 'image4.jpg']" src="image1.jpg">


问:
Loading a Fragment from an Activity to another Activity which is already in backstack
I have an activity(let's call it Home Activity) with bottom navigation view where I replace all of my fragments. In Home Activity I have loaded a fragment which has a search icon. That search icon redirects to an activity that is Search Activity.

When I click any of the search result I go to my Home Activity and replace the previous fragment to show my recent search result click implementation.

In this case, the complexity is - when I'm trying to replace the previous fragment - it's visible to the user. And as I have a transition animation - I can see the previous fragment is exiting and the latest fragment is entering.

This is not at all a good experience for the user. How may I improve the functionality so that previous fragment is not visible to the user?

答:
Try out this code section. Create animation as you need.

```<code>public static void callFragment(Fragment fragment, Context context, String TAG) {
    FragmentManager fragmentManager = ((AppCompatActivity) context).getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
    if (fragment.isAdded()) {
        fragmentTransaction.show(fragment);
    } else {
        //   fragmentTransaction.setCustomAnimations(R.anim.fade_in, R.anim.face_out);
        fragmentTransaction.setCustomAnimations(R.anim.fragment_slide_top_enter, R.anim.fragment_slide_top_exit, R.anim.fragment_slide_bottom_enter, R.anim.fragment_slide_bottom_exit);
        fragmentTransaction.replace(R.id.content_frame, fragment);
        fragmentTransaction.addToBackStack(TAG);
    }
    fragmentTransaction.commit();
}
</code>```

And also provide background to your fragment layout files.

Body:
Try out this code section. Create animation as you need.

public static void callFragment(Fragment fragment, Context context, String TAG) {
    FragmentManager fragmentManager = ((AppCompatActivity) context).getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
    if (fragment.isAdded()) {
        fragmentTransaction.show(fragment);
    } else {
        //   fragmentTransaction.setCustomAnimations(R.anim.fade_in, R.anim.face_out);
        fragmentTransaction.setCustomAnimations(R.anim.fragment_slide_top_enter, R.anim.fragment_slide_top_exit, R.anim.fragment_slide_bottom_enter, R.anim.fragment_slide_bottom_exit);
        fragmentTransaction.replace(R.id.content_frame, fragment);
        fragmentTransaction.addToBackStack(TAG);
    }
    fragmentTransaction.commit();
}

And also provide background to your fragment layout files.


问:
Suggestions for porting linux application to windows
I'd like to port an application written under linux to windows. Currently I'm using Cygwin but I'm curious if there are any other options that don't force me to release my source since I'm not in the position to do so right now. Are there any other options short of having to completely re-write it or buying a license?  </p>

答:
There is also a commercial license for Cygwin.

http://www.redhat.com/services/custom/cygwin/


问:
How can I replace a file if already exists in the destination folder?
I just want to move a file from one folder to another (already know how to do that) and in the process check all the files in the destination folder and delete the files with the same name.

I have two folders /src and /dst.

In folder /src I have:

'access.log.1.txt'

and in folder /dst :

'access.log.1.20171110_115840565311.txt'

'access.log.1.20171110_115940565311.txt'

'access.log.2.20171110_115940565311.txt'

When I move the file in /src to /dst I want to delete all the files named as the file in /src excluding the datetime() extension in the files of /dst.

So the /dst folder should look like this after the execution:

'access.log.1.txt'

'access.log.2.20171110_115940565311.txt'

This is the code I have to move files from /src to /dst:

```<code>entrada = ENTRADA   #This 3 are the paths to the folders  /src
salida = SALIDA     #                                     /dst
error=ERROR         #                                     /err
files=glob.glob(entrada)
for file in files:
   fichero=open(file,encoding='utf-8')
   try:
       for line in fichero:
          la=line.replace("-","")
          li=la.replace('”'+chr(10),'')
          li=li.split('"')
          line_DB(li)
       fichero.close()
       if TIME_RENAME=='True':
          execution=str(datetime.now())
          execution=execution.replace('.','')
          execution=execution.replace('-','')
          execution=execution.replace(' ','_')
          execution_time=execution.replace(':','')
          base = os.path.splitext(file)[0]
          base=base+'.'+execution_time+'.txt'
          os.rename(file,base)
          file=base
       else:
          print('Hello')
          #This is where I need the code

       shutil.move(file, salida)
       con.commit()
   except:
       logging.error(sys.exc_info())
       print(sys.exc_info())
       fichero.close()
       shutil.move(file, error)
</code>```

Anyone could help me?

Thanks!!

答:
Sandip's answer should work, but if you specifically want it the way you've stated in your question, this could work:

```<code>import os

src_filename = "access.log.1.txt"
dst_dir = "test"

for filename in os.listdir(dst_dir):

    # Filter files based on number of . in filename
    if filename.count(".") < 4:
        continue

    # We need to remove the datetime extension before comparing with our filename
    filename_tokens = filename.split(".")  # List of words separated by . in the filename
    print "Tokens:", filename_tokens

    # Keep only indexes 0, 1, 2 and 4 (exclude index 3, which is the datetime-string)
    datetime_string = filename_tokens.pop(3)  # pop() also removes the datetime-string
    print "Datetime:", datetime_string
    dst_filename = ".".join(filename_tokens)
    print "Destination filename:", dst_filename

    # Check if the destination filename now matches our source filename
    if dst_filename == src_filename:
        # Get full path of file to be deleted
        filepath = os.path.join(dst_dir, filename)
        # Delete it
        print "Deleting:", filepath
        os.remove(filepath)
    print "----------------------"
</code>```

Note that this approach assumes that all your destination file names looks like they do in your question, i.e. that all of them have 4 periods (.) and that the datetime string is always between your third and fourth period.

Body:
I just want to move a file from one folder to another (already know how to do that) and in the process check all the files in the destination folder and delete the files with the same name.

I have two folders /src and /dst.

In folder /src I have:

'access.log.1.txt'

and in folder /dst :

'access.log.1.20171110_115840565311.txt'

'access.log.1.20171110_115940565311.txt'

'access.log.2.20171110_115940565311.txt'

When I move the file in /src to /dst I want to delete all the files named as the file in /src excluding the datetime() extension in the files of /dst.

So the /dst folder should look like this after the execution:

'access.log.1.txt'

'access.log.2.20171110_115940565311.txt'

This is the code I have to move files from /src to /dst:

entrada = ENTRADA   #This 3 are the paths to the folders  /src
salida = SALIDA     #                                     /dst
error=ERROR         #                                     /err
files=glob.glob(entrada)
for file in files:
   fichero=open(file,encoding='utf-8')
   try:
       for line in fichero:
          la=line.replace("-","")
          li=la.replace('”'+chr(10),'')
          li=li.split('"')
          line_DB(li)
       fichero.close()
       if TIME_RENAME=='True':
          execution=str(datetime.now())
          execution=execution.replace('.','')
          execution=execution.replace('-','')
          execution=execution.replace(' ','_')
          execution_time=execution.replace(':','')
          base = os.path.splitext(file)[0]
          base=base+'.'+execution_time+'.txt'
          os.rename(file,base)
          file=base
       else:
          print('Hello')
          #This is where I need the code

       shutil.move(file, salida)
       con.commit()
   except:
       logging.error(sys.exc_info())
       print(sys.exc_info())
       fichero.close()
       shutil.move(file, error)

Anyone could help me?

Thanks!!

Body:
Sandip's answer should work, but if you specifically want it the way you've stated in your question, this could work:

import os

src_filename = "access.log.1.txt"
dst_dir = "test"

for filename in os.listdir(dst_dir):

    # Filter files based on number of . in filename
    if filename.count(".") < 4:
        continue

    # We need to remove the datetime extension before comparing with our filename
    filename_tokens = filename.split(".")  # List of words separated by . in the filename
    print "Tokens:", filename_tokens

    # Keep only indexes 0, 1, 2 and 4 (exclude index 3, which is the datetime-string)
    datetime_string = filename_tokens.pop(3)  # pop() also removes the datetime-string
    print "Datetime:", datetime_string
    dst_filename = ".".join(filename_tokens)
    print "Destination filename:", dst_filename

    # Check if the destination filename now matches our source filename
    if dst_filename == src_filename:
        # Get full path of file to be deleted
        filepath = os.path.join(dst_dir, filename)
        # Delete it
        print "Deleting:", filepath
        os.remove(filepath)
    print "----------------------"

Note that this approach assumes that all your destination file names looks like they do in your question, i.e. that all of them have 4 periods (.) and that the datetime string is always between your third and fourth period.


问:
Ajax Post not Working in Wordpress
I have a simple ajax post method to send data to Web api but this code does not post data even there is no error in console.
Please help me to solve this I have also changed $ with jQuery as describe Here.I am using Wordpress 4.9.
Here is the source code written in wordpress.

Code

```<code>var ServiceAndVisitroData = {
  //orderid
  selectedService: selecteddata,
  userId: $('#userid').val().trim(),
  OrderId: $('#orderid').val().trim(),
  DealInfo: $('#deals').val().trim(),
  IPAddress: userip,
  deviceName: userDevicedata[0],
  OSName: jscd.os + "," + jscd.osVersion,
  browserName: jscd.browser + "," + jscd.browserMajorVersion + "," + jscd.browserVersion,
  IsCustomllogo: false,
  userToken: cookiesplit[1],
  firstname: cookiesplit[2],
  lastname: last[0]

};

$.ajax({
  type: "POST",
  url: 'http://test.com/api/agency/postcheckout',
  // contentType: "application/json; charset=utf-8",
  //data: JSON.stringify(ServiceAndVisitroData),
  data: ServiceAndVisitroData,
  dataType: "json",
  success: function (result) {
    //  alert(result.firstname);
    //  alert(result.lastname);
    //  alert(result.tokenn);
    // alert(result.useridd);

    if (result.success == "pymt") {

      window.location.href = 'http://test.com/api/agency/payment/' + result.Id + '/' + result.Showbutton + '/' + result.firstname + '/' + result.firstname + '/' + result.lastname
      return false;

    }
    else if (result.success == "ord") {

      window.location.href = 'http://test.com/api/agency/order/' + result.Id + '/' + result.Showbutton + '/' + result.firstname + '/' + result.lastname;
      return false;
    }
    else {
      // alert('Your form has been submitted.');

      //alert(result.id);
      window.location.href = '/';
    }
  },
  error: function (result) {
    alert('Oh no ');
    window.location.href = result.Url;
  }

});
</code>```

答:
you have to user like this

```<code> var ServiceAndVisitroData = {
                        //orderid
                        selectedService: selecteddata,
                        userId: $('#userid').val().trim(),
                        OrderId: $('#orderid').val().trim(),
                        DealInfo: $('#deals').val().trim(),
                        IPAddress: userip,
                        deviceName: userDevicedata[0],
                        OSName: jscd.os + "," + jscd.osVersion,
                        browserName: jscd.browser + "," + jscd.browserMajorVersion + "," + jscd.browserVersion,
                        IsCustomllogo: false,
                        userToken: cookiesplit[1],
                        firstname: cookiesplit[2],
                        lastname: last[0]

                    };

        jQuery.ajax({
          url: "<?php echo admin_url( 'admin-ajax.php' );?>",
          data: {action: 'ajax_call_back_func', data:ServiceAndVisitroData},
          type: "POST",
          success: function(result, textStatus, XMLHttpRequest){

                            if (result.success == "pymt") {

                                window.location.href = 'http://test.com/api/agency/payment/' + result.Id + '/' + result.Showbutton + '/' + result.firstname + '/' + result.firstname + '/' + result.lastname
                                return false;

                            }
                            else if (result.success == "ord") {
                                window.location.href = 'http://test.com/api/agency/order/' + result.Id + '/' + result.Showbutton + '/' + result.firstname + '/' + result.lastname;
                                return false;
                            }
                            else {
                                // alert('Your form has been submitted.');

                                //alert(result.id);
                                window.location.href = '/';
                            }
                        },
                        error: function (result) {
                            alert('Oh no ');
                            window.location.href = result.Url;
                        }

                    });
</code>```

in functions.php

```<code>function ajax_call_back_func(){
  print_r($_POST);exit;
}

add_action('wp_ajax_ajax_call_back_func',  'ajax_call_back_func');
add_action('wp_ajax_nopriv_ajax_call_back_func', 'ajax_call_back_func');
</code>```

Title: Ajax Post not Working in Wordpress

Body:
I have a simple ajax post method to send data to Web api but this code does not post data even there is no error in console.
Please help me to solve this I have also changed $ with jQuery as describe Here.I am using Wordpress 4.9.
Here is the source code written in wordpress.

Code

var ServiceAndVisitroData = {
  //orderid
  selectedService: selecteddata,
  userId: $('#userid').val().trim(),
  OrderId: $('#orderid').val().trim(),
  DealInfo: $('#deals').val().trim(),
  IPAddress: userip,
  deviceName: userDevicedata[0],
  OSName: jscd.os + "," + jscd.osVersion,
  browserName: jscd.browser + "," + jscd.browserMajorVersion + "," + jscd.browserVersion,
  IsCustomllogo: false,
  userToken: cookiesplit[1],
  firstname: cookiesplit[2],
  lastname: last[0]

};

$.ajax({
  type: "POST",
  url: 'http://test.com/api/agency/postcheckout',
  // contentType: "application/json; charset=utf-8",
  //data: JSON.stringify(ServiceAndVisitroData),
  data: ServiceAndVisitroData,
  dataType: "json",
  success: function (result) {
    //  alert(result.firstname);
    //  alert(result.lastname);
    //  alert(result.tokenn);
    // alert(result.useridd);

    if (result.success == "pymt") {

      window.location.href = 'http://test.com/api/agency/payment/' + result.Id + '/' + result.Showbutton + '/' + result.firstname + '/' + result.firstname + '/' + result.lastname
      return false;

    }
    else if (result.success == "ord") {

      window.location.href = 'http://test.com/api/agency/order/' + result.Id + '/' + result.Showbutton + '/' + result.firstname + '/' + result.lastname;
      return false;
    }
    else {
      // alert('Your form has been submitted.');

      //alert(result.id);
      window.location.href = '/';
    }
  },
  error: function (result) {
    alert('Oh no ');
    window.location.href = result.Url;
  }

});

Body:
you have to user like this

 var ServiceAndVisitroData = {
                        //orderid
                        selectedService: selecteddata,
                        userId: $('#userid').val().trim(),
                        OrderId: $('#orderid').val().trim(),
                        DealInfo: $('#deals').val().trim(),
                        IPAddress: userip,
                        deviceName: userDevicedata[0],
                        OSName: jscd.os + "," + jscd.osVersion,
                        browserName: jscd.browser + "," + jscd.browserMajorVersion + "," + jscd.browserVersion,
                        IsCustomllogo: false,
                        userToken: cookiesplit[1],
                        firstname: cookiesplit[2],
                        lastname: last[0]

                    };

        jQuery.ajax({
          url: "<?php echo admin_url( 'admin-ajax.php' );?>",
          data: {action: 'ajax_call_back_func', data:ServiceAndVisitroData},
          type: "POST",
          success: function(result, textStatus, XMLHttpRequest){

                            if (result.success == "pymt") {

                                window.location.href = 'http://test.com/api/agency/payment/' + result.Id + '/' + result.Showbutton + '/' + result.firstname + '/' + result.firstname + '/' + result.lastname
                                return false;

                            }
                            else if (result.success == "ord") {
                                window.location.href = 'http://test.com/api/agency/order/' + result.Id + '/' + result.Showbutton + '/' + result.firstname + '/' + result.lastname;
                                return false;
                            }
                            else {
                                // alert('Your form has been submitted.');

                                //alert(result.id);
                                window.location.href = '/';
                            }
                        },
                        error: function (result) {
                            alert('Oh no ');
                            window.location.href = result.Url;
                        }

                    });

in functions.php

function ajax_call_back_func(){
  print_r($_POST);exit;
}

add_action('wp_ajax_ajax_call_back_func',  'ajax_call_back_func');
add_action('wp_ajax_nopriv_ajax_call_back_func', 'ajax_call_back_func');