问:
segment:offset in a constant

I'm trying to learn assembly. I've written this short real mode function that works as I want to.

```<code>getndrives:
        push    bx
        push    es
        push    si
            mov     bx,0040h
            mov     es,bx
            mov     si,0075h
            mov     al,byte [es:si]
        pop     si
        pop     es
        pop     bx
    ret
</code>```

I would like to have the segment:offset in a constant instead and eliminate the need to push/pop es+si. Something like

```<code>biosmem EQU 0040h:0075h
mov al,[biosmem]
</code>```

above code compiles but does not return the intended result.

答:
x86 doesn't have a way to load from an immediate-constant far-pointer in one instruction.  There's a far jmp ptr16:16 that can set cs:ip to a 32-bit immediate, but for loads I don't see any option that doesn't use a segment register.

NASM docs suggest that it is/was typical in 16-bit calling conventions for DS to be call-preserved, but that ES could be considered call-clobbered for exactly the reason you want (in memory models that don't keep everything in a single segment).

So you could consider using a calling convention for this function that allows it to clobber ES.  (Or FS or GS if your code only needs to run on 386 or later.)

You can also save instructions by reusing the same register for the segment.  You could have used si both times instead of bx, because you're done with bx as soon as you set es.

```<code>getndrives:
 ;; return in AL (zero-extended to AX; the upper byte of 0040h happens to be 0)
 ;; clobbers: AH, ES
    mov     ax, 0x0040
    mov     es, ax
    mov     al, [es:0x0475]
    ret
</code>```

As a bonus, you're loading into AL so it can use the special moffs encoding of mov that skips the ModR/M byte so it's just (ES segment override prefix) + A0 75 04.

You can of course still push/pop es and/or ax around this if you want, but this is obviously clunkier.  And if you're going to save/restore a segment register, @Fifoernik points out it might as well be DS to save a prefix on the mov (unless you have any interrupt handlers that assume DS stays constant).

```<code>getndrives:
 ;; return in AL (zero-extended to AX; the upper byte of 0040h happens to be 0)
 ;; clobbers: AH,  or nothing if you uncomment the push/pop of AX
    push    es
    ;push    ax                 ; you might as well use a reg other than AX to simplify this, if you do want to preserve AH, too.  And also for performance on CPUs that don't rename low8 partial regs separately, so mov al,[mem] has a dependency on the pop.
      mov     ax, 0x0040
      mov     es, ax            ; or use DS if you don't need it in any interrupt handler
    ;pop     ax
      mov     al, [es:0x0475]
    pop     es
    ret
</code>```

If you only care about 186 and newer, push 0040h / pop es would avoid clobbering AH.  (8086 doesn't have push imm8/imm16).

In your case, you can probably avoid modifying a segment register in the first place.  Notice that 0040h:0075h is a linear address of 0475h, which you can access with just an offset from any DS value from 0 to 47h.  (In real mode, linear = (segment << 4) + offset, i.e. left-shift by one hex digit).

With DS=0, you can still access your boot-sector code/data (according to this PC memory map, loaded at 07C0:0, aka 0:7C00), and anywhere else in the low 64kiB of memory.

I don't actually write 16-bit code, so I'm not sure exactly how you'd tell NASM that you're going to set DS=0 and then have it generate offsets accordingly.  But hopefully that's possible.

As a bonus, it saves code size: xor ax,ax is smaller than mov ax, imm16.  But I guess if you were optimizing for code size, you'd push 0 / pop ds.  (But 8086 doesn't have push imm, that came later).  And I guess if you want stack pointers to be compatible with other pointers, you'd need to mov ss, ax / mov sp, whatever so that's more code.

But anyway, then your function would look like this.

```<code>getndrives:
 ;; return in AL
 ;; requires/assumes: DS=0
    mov     al, [0x0475]
    ret
</code>```

At this point it's silly to make it a function.  Make it a macro, or better, or %define BIOS_BDA_ndrives 0x0475 so you can do stuff like add dl, [BIOS_BDA_ndrives].  Or possibly %define BIOS_BDA_ndrives byte [0x0475] to get build-time type checking, e.g. mov ax, BIOS_BDA_ndrives would then fail to assemble with an operand-size mismatch.

Title: segment:offset in a constant

Body:
I'm trying to learn assembly. I've written this short real mode function that works as I want to.

getndrives:
        push    bx
        push    es
        push    si
            mov     bx,0040h
            mov     es,bx
            mov     si,0075h
            mov     al,byte [es:si]
        pop     si
        pop     es
        pop     bx
    ret

I would like to have the segment:offset in a constant instead and eliminate the need to push/pop es+si. Something like

biosmem EQU 0040h:0075h
mov al,[biosmem]

above code compiles but does not return the intended result.

Body:
x86 doesn't have a way to load from an immediate-constant far-pointer in one instruction.  There's a far jmp ptr16:16 that can set cs:ip to a 32-bit immediate, but for loads I don't see any option that doesn't use a segment register.

NASM docs suggest that it is/was typical in 16-bit calling conventions for DS to be call-preserved, but that ES could be considered call-clobbered for exactly the reason you want (in memory models that don't keep everything in a single segment).

So you could consider using a calling convention for this function that allows it to clobber ES.  (Or FS or GS if your code only needs to run on 386 or later.)

You can also save instructions by reusing the same register for the segment.  You could have used si both times instead of bx, because you're done with bx as soon as you set es.

getndrives:
 ;; return in AL (zero-extended to AX; the upper byte of 0040h happens to be 0)
 ;; clobbers: AH, ES
    mov     ax, 0x0040
    mov     es, ax
    mov     al, [es:0x0475]
    ret

As a bonus, you're loading into AL so it can use the special moffs encoding of mov that skips the ModR/M byte so it's just (ES segment override prefix) + A0 75 04.

You can of course still push/pop es and/or ax around this if you want, but this is obviously clunkier.  And if you're going to save/restore a segment register, @Fifoernik points out it might as well be DS to save a prefix on the mov (unless you have any interrupt handlers that assume DS stays constant).

getndrives:
 ;; return in AL (zero-extended to AX; the upper byte of 0040h happens to be 0)
 ;; clobbers: AH,  or nothing if you uncomment the push/pop of AX
    push    es
    ;push    ax                 ; you might as well use a reg other than AX to simplify this, if you do want to preserve AH, too.  And also for performance on CPUs that don't rename low8 partial regs separately, so mov al,[mem] has a dependency on the pop.
      mov     ax, 0x0040
      mov     es, ax            ; or use DS if you don't need it in any interrupt handler
    ;pop     ax
      mov     al, [es:0x0475]
    pop     es
    ret

If you only care about 186 and newer, push 0040h / pop es would avoid clobbering AH.  (8086 doesn't have push imm8/imm16).

In your case, you can probably avoid modifying a segment register in the first place.  Notice that 0040h:0075h is a linear address of 0475h, which you can access with just an offset from any DS value from 0 to 47h.  (In real mode, linear = (segment << 4) + offset, i.e. left-shift by one hex digit).

With DS=0, you can still access your boot-sector code/data (according to this PC memory map, loaded at 07C0:0, aka 0:7C00), and anywhere else in the low 64kiB of memory.

I don't actually write 16-bit code, so I'm not sure exactly how you'd tell NASM that you're going to set DS=0 and then have it generate offsets accordingly.  But hopefully that's possible.

As a bonus, it saves code size: xor ax,ax is smaller than mov ax, imm16.  But I guess if you were optimizing for code size, you'd push 0 / pop ds.  (But 8086 doesn't have push imm, that came later).  And I guess if you want stack pointers to be compatible with other pointers, you'd need to mov ss, ax / mov sp, whatever so that's more code.

But anyway, then your function would look like this.

getndrives:
 ;; return in AL
 ;; requires/assumes: DS=0
    mov     al, [0x0475]
    ret

At this point it's silly to make it a function.  Make it a macro, or better, or %define BIOS_BDA_ndrives 0x0475 so you can do stuff like add dl, [BIOS_BDA_ndrives].  Or possibly %define BIOS_BDA_ndrives byte [0x0475] to get build-time type checking, e.g. mov ax, BIOS_BDA_ndrives would then fail to assemble with an operand-size mismatch.


来源: stackexchange

问:
Failed dependencies when install pxf service
When I rpm pxf service in hawq, I got some errors:

```<code>error: Failed dependencies:
        hadoop >= 2.6.0 is needed by pxf-service-0:3.0.0-root.noarch
        hadoop-hdfs >= 2.6.0 is needed by pxf-service-0:3.0.0-root.noarch
</code>```

What's your advice here ?

答:
The wiki here use the rpm bigtop(hadoop).
https://cwiki.apache.org/confluence/display/HAWQ/Build+Package+and+Install+with+RPM

It means if I install with rpm(HAWQ 2.2.0), the other ways (using binary hadoop without rpm installs like tar) are not support.

If I install hadoop use tar, I must build HAWQ from source code for now.

Please refer to:
https://issues.apache.org/jira/browse/HAWQ-1568

ContentLicense: CC BY-SA 3.0

Body:
When I rpm pxf service in hawq, I got some errors:

error: Failed dependencies:
        hadoop >= 2.6.0 is needed by pxf-service-0:3.0.0-root.noarch
        hadoop-hdfs >= 2.6.0 is needed by pxf-service-0:3.0.0-root.noarch

What's your advice here ?


问:
Can't get parameters from URL in angular io (5)
The params is empty object.

I try to navigate directly to localhost:3000/bla?id=5,

```<code>this.activatedRoute.params.subscribe(params => {
  console.log(params);
});
</code>```

答:
In angular, router is supported by ; stead for ? , So change your url like following:

url

```<code> localhost:3000/bla;id=5;
</code>```

Body:
The params is empty object.

I try to navigate directly to localhost:3000/bla?id=5,

this.activatedRoute.params.subscribe(params => {
  console.log(params);
});

Body:
In angular, router is supported by ; stead for ? , So change your url like following:

url

 localhost:3000/bla;id=5;


问:
SQL Server Unable to convert a string to a date in a where clause (Code 241)
I have a query which cut a substring out of a char field and returns it a a date.
And it works:

```<code>select
    ujp_jobid, ujp_lfdnr,
    isnull(convert(date, substring(ujp_parawert, charindex(' ', ujp_parawert) + 1,10), 104), convert(date, getDate())) para_date,
    datediff(day, isnull(convert(date, substring(ujp_parawert, charindex(' ', ujp_parawert) + 1,10), 104), convert(date,getDate())), convert(date,getDate())) datedif
from
    uno_jobpara
where
    ujp_jobid between 0 and 30000
    and ujp_paraname = 'P_PGENDE'
</code>```

The result is:

```<code>1   6   2017-11-28  8
2   372 2017-05-06  214
3   84  2017-05-01  219
</code>```

...

I first tried the to use the datedif part as where clause:

```<code>...
and ujp_paraname = 'P_PGENDE'
    and datediff(day, isnull(convert(date, substring(ujp_parawert, charindex(' ', ujp_parawert) + 1,10), 104), convert(date,getDate()) ), convert(date,getDate())) > 0
</code>```

Suddenly the server raised an Error:

[Code: 241, SQL State: S0001]  Fehler beim Konvertieren einer Zeichenfolge in ein Datum und/oder eine Uhrzeit.

  (rough translation: Error converting a string to a date and/or a time)

Not quite sure why this is, but I guessed, that there the server tries to check the where conditional first and thinks that it might run into an an error.

However I tried to put in all in another select:

```<code>select
    ujp_jobid, ujp_lfdnr, para_date, datedif
from
    (select
         ujp_jobid, ujp_lfdnr,
         isnull(convert(date, substring(ujp_parawert, charindex(' ', ujp_parawert) + 1,10), 104), convert(date,getDate()) ) para_date,
         datediff(day, isnull(convert(date, substring(ujp_parawert, charindex(' ', ujp_parawert) + 1,10), 104), convert(date, getDate()) ), convert(date, getDate())) datedif
     from
         uno_jobpara
     where
         ujp_jobid between 0 and 30000
         and ujp_paraname = 'P_PGENDE') as tt
where
    tt.datedif > 0;
</code>```

The same error?! Why, and how can I tell SQL Server to run a subquery first? Do I really need a temp table?

TIA

Jo

答:
This doesn't look like something to be solved with a temp table.
Firstly I'd avoid using convert(date,getdate()) because it converts the getdate() into a string and back again, hoping that the formats fit. I'd use cast(getdate() as date).
Secondly the issue should happen in your inner query, too, if you really scroll down to the end.
You could test whether the substring is valid with a like '[0-9][0-9][0-9][0-9]-[0-1][0-9]-[0-3][0-9]'
Regards, Manfred</p>

Body:
I have a query which cut a substring out of a char field and returns it a a date.
And it works:

select
    ujp_jobid, ujp_lfdnr,
    isnull(convert(date, substring(ujp_parawert, charindex(' ', ujp_parawert) + 1,10), 104), convert(date, getDate())) para_date,
    datediff(day, isnull(convert(date, substring(ujp_parawert, charindex(' ', ujp_parawert) + 1,10), 104), convert(date,getDate())), convert(date,getDate())) datedif
from
    uno_jobpara
where
    ujp_jobid between 0 and 30000
    and ujp_paraname = 'P_PGENDE'

The result is:

1   6   2017-11-28  8
2   372 2017-05-06  214
3   84  2017-05-01  219

...

I first tried the to use the datedif part as where clause:

...
and ujp_paraname = 'P_PGENDE'
    and datediff(day, isnull(convert(date, substring(ujp_parawert, charindex(' ', ujp_parawert) + 1,10), 104), convert(date,getDate()) ), convert(date,getDate())) > 0

Suddenly the server raised an Error:

[Code: 241, SQL State: S0001]  Fehler beim Konvertieren einer Zeichenfolge in ein Datum und/oder eine Uhrzeit.

  (rough translation: Error converting a string to a date and/or a time)

Not quite sure why this is, but I guessed, that there the server tries to check the where conditional first and thinks that it might run into an an error.

However I tried to put in all in another select:

select
    ujp_jobid, ujp_lfdnr, para_date, datedif
from
    (select
         ujp_jobid, ujp_lfdnr,
         isnull(convert(date, substring(ujp_parawert, charindex(' ', ujp_parawert) + 1,10), 104), convert(date,getDate()) ) para_date,
         datediff(day, isnull(convert(date, substring(ujp_parawert, charindex(' ', ujp_parawert) + 1,10), 104), convert(date, getDate()) ), convert(date, getDate())) datedif
     from
         uno_jobpara
     where
         ujp_jobid between 0 and 30000
         and ujp_paraname = 'P_PGENDE') as tt
where
    tt.datedif > 0;

The same error?! Why, and how can I tell SQL Server to run a subquery first? Do I really need a temp table?

TIA

Jo


问:
Cannot receive Strings from Android Firebase Database
I want to get the name (String) and the location (String) from my firebase database into a listview of a fragment page of my app. It doesnt give any errors but the name and location text just dont appear on the app. thanks for help. I think there is a problem to get the strings from the firebase server.

```<code>Firebase hierarchy : FIREBASE -> Events -> XmasParty -> location = Germany
                                                     -> name = XmasParty
</code>```

FRAGMENT :

```<code>public class RequestsFragment extends Fragment {

    private Button create_event_btn;
    private View mMainView2;
    private RecyclerView mEventList;
    private DatabaseReference mEventsDatabase;
    private LinearLayoutManager mLayoutManager;

    public void ChatsFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        mMainView2 = inflater.inflate(R.layout.fragment_requests, container, false);
        mEventsDatabase = FirebaseDatabase.getInstance().getReference().child("Events");

        mLayoutManager = new LinearLayoutManager(getContext());
        create_event_btn = (Button) mMainView2.findViewById(R.id.create_btn);
        mEventList = (RecyclerView) mMainView2.findViewById(R.id.event_list);
        mEventList.setHasFixedSize(true);
        mEventList.setLayoutManager(mLayoutManager);

        create_event_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), Create_EventActivity.class);
                startActivity(intent);
            }
        });

        // Inflate the layout for this fragment
        return mMainView2;
    }

    @Override
    public void onStart() {
        super.onStart();

        FirebaseRecyclerAdapter<Events, RequestsFragment.EventsViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Events, EventsViewHolder>(

                Events.class,
                R.layout.users_single_layout,
                RequestsFragment.EventsViewHolder.class,
                mEventsDatabase

        ) {
            @Override
            protected void populateViewHolder(RequestsFragment.EventsViewHolder eventsViewHolder, Events events, int position) {

                eventsViewHolder.setDisplayName(events.getName());
                eventsViewHolder.setUserStatus(events.getLocation());
               // usersViewHolder.setUserImage(users.getThumb_image(), getApplicationContext());

                final String event_id = getRef(position).getKey();

                eventsViewHolder.mView2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        //Intent profileIntent = new Intent(UsersActivity.this, ProfileActivity.class);
                       // profileIntent.putExtra("user_id", user_id);
                       // startActivity(profileIntent);

                    }
                });

            }
        };

        mEventList.setAdapter(firebaseRecyclerAdapter);

    }

    public static class EventsViewHolder extends RecyclerView.ViewHolder {

        View mView2;

        public EventsViewHolder(View itemView2) {
            super(itemView2);

            mView2 = itemView2;

        }

        public void setDisplayName(String name){

            TextView userNameView = (TextView) mView2.findViewById(R.id.user_single_name);
            userNameView.setText(name);

        }

        public void setUserStatus(String status){

            TextView userStatusView = (TextView) mView2.findViewById(R.id.user_single_status);
            userStatusView.setText(status);

        }

        }
    }
}
</code>```

EVENTS CLASS

```<code>public class Events {

    public String name;
    public String location;
    public String time;

    public Events(){

    }

    public Events(String name, String location, String time) {
        this.name = name;
        this.location = location;
        this.time = time;
    }

    public String getName() {return name;}
    public void setName(String name) {
        this.name = name;
    }

    public String getLocation() {
        return location;
    }
    public void setLocation(String location) {
        this.location = location;
    }

    public String getTime() {return time;}
    public void setTime(String time) {this.time = time;}

}
</code>```

答:
To get the value of location and name, please use the following code:

```<code>DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference yourRef = rootRef.child("Events").child("XmasParty");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        String location = dataSnapshot.child("location").getValue(String.class);
        String name = dataSnapshot.child("name").getValue(String.class);
        Log.d("TAG", location + " / " + name);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
yourRef.addListenerForSingleValueEvent(eventListener);
</code>```

The output will be:

```<code>Germany / XmasParty
</code>```

Body:
I want to get the name (String) and the location (String) from my firebase database into a listview of a fragment page of my app. It doesnt give any errors but the name and location text just dont appear on the app. thanks for help. I think there is a problem to get the strings from the firebase server.

Firebase hierarchy : FIREBASE -> Events -> XmasParty -> location = Germany
                                                     -> name = XmasParty

FRAGMENT :

public class RequestsFragment extends Fragment {

    private Button create_event_btn;
    private View mMainView2;
    private RecyclerView mEventList;
    private DatabaseReference mEventsDatabase;
    private LinearLayoutManager mLayoutManager;

    public void ChatsFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        mMainView2 = inflater.inflate(R.layout.fragment_requests, container, false);
        mEventsDatabase = FirebaseDatabase.getInstance().getReference().child("Events");

        mLayoutManager = new LinearLayoutManager(getContext());
        create_event_btn = (Button) mMainView2.findViewById(R.id.create_btn);
        mEventList = (RecyclerView) mMainView2.findViewById(R.id.event_list);
        mEventList.setHasFixedSize(true);
        mEventList.setLayoutManager(mLayoutManager);

        create_event_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), Create_EventActivity.class);
                startActivity(intent);
            }
        });

        // Inflate the layout for this fragment
        return mMainView2;
    }

    @Override
    public void onStart() {
        super.onStart();

        FirebaseRecyclerAdapter<Events, RequestsFragment.EventsViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Events, EventsViewHolder>(

                Events.class,
                R.layout.users_single_layout,
                RequestsFragment.EventsViewHolder.class,
                mEventsDatabase

        ) {
            @Override
            protected void populateViewHolder(RequestsFragment.EventsViewHolder eventsViewHolder, Events events, int position) {

                eventsViewHolder.setDisplayName(events.getName());
                eventsViewHolder.setUserStatus(events.getLocation());
               // usersViewHolder.setUserImage(users.getThumb_image(), getApplicationContext());

                final String event_id = getRef(position).getKey();

                eventsViewHolder.mView2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        //Intent profileIntent = new Intent(UsersActivity.this, ProfileActivity.class);
                       // profileIntent.putExtra("user_id", user_id);
                       // startActivity(profileIntent);

                    }
                });

            }
        };

        mEventList.setAdapter(firebaseRecyclerAdapter);

    }

    public static class EventsViewHolder extends RecyclerView.ViewHolder {

        View mView2;

        public EventsViewHolder(View itemView2) {
            super(itemView2);

            mView2 = itemView2;

        }

        public void setDisplayName(String name){

            TextView userNameView = (TextView) mView2.findViewById(R.id.user_single_name);
            userNameView.setText(name);

        }

        public void setUserStatus(String status){

            TextView userStatusView = (TextView) mView2.findViewById(R.id.user_single_status);
            userStatusView.setText(status);

        }

        }
    }
}

EVENTS CLASS

public class Events {

    public String name;
    public String location;
    public String time;

    public Events(){

    }

    public Events(String name, String location, String time) {
        this.name = name;
        this.location = location;
        this.time = time;
    }

    public String getName() {return name;}
    public void setName(String name) {
        this.name = name;
    }

    public String getLocation() {
        return location;
    }
    public void setLocation(String location) {
        this.location = location;
    }

    public String getTime() {return time;}
    public void setTime(String time) {this.time = time;}

}

Body:
To get the value of location and name, please use the following code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference yourRef = rootRef.child("Events").child("XmasParty");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        String location = dataSnapshot.child("location").getValue(String.class);
        String name = dataSnapshot.child("name").getValue(String.class);
        Log.d("TAG", location + " / " + name);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
yourRef.addListenerForSingleValueEvent(eventListener);

The output will be:

Germany / XmasParty


问:
Create Clone applications in android
I have created a project in android.
But now i need to create the same project for multiple vendors, Only color scheme and Web Services will change.

I am trying to do make copy of the apps and change the package name of the application. But in any case if there is change in 1 app then i need to work on other apps too. So please let me know is there any way so that i can create a single source code and May able to change the UI in the existing app so every app have the same update .

Need to change :

Color scheme.

Logo.

Name of the app.

Web Apis.

Google Map Key and the push notification certificates.

But source code will be same for all

Regards
Amit

答:
Here you can find a nice tutorial about flavours. I think that's exactly what you need.

The steps for building flavours in Android are:

Use the productFlavors closure of you app/build.gradle file to define different variants of your product.

```<code>productFlavors {
    prod {
        applicationId = "com.vogella.android.gradlebuildflavors.prod"
        versionName = "1.0-paid"
    }

    mock {
        applicationId = "com.vogella.android.gradlebuildflavors.mock"
        versionName = "1.0-free"
    }
}
</code>```

After defining these flavors you can select them in the Build Variants view in Android Studio.

Providing different resources for the flavors

In order to define a different behavior for a certain flavor, you need to create suitable folders for the defined flavors under app/src/.

Flavor specific resources override the main resources. For example, if you provide a different application icon in a flavor the Android build system picks up the flavor specific one.

Providing different source sets for the product flavors

The directories in the src/ folder are called source sets. Every product flavor can define its own source set.

Code files are not replaced as resources, they are combined. For example, you cannot have a com.example.MainActivity activity in your app/main/java/ folder and a different implementation in another flavor. If you try this, you receive an error message about duplicate class definitions.

You can still provide different implementations by avoiding the creation of the class in your main source folder and instead create a class in each flavor.

Example of different src's:

Title: Create Clone applications in android

Body:
Here you can find a nice tutorial about flavours. I think that's exactly what you need.

The steps for building flavours in Android are:

Use the productFlavors closure of you app/build.gradle file to define different variants of your product.

productFlavors {
    prod {
        applicationId = "com.vogella.android.gradlebuildflavors.prod"
        versionName = "1.0-paid"
    }

    mock {
        applicationId = "com.vogella.android.gradlebuildflavors.mock"
        versionName = "1.0-free"
    }
}

After defining these flavors you can select them in the Build Variants view in Android Studio.

Providing different resources for the flavors

In order to define a different behavior for a certain flavor, you need to create suitable folders for the defined flavors under app/src/.

Flavor specific resources override the main resources. For example, if you provide a different application icon in a flavor the Android build system picks up the flavor specific one.

Providing different source sets for the product flavors

The directories in the src/ folder are called source sets. Every product flavor can define its own source set.

Code files are not replaced as resources, they are combined. For example, you cannot have a com.example.MainActivity activity in your app/main/java/ folder and a different implementation in another flavor. If you try this, you receive an error message about duplicate class definitions.

You can still provide different implementations by avoiding the creation of the class in your main source folder and instead create a class in each flavor.

Example of different src's:


问:
Why does my Android app keep telling me I need to define a ListView id when it is already defined?
Whenever I try to run my app, the following exception is thrown:

01-22 00:40:51.868: ERROR/AndroidRuntime(2219): java.lang.RuntimeException: Unable to start activity ComponentInfo{[Redacted]}: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'

Here is the markup for the ListView in question:

```<code><ListView
 android:id="@+id/list"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:dividerHeight="1px"></ListView>
</code>```

So, since the id is clearly defined as "list," what gives here? I've run through my code multiple times in the past couple of hours trying to track down the cause of this and I'm stumped. Can anyone offer any pointers?

答:
I guess you have accidentl imported android.R package.

remove the import and you should do fine.

ContentLicense: CC BY-SA 2.5

Body:
Whenever I try to run my app, the following exception is thrown:

01-22 00:40:51.868: ERROR/AndroidRuntime(2219): java.lang.RuntimeException: Unable to start activity ComponentInfo{[Redacted]}: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'

Here is the markup for the ListView in question:

<ListView
 android:id="@+id/list"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:dividerHeight="1px"></ListView>

So, since the id is clearly defined as "list," what gives here? I've run through my code multiple times in the past couple of hours trying to track down the cause of this and I'm stumped. Can anyone offer any pointers?


问:
"INSERT...ON DUPLICATE KEY UPDATE id=id" still inserts on duplicate
I have a table name "slot_place_box". It looks like this :

id_slot_pb (PRIMARY KEY)

id_place_box (INT)

date (DATE)

hour (HOUR)

slot_available (INT)

I have an UNIQUE index for (id_place_box + date + hour).

In PHP I'm building an SQL request, it looks like this :

```<code>$sql_request = "
INSERT INTO media.slot_place_box (id_place_box, date, hour)VALUES (32, '2017-12-10', NULL)ON DUPLICATE KEY UPDATE id_place_box = id_place_box;
SET @id = (SELECT SPB.id_slot_pb FROM media.slot_place_box as SPB WHERE
SPB.id_place_box = 32 AND SPB.date = '2017-12-10' AND SPB.hour IS NULL);
INSERT INTO media.slot_config (id_config, id_slot_pb) VALUES (125, @id);

INSERT INTO media.slot_place_box (id_place_box, date, hour)VALUES (32, '2017-12-11', NULL)ON DUPLICATE KEY UPDATE id_place_box = id_place_box;
SET @id = (SELECT SPB.id_slot_pb FROM media.slot_place_box as SPB WHERE SPB.id_place_box = 32 AND SPB.date = '2017-12-11' AND SPB.hour IS NULL);
INSERT INTO media.slot_config (id_config, id_slot_pb) VALUES (125, @id);

INSERT INTO media.slot_place_box (id_place_box, date, hour)VALUES (32, '2017-12-12', NULL)ON DUPLICATE KEY UPDATE id_place_box = id_place_box;
SET @id = (SELECT SPB.id_slot_pb FROM media.slot_place_box as SPB WHERE SPB.id_place_box = 32 AND SPB.date = '2017-12-12' AND SPB.hour IS NULL);
INSERT INTO media.slot_config (id_config, id_slot_pb) VALUES (125, @id);

//etc

";
</code>```

My problem is that my "INSERT...ON DUPLICATE KEY UPDATE" still insert a new line when I have a duplicate key (= another "slot_place_box" in the database with same "id_place_box + date + hour", so my @id get more than one result and the script bug. It just adds a row in my table for my first "INSERT" and does nothing after (when I have duplicate row).

Right now this is the clues I have :

I added a "UNIQUE" index for the combination of "id_config + date + hour", is it enough for the "ON DUPLICATE KEY" or I absolutely need the PRIMARY KEY?

Maybe I have trouble with my field name "date" and "hour"?

The fact that I have a "NULL" value for "hour" maybe create some trouble with my UNIQUE indexes...

Do you have an idea why please?

答:
As @Solarflare said in comments, my problem is because of the "NULL" value of my field "hour" (see here).

I can't use the workaround solution he shows me (here) because I use MySQL 5.6 and not 5.7.

I will have to change my request a little OR change my table logic OR put a value in "HOUR" (negative for example) but I will have to change part of my code where I used this "NULL".

Body:
I have a table name "slot_place_box". It looks like this :

id_slot_pb (PRIMARY KEY)

id_place_box (INT)

date (DATE)

hour (HOUR)

slot_available (INT)

I have an UNIQUE index for (id_place_box + date + hour).

In PHP I'm building an SQL request, it looks like this :

$sql_request = "
INSERT INTO media.slot_place_box (id_place_box, date, hour)VALUES (32, '2017-12-10', NULL)ON DUPLICATE KEY UPDATE id_place_box = id_place_box;
SET @id = (SELECT SPB.id_slot_pb FROM media.slot_place_box as SPB WHERE
SPB.id_place_box = 32 AND SPB.date = '2017-12-10' AND SPB.hour IS NULL);
INSERT INTO media.slot_config (id_config, id_slot_pb) VALUES (125, @id);

INSERT INTO media.slot_place_box (id_place_box, date, hour)VALUES (32, '2017-12-11', NULL)ON DUPLICATE KEY UPDATE id_place_box = id_place_box;
SET @id = (SELECT SPB.id_slot_pb FROM media.slot_place_box as SPB WHERE SPB.id_place_box = 32 AND SPB.date = '2017-12-11' AND SPB.hour IS NULL);
INSERT INTO media.slot_config (id_config, id_slot_pb) VALUES (125, @id);

INSERT INTO media.slot_place_box (id_place_box, date, hour)VALUES (32, '2017-12-12', NULL)ON DUPLICATE KEY UPDATE id_place_box = id_place_box;
SET @id = (SELECT SPB.id_slot_pb FROM media.slot_place_box as SPB WHERE SPB.id_place_box = 32 AND SPB.date = '2017-12-12' AND SPB.hour IS NULL);
INSERT INTO media.slot_config (id_config, id_slot_pb) VALUES (125, @id);

//etc

";

My problem is that my "INSERT...ON DUPLICATE KEY UPDATE" still insert a new line when I have a duplicate key (= another "slot_place_box" in the database with same "id_place_box + date + hour", so my @id get more than one result and the script bug. It just adds a row in my table for my first "INSERT" and does nothing after (when I have duplicate row).

Right now this is the clues I have :

I added a "UNIQUE" index for the combination of "id_config + date + hour", is it enough for the "ON DUPLICATE KEY" or I absolutely need the PRIMARY KEY?

Maybe I have trouble with my field name "date" and "hour"?

The fact that I have a "NULL" value for "hour" maybe create some trouble with my UNIQUE indexes...

Do you have an idea why please?


问:
Pandas Multi-index slice only on secondary index
I have the following pandas (related to the example here: pandas: slice a MultiIndex by range of secondary index)

```<code>import numpy as np
import pandas as pd

variable = np.repeat(['a','b','c'], [5,5,5])
time = [0,1,5,10,20,0,1,5,10,20,0,1,5,10,20]

arra = [variable, time]

index=pd.MultiIndex.from_arrays(arra, names=("variable", "time"))

s = pd.Series(
    np.random.randn(len(sequence)),
    index=index
)
</code>```

Output would be

```<code># In [1]: s
variable  time
a         0      -1.284692
          1      -0.313895
          5      -0.980222
          10     -1.452306
          20     -0.423921
b         0       0.248625
          1       0.183721
          5      -0.733377
          10      1.562653
          20     -1.092559
c         0       0.061172
          1       0.133960
          5       0.765271
          10     -0.648834
          20      0.147158
dtype: float64
</code>```

If I slice here on both multiindex, it would work like this:

```<code># In [2]: s.loc[("a",0),:]
variable  time
a         0       1.583589
          1      -1.081401
          5      -0.497904
          10      0.352880
          20     -0.179062
dtype: float64
</code>```

But how can I just slice on secondary index "time" at e.g. time=0 and get every row with first index? The following won't work:

```<code># In [3]: s.loc[(0),:]

KeyError: 0
</code>```

How would I do that here?

答:
The answer suggested by jezrael is neat and works.
As an alternative approach you could use swaplevel() like this:

print(s.swaplevel().loc[0, :])

variable
a    1.534837
b    1.311133
c    0.215539
dtype: float64
```

Body:
I have the following pandas (related to the example here: pandas: slice a MultiIndex by range of secondary index)

import numpy as np
import pandas as pd

variable = np.repeat(['a','b','c'], [5,5,5])
time = [0,1,5,10,20,0,1,5,10,20,0,1,5,10,20]

arra = [variable, time]

index=pd.MultiIndex.from_arrays(arra, names=("variable", "time"))

s = pd.Series(
    np.random.randn(len(sequence)),
    index=index
)

Output would be

# In [1]: s
variable  time
a         0      -1.284692
          1      -0.313895
          5      -0.980222
          10     -1.452306
          20     -0.423921
b         0       0.248625
          1       0.183721
          5      -0.733377
          10      1.562653
          20     -1.092559
c         0       0.061172
          1       0.133960
          5       0.765271
          10     -0.648834
          20      0.147158
dtype: float64

If I slice here on both multiindex, it would work like this:

# In [2]: s.loc[("a",0),:]
variable  time
a         0       1.583589
          1      -1.081401
          5      -0.497904
          10      0.352880
          20     -0.179062
dtype: float64

But how can I just slice on secondary index "time" at e.g. time=0 and get every row with first index? The following won't work:

# In [3]: s.loc[(0),:]

KeyError: 0

How would I do that here?


问:
Count Variable column wise in MySQL
I have a tableA

```<code>|Column1|Column2|Column3|
|NO     |NO     |YES    |
|YES    |YES    |NO     |
|NO     |NO     |NO     |
</code>```

My requirement is to count the number of Yes or No per row and display the greatest (or equal to) of them. My sample output should be like:

```<code>|Column1|Column2|Column3|Answer
|NO     |NO     |YES    |No
|YES    |YES    |NO     |Yes
|NO     |NO     |NO     |No
</code>```

I know i can use a where clause if my requirement was to count them column wise, but how do I get this to be done row wise?

答:
Following query will work:</p>

```<code>SELECT
    c1,c2,c3,
   (
     case when
       ROUND
       (
          (
            CHAR_LENGTH(concat_ws(" ",c1,c2,c3))
            - CHAR_LENGTH( REPLACE ( concat_ws(" ",c1,c2,c3), "NO", "") )
          ) / CHAR_LENGTH("NO")
       ) > ROUND
       (
          (
            CHAR_LENGTH(concat_ws(" ",c1,c2,c3))
            - CHAR_LENGTH( REPLACE ( concat_ws(" ",c1,c2,c3), "YES", "") )
          ) / CHAR_LENGTH("YES")
       )
        then 'NO'
        else 'YES'
        end
 )
     AS Answer
FROM t;
</code>```

Title: Count Variable column wise in MySQL

Body:
I have a tableA

|Column1|Column2|Column3|
|NO     |NO     |YES    |
|YES    |YES    |NO     |
|NO     |NO     |NO     |

My requirement is to count the number of Yes or No per row and display the greatest (or equal to) of them. My sample output should be like:

|Column1|Column2|Column3|Answer
|NO     |NO     |YES    |No
|YES    |YES    |NO     |Yes
|NO     |NO     |NO     |No

I know i can use a where clause if my requirement was to count them column wise, but how do I get this to be done row wise?

Body:
Following query will work:

SELECT
    c1,c2,c3,
   (
     case when
       ROUND
       (
          (
            CHAR_LENGTH(concat_ws(" ",c1,c2,c3))
            - CHAR_LENGTH( REPLACE ( concat_ws(" ",c1,c2,c3), "NO", "") )
          ) / CHAR_LENGTH("NO")
       ) > ROUND
       (
          (
            CHAR_LENGTH(concat_ws(" ",c1,c2,c3))
            - CHAR_LENGTH( REPLACE ( concat_ws(" ",c1,c2,c3), "YES", "") )
          ) / CHAR_LENGTH("YES")
       )
        then 'NO'
        else 'YES'
        end
 )
     AS Answer
FROM t;


问:
Common JSON schema in Java server side and Angular app
I have a Java server side and Angular app. They communicate by JSON object. I want them to have common JSON schema.

How can I do it?

答:
Here is how we do it,

Create a schema JSON file,

Create an API which will be used to send you the same if called,

Configure your angular application with APP_Initialize in your module.ts and then use the same schema in your client as well.

That way you will always have same schema file for your front end and backend.


问:
VB Radiobutton.checked state returns -1 when performed arithmetic operations with it
I am a beginner in visual basic, I am developing a calculator in which i have the following piece of code.

labeltotal.text = (radiobutton1.Checked) * 1000

My expectation from the above code is that , if the radiobutton1 is checked , the value of the total should be 1000  otherwise it should be 0.

But what i am getting is , if radiobutton1 is checked, total value changes to -1000 otherwise it goes to 0.

But if i use checkbox , i get correct values. For example,
labeltotal.text = (checkbox1.Checkstate) * 1000
it givse me correct values as expected depending on the checkstate.

How can i make the radio button to behave the same way as checkbox in above code?

答:
First of all, you should switch Option Strict to On.

If a Boolean is converted to Integer, you'll get -1 for True and 0 for False.

For further information see: Convert Boolean to Integer in VB.NET

So one of the following should return the result you want:

```<code>labeltotal.Text = (CInt(radiobutton1.Checked) * 1000 * -1).ToString

labeltotal.Text = (CInt(radioButton1.Checked) ^ 2 * 1000).ToString
</code>```

There's also the function Convert.ToInt32 which will return a 1 for True:

```<code>labeltotal.Text = (Convert.ToInt32(radioButton1.Checked) * 1000).ToString
</code>```

But in this specific case, calculation does not really make sense.

The following is more clear and fits better for this case:

```<code>labeltotal.Text = If(radioButton1.Checked, "1000", "0")
</code>```

Body:
First of all, you should switch Option Strict to On.

If a Boolean is converted to Integer, you'll get -1 for True and 0 for False.

For further information see: Convert Boolean to Integer in VB.NET

So one of the following should return the result you want:

labeltotal.Text = (CInt(radiobutton1.Checked) * 1000 * -1).ToString

labeltotal.Text = (CInt(radioButton1.Checked) ^ 2 * 1000).ToString

There's also the function Convert.ToInt32 which will return a 1 for True:

labeltotal.Text = (Convert.ToInt32(radioButton1.Checked) * 1000).ToString

But in this specific case, calculation does not really make sense.

The following is more clear and fits better for this case:

labeltotal.Text = If(radioButton1.Checked, "1000", "0")


问:
.js file only loads after refreshing the page in rails
I have the following JavaScript code on a rails project

```<code>// app/assets/javascript/simple_effects.js

$(function() {
  // Hide completed tasks when checkbox is clicked. projects/show
  $('#hide-completed').click(function() {
    $('.task-completed').toggle();
  });
  // Change label to checkbox that hides completed tasks. project/show
  $('#hide-completed').change(function(){
    var c = this.checked ? ' Show completed tasks' : ' Hide completed tasks';
    $('#checkbox-label').text(c);
  });

});
</code>```

The code does not trigger when I enter the page but only after refreshing it. I am using turbolinks.

I am aware of this question:
Rails loading my javascript only after a page reload
But I don't really know if that solution can be used in my case as well.
Thank you!

Edit:
This is my application.js file

```<code>//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require bootstrap-sprockets
//= require_tree .
</code>```

答:
If you're using turbolinks 5+, jquery-turbolinks doesn't work anymore (see https://github.com/kossnocorp/jquery.turbolinks).

Instead you can wrap your code into the function $(document).on "turbolinks:load", ->.

E.g.

```<code>$ ->
  $("#add-artwork-btn").on 'click', ->
    div = $("#add-artwork-div")
    div.toggle(200)
</code>```

becomes to

```<code>$(document).on "turbolinks:load", ->
  $ ->
    $("#add-artwork-btn").on 'click', ->
      div = $("#add-artwork-div")
      div.toggle(200)
</code>```

Body:
I have the following JavaScript code on a rails project

// app/assets/javascript/simple_effects.js

$(function() {
  // Hide completed tasks when checkbox is clicked. projects/show
  $('#hide-completed').click(function() {
    $('.task-completed').toggle();
  });
  // Change label to checkbox that hides completed tasks. project/show
  $('#hide-completed').change(function(){
    var c = this.checked ? ' Show completed tasks' : ' Hide completed tasks';
    $('#checkbox-label').text(c);
  });

});

The code does not trigger when I enter the page but only after refreshing it. I am using turbolinks.

I am aware of this question:
Rails loading my javascript only after a page reload
But I don't really know if that solution can be used in my case as well.
Thank you!

Edit:
This is my application.js file

//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require bootstrap-sprockets
//= require_tree .

Body:
If you're using turbolinks 5+, jquery-turbolinks doesn't work anymore (see https://github.com/kossnocorp/jquery.turbolinks).

Instead you can wrap your code into the function $(document).on "turbolinks:load", ->.

E.g.

$ ->
  $("#add-artwork-btn").on 'click', ->
    div = $("#add-artwork-div")
    div.toggle(200)

becomes to

$(document).on "turbolinks:load", ->
  $ ->
    $("#add-artwork-btn").on 'click', ->
      div = $("#add-artwork-div")
      div.toggle(200)


问:
Passing strings to Fortran subroutine using ctypes
I am currently trying to pass a string to a Fortran library. I have gotten other functions from this library to work, but this particular one seems to be unique in that it wants a string passed to it as an argument to the function.

Looking at the source code, the function requires three arguments

```<code>SUBROUTINE EZVOLLIB(VOLEQI,DBHOB,HTTOT,VOL)
</code>```

and the arguments are defined:

```<code>  IMPLICIT NONE

  CHARACTER*(*)   VOLEQI
  CHARACTER*10 VOLEQ
  REAL DBHOB,HTTOT,TOPD, VOL(15), MHT
  INTEGER REGN,ERRFLG
</code>```

In Python my call to the function looks like

```<code>from ctypes import *

mylib = cdll.LoadLibrary('/home/bryce/Programming/opencompile/libvollib.so')

dbhob = c_float(42.2)
vol = (c_float * 15)()
voleqi = c_char_p("101DVEW119 ")

mylib.ezvollib_(voleqi, dbhob, vol)
</code>```

This runs without a segmentation fault, but does not seem to "fill" the variable vol with the desired 15 float values.

Is there any way to get vol to retrieve the values being returned from the EZVOLLIB function?

答:
There are many similar questions here, but it is hard to find an exact duplicate. There are several possible ways to do that with different degrees of universal correctness and portability.

The most correct way is to use modern Fortran to C interoperability as explained in fortran77, iso_c_binding and c string  That requires writing more Fortran wrapping code.

There are people who are strictly against writing any more Fortran, even-though that is the only portable solution. In that case they must explore what is the actual calling convention for Fortran strings in their compiler. Usually a hidden integer argument with the string length is passed to the subroutine. For gfortran see https://gcc.gnu.org/onlinedocs/gfortran/Argument-passing-conventions.html

Your ctypes interface could employ these compiler-specific calling conventions but then the interface will be, well, compiler-specific. But you are already relying on the specific name mangling ezvollib_ and that is compiler-specific as well. You can find examples here on SO where people were bitten by relying on that.

Also note, as noted by High Performance Mark, that the subroutine in question has four arguments, not three: EZVOLLIB(VOLEQI,DBHOB,HTTOT,VOL). Calling it with just three as in mylib.ezvollib_(voleqi, dbhob, vol) is an error. You are missing the HTTOT argument.

Body:
I am currently trying to pass a string to a Fortran library. I have gotten other functions from this library to work, but this particular one seems to be unique in that it wants a string passed to it as an argument to the function.

Looking at the source code, the function requires three arguments

SUBROUTINE EZVOLLIB(VOLEQI,DBHOB,HTTOT,VOL)

and the arguments are defined:

  IMPLICIT NONE

  CHARACTER*(*)   VOLEQI
  CHARACTER*10 VOLEQ
  REAL DBHOB,HTTOT,TOPD, VOL(15), MHT
  INTEGER REGN,ERRFLG

In Python my call to the function looks like

from ctypes import *

mylib = cdll.LoadLibrary('/home/bryce/Programming/opencompile/libvollib.so')

dbhob = c_float(42.2)
vol = (c_float * 15)()
voleqi = c_char_p("101DVEW119 ")

mylib.ezvollib_(voleqi, dbhob, vol)

This runs without a segmentation fault, but does not seem to "fill" the variable vol with the desired 15 float values.

Is there any way to get vol to retrieve the values being returned from the EZVOLLIB function?


问:
Add span to page at the cursor position
I have the following JavaScript, I am trying to insert the span at where ever the cursor position is in the div.

```<code>var appendPlaceHolder = function (field) {
        var e = document.getElementById("t");
        e.innerHTML += (' <span class="nonEditable tags">{' + field + '} <span onclick=removePlaceholder(this) class="testing"></span>x</span> ');
    }

<div id="t" contenteditable="true">
  Hello
</div>
</code>```

How do I go about doing it?

答:
Here is an old script I've written.Hope it helps.

continent is the mouse entered div, tooltipOutput

```<code>function continentTooltip(continent, tooltipOutput) {
    var tooltip = $('.map__tooltip');

    $(continent).mouseenter(function() {

       $(document).off('mousemove').bind('mousemove', function(e){

          var positionX = (e.pageX + 20) + 'px';
          var positionY = e.pageY + 'px';

          $('.map__tooltip').css(
             "transform" , 'translate(' + positionX + ', ' + positionY + ')'
          );
       });

       tooltip.addClass('map__tooltip--show');
       tooltip.text(tooltipOutput)
    })

    $(continent).mouseleave(function() {
        tooltip.removeClass('map__tooltip--show');
    });
  }
  //call script
  continentTooltip(africa, 'Vacations in Africa');
</code>```

HTML:

```<code><div class="map__tooltip"></div>
</code>```

CSS:

```<code>.map__tooltip {
     display: none;
     background-color: #FFF;
     border-radius: $radius;
     padding: 4px;
     position: absolute;
     top: 0;
     left: 0;
}

.map__tooltip--show {
    display: block;
}

@media screen and (max-width: 1300px) {

    .map__tooltip--show {
        display: none;
    }
}
</code>```

Title: Add span to page at the cursor position

Body:
I have the following JavaScript, I am trying to insert the span at where ever the cursor position is in the div.

var appendPlaceHolder = function (field) {
        var e = document.getElementById("t");
        e.innerHTML += (' {' + field + '} x ');
    }

  Hello

How do I go about doing it?

Body:
Here is an old script I've written.Hope it helps.

continent is the mouse entered div, tooltipOutput

function continentTooltip(continent, tooltipOutput) {
    var tooltip = $('.map__tooltip');

    $(continent).mouseenter(function() {

       $(document).off('mousemove').bind('mousemove', function(e){

          var positionX = (e.pageX + 20) + 'px';
          var positionY = e.pageY + 'px';

          $('.map__tooltip').css(
             "transform" , 'translate(' + positionX + ', ' + positionY + ')'
          );
       });

       tooltip.addClass('map__tooltip--show');
       tooltip.text(tooltipOutput)
    })

    $(continent).mouseleave(function() {
        tooltip.removeClass('map__tooltip--show');
    });
  }
  //call script
  continentTooltip(africa, 'Vacations in Africa');

HTML:

<div class="map__tooltip"></div>

CSS:

.map__tooltip {
     display: none;
     background-color: #FFF;
     border-radius: $radius;
     padding: 4px;
     position: absolute;
     top: 0;
     left: 0;
}

.map__tooltip--show {
    display: block;
}

@media screen and (max-width: 1300px) {

    .map__tooltip--show {
        display: none;
    }
}


答:
If there are only 3 fixed columns then you can get expected result set by using CASE statement

```<code>SELECT
  *,
  CASE
    WHEN Column1 = Column2
    THEN Column1
    WHEN Column1 = Column3
    THEN Column1
    WHEN Column2 = Column3
    THEN Column2
    ELSE NULL
  END answer
FROM
  demo a
</code>```

Demo

Title: Count Variable column wise in MySQL

Body:
If there are only 3 fixed columns then you can get expected result set by using CASE statement

SELECT
  *,
  CASE
    WHEN Column1 = Column2
    THEN Column1
    WHEN Column1 = Column3
    THEN Column1
    WHEN Column2 = Column3
    THEN Column2
    ELSE NULL
  END answer
FROM
  demo a

Demo


问:
It's secure to redirect tha API calls made with HTTP to my server to HTTPS?
I have a Nodejs server that communicates via a REST API with HTTP. I would like now to change the protocol of transmission of all my requests from HTTP to HTTPS. The problem is that I cannot change the client code.

I would like to know if redirecting all HTTP request on the server to https is enough to have the data sent with encryption. Or if I must modify the code that runs on the client and that makes the request with HTTP protocol.

I have to do it because the data should not be sent in clear as there are some sensitive data that are sent (username, password, position information).

Thanks.

答:
The purpose of using HTTPS is not just encryption. It also provides authentication of the server to the client, among others.

One problem with having a client that makes plain http requests (regardless of then being redirected) is that an attacker may create a fake server, to which the client would talk to, revealing secrets or pulling fake data. Without requests being made over https initially, there is nothing to stop an attacker from doing this.

Even worse, an attacker can just listen in to traffic to the real server. If a man-in-the-middle attack is possible (like for example the attacker is on the same local network as either the client or the server), the attacker can hijack the initial plaintext request, talk on HTTPS to the API, then respond on plain http to the client, and so on, for all requests. From the client's perspective, it "just works", from the server's perspective, it's all good, on https.

This is called SSL Stripping.

So the only solution is to have the client do all requests (including the first one) over https. One way to ensure this with browser clients is to use the Strict-Transport-Security (HSTS) response header. For non-browser clients, you can implement them to either comply with HSTS or simply make all requests over https.


问:
iOS, Android, Blackberry etc, which of the mobile OS is the most hacker-friendly?
I'm a developer and I have the desire to do everything technically possible with my mobile device, such as programmatically placing calls, programmatically deciding whether what to do with an incoming call (hang up, divert to voicemail, play an automated message etc), programmatically sending text messages, accepting push notifications from my own servers, allowing me to read data from the GPS device, periodically taking pictures, running my own programs without making them to the app store, etc...

Which of the existing mobile device platforms has the most liberal and feature-complete API that may allow some of the above? Good documentation would be a plus :=)

答:
If you feel hackish in anyway and your only purpose is to taylor YOUR phone the way you want without feeling the need to make your hack-thingie available into an appstore...then the answer is easy :

Android.

The documentation is poor, badly written, the apis are full of little annoying bugs and all that BUT : Whatever you don't find in the official API's you can hack by forking your own Android.

For example none of the mobile frameworks allow developers to send audio to a caller during a call. I personally cannot see the reason but you just can't. Fork your Android, add the missing bits and off you go.


问:
Inject service into angular 1.5 component
I'm trying to initialize a test.service.js from an angular1.5 component and I don't really know how to that. I have used this structure for angular components:

```<code>var testComponent =  {
    templateUrl: "app/components/test.component.html",
    controllerAs: "mvm",
    bindings:{
        bindingInput: "=",
},
controller: function(){
      var mvm = this;

    }
};
angular.module('myApp').component('testComponent', testComponent);
</code>```

答:
Just inject it using the controller as following :</p>

```<code>...
},
controller: ['testService', function(testService){
  var mvm = this;
}],
...
</code>```

Body:
I'm trying to initialize a test.service.js from an angular1.5 component and I don't really know how to that. I have used this structure for angular components:

var testComponent =  {
    templateUrl: "app/components/test.component.html",
    controllerAs: "mvm",
    bindings:{
        bindingInput: "=",
},
controller: function(){
      var mvm = this;

    }
};
angular.module('myApp').component('testComponent', testComponent);

Body:
Just inject it using the controller as following :

...
},
controller: ['testService', function(testService){
  var mvm = this;
}],
...


答:
The problem is that Table[1] is a list, and so you cannot add an integer to it.

This should work:

```<code>Table[1][0] = Table[1][0] + 1
</code>```

Title: python increasing value in a 2d array

Body:
I needed to be able to increase the value of one of the elements but i keep getting the error can anyone help.

Table = {56:[12],54:[9],58:[9],4:[8],16:[8],20:[8],
             49:[8],1:[7],2:[7],11:[7],14:[7],25:[7],
             30:[7],35:[7],36:[7],41:[7],50:[7],52:[7],
             55:[7],59:[7],18:[6],21:[6],27:[6],42:[6],
             45:[6],6:[5],7:[5],13:[5],17:[5],29:[5],32:[5],
             34:[5],37:[5],44:[5],47:[5],5:[4],8:[4],10:[4],
             15:[4],24:[4],43:[4],46:[4],51:[4],3:[3],12:[3],
             19:[3],22:[3],23:[3],26:[3],38:[3],39:[3],40:[3],
             53:[3],9:[2],28:[2],31:[2],33:[2],57:[2],48:[1]}

print(str(Table[1]))
x = Table[1]
Table[1]= [x+1]
print(str(Table[1]))

[7]
Traceback (most recent call last):
  File "N:\CS Predictive algorithm\CS Predictive algorithm\CodeRelated\test.py", line 14, in <module>
    Table[1]= [x+1]
TypeError: can only concatenate list (not "int") to list

Body:
The problem is that Table[1] is a list, and so you cannot add an integer to it.

This should work:

Table[1][0] = Table[1][0] + 1


问:
laravel - inserting id from one table to another right after submitting a form
Since I'm new in Laravel (started using this framework 2 weeks ago), I'm having a hard time inserting an id from one table to another right after submitting a form.

The scenario is that I have a form and what I wanted is that the id (p_id) of the newly submitted data from the 1st table (packages table) will be inserted to the 2nd table (itineraries table). Below are the codes of my controller and my model:

Controller

```<code>public function store(Request $request){
    request()->validate([
        'packageName' => 'required',
        'adultPrice' => 'required',
        'childPrice' => 'required',
        'infantPrice' => 'required',
        'excessPrice' => 'required',
        'type' => 'required',
        'inclusions' => 'required',
        'additionalInfo' => 'required',
        'reminders' => 'required',
        'photo' => 'required',
        'tags' => 'required',
        'noOfDays' => 'required',
        'day' => 'required',
        'time' => 'required',
        'destination' => 'required'
    ]);
    Packages::create($request->all());
    Itinerary::create($request->all());
    return redirect()->route('Agent.Packages');
}
</code>```

Itinerary Model

```<code>class Itinerary extends Model{
   public $fillable = [
       'noOfDays',
       'day',
       'time',
       'destination',
       ];
}
</code>```

答:
To insert Data from first table to second table,
First of all you need to get the last Insert Id.

Change your code as follows:

```<code>$package = Packages::create($request->all());
$p_id = $package->id;    // You will get your Id.
// Later you need to add it to below method.
$data = array_merge($p_id,$request->all());   // I`m not sure about this line...
Itinerary::create($data);
</code>```

Body:
Since I'm new in Laravel (started using this framework 2 weeks ago), I'm having a hard time inserting an id from one table to another right after submitting a form.

The scenario is that I have a form and what I wanted is that the id (p_id) of the newly submitted data from the 1st table (packages table) will be inserted to the 2nd table (itineraries table). Below are the codes of my controller and my model:

Controller

public function store(Request $request){
    request()->validate([
        'packageName' => 'required',
        'adultPrice' => 'required',
        'childPrice' => 'required',
        'infantPrice' => 'required',
        'excessPrice' => 'required',
        'type' => 'required',
        'inclusions' => 'required',
        'additionalInfo' => 'required',
        'reminders' => 'required',
        'photo' => 'required',
        'tags' => 'required',
        'noOfDays' => 'required',
        'day' => 'required',
        'time' => 'required',
        'destination' => 'required'
    ]);
    Packages::create($request->all());
    Itinerary::create($request->all());
    return redirect()->route('Agent.Packages');
}

Itinerary Model

class Itinerary extends Model{
   public $fillable = [
       'noOfDays',
       'day',
       'time',
       'destination',
       ];
}

Body:
To insert Data from first table to second table,
First of all you need to get the last Insert Id.

Change your code as follows:

$package = Packages::create($request->all());
$p_id = $package->id;    // You will get your Id.
// Later you need to add it to below method.
$data = array_merge($p_id,$request->all());   // I`m not sure about this line...
Itinerary::create($data);


问:
How To pass php variable into ajax data
How can I send PHP  variable sprod into ajax i need to send this id to check.php page </p>

```<code><script>
function getState(val) {

    $.ajax({
    type: "POST",
    url: "check.php",
    data: {id: val, id2:$prod },
    dataType:'json',
    success: function(data){
        $("#style_code").children().remove();
        $("#style_image").children().remove();

         data.option.forEach(function (item) {
                $("#style_code").append('<option value="' + item.color_name + '">' + item.size + '</option>');
                $('#style_image').append('<img  src="images/'+item.image_name+'" data-imagezoom="true" class="img-responsive" alt="" />')
            //$("#style_image").html(data);
            });
    }
    });
}
</script>
</code>```

答:
You can use <?php ?> tags in your script because you run it into ur .php file.

But you need to to open the <?php ?> tags to use php in the script tags.

Change

```<code>data: {id: val, id2:$prod },
</code>```

To

```<code>data: {'id':val, 'id2':<?php echo $prod ?> },
</code>```

Also(Better by my oppinion)

```<code>data: {'id': val, 'id2':<?= $prod ?> },
</code>```

U can use <?=?> instead of <?php ?> to print something, so you don't need to write echo again.

Title: How To pass php variable into ajax data

Body:
You can use <?php ?> tags in your script because you run it into ur .php file.

But you need to to open the <?php ?> tags to use php in the script tags.

Change

data: {id: val, id2:$prod },

To

data: {'id':val, 'id2':<?php echo $prod ?> },

Also(Better by my oppinion)

data: {'id': val, 'id2':<?= $prod ?> },

U can use <?=?> instead of <?php ?> to print something, so you don't need to write echo again.


问:
Getting NullPointer Exception on FileUpload using Struts2 and Ajax
I am implementing Struts2 File Upload using Ajax; I have added the jquery code as below

```<code>$("#btnUploadAttach").click(function () {
            alert("Uploading your file");
            //stop submit the form, we will post it manually.
            event.preventDefault();

            // Get form
            var form = $('#fileUploadForm')[0];

            // Create an FormData object
            var data = new FormData(form);

            alert("Uploading your file" + data);
            $.ajax({
                type: 'POST',
                enctype: 'multipart/form-data',
                data: data,
                contentType: false,
                processData: false,
                cache: false,
                timeout: 600000,
                url: "/Dashboard/UploadFile.action",
                success: function (data) {
                    alert("file saved successfully");
                }
            });
        });
</code>```

Also Please find the below code of JSP :

```<code><s:form id="fileUploadForm" enctype="multipart/form-data" method="POST">
                        <div class="col-md-12">
                            <s:label for="CashReqFileUpload">Select Your File:</s:label>
                            </div>
                            <div class="col-md-12">
                                <div class="col-md-4">
                                <s:file name="CashReqFileUpload" id="CashReqFileUpload"/>

                            </div>
                            <div class="col-md-4"><input type="submit" value="Upload Document" id="btnUploadAttach" ></div>
                            <div class="col-md-4">
                                <button id="btnPrint" class="btn btn-success">Print</button>
                            </div>
                        </div>
                    </s:form>
</code>```

And my action class as below :

```<code> private File CashReqFileUpload;
private String CashReqFileUploadFileName;
private String CashReqFileUploadContentType;
private String destPath;

public String execute(){
    return SUCCESS;
}

public String uploadFileOnServer() throws IOException {
    destPath = "D:/Temp/";
    System.out.println("CashReqFileUpload File name: " + CashReqFileUpload);
    System.out.println("CashReqFileUploadFileName File name: " + CashReqFileUploadFileName);
    System.out.println("destPath File Name : "+destPath);
    File destFile = new File(destPath, CashReqFileUploadFileName);
    FileUtils.copyFile(CashReqFileUpload, destFile);
    return SUCCESS;
}

public File getCashReqFileUpload() {
    return CashReqFileUpload;
}

public void setCashReqFileUpload(File CashReqFileUpload) {
    this.CashReqFileUpload = CashReqFileUpload;
}

public String getCashReqFileUploadFileName() {
    return CashReqFileUploadFileName;
}

public void setCashReqFileUploadFileName(String CashReqFileUploadFileName) {
    this.CashReqFileUploadFileName = CashReqFileUploadFileName;
}

public String getCashReqFileUploadContentType() {
    return CashReqFileUploadContentType;
}

public void setCashReqFileUploadContentType(String CashReqFileUploadContentType) {
    this.CashReqFileUploadContentType = CashReqFileUploadContentType;
}
</code>```

I have tried with Serialize(), but it didn't workout, I found one solution on https://www.mkyong.com/jquery/jquery-ajax-submit-a-multipart-form/ to implement using Ajax. It is giving me NullPointerException as below :

```<code>Severe:   java.lang.NullPointerException
    at java.io.File.<init>(File.java:317)
    at com.ISG.CIA.CTI.operations.UploadFile.uploadFileOnServer(UploadFile.java:35)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at ognl.OgnlRuntime.invokeMethod(OgnlRuntime.java:899)
    at ognl.OgnlRuntime.callAppropriateMethod(OgnlRuntime.java:1544)
    at ognl.ObjectMethodAccessor.callMethod(ObjectMethodAccessor.java:68)
    at com.opensymphony.xwork2.ognl.accessor.XWorkMethodAccessor.callMethodWithDebugInfo(XWorkMethodAccessor.java:96)
    at com.opensymphony.xwork2.ognl.accessor.XWorkMethodAccessor.callMethod(XWorkMethodAccessor.java:88)
    at ognl.OgnlRuntime.callMethod(OgnlRuntime.java:1620)
    at ognl.ASTMethod.getValueBody(ASTMethod.java:91)
    at ognl.SimpleNode.evaluateGetValueBody(SimpleNode.java:212)
    at ognl.SimpleNode.getValue(SimpleNode.java:258)
    at ognl.Ognl.getValue(Ognl.java:470)
    at ognl.Ognl.getValue(Ognl.java:434)
    at com.opensymphony.xwork2.ognl.OgnlUtil$3.execute(OgnlUtil.java:371)
    at com.opensymphony.xwork2.ognl.OgnlUtil.compileAndExecuteMethod(OgnlUtil.java:423)
    at com.opensymphony.xwork2.ognl.OgnlUtil.callMethod(OgnlUtil.java:369)
    at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:436)
    at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:291)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:252)
    at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:253)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:176)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:260)
    at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:52)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.doIntercept(ConversionErrorInterceptor.java:139)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:134)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:134)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:199)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:69)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at org.apache.struts2.interceptor.DateTextFieldInterceptor.intercept(DateTextFieldInterceptor.java:115)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:88)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:246)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:99)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:139

Severe:   hain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
at java.lang.Thread.run(Thread.java:744)
</code>```

I want to implement file upload using Struts and Ajax only. Not using with any other plugin. I searched on StackOverflow, but their solution is not what my requirement is.

EDIT

Uploading Struts.xml :

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
   "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
   "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
<constant name = "struts.devMode" value = "true" />
<constant name="struts.ui.theme" value="simple"/>
<constant name="struts.custom.i18n.resources" value="operationProp.OperationalProp" />
<package name = "CTI" extends = "struts-default">
    <interceptors>
        <interceptor-stack name="modelParamsPrepareParamsStack">
            <interceptor-ref name="exception"/>
            <interceptor-ref name="alias"/>
            <interceptor-ref name="i18n"/>
            <interceptor-ref name="checkbox"/>
            <interceptor-ref name="multiselect"/>
            <interceptor-ref name="modelDriven"/>
            <interceptor-ref name="params">
                <param name="excludeParams">^dojo\..*,^struts\..*,^session\..*,^request\..*,^application\..*,^servlet(Request|Response)\..*,^parameters\..*,^action:.*,^method:.*</param>
            </interceptor-ref>
            <interceptor-ref name="servletConfig"/>
            <interceptor-ref name="prepare"/>
            <interceptor-ref name="chain"/>
            <interceptor-ref name="fileUpload"/>
            <interceptor-ref name="staticParams"/>
            <interceptor-ref name="actionMappingParams"/>
            <interceptor-ref name="params">
                <param name="excludeParams">^dojo\..*,^struts\..*,^session\..*,^request\..*,^application\..*,^servlet(Request|Response)\..*,^parameters\..*,^action:.*,^method:.*</param>
            </interceptor-ref>
            <interceptor-ref name="conversionError"/>
            <interceptor-ref name="validation">
                <param name="excludeMethods">input,back,cancel,browse</param>
            </interceptor-ref>
            <interceptor-ref name="workflow">
                <param name="excludeMethods">input,back,cancel,browse</param>
            </interceptor-ref>
        </interceptor-stack>
    </interceptors>
    <action name = "OnLoadAction"
            class = "com.ISG.CIA.CTI.CashRequestManagement"
            method = "execute">
        <result name = "success">/ApprovedHistory.jsp</result>
    </action>
    <action name = "OnClickOfCreateNewReq"
            class = "com.ISG.CIA.CTI.CashRequestManagement"
            method = "getCashReqDataForNewReq">
        <result name = "success">/CashRequestForm.jsp</result>
    </action>
    <action name = "onLoadForm"
            class = "com.ISG.CIA.CTI.CashRequestManagement"
            method = "getCashReqDataForSavedRequest">
        <result name = "success">/CashRequestForm.jsp</result>
    </action>
    <action name = "OnClickOfSaveRequest"
            class = "com.ISG.CIA.CTI.CashRequestManagement"
            method = "SaveCashRequest">
        <result name = "success">/CashRequestForm.jsp</result>
    </action>
    <action name="CashReqRej"
            class="com.ISG.CIA.CTI.CashRequestManagement"
            method="cancelCashReq">
        <result name="success">/CashRequestForm.jsp</result>
    </action>
    <action name="CashReqApprove"
            class="com.ISG.CIA.CTI.CashRequestManagement"
            method="approveCashReq">
        <result name="success">/CashRequestForm.jsp</result>
    </action>
    <action name="UploadFile"
            class="com.ISG.CIA.CTI.operations.UploadFile"
            method="uploadFileOnServer">
        <interceptor-ref name="modelDriven"/>
        <interceptor-ref name="defaultStack"/>
        <interceptor-ref name="fileUpload"/>
        <interceptor-ref name="basicStack"/>
        <result name="none">/CashRequestForm.jsp</result>
    </action>
</package>
</code>```

May be struts.xml may help to identify the issue.

答:
Try file upload interceptor before other like</p>

```<code><action name="UploadFile"
        class="com.ISG.CIA.CTI.operations.UploadFile"
        method="uploadFileOnServer">
    <interceptor-ref name="fileUpload"/>
    <interceptor-ref name="modelDriven"/>
    <interceptor-ref name="defaultStack"/>
    <interceptor-ref name="basicStack"/>
    <result name="none">/CashRequestForm.jsp</result>
</action>
</code>```

Body:
I am implementing Struts2 File Upload using Ajax; I have added the jquery code as below

$("#btnUploadAttach").click(function () {
            alert("Uploading your file");
            //stop submit the form, we will post it manually.
            event.preventDefault();

            // Get form
            var form = $('#fileUploadForm')[0];

            // Create an FormData object
            var data = new FormData(form);

            alert("Uploading your file" + data);
            $.ajax({
                type: 'POST',
                enctype: 'multipart/form-data',
                data: data,
                contentType: false,
                processData: false,
                cache: false,
                timeout: 600000,
                url: "/Dashboard/UploadFile.action",
                success: function (data) {
                    alert("file saved successfully");
                }
            });
        });

Also Please find the below code of JSP :

<s:form id="fileUploadForm" enctype="multipart/form-data" method="POST">

                            <s:label for="CashReqFileUpload">Select Your File:</s:label>

                                <s:file name="CashReqFileUpload" id="CashReqFileUpload"/>

<input type="submit" value="Upload Document" id="btnUploadAttach" >

                                <button id="btnPrint" class="btn btn-success">Print</button>

                    </s:form>

And my action class as below :

 private File CashReqFileUpload;
private String CashReqFileUploadFileName;
private String CashReqFileUploadContentType;
private String destPath;

public String execute(){
    return SUCCESS;
}

public String uploadFileOnServer() throws IOException {
    destPath = "D:/Temp/";
    System.out.println("CashReqFileUpload File name: " + CashReqFileUpload);
    System.out.println("CashReqFileUploadFileName File name: " + CashReqFileUploadFileName);
    System.out.println("destPath File Name : "+destPath);
    File destFile = new File(destPath, CashReqFileUploadFileName);
    FileUtils.copyFile(CashReqFileUpload, destFile);
    return SUCCESS;
}

public File getCashReqFileUpload() {
    return CashReqFileUpload;
}

public void setCashReqFileUpload(File CashReqFileUpload) {
    this.CashReqFileUpload = CashReqFileUpload;
}

public String getCashReqFileUploadFileName() {
    return CashReqFileUploadFileName;
}

public void setCashReqFileUploadFileName(String CashReqFileUploadFileName) {
    this.CashReqFileUploadFileName = CashReqFileUploadFileName;
}

public String getCashReqFileUploadContentType() {
    return CashReqFileUploadContentType;
}

public void setCashReqFileUploadContentType(String CashReqFileUploadContentType) {
    this.CashReqFileUploadContentType = CashReqFileUploadContentType;
}

I have tried with Serialize(), but it didn't workout, I found one solution on https://www.mkyong.com/jquery/jquery-ajax-submit-a-multipart-form/ to implement using Ajax. It is giving me NullPointerException as below :

Severe:   java.lang.NullPointerException
    at java.io.File.<init>(File.java:317)
    at com.ISG.CIA.CTI.operations.UploadFile.uploadFileOnServer(UploadFile.java:35)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at ognl.OgnlRuntime.invokeMethod(OgnlRuntime.java:899)
    at ognl.OgnlRuntime.callAppropriateMethod(OgnlRuntime.java:1544)
    at ognl.ObjectMethodAccessor.callMethod(ObjectMethodAccessor.java:68)
    at com.opensymphony.xwork2.ognl.accessor.XWorkMethodAccessor.callMethodWithDebugInfo(XWorkMethodAccessor.java:96)
    at com.opensymphony.xwork2.ognl.accessor.XWorkMethodAccessor.callMethod(XWorkMethodAccessor.java:88)
    at ognl.OgnlRuntime.callMethod(OgnlRuntime.java:1620)
    at ognl.ASTMethod.getValueBody(ASTMethod.java:91)
    at ognl.SimpleNode.evaluateGetValueBody(SimpleNode.java:212)
    at ognl.SimpleNode.getValue(SimpleNode.java:258)
    at ognl.Ognl.getValue(Ognl.java:470)
    at ognl.Ognl.getValue(Ognl.java:434)
    at com.opensymphony.xwork2.ognl.OgnlUtil$3.execute(OgnlUtil.java:371)
    at com.opensymphony.xwork2.ognl.OgnlUtil.compileAndExecuteMethod(OgnlUtil.java:423)
    at com.opensymphony.xwork2.ognl.OgnlUtil.callMethod(OgnlUtil.java:369)
    at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:436)
    at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:291)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:252)
    at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:253)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:176)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:260)
    at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:52)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.doIntercept(ConversionErrorInterceptor.java:139)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:134)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:134)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:199)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:69)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at org.apache.struts2.interceptor.DateTextFieldInterceptor.intercept(DateTextFieldInterceptor.java:115)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:88)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:246)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:99)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:139

Severe:   hain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
at java.lang.Thread.run(Thread.java:744)

I want to implement file upload using Struts and Ajax only. Not using with any other plugin. I searched on StackOverflow, but their solution is not what my requirement is.

EDIT

Uploading Struts.xml :

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
   "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
   "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
<constant name = "struts.devMode" value = "true" />
<constant name="struts.ui.theme" value="simple"/>
<constant name="struts.custom.i18n.resources" value="operationProp.OperationalProp" />
<package name = "CTI" extends = "struts-default">
    <interceptors>
        <interceptor-stack name="modelParamsPrepareParamsStack">
            <interceptor-ref name="exception"/>
            <interceptor-ref name="alias"/>
            <interceptor-ref name="i18n"/>
            <interceptor-ref name="checkbox"/>
            <interceptor-ref name="multiselect"/>
            <interceptor-ref name="modelDriven"/>
            <interceptor-ref name="params">
                <param name="excludeParams">^dojo\..*,^struts\..*,^session\..*,^request\..*,^application\..*,^servlet(Request|Response)\..*,^parameters\..*,^action:.*,^method:.*</param>
            </interceptor-ref>
            <interceptor-ref name="servletConfig"/>
            <interceptor-ref name="prepare"/>
            <interceptor-ref name="chain"/>
            <interceptor-ref name="fileUpload"/>
            <interceptor-ref name="staticParams"/>
            <interceptor-ref name="actionMappingParams"/>
            <interceptor-ref name="params">
                <param name="excludeParams">^dojo\..*,^struts\..*,^session\..*,^request\..*,^application\..*,^servlet(Request|Response)\..*,^parameters\..*,^action:.*,^method:.*</param>
            </interceptor-ref>
            <interceptor-ref name="conversionError"/>
            <interceptor-ref name="validation">
                <param name="excludeMethods">input,back,cancel,browse</param>
            </interceptor-ref>
            <interceptor-ref name="workflow">
                <param name="excludeMethods">input,back,cancel,browse</param>
            </interceptor-ref>
        </interceptor-stack>
    </interceptors>
    <action name = "OnLoadAction"
            class = "com.ISG.CIA.CTI.CashRequestManagement"
            method = "execute">
        <result name = "success">/ApprovedHistory.jsp</result>
    </action>
    <action name = "OnClickOfCreateNewReq"
            class = "com.ISG.CIA.CTI.CashRequestManagement"
            method = "getCashReqDataForNewReq">
        <result name = "success">/CashRequestForm.jsp</result>
    </action>
    <action name = "onLoadForm"
            class = "com.ISG.CIA.CTI.CashRequestManagement"
            method = "getCashReqDataForSavedRequest">
        <result name = "success">/CashRequestForm.jsp</result>
    </action>
    <action name = "OnClickOfSaveRequest"
            class = "com.ISG.CIA.CTI.CashRequestManagement"
            method = "SaveCashRequest">
        <result name = "success">/CashRequestForm.jsp</result>
    </action>
    <action name="CashReqRej"
            class="com.ISG.CIA.CTI.CashRequestManagement"
            method="cancelCashReq">
        <result name="success">/CashRequestForm.jsp</result>
    </action>
    <action name="CashReqApprove"
            class="com.ISG.CIA.CTI.CashRequestManagement"
            method="approveCashReq">
        <result name="success">/CashRequestForm.jsp</result>
    </action>
    <action name="UploadFile"
            class="com.ISG.CIA.CTI.operations.UploadFile"
            method="uploadFileOnServer">
        <interceptor-ref name="modelDriven"/>
        <interceptor-ref name="defaultStack"/>
        <interceptor-ref name="fileUpload"/>
        <interceptor-ref name="basicStack"/>
        <result name="none">/CashRequestForm.jsp</result>
    </action>
</package>

May be struts.xml may help to identify the issue.

Body:
Try file upload interceptor before other like

<action name="UploadFile"
        class="com.ISG.CIA.CTI.operations.UploadFile"
        method="uploadFileOnServer">
    <interceptor-ref name="fileUpload"/>
    <interceptor-ref name="modelDriven"/>
    <interceptor-ref name="defaultStack"/>
    <interceptor-ref name="basicStack"/>
    <result name="none">/CashRequestForm.jsp</result>
</action>


问:
Reading external styles.xml file and apply to our workbook
I'm gathering that if we can read external styles.xml file and apply to our workbook using OpenXML would be more efficiently than styling in our code. I have done a lot of research but still not get any solution.

Please tell me if it possible or not and give me some resources (if any) about this.

答:
Yes, it's possible to modify styles.xml directly but that doesn't mean it's a good idea.  I've seen a few people try to work directly with the styles but I have yet to see it turn out well -- and these are people with many years of experience with XML, coding and Excel is general, who figured they had exhausted usability of Excel's built-in features and figured they could do a better job at it than Microsoft can.

If you are confident that you can build a stylesheet more appropriate for your project (than what Excel's developer provided) you'll be able to find full specifications by researching ISO 29500-1.

Overview from Wikipedia

ISO/IEC 29500-1:2016 (7000+ pages)

Generating Excel 2010 Workbooks by using the Open XML SDK 2.0

How to: Manipulate Office Open XML Formats Documents

How to Diagnose Excel file corruption and Repair Workbooks

[Solved] File corrupt and therefore cannot be repaired

*I'll admit I'm very curious about how Excel's stylesheet is no longer suitable for your organization's requirements!


问:
jQuery : Split the DOM Node using jQuery
My problem is to split the Dom element using jquery.

```<code><span class="start">
  <span class="second">
   new text <span class='split'>is written</span> in this place.
 </span>
</span>
</code>```

And I want to Split the above DOM Like this.

```<code><span class="start"><span class="second">new text</span></span>

<span class="start"><span class="second">is written</span></span>

<span class="start"><span class="second">in this place.</span></span>
</code>```

Please, anybody give me some advice.

答:
One way to do it would be:

```<code>last_text=$('.split')[0].nextSibling; //get textNode after split span
prev_text=$('.split')[0].previousSibling; //get text Node before split span
current=$('.split').text(); //get split span text

$('.second').html(' '); //clear current html

cloned1=$('.start').clone(); // clone el
cloned1.insertAfter($('.start'));
cloned2=$('.start').first().clone(); //clone one more
cloned2.insertAfter($('.start').last());
//set text for elements
$('.start .second').eq(0).html(prev_text);
$('.start .second').eq(1).html(current);
$('.start .second').eq(2).html(last_text);
</code>```

Demo:

last_text=$('.split')[0].nextSibling; //get textNode after split span
prev_text=$('.split')[0].previousSibling; //get text Node before split span
current=$('.split').text(); //get split span text

$('.second').html(' '); //clear current html

cloned1=$('.start').clone(); // clone el
cloned1.insertAfter($('.start'));
cloned2=$('.start').first().clone(); //clone one more
cloned2.insertAfter($('.start').last());
//set text for elements
$('.start .second').eq(0).html(prev_text);
$('.start .second').eq(1).html(current);
$('.start .second').eq(2).html(last_text);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="start">
  <span class="second">
   new text <span class='split'>is written</span> in this place.
 </span>
</span></code>```

P.S. If there are no classes (i guess that could be the case), you will have to use different selectors, to target spans (inside container?), with eq(), maybe, but, basically, this simple logic should work...

Body:
My problem is to split the Dom element using jquery.

   new text is written in this place.

And I want to Split the above DOM Like this.

new text

is written

in this place.

Please, anybody give me some advice.

Body:
One way to do it would be:

last_text=$('.split')[0].nextSibling; //get textNode after split span
prev_text=$('.split')[0].previousSibling; //get text Node before split span
current=$('.split').text(); //get split span text

$('.second').html(' '); //clear current html

cloned1=$('.start').clone(); // clone el
cloned1.insertAfter($('.start'));
cloned2=$('.start').first().clone(); //clone one more
cloned2.insertAfter($('.start').last());
//set text for elements
$('.start .second').eq(0).html(prev_text);
$('.start .second').eq(1).html(current);
$('.start .second').eq(2).html(last_text);

Demo:

last_text=$('.split')[0].nextSibling; //get textNode after split span
prev_text=$('.split')[0].previousSibling; //get text Node before split span
current=$('.split').text(); //get split span text

$('.second').html(' '); //clear current html

cloned1=$('.start').clone(); // clone el
cloned1.insertAfter($('.start'));
cloned2=$('.start').first().clone(); //clone one more
cloned2.insertAfter($('.start').last());
//set text for elements
$('.start .second').eq(0).html(prev_text);
$('.start .second').eq(1).html(current);
$('.start .second').eq(2).html(last_text);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="start">
  <span class="second">
   new text <span class='split'>is written</span> in this place.
 </span>
</span>

P.S. If there are no classes (i guess that could be the case), you will have to use different selectors, to target spans (inside container?), with eq(), maybe, but, basically, this simple logic should work...