问:
RelativeLayout.LayoutParams causing app crash in android
I had a recycler view for which I have a linear layout as parent and a relative layout as child. I'm changing the layout params to these dynamically. My code is working pretty well for linear layout but when it comes to relative layout it is crashing.

It is not even showing the line number which is causing crash and after so many runs I figured out the line which is causing crash. This is the recycler view adapter class.

```<code>    @Override
    public void onBindViewHolder(Holder holder, int position) {
        ChatListItem listItem = listdata.get(position);
        LinearLayout parent=holder.parent;
        RelativeLayout chatView=holder.relLayout;
        holder.time.setText(listItem.time);
        holder.message.setText(listItem.message);
        if (!listItem.sentByCustomer) {
            int match_parent= LinearLayout.LayoutParams.MATCH_PARENT;
            int wrap_content= LinearLayout.LayoutParams.WRAP_CONTENT;
            chatView.setBackground(context.getResources().getDrawable(R.drawable.incoming_normal));

            LinearLayout.LayoutParams parentParams=new LinearLayout.LayoutParams(match_parent,wrap_content);
            parentParams.setMarginStart(5);
            parent.setLayoutParams(parentParams);

            int rel_wrap_content=RelativeLayout.LayoutParams.WRAP_CONTENT;
            RelativeLayout.LayoutParams relParams=new RelativeLayout.LayoutParams(rel_wrap_content,rel_wrap_content);
            relParams.setMarginEnd(50);

            chatView.setLayoutParams(relParams); // This line is  causing crash

        }
    }

    class Holder extends RecyclerView.ViewHolder  {
        LinearLayout parent;
        RelativeLayout relLayout;
        TextView message, time;

        public Holder(View itemView) {
            super(itemView);
            parent=(LinearLayout)itemView.findViewById(R.id.chat_view_parent);
            relLayout = (RelativeLayout) itemView.findViewById(R.id.customer_chat_view);
            message = (TextView) itemView.findViewById(R.id.customer_chat_message);
            time = (TextView) itemView.findViewById(R.id.chat_time);
        }
    }
}
</code>```

Everything is fine the layout params belong to relative layout params and I'm setting them to a relative layout and I've also cross checked the xml file and that one is also a relative layout. Still the error log is saying it can't cast the linear layout params to relative layout params. Even the debugger is saying it as relative layout but why am I getting the error ? Here is the error log

```<code>07-04 15:09:13.609 5441-5441/com.motowala E/UncaughtException: java.lang.ClassCastException: android.widget.RelativeLayout$LayoutParams cannot be cast to android.widget.LinearLayout$LayoutParams
                                                                   at android.widget.LinearLayout.measureHorizontal(LinearLayout.java:1071)
                                                                   at android.widget.LinearLayout.onMeasure(LinearLayout.java:642)
                                                                   at android.view.View.measure(View.java:19861)
                                                                   at android.support.v7.widget.RecyclerView$LayoutManager.measureChildWithMargins(RecyclerView.java:8636)
                                                                   at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1577)
                                                                   at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1511)
                                                                   at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:570)
                                                                   at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3583)
                                                                   at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3312)
                                                                   at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3844)
                                                                   at android.view.View.layout(View.java:17641)
                                                                   at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                   at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1079)
                                                                   at android.view.View.layout(View.java:17641)
                                                                   at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                   at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
                                                                   at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                   at android.view.View.layout(View.java:17641)
                                                                   at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                   at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1741)
                                                                   at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
                                                                   at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
                                                                   at android.view.View.layout(View.java:17641)
                                                                   at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                   at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
                                                                   at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                   at android.view.View.layout(View.java:17641)
                                                                   at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                   at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1741)
                                                                   at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
                                                                   at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
                                                                   at android.view.View.layout(View.java:17641)
                                                                   at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                   at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
                                                                   at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                   at com.android.internal.policy.DecorView.onLayout(DecorView.java:728)
                                                                   at android.view.View.layout(View.java:17641)
                                                                   at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                   at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2346)
                                                                   at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2068)
                                                                   at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1254)
                                                                   at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6343)
                                                                   at android.view.Choreographer$CallbackRecord.run(Choreographer.java:874)
                                                                   at android.view.Choreographer.doCallbacks(Choreographer.java:686)
                                                                   at android.view.Choreographer.doFrame(Choreographer.java:621)
                                                                   at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:860)
                                                                   at android.os.Handler.handleCallback(Handler.java:751)
                                                                   at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                   at android.os.Looper.loop(Looper.java:154)
                                                                   at android.app.ActivityThread.main(ActivityThread.java:6176)
                                                                   at java.lang.reflect.Method.invoke(Native Method)
                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888)
                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778)
07-04 15:09:13.613 5441-5502/com.motowala D/FA: Logging event (FE): _ae, Bundle[{_o=crash, _sc=CustomerChatActivity, _si=6120152536016377641, timestamp=1499161153609, fatal=1}]
07-04 15:09:13.906 5441-5441/com.motowala E/AndroidRuntime: FATAL EXCEPTION: main
                                                            Process: com.motowala, PID: 5441
                                                            java.lang.ClassCastException: android.widget.RelativeLayout$LayoutParams cannot be cast to android.widget.LinearLayout$LayoutParams
                                                                at android.widget.LinearLayout.measureHorizontal(LinearLayout.java:1071)
                                                                at android.widget.LinearLayout.onMeasure(LinearLayout.java:642)
                                                                at android.view.View.measure(View.java:19861)
                                                                at android.support.v7.widget.RecyclerView$LayoutManager.measureChildWithMargins(RecyclerView.java:8636)
                                                                at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1577)
                                                                at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1511)
                                                                at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:570)
                                                                at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3583)
                                                                at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3312)
                                                                at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3844)
                                                                at android.view.View.layout(View.java:17641)
                                                                at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1079)
                                                                at android.view.View.layout(View.java:17641)
                                                                at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
                                                                at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                at android.view.View.layout(View.java:17641)
                                                                at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1741)
                                                                at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
                                                                at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
                                                                at android.view.View.layout(View.java:17641)
                                                                at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
                                                                at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                at android.view.View.layout(View.java:17641)
                                                                at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1741)
                                                                at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
                                                                at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
                                                                at android.view.View.layout(View.java:17641)
                                                                at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
                                                                at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                at com.android.internal.policy.DecorView.onLayout(DecorView.java:728)
                                                                at android.view.View.layout(View.java:17641)
                                                                at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2346)
                                                                at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2068)
                                                                at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1254)
                                                                at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6343)
                                                                at android.view.Choreographer$CallbackRecord.run(Choreographer.java:874)
                                                                at android.view.Choreographer.doCallbacks(Choreographer.java:686)
                                                                at android.view.Choreographer.doFrame(Choreographer.java:621)
                                                                at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:860)
                                                                at android.os.Handler.handleCallback(Handler.java:751)
                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                at android.os.Looper.loop(Looper.java:154)
                                                                at android.app.ActivityThread.main(ActivityThread.java:6176)
                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888)
                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778)
</code>```

Thanks a lot in advance....

答:
It clearly says

android.widget.RelativeLayout$LayoutParams cannot be cast to
  android.widget.LinearLayout$LayoutParams

You are trying to cast LinearLayout.LayoutParams into RelativeLayout.LayoutParams. Its just like trying to convert apple into orange.

Change this:

```<code>int match_parent= LinearLayout.LayoutParams.MATCH_PARENT;
int wrap_content= LinearLayout.LayoutParams.WRAP_CONTENT;
chatView.setBackground(context.getResources().getDrawable(R.drawable.incoming_normal));

LinearLayout.LayoutParams parentParams=new LinearLayout.LayoutParams(match_parent,wrap_content);
parentParams.setMarginStart(5);
parent.setLayoutParams(parentParams);
</code>```

into this and try to run.

```<code>int match_parent= RelativeLayout.LayoutParams.MATCH_PARENT;
int wrap_content= RelativeLayout.LayoutParams.WRAP_CONTENT;
chatView.setBackground(context.getResources().getDrawable(R.drawable.incoming_normal));

RelativeLayout.LayoutParams parentParams=new RelativeLayout.LayoutParams(match_parent,wrap_content);
parentParams.setMarginStart(5);
parent.setLayoutParams(parentParams);
</code>```

Body:
I had a recycler view for which I have a linear layout as parent and a relative layout as child. I'm changing the layout params to these dynamically. My code is working pretty well for linear layout but when it comes to relative layout it is crashing.

It is not even showing the line number which is causing crash and after so many runs I figured out the line which is causing crash. This is the recycler view adapter class.

    @Override
    public void onBindViewHolder(Holder holder, int position) {
        ChatListItem listItem = listdata.get(position);
        LinearLayout parent=holder.parent;
        RelativeLayout chatView=holder.relLayout;
        holder.time.setText(listItem.time);
        holder.message.setText(listItem.message);
        if (!listItem.sentByCustomer) {
            int match_parent= LinearLayout.LayoutParams.MATCH_PARENT;
            int wrap_content= LinearLayout.LayoutParams.WRAP_CONTENT;
            chatView.setBackground(context.getResources().getDrawable(R.drawable.incoming_normal));

            LinearLayout.LayoutParams parentParams=new LinearLayout.LayoutParams(match_parent,wrap_content);
            parentParams.setMarginStart(5);
            parent.setLayoutParams(parentParams);

            int rel_wrap_content=RelativeLayout.LayoutParams.WRAP_CONTENT;
            RelativeLayout.LayoutParams relParams=new RelativeLayout.LayoutParams(rel_wrap_content,rel_wrap_content);
            relParams.setMarginEnd(50);

            chatView.setLayoutParams(relParams); // This line is  causing crash

        }
    }

    class Holder extends RecyclerView.ViewHolder  {
        LinearLayout parent;
        RelativeLayout relLayout;
        TextView message, time;

        public Holder(View itemView) {
            super(itemView);
            parent=(LinearLayout)itemView.findViewById(R.id.chat_view_parent);
            relLayout = (RelativeLayout) itemView.findViewById(R.id.customer_chat_view);
            message = (TextView) itemView.findViewById(R.id.customer_chat_message);
            time = (TextView) itemView.findViewById(R.id.chat_time);
        }
    }
}

Everything is fine the layout params belong to relative layout params and I'm setting them to a relative layout and I've also cross checked the xml file and that one is also a relative layout. Still the error log is saying it can't cast the linear layout params to relative layout params. Even the debugger is saying it as relative layout but why am I getting the error ? Here is the error log

07-04 15:09:13.609 5441-5441/com.motowala E/UncaughtException: java.lang.ClassCastException: android.widget.RelativeLayout$LayoutParams cannot be cast to android.widget.LinearLayout$LayoutParams
                                                                   at android.widget.LinearLayout.measureHorizontal(LinearLayout.java:1071)
                                                                   at android.widget.LinearLayout.onMeasure(LinearLayout.java:642)
                                                                   at android.view.View.measure(View.java:19861)
                                                                   at android.support.v7.widget.RecyclerView$LayoutManager.measureChildWithMargins(RecyclerView.java:8636)
                                                                   at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1577)
                                                                   at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1511)
                                                                   at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:570)
                                                                   at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3583)
                                                                   at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3312)
                                                                   at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3844)
                                                                   at android.view.View.layout(View.java:17641)
                                                                   at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                   at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1079)
                                                                   at android.view.View.layout(View.java:17641)
                                                                   at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                   at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
                                                                   at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                   at android.view.View.layout(View.java:17641)
                                                                   at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                   at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1741)
                                                                   at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
                                                                   at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
                                                                   at android.view.View.layout(View.java:17641)
                                                                   at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                   at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
                                                                   at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                   at android.view.View.layout(View.java:17641)
                                                                   at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                   at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1741)
                                                                   at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
                                                                   at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
                                                                   at android.view.View.layout(View.java:17641)
                                                                   at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                   at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
                                                                   at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                   at com.android.internal.policy.DecorView.onLayout(DecorView.java:728)
                                                                   at android.view.View.layout(View.java:17641)
                                                                   at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                   at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2346)
                                                                   at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2068)
                                                                   at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1254)
                                                                   at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6343)
                                                                   at android.view.Choreographer$CallbackRecord.run(Choreographer.java:874)
                                                                   at android.view.Choreographer.doCallbacks(Choreographer.java:686)
                                                                   at android.view.Choreographer.doFrame(Choreographer.java:621)
                                                                   at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:860)
                                                                   at android.os.Handler.handleCallback(Handler.java:751)
                                                                   at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                   at android.os.Looper.loop(Looper.java:154)
                                                                   at android.app.ActivityThread.main(ActivityThread.java:6176)
                                                                   at java.lang.reflect.Method.invoke(Native Method)
                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888)
                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778)
07-04 15:09:13.613 5441-5502/com.motowala D/FA: Logging event (FE): _ae, Bundle[{_o=crash, _sc=CustomerChatActivity, _si=6120152536016377641, timestamp=1499161153609, fatal=1}]
07-04 15:09:13.906 5441-5441/com.motowala E/AndroidRuntime: FATAL EXCEPTION: main
                                                            Process: com.motowala, PID: 5441
                                                            java.lang.ClassCastException: android.widget.RelativeLayout$LayoutParams cannot be cast to android.widget.LinearLayout$LayoutParams
                                                                at android.widget.LinearLayout.measureHorizontal(LinearLayout.java:1071)
                                                                at android.widget.LinearLayout.onMeasure(LinearLayout.java:642)
                                                                at android.view.View.measure(View.java:19861)
                                                                at android.support.v7.widget.RecyclerView$LayoutManager.measureChildWithMargins(RecyclerView.java:8636)
                                                                at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1577)
                                                                at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1511)
                                                                at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:570)
                                                                at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3583)
                                                                at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3312)
                                                                at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3844)
                                                                at android.view.View.layout(View.java:17641)
                                                                at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1079)
                                                                at android.view.View.layout(View.java:17641)
                                                                at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
                                                                at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                at android.view.View.layout(View.java:17641)
                                                                at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1741)
                                                                at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
                                                                at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
                                                                at android.view.View.layout(View.java:17641)
                                                                at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
                                                                at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                at android.view.View.layout(View.java:17641)
                                                                at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1741)
                                                                at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
                                                                at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
                                                                at android.view.View.layout(View.java:17641)
                                                                at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
                                                                at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                at com.android.internal.policy.DecorView.onLayout(DecorView.java:728)
                                                                at android.view.View.layout(View.java:17641)
                                                                at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2346)
                                                                at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2068)
                                                                at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1254)
                                                                at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6343)
                                                                at android.view.Choreographer$CallbackRecord.run(Choreographer.java:874)
                                                                at android.view.Choreographer.doCallbacks(Choreographer.java:686)
                                                                at android.view.Choreographer.doFrame(Choreographer.java:621)
                                                                at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:860)
                                                                at android.os.Handler.handleCallback(Handler.java:751)
                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                at android.os.Looper.loop(Looper.java:154)
                                                                at android.app.ActivityThread.main(ActivityThread.java:6176)
                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888)
                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778)

Thanks a lot in advance....

Body:
It clearly says

android.widget.RelativeLayout$LayoutParams cannot be cast to
  android.widget.LinearLayout$LayoutParams

You are trying to cast LinearLayout.LayoutParams into RelativeLayout.LayoutParams. Its just like trying to convert apple into orange.

Change this:

int match_parent= LinearLayout.LayoutParams.MATCH_PARENT;
int wrap_content= LinearLayout.LayoutParams.WRAP_CONTENT;
chatView.setBackground(context.getResources().getDrawable(R.drawable.incoming_normal));

LinearLayout.LayoutParams parentParams=new LinearLayout.LayoutParams(match_parent,wrap_content);
parentParams.setMarginStart(5);
parent.setLayoutParams(parentParams);

into this and try to run.

int match_parent= RelativeLayout.LayoutParams.MATCH_PARENT;
int wrap_content= RelativeLayout.LayoutParams.WRAP_CONTENT;
chatView.setBackground(context.getResources().getDrawable(R.drawable.incoming_normal));

RelativeLayout.LayoutParams parentParams=new RelativeLayout.LayoutParams(match_parent,wrap_content);
parentParams.setMarginStart(5);
parent.setLayoutParams(parentParams);


来源: stackexchange

问:
Complex html to plain text - Angular 4 / Javascript
I am working on the project and I have a problem. The thing is I need to decode html that I get as a part of JSON object from API. The html is quite tricky so I need to ask for your help guys.

That is the sample value that I need to translate into plain text:

\rSave up to 49% bla bla some text, text, text World of text and text text. For text details of text prices, click on the location required.
\r

To text your text text call

0871 222 text and quote

ELG2017

\r

Yeah I know, it's horrible. Well, that's what I have to decode..

Thanks a lot!

ContentLicense: CC BY-SA 3.0

Body: text.replace(/<[^>]*>/g, '');


问:
How this line is working in this C++ code snippet?
In main function there is a line

```<code>vector<bookStatusEnum> booksStatus(numbooks, available);
</code>```

can you please explain how this line is executing? i see there is no booksStatus function in the code snippet. so what is it actually.

```<code>#include <string>
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>

using namespace std;

struct book
{
    string title, author;

    inline bool operator<(const book& other) const
    {
        if (author != other.author)
            return author < other.author;

        return title < other.title;
    }
};

void ReadInBooks(vector<book> & allBooks)
{
    string temp;

    book currentBook;

    while (cin >> temp, temp != "END")
    {
        currentBook.title = "";

        bool first = true;

        while (*(temp.end() - 1) != '"')
        {
            if (!first)
                currentBook.title += ' ';

            first = false;
            currentBook.title += temp;

            cin >> temp;
        }

        if (!first)
            currentBook.title += ' ';

        currentBook.title += temp;

        // Ignore 'by'
        cin >> temp;
        // ignore the space after the by
        cin.ignore();

        getline(cin, currentBook.author);
        allBooks.push_back(currentBook);
    }
}

enum bookStatusEnum { available, borrowed, returned };

int main()
{
    vector<book> allBooks;
    ReadInBooks(allBooks);
    int numBooks = allBooks.size();
    std::sort(allBooks.begin(), allBooks.end());

    vector<bookStatusEnum> booksStatus(numBooks, available);

    map<string, int> positionInAllBooks;
    for (int i = 0; i < numBooks; ++i)
        positionInAllBooks[allBooks[i].title] = i;

    vector<bool> borrowed(allBooks.size(), false);
    vector<bool> returned(allBooks.size(), false);

    string command;
    string bookName;
    while (cin >> command, command != "END")
    {
        if (command == "BORROW")
        {
            cin.ignore();
            getline(cin, bookName);
            int pos = positionInAllBooks[bookName];
            borrowed[pos] = true;
            returned[pos] = false;
        }

        else if (command == "RETURN")
        {
            cin.ignore();
            getline(cin, bookName);
            returned[positionInAllBooks[bookName]] = true;
        }

        else // SHELVE
        {
            int previous = -1;
            for (int i = 0; i < numBooks; ++i)
            {
                if (!borrowed[i])
                    previous = i;
                else if (returned[i])
                {
                    if (previous == -1)
                        cout << "Put " << allBooks[i].title << " first\n";
                    else
                        cout << "Put " << allBooks[i].title << " after " << allBooks[previous].title << '\n';

                    returned[i] = false;
                    borrowed[i] = false;
                    previous = i;
                }
            }

            cout << "END\n";
        }
    }
}
</code>```

P.S: I didn't find a suitable title for it. please feel free to suggest.

答:
bookStatus is a vector, an array, and it contains elements of type bookStatusEnum.

As stated in the C++ documentation, that constructor should be:

vector(size_type count, const T& value, const Allocator& alloc = Allocator());

Constructs the container with count copies of elements with value value.

So, numbooks is defined as an integer and is the first parameter of the called constructor, therefore that is count, the size of the vector; and available is an enumerator part of bookStatusEnum, the value,  (technically in c++, the enum values by default are some integer type).

Therefore the vector contains numbooks copies of the value available.

```<code>vector<bookStatusEnum> booksStatus(numbooks, available);
</code>```

Body:
In main function there is a line

vector<bookStatusEnum> booksStatus(numbooks, available);

can you please explain how this line is executing? i see there is no booksStatus function in the code snippet. so what is it actually.

#include <string>
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>

using namespace std;

struct book
{
    string title, author;

    inline bool operator<(const book& other) const
    {
        if (author != other.author)
            return author < other.author;

        return title < other.title;
    }
};

void ReadInBooks(vector<book> & allBooks)
{
    string temp;

    book currentBook;

    while (cin >> temp, temp != "END")
    {
        currentBook.title = "";

        bool first = true;

        while (*(temp.end() - 1) != '"')
        {
            if (!first)
                currentBook.title += ' ';

            first = false;
            currentBook.title += temp;

            cin >> temp;
        }

        if (!first)
            currentBook.title += ' ';

        currentBook.title += temp;

        // Ignore 'by'
        cin >> temp;
        // ignore the space after the by
        cin.ignore();

        getline(cin, currentBook.author);
        allBooks.push_back(currentBook);
    }
}

enum bookStatusEnum { available, borrowed, returned };

int main()
{
    vector<book> allBooks;
    ReadInBooks(allBooks);
    int numBooks = allBooks.size();
    std::sort(allBooks.begin(), allBooks.end());

    vector<bookStatusEnum> booksStatus(numBooks, available);

    map<string, int> positionInAllBooks;
    for (int i = 0; i < numBooks; ++i)
        positionInAllBooks[allBooks[i].title] = i;

    vector<bool> borrowed(allBooks.size(), false);
    vector<bool> returned(allBooks.size(), false);

    string command;
    string bookName;
    while (cin >> command, command != "END")
    {
        if (command == "BORROW")
        {
            cin.ignore();
            getline(cin, bookName);
            int pos = positionInAllBooks[bookName];
            borrowed[pos] = true;
            returned[pos] = false;
        }

        else if (command == "RETURN")
        {
            cin.ignore();
            getline(cin, bookName);
            returned[positionInAllBooks[bookName]] = true;
        }

        else // SHELVE
        {
            int previous = -1;
            for (int i = 0; i < numBooks; ++i)
            {
                if (!borrowed[i])
                    previous = i;
                else if (returned[i])
                {
                    if (previous == -1)
                        cout << "Put " << allBooks[i].title << " first\n";
                    else
                        cout << "Put " << allBooks[i].title << " after " << allBooks[previous].title << '\n';

                    returned[i] = false;
                    borrowed[i] = false;
                    previous = i;
                }
            }

            cout << "END\n";
        }
    }
}

P.S: I didn't find a suitable title for it. please feel free to suggest.

Body:
bookStatus is a vector, an array, and it contains elements of type bookStatusEnum.

As stated in the C++ documentation, that constructor should be:

vector(size_type count, const T& value, const Allocator& alloc = Allocator());

Constructs the container with count copies of elements with value value.

So, numbooks is defined as an integer and is the first parameter of the called constructor, therefore that is count, the size of the vector; and available is an enumerator part of bookStatusEnum, the value,  (technically in c++, the enum values by default are some integer type).

Therefore the vector contains numbooks copies of the value available.

vector<bookStatusEnum> booksStatus(numbooks, available);


问:
Returning values with &&
What does it mean to return a value with &&? </p>

```<code>else if (document.defaultView && document.defaultView.getComputedStyle) {

    // It uses the traditional ' text-align' style of rule writing,
    // instead of textAlign
    name = name.replace(/([A-Z]) /g, " -$1" );
    name = name.toLowerCase();
    // Get the style object and get the value of the property (if it exists)
    var s = document.defaultView.getComputedStyle(elem, " ") ;
    return s && s.getPropertyValue(name) ;
</code>```

答:
The logical AND operator, &&,  works similarly.  If the first object is falsy, it returns that object. If it is truthy, it returns the second object. (from https://www.nfriedly.com/techblog/2009/07/advanced-javascript-operators-and-truthy-falsy/).

Interesting stuff!

EDIT:
So, in your case, if document.defaultView.getComputedStyle(elem, " ") does not return a meaningful ("truthy") value, that value is returned. Otherwise, it returns s.getPropertyValue(name).

ContentLicense: CC BY-SA 4.0

Title: Returning values with &&

Body:
What does it mean to return a value with &&?

else if (document.defaultView && document.defaultView.getComputedStyle) {

    // It uses the traditional ' text-align' style of rule writing,
    // instead of textAlign
    name = name.replace(/([A-Z]) /g, " -$1" );
    name = name.toLowerCase();
    // Get the style object and get the value of the property (if it exists)
    var s = document.defaultView.getComputedStyle(elem, " ") ;
    return s && s.getPropertyValue(name) ;


问:
NPM: how to use groan and where to get the php session file name
I want to access php session in nodejs

I searched online and found Read PHP Session data in node.js

and used the sample code from https://www.npmjs.com/package/groan

but it shows the following error:

Error: ENOENT: no such file or directory, open
  '/tmpsess_1234567890abcdef'

答: That's because you pasted the SAMPLE code from the repo. You should probably get that ID (the 1234567890abcdef) from the client cookie where PHP stores the session, and then use that to verify that the file exists and use the parser to retrieve the object.


问:
Full size background image for col-*-* in Bootstrap
i already found some questions regarding this topic but none of them could really help me solving my problem.

I like to build a simple Bootstrap grid looking like this:

```<code><div class="container-fluid">
  <div class="row">
    <div class="col-sm-8"> Some Text </div>
    <div class="col-sm-4">
      <img src="..." alt="Full Size Background Image" />
    </div>
  </div>
  <div class="row">
    <div class="col-sm-4">
      <img src="..." alt="Full Size Background Image" />
    </div>
    <div class="col-sm-8"> Some Text </div>
  </div>
</div>
</code>```

The col-sm-4-DIVs should contain a full size background image with the same height as the text and no padding.

Here's a photo of what I mean. I want the background image to cover the red area:

See Example

Any ideas how to do that?

Thank you very much for your help!!!

答:
First option, you can set min-width:100% in your img tag:

```<code>img {
    min-width: 100%;
}
</code>```

Or Second option, you can set the image as a background and set it in the div that you want:

```<code><div class="col-sm-4 full-img">
</code>```

And the css:

```<code>.full-img {
    background-image: url("....");
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
}
</code>```

Body:
i already found some questions regarding this topic but none of them could really help me solving my problem.

I like to build a simple Bootstrap grid looking like this:

 Some Text

 Some Text

The col-sm-4-DIVs should contain a full size background image with the same height as the text and no padding.

Here's a photo of what I mean. I want the background image to cover the red area:

See Example

Any ideas how to do that?

Thank you very much for your help!!!

Body:
First option, you can set min-width:100% in your img tag:

img {
    min-width: 100%;
}

Or Second option, you can set the image as a background and set it in the div that you want:

<div class="col-sm-4 full-img">

And the css:

.full-img {
    background-image: url("....");
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
}


问:
How to use FFTW wisdom from modern Fortran
I want to use the FFTW wisdom system to remember FFTW plans between jobs. The use of wisdom from a C program is documented here: http://www.fftw.org/fftw2_doc/fftw_2.html  For C, the relevant string would be modified to FFTW_MEASURE | FFTW_USE_WISDOM.  I have tried to emulate that here:

```<code>!! to compile: gfortran -O3 --fast-math -I/usr/include -o usewisdom usewisdom.f90 -lfftw3
</code>```

```<code>Module FFTW3
    use, intrinsic :: iso_c_binding
    include 'fftw3.f03'
End Module FFTW3

Program usewisdom
  use FFTW3
  integer (kind=c_int), parameter :: nx=2048,ny=2048,np=ny/2+1
  real (kind=c_double) :: omega(ny,nx)=1.d0
  complex (kind=c_double_complex) :: fftomega(np,nx)
  ier=fftw_import_wisdom_from_filename("wisdom")
  print *,"wisdom output should not be 0:",ier
  call dfftw_plan_dft_r2c_2d(fwd,ny,nx,omega,fftomega,&
       &FFTW_PATIENT | FFTW_USE_WISDOM)
  call dfftw_execute_dft_r2c(fwd,omega,fftomega) !rem clobbers omega

End Program usewisdom
</code>```

but gfortran doesn't like the string:

```<code>gfortran -O3 --fast-math -I/usr/include -o usewisdom usewisdom.f90 -lfftw3
usewisdom.f90:16:21:

    &FFTW_PATIENT | FFTW_USE_WISDOM)
                 1
Error: Syntax error in argument list at (1)
</code>```

Any suggestions?

答:
According to the Modern Fortran interface documentation:

Multiple planner flags are combined with ior (equivalent to ‘|’ in C). e.g. FFTW_MEASURE | FFTW_DESTROY_INPUT becomes ior(FFTW_MEASURE, FFTW_DESTROY_INPUT). (You can also use ‘+’ as long as you don’t try to include a given flag more than once.)

You should thus include the FFTW_USE_WISDOM planner flag as follows:

```<code>  call dfftw_plan_dft_r2c_2d(fwd,ny,nx,omega,fftomega,&
     &ior(FFTW_PATIENT, FFTW_USE_WISDOM))
</code>```

or

```<code>  call dfftw_plan_dft_r2c_2d(fwd,ny,nx,omega,fftomega,&
     &FFTW_PATIENT + FFTW_USE_WISDOM)
</code>```

Note that a similar syntax for combining flags can also be used for Legacy Fortran as described in this section of the documentation.

Body:
I want to use the FFTW wisdom system to remember FFTW plans between jobs. The use of wisdom from a C program is documented here: http://www.fftw.org/fftw2_doc/fftw_2.html  For C, the relevant string would be modified to FFTW_MEASURE | FFTW_USE_WISDOM.  I have tried to emulate that here:

!! to compile: gfortran -O3 --fast-math -I/usr/include -o usewisdom usewisdom.f90 -lfftw3

Module FFTW3
    use, intrinsic :: iso_c_binding
    include 'fftw3.f03'
End Module FFTW3

Program usewisdom
  use FFTW3
  integer (kind=c_int), parameter :: nx=2048,ny=2048,np=ny/2+1
  real (kind=c_double) :: omega(ny,nx)=1.d0
  complex (kind=c_double_complex) :: fftomega(np,nx)
  ier=fftw_import_wisdom_from_filename("wisdom")
  print *,"wisdom output should not be 0:",ier
  call dfftw_plan_dft_r2c_2d(fwd,ny,nx,omega,fftomega,&
       &FFTW_PATIENT | FFTW_USE_WISDOM)
  call dfftw_execute_dft_r2c(fwd,omega,fftomega) !rem clobbers omega

End Program usewisdom

but gfortran doesn't like the string:

gfortran -O3 --fast-math -I/usr/include -o usewisdom usewisdom.f90 -lfftw3
usewisdom.f90:16:21:

    &FFTW_PATIENT | FFTW_USE_WISDOM)
                 1
Error: Syntax error in argument list at (1)

Any suggestions?

Body:
According to the Modern Fortran interface documentation:

Multiple planner flags are combined with ior (equivalent to ‘|’ in C). e.g. FFTW_MEASURE | FFTW_DESTROY_INPUT becomes ior(FFTW_MEASURE, FFTW_DESTROY_INPUT). (You can also use ‘+’ as long as you don’t try to include a given flag more than once.)

You should thus include the FFTW_USE_WISDOM planner flag as follows:

  call dfftw_plan_dft_r2c_2d(fwd,ny,nx,omega,fftomega,&
     &ior(FFTW_PATIENT, FFTW_USE_WISDOM))

or

  call dfftw_plan_dft_r2c_2d(fwd,ny,nx,omega,fftomega,&
     &FFTW_PATIENT + FFTW_USE_WISDOM)

Note that a similar syntax for combining flags can also be used for Legacy Fortran as described in this section of the documentation.


问:
How to launch Native App from Web app in iPhone?
I want to access TTS (Text-To-Speech) and STT (Speech-To-Text) functionality of iOS from web app. Since web app dont access ios device functions, is it possible to launch Native app from Web app?
e.g. When user wants to access TTS (e.g. Dragon Dictation), web page will launch Native app, take recording and send the recorded text to web app again.

Or we can access TTS/STT functionality right from web app?

答:
The only native apps you can access from web apps are those with custom URL schemes set up, and the built-in ones e.g. SMS (sms://), phone (tel://), iTunes (itms://) and YouTube (http://youtube.com/watch?...).

If the apps you mention don't have their own custom URL schemes which you can use to get to them, there's no other way you can do this.

ContentLicense: CC BY-SA 2.5


问:
jsp List populate into javascript array
I'am trying to pass Spring JavaList over jsp-list to javascript array.

My code:

```<code><c:set var = "currentcars" scope = "session" value = "${cars}"/>
</code>```

Now I want populate content from "currentcars" within jsp into javascript-array, but I am not so familiar with jsp-syntax.

Within jsp:

```<code><script ....>
    var carsArray = new Array();
</script>

<c:forEach items="currentcars" var="car">

    //pseudocode:
    carsArray.push(<c:out value="${car}"/>);

<c:forEach>
</code>```

How could I do that?

答:
In your script tag you can do something like this(car is not primitive type):</p>

```<code>    var carsArray = new Array();
    <c:forEach items="currentcars" var="car">
        c = new Object();
//name property example
        c.name= '${car.name}';
//other properties

        carsArray.push(c);
    </c:forEach>
</code>```

Title: jsp List populate into javascript array

Body:
I'am trying to pass Spring JavaList over jsp-list to javascript array.

My code:

<c:set var = "currentcars" scope = "session" value = "${cars}"/>

Now I want populate content from "currentcars" within jsp into javascript-array, but I am not so familiar with jsp-syntax.

Within jsp:

<c:forEach items="currentcars" var="car">

    //pseudocode:
    carsArray.push(<c:out value="${car}"/>);

<c:forEach>

How could I do that?

Body:
In your script tag you can do something like this(car is not primitive type):

    var carsArray = new Array();
    <c:forEach items="currentcars" var="car">
        c = new Object();
//name property example
        c.name= '${car.name}';
//other properties

        carsArray.push(c);
    </c:forEach>


问:
Combine multiple images and display it in Qt
I am a beginner in OpenCV and Qt, my project now is combining multiple images and display it on Qt Creator.

```<code>#include <stdio.h>
#include <iostream>
#include <mutex>
#include <opencv2/opencv.hpp>
using namespace std;
int main(int argc, char** argv) {
string img_path = "/home/m/pictures/cat.jpg";
std::vector<cv::Mat> img_pool;
for (int i=0;i<10;i++)
{
    cv::Mat data = cv::imread(img_path,-1);
    img_pool.push_back(data);
}
    cv::Mat data = cv::imread(img_path,-1);
cv::namedWindow("image", CV_WINDOW_NORMAL);
cv::imshow("image",data);
cv::waitKey(0);
cv::Mat data_dst = cv::Mat::zeros(500, 500, data.type());
cv::Mat data_resize;

for(int i=0;i<10;i++)
{
    for(int j=0;j<10;j++)
    {
        cv::resize( img_pool[3], data_resize, cv::Size(50,50));
        cv::Rect f_target(i*50,j*50,50,50);
        data_resize.copyTo(data_dst(f_target));
    }
}
cv::namedWindow("image_n", CV_WINDOW_NORMAL);
cv::imshow("image_n",data_dst);
cv::waitKey(0);
return 0;
}
</code>```

Here is the result:

My code now can display one image but what I want to do is display different multiple images, I think I need to load the images or image path to the vector but I failed, so someone can help me?

答:
There is no Qt used in your code. If you want something like this with Qt, you can use a simple widget with a grid layout or a flowlayout. Then load all the images from a path in an array of QImage and the display it.

You can find an example with FlowLayout here. You can use a QLabel to display the image, convert your QImage to QPixmap and the use:

```<code> QImage yourImage("path");
 QLabel image new QLabel(centralwidget);
 imagelabel->setGeometry(QRect(20, 10, 371, 311));
 imagelabel->setPixmap(QPixmap(QPixmap::fromImage(yourImage));
</code>```

If you are new with Qt, you can integrate it easily with QML using a FlowLayout and and array of QML components. Look this example of the usage of an ImageViewer

Body:
I am a beginner in OpenCV and Qt, my project now is combining multiple images and display it on Qt Creator.

#include <stdio.h>
#include <iostream>
#include <mutex>
#include <opencv2/opencv.hpp>
using namespace std;
int main(int argc, char** argv) {
string img_path = "/home/m/pictures/cat.jpg";
std::vector<cv::Mat> img_pool;
for (int i=0;i<10;i++)
{
    cv::Mat data = cv::imread(img_path,-1);
    img_pool.push_back(data);
}
    cv::Mat data = cv::imread(img_path,-1);
cv::namedWindow("image", CV_WINDOW_NORMAL);
cv::imshow("image",data);
cv::waitKey(0);
cv::Mat data_dst = cv::Mat::zeros(500, 500, data.type());
cv::Mat data_resize;

for(int i=0;i<10;i++)
{
    for(int j=0;j<10;j++)
    {
        cv::resize( img_pool[3], data_resize, cv::Size(50,50));
        cv::Rect f_target(i*50,j*50,50,50);
        data_resize.copyTo(data_dst(f_target));
    }
}
cv::namedWindow("image_n", CV_WINDOW_NORMAL);
cv::imshow("image_n",data_dst);
cv::waitKey(0);
return 0;
}

Here is the result:

My code now can display one image but what I want to do is display different multiple images, I think I need to load the images or image path to the vector but I failed, so someone can help me?

Body:
There is no Qt used in your code. If you want something like this with Qt, you can use a simple widget with a grid layout or a flowlayout. Then load all the images from a path in an array of QImage and the display it.

You can find an example with FlowLayout here. You can use a QLabel to display the image, convert your QImage to QPixmap and the use:

 QImage yourImage("path");
 QLabel image new QLabel(centralwidget);
 imagelabel->setGeometry(QRect(20, 10, 371, 311));
 imagelabel->setPixmap(QPixmap(QPixmap::fromImage(yourImage));

If you are new with Qt, you can integrate it easily with QML using a FlowLayout and and array of QML components. Look this example of the usage of an ImageViewer


问:
Making button close a div for whole session
I have some code, which shows a message when the browser window is sized to landscape mode. This works well, but now I want the user to be able to close the message with a button, and that the user only needs to do this once for the whole session. I guess you need sessionStorage for this but I do not know how to code this combined my existing code. Any help would be greatly appreciated.

AN EXAMPLE HERE

```<code>        Please open in "full page" mode and scale your window to a portrait size to see the message appear.
    <br>
    <br>
    <div id="warning-message">
        <button type="button" id="landscape-button">X</button>
        <p><span id="headertext">please rotate your screen</span>
            <br>
            <br>This website is best viewed in landscape mode. So please, rotate your mobile device, and if activated also disable your screen rotation lock. If you prefer to remain in portrait mode, ignore this message and close it at the "x".</p>
    </div>

#warning-message {
    display: none;
}

@media only screen and (orientation:portrait) {
    #warning-message {
        display: block;
    }
}

@media only screen and (orientation:landscape) {
    #warning-message {
        display: none;
    }
}

#warning-message {
    position: fixed;
    margin: 0 auto 0 auto;
    z-index: 99999999;
    background-color: #2A3847;
    width: 90vw;
    min-height: 90vh;
    text-align: center;
    padding: 25px 15px 35px 15px;
    right: 0;
    left: 0;
}

#landscape-button {
    background-color: #2A3847;
    color: #ffffff;
    border-radius: 0px;
    border: 1px solid white;
    padding: 10px 10px 10px 10px;
    float: right;
    margin-top: -25px;
    margin-right: -15px;
    font-size: 1.3em;
}

p {
    font-size: 1.3em;
    color: #ffffff;
    positie: absolute;
    text-align: center;
    "><span style="margin: 0 0 0 25px;
    text-align: center;
    font-size: 1.5em;
    letter-spacing: -0.04em;
}

#headertext {
    margin: 0 0 0 25px;
    text-align: center;
    font-size: 2em;
    letter-spacing: -0.04em;
}
</code>```

答:
```<code>$('#warning-message').on('click',function(){
var data = sessionStorage.getItem('isfirst');
if(data == undefined)
{
sessionStorage.setItem('isfirst', 'true');
//close the pop
}
})
</code>```

Now each time check

```<code>sessionStorage.getItem('isfirst');
</code>```

this will be stored thought the session

Body:
I have some code, which shows a message when the browser window is sized to landscape mode. This works well, but now I want the user to be able to close the message with a button, and that the user only needs to do this once for the whole session. I guess you need sessionStorage for this but I do not know how to code this combined my existing code. Any help would be greatly appreciated.

AN EXAMPLE HERE

        Please open in "full page" mode and scale your window to a portrait size to see the message appear.

        <button type="button" id="landscape-button">X</button>

please rotate your screen

This website is best viewed in landscape mode. So please, rotate your mobile device, and if activated also disable your screen rotation lock. If you prefer to remain in portrait mode, ignore this message and close it at the "x".

#warning-message {
    display: none;
}

@media only screen and (orientation:portrait) {
    #warning-message {
        display: block;
    }
}

@media only screen and (orientation:landscape) {
    #warning-message {
        display: none;
    }
}

#warning-message {
    position: fixed;
    margin: 0 auto 0 auto;
    z-index: 99999999;
    background-color: #2A3847;
    width: 90vw;
    min-height: 90vh;
    text-align: center;
    padding: 25px 15px 35px 15px;
    right: 0;
    left: 0;
}

#landscape-button {
    background-color: #2A3847;
    color: #ffffff;
    border-radius: 0px;
    border: 1px solid white;
    padding: 10px 10px 10px 10px;
    float: right;
    margin-top: -25px;
    margin-right: -15px;
    font-size: 1.3em;
}

p {
    font-size: 1.3em;
    color: #ffffff;
    positie: absolute;
    text-align: center;
    "><span style="margin: 0 0 0 25px;
    text-align: center;
    font-size: 1.5em;
    letter-spacing: -0.04em;
}

#headertext {
    margin: 0 0 0 25px;
    text-align: center;
    font-size: 2em;
    letter-spacing: -0.04em;
}

Body:
$('#warning-message').on('click',function(){
var data = sessionStorage.getItem('isfirst');
if(data == undefined)
{
sessionStorage.setItem('isfirst', 'true');
//close the pop
}
})

Now each time check

sessionStorage.getItem('isfirst');

this will be stored thought the session


问:
Find city radius
I am working on an app where I need to check if some points are within a city or X km outside of it, so I need to find the city's radius then add the X variable to it. I've been looking on Google Maps and OpenStreetMap and I could not find such info.
Is there any API that provides the city's average width? Or distance between the center and the edge?</p>

答:
Based on the Latitude & Longitude of two given points, you can find the distance between those points.

So fetch the Location (Latitude & Longitude) for the centre of city and the point needed, using Google Maps API's and find out the distance implementing the logic.

Logic is described in below link :
http://www.movable-type.co.uk/scripts/latlong.html

Post calculation of distance, you verify if it is in the required range based on X.

Title: Find city radius


问:
Substring is not found in string
I use bash version 3.2.51(1)

I work with job chains and want to start a new job when the old one is finished.
So I check which jobs are currently running and only if the job number of the last run can not be found, a new job is to be submitted.

Here is the part of my script:

```<code>    Job_ID=$(msub -E fvcom.pbs)

    # test whether job is still running

    CONTINUE="just started"
    # do this loop, until the CONTINUE variable is empty (i.e. job is finished)
    until [ -z "$CONTINUE" ] ; do
       # wait $WAIT seconds
       sleep $WAIT
       # query if job is still running
       RUNNING=$(./show_my_run)
      echo $RUNNING
      echo $Job_ID

       # check whether specific job is still running
       # then job ID is present in job overview
       if [[ $RUNNING == *"$Job_ID"* ]] ; then
       CONTINUE="Job_ID found"
       echo $CONTINUE
       else
       CONTINUE=""
       echo "Job_ID not found"
       fi

    done
</code>```

The output is:

city.12345/1202110.batch.com kdd046 Running 4 00:59:14 Tue Jul 4

city.12345

Job_ID not found

Obviously I can see that Job_ID is present and the job is still running...
The pattern is only recognized if there are several jobs running and the pattern is somewhere in the middle:

city.54321/1202133.batch.com kdd046 Running 4 00:59:14 Tue Jul 4  city.12345/1202110.batch.com kdd046 Running 4 00:56:19 Tue Jul 4

city.12345

Job_ID found

I also tried using

...

if echo "$RUNNING" | grep -q "$Job_ID"; then

...

but with same results.

What am I doing wrong?

答:
Try this:

```<code>RUNNING="city.12345/test"
Job_ID="city.12345"

if [[ "$RUNNING" =~ ".*$Job_ID*" ]]; then
echo "match"
fi
</code>```

(edit: now, if X contains Y)

Title: Substring is not found in string

Body:
I use bash version 3.2.51(1)

I work with job chains and want to start a new job when the old one is finished.
So I check which jobs are currently running and only if the job number of the last run can not be found, a new job is to be submitted.

Here is the part of my script:

    Job_ID=$(msub -E fvcom.pbs)

    # test whether job is still running

    CONTINUE="just started"
    # do this loop, until the CONTINUE variable is empty (i.e. job is finished)
    until [ -z "$CONTINUE" ] ; do
       # wait $WAIT seconds
       sleep $WAIT
       # query if job is still running
       RUNNING=$(./show_my_run)
      echo $RUNNING
      echo $Job_ID

       # check whether specific job is still running
       # then job ID is present in job overview
       if [[ $RUNNING == *"$Job_ID"* ]] ; then
       CONTINUE="Job_ID found"
       echo $CONTINUE
       else
       CONTINUE=""
       echo "Job_ID not found"
       fi

    done

The output is:

city.12345/1202110.batch.com kdd046 Running 4 00:59:14 Tue Jul 4

city.12345

Job_ID not found

Obviously I can see that Job_ID is present and the job is still running...
The pattern is only recognized if there are several jobs running and the pattern is somewhere in the middle:

city.54321/1202133.batch.com kdd046 Running 4 00:59:14 Tue Jul 4  city.12345/1202110.batch.com kdd046 Running 4 00:56:19 Tue Jul 4

city.12345

Job_ID found

I also tried using

...

if echo "$RUNNING" | grep -q "$Job_ID"; then

...

but with same results.

What am I doing wrong?

Body:
Try this:

RUNNING="city.12345/test"
Job_ID="city.12345"

if [[ "$RUNNING" =~ ".*$Job_ID*" ]]; then
echo "match"
fi

(edit: now, if X contains Y)


问:
What are the best steps to install ZeroMQ in Windows 10 64 bit?
I am trying to install ZeroMQ in my windows.

I have xampp and php version 7.0, so what are the best steps to install this library?

答:
Try this

You can directly download and install .exe file


问:
length function not giving output
$select.Length is not giving output. Please find code below:

```<code>clear
$filePath = "c:\temp\result.txt"
$select = Select-String -Pattern "Final result:" -Path 'C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Log\Summary.txt' #| Out-File c:\pattern.txt
$select1 = Select-String -Pattern "Final result:" -Path 'C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Log\Summary.txt' | Out-File D:\temp\pattern.txt
Write-Host($select.Length)

if ($select.Length -gt 0) {
    Write-Host 'Contains String'
    $select2 = Select-String -Pattern "Passed" -Path 'D:\temp\pattern.txt'

    if ($select2.Length -gt 0) {
        #Out-File C:\temp\result.txt $filePath -Append
        New-Item $filePath -ItemType file
        'Success' | Out-File -FilePath $filePath -Append
    } else {
        New-Item $filePath -ItemType file
        'Failed' | Out-File -FilePath $filePath -Append
    }
} else {
    Write-Host 'Does not contain String'
}
</code>```

Ideally it should generate file with success as text in result.txt, but it's not working. I'm not getting any error.

答:
this will count the matches:</p>

```<code>$select2.Matches.Count
</code>```

Title: length function not giving output

Body:
$select.Length is not giving output. Please find code below:

clear
$filePath = "c:\temp\result.txt"
$select = Select-String -Pattern "Final result:" -Path 'C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Log\Summary.txt' #| Out-File c:\pattern.txt
$select1 = Select-String -Pattern "Final result:" -Path 'C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Log\Summary.txt' | Out-File D:\temp\pattern.txt
Write-Host($select.Length)

if ($select.Length -gt 0) {
    Write-Host 'Contains String'
    $select2 = Select-String -Pattern "Passed" -Path 'D:\temp\pattern.txt'

    if ($select2.Length -gt 0) {
        #Out-File C:\temp\result.txt $filePath -Append
        New-Item $filePath -ItemType file
        'Success' | Out-File -FilePath $filePath -Append
    } else {
        New-Item $filePath -ItemType file
        'Failed' | Out-File -FilePath $filePath -Append
    }
} else {
    Write-Host 'Does not contain String'
}

Ideally it should generate file with success as text in result.txt, but it's not working. I'm not getting any error.

Body:
this will count the matches:

$select2.Matches.Count


问:
FileNotFoundError: [Errno 2] No such file or directory with ABSOLUTE file path
I have read through several other questions about this topic, but none seem to work.

Here's my code:

```<code>fileIN_csv = "C:/OpenWeatherMap_Stockholm_bulk_5years.csv"
with open(fileIN_csv) as csvfile:
    readCSV = csv.reader(csvfile, delimeter=',')
</code>```

And here is proof of the file's path:
File Path

And here is the specific error:

```<code>FileNotFoundError: [Errno 2] No such file or directory:
'C:/OpenWeatherMap_Stockholm_bulk_5years.csv'
</code>```

答:
What does

```<code>from pathlib import Path

file_path = Path('C:/OpenWeatherMap_Stockholm_bulk_5years.csv')
print(file_path, file_path.exists())
</code>```

say?

Body:
I have read through several other questions about this topic, but none seem to work.

Here's my code:

fileIN_csv = "C:/OpenWeatherMap_Stockholm_bulk_5years.csv"
with open(fileIN_csv) as csvfile:
    readCSV = csv.reader(csvfile, delimeter=',')

And here is proof of the file's path:
File Path

And here is the specific error:

FileNotFoundError: [Errno 2] No such file or directory:
'C:/OpenWeatherMap_Stockholm_bulk_5years.csv'

Body:
What does

from pathlib import Path

file_path = Path('C:/OpenWeatherMap_Stockholm_bulk_5years.csv')
print(file_path, file_path.exists())

say?


问:
Calculate business hours between two dates
How can I calculate business hours between two dates?
For example we have two dates; 01/01/2010 15:00 and 04/01/2010 12:00
And we have working hours 09:00 to 17:00 in weekdays
How can I calculate working hours with sql?</p>

答:
The first step would be to calculate working days, as shown in the script below:

```<code>DECLARE @TotalWorkDays INT, @TotalTimeDiff DECIMAL(18, 2), @DateFrom DATETIME, @DateTo DATETIME;
SET @DateFrom = '2017-06-05 11:19:11.287';
SET @DateTo = '2017-06-07 09:53:14.750';

SET @TotalWorkDays = DATEDIFF(DAY, @DateFrom, @DateTo)
    -(DATEDIFF(WEEK, @DateFrom, @DateTo) * 2)
   -CASE
                                    WHEN DATENAME(WEEKDAY, @DateFrom) = 'Sunday'
                                    THEN 1
                                    ELSE 0
                                END+CASE
                                        WHEN DATENAME(WEEKDAY, @DateTo) = 'Saturday'
                                        THEN 1
                                        ELSE 0
                                    END;
</code>```

The second step involves getting a difference in seconds between the two dates and converting that difference into hours by dividing by 3600.0 as shown in this following script:

```<code>SET @TotalTimeDiff =
(
    SELECT DATEDIFF(SECOND,
                   (
                       SELECT CONVERT(TIME, @DateFrom)
                   ),
                   (
                       SELECT CONVERT(TIME, @DateTo)
                   )) / 3600.0
);
</code>```

The last part involves multiplying the output the first step above by 24 (total number of hours in a day) and then later adding that to the output of the second step:

```<code>SELECT(@TotalWorkDays * 24.00) + @TotalTimeDiff;
</code>```

Finally, the complete script that can be used to create a user defined function for calculating working hours is shown below:

```<code>CREATE FUNCTION [dbo].[fn_GetTotalWorkingHours]
(
    @DateFrom Datetime,
    @DateTo Datetime
)
RETURNS DECIMAL(18,2)
AS
BEGIN

DECLARE @TotalWorkDays INT, @TotalTimeDiff DECIMAL(18, 2)

SET @TotalWorkDays = DATEDIFF(DAY, @DateFrom, @DateTo)
    -(DATEDIFF(WEEK, @DateFrom, @DateTo) * 2)
   -CASE
                                    WHEN DATENAME(WEEKDAY, @DateFrom) = 'Sunday'
                                    THEN 1
                                    ELSE 0
                                END+CASE
                                        WHEN DATENAME(WEEKDAY, @DateTo) = 'Saturday'
                                        THEN 1
                                        ELSE 0
                                    END;
SET @TotalTimeDiff =
(
    SELECT DATEDIFF(SECOND,
                   (
                       SELECT CONVERT(TIME, @DateFrom)
                   ),
                   (
                       SELECT CONVERT(TIME, @DateTo)
                   )) / 3600.0
);

RETURN  (SELECT(@TotalWorkDays * 24.00) + @TotalTimeDiff)

END
GO
</code>```

The complete method is descibed in this article:
https://www.sqlshack.com/how-to-calculate-work-days-and-hours-in-sql-server/

Body:
The first step would be to calculate working days, as shown in the script below:

DECLARE @TotalWorkDays INT, @TotalTimeDiff DECIMAL(18, 2), @DateFrom DATETIME, @DateTo DATETIME;
SET @DateFrom = '2017-06-05 11:19:11.287';
SET @DateTo = '2017-06-07 09:53:14.750';

SET @TotalWorkDays = DATEDIFF(DAY, @DateFrom, @DateTo)
    -(DATEDIFF(WEEK, @DateFrom, @DateTo) * 2)
   -CASE
                                    WHEN DATENAME(WEEKDAY, @DateFrom) = 'Sunday'
                                    THEN 1
                                    ELSE 0
                                END+CASE
                                        WHEN DATENAME(WEEKDAY, @DateTo) = 'Saturday'
                                        THEN 1
                                        ELSE 0
                                    END;

The second step involves getting a difference in seconds between the two dates and converting that difference into hours by dividing by 3600.0 as shown in this following script:

SET @TotalTimeDiff =
(
    SELECT DATEDIFF(SECOND,
                   (
                       SELECT CONVERT(TIME, @DateFrom)
                   ),
                   (
                       SELECT CONVERT(TIME, @DateTo)
                   )) / 3600.0
);

The last part involves multiplying the output the first step above by 24 (total number of hours in a day) and then later adding that to the output of the second step:

SELECT(@TotalWorkDays * 24.00) + @TotalTimeDiff;

Finally, the complete script that can be used to create a user defined function for calculating working hours is shown below:

CREATE FUNCTION [dbo].[fn_GetTotalWorkingHours]
(
    @DateFrom Datetime,
    @DateTo Datetime
)
RETURNS DECIMAL(18,2)
AS
BEGIN

DECLARE @TotalWorkDays INT, @TotalTimeDiff DECIMAL(18, 2)

SET @TotalWorkDays = DATEDIFF(DAY, @DateFrom, @DateTo)
    -(DATEDIFF(WEEK, @DateFrom, @DateTo) * 2)
   -CASE
                                    WHEN DATENAME(WEEKDAY, @DateFrom) = 'Sunday'
                                    THEN 1
                                    ELSE 0
                                END+CASE
                                        WHEN DATENAME(WEEKDAY, @DateTo) = 'Saturday'
                                        THEN 1
                                        ELSE 0
                                    END;
SET @TotalTimeDiff =
(
    SELECT DATEDIFF(SECOND,
                   (
                       SELECT CONVERT(TIME, @DateFrom)
                   ),
                   (
                       SELECT CONVERT(TIME, @DateTo)
                   )) / 3600.0
);

RETURN  (SELECT(@TotalWorkDays * 24.00) + @TotalTimeDiff)

END
GO

The complete method is descibed in this article:
https://www.sqlshack.com/how-to-calculate-work-days-and-hours-in-sql-server/


问:
SSH Tunnel Issue
I'm trying to tunnel to a remote VM.

I previously used the below command:

```<code>ssh -N -p 22 username@1.2.3.4 -o StrictHostKeyChecking=no -L 127.0.0.1:8080:5.6.7.8:443
</code>```

Something went wrong with the server at the weekend and the SA had to restore the image.

Now when I try to do this I get prompted with the following:

```<code>Permission denied, please try again.
username@1.2.3.4's password:
</code>```

I don't know what this password should be and the SA isn't available.
I am able to ssh directly onto 1.2.3.4 using my public key and when on it I can ssh onto 5.6.7.8 with this command:

```<code>ssh -A blueboxadmin@5.6.7.8
</code>```

Is there any way I can use this to tunnel right through. Failing that, is there anything I can setup on 1.2.3.4 that will allow me to tunnel through?

答:
Looks like the ssh key value pair is missing from the remote server.

You will have to copy the entry of you server ssh key (from $HOME/.ssh/id_rsa.pub file) into the remote server's $HOME/.ssh/authorized_keys file. Make sure the key is pasted in a single line. After doing this, you should be able to connect.

Title: SSH Tunnel Issue

Body:
I'm trying to tunnel to a remote VM.

I previously used the below command:

ssh -N -p 22 username@1.2.3.4 -o StrictHostKeyChecking=no -L 127.0.0.1:8080:5.6.7.8:443

Something went wrong with the server at the weekend and the SA had to restore the image.

Now when I try to do this I get prompted with the following:

Permission denied, please try again.
username@1.2.3.4's password:

I don't know what this password should be and the SA isn't available.
I am able to ssh directly onto 1.2.3.4 using my public key and when on it I can ssh onto 5.6.7.8 with this command:

ssh -A blueboxadmin@5.6.7.8

Is there any way I can use this to tunnel right through. Failing that, is there anything I can setup on 1.2.3.4 that will allow me to tunnel through?


问:
CURL: have to specify cacert
I've got problem with curl and https. I have to specify cacert at every request, can somebody tell me what to do? I use debian jessie.

```<code>$ curl -XGET --cacert /etc/ssl/certs/ca-certificates.crt 'https://www.google.com'
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>302 Moved</TITLE></HEAD><BODY>
<H1>302 Moved</H1>
The document has moved
<A HREF="https://www.google.fr/?gfe_rd=cr&ei=M69TWfebI4P_8AeJ1KPACA">here</A>.
</BODY></HTML>
</code>```

when I don't specify the cacert:

```<code>$ curl -XGET 'https://www.google.com' -v
* Rebuilt URL to: https://www.google.com/
* Hostname was NOT found in DNS cache
*   Trying 216.58.204.132...
* Connected to www.google.com (216.58.204.132) port 443 (#0)
* successfully set certificate verify locations:
*   CAfile: none
  CApath: /etc/ssl/certs
* SSLv3, TLS Unknown, Unknown (22):
* SSLv3, TLS handshake, Client hello (1):
* SSLv2, Unknown (22):
* SSLv3, TLS handshake, Server hello (2):
* SSLv2, Unknown (22):
* SSLv3, TLS handshake, CERT (11):
* SSLv2, Unknown (21):
* SSLv3, TLS alert, Server hello (2):
* SSL certificate problem: unable to get local issuer certificate
* Closing connection 0
* SSLv2, Unknown (21):
* SSLv3, TLS alert, Client hello (1):
curl: (60) SSL certificate problem: unable to get local issuer certificate
More details here: http://curl.haxx.se/docs/sslcerts.html

curl performs SSL certificate verification by default, using a "bundle"
 of Certificate Authority (CA) public keys (CA certs). If the default
 bundle file isn't adequate, you can specify an alternate file
 using the --cacert option.
If this HTTPS server uses a certificate signed by a CA represented in
 the bundle, the certificate verification probably failed due to a
 problem with the certificate (it might be expired, or the name might
 not match the domain name in the URL).
If you'd like to turn off curl's verification of the certificate, use
 the -k (or --insecure) option.
</code>```

Of course I don't want to ignore certification, I'd like to solve the issue.

My curl version:

```<code>$ curl --version
curl 7.38.0 (x86_64-pc-linux-gnu) libcurl/7.38.0 OpenSSL/1.0.2k zlib/1.2.8 libidn/1.29 libssh2/1.4.3 librtmp/2.3
Protocols: dict file ftp ftps gopher http https imap imaps ldap ldaps pop3 pop3s rtmp rtsp scp sftp smtp smtps telnet tftp
Features: AsynchDNS IDN IPv6 Largefile GSS-API SPNEGO NTLM NTLM_WB SSL libz TLS-SRP
</code>```

答:
From the -v output looks like it is getting to the correct folder but unable to get a cert

```<code>* successfully set certificate verify locations:
*   CAfile: none
  CApath: /etc/ssl/certs
</code>```

Try doing this to update the current CA list.

```<code>cd /etc/ssl/certs
sudo wget http://curl.haxx.se/ca/cacert.pem
</code>```

I think curl looks into the .pem file and not the .crt file.  Also see this thread https://serverfault.com/questions/151157/ubuntu-10-04-curl-how-do-i-fix-update-the-ca-bundle

Title: CURL: have to specify cacert

Body:
I've got problem with curl and https. I have to specify cacert at every request, can somebody tell me what to do? I use debian jessie.

$ curl -XGET --cacert /etc/ssl/certs/ca-certificates.crt 'https://www.google.com'
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>302 Moved</TITLE>

302 Moved

The document has moved
here.

when I don't specify the cacert:

$ curl -XGET 'https://www.google.com' -v
* Rebuilt URL to: https://www.google.com/
* Hostname was NOT found in DNS cache
*   Trying 216.58.204.132...
* Connected to www.google.com (216.58.204.132) port 443 (#0)
* successfully set certificate verify locations:
*   CAfile: none
  CApath: /etc/ssl/certs
* SSLv3, TLS Unknown, Unknown (22):
* SSLv3, TLS handshake, Client hello (1):
* SSLv2, Unknown (22):
* SSLv3, TLS handshake, Server hello (2):
* SSLv2, Unknown (22):
* SSLv3, TLS handshake, CERT (11):
* SSLv2, Unknown (21):
* SSLv3, TLS alert, Server hello (2):
* SSL certificate problem: unable to get local issuer certificate
* Closing connection 0
* SSLv2, Unknown (21):
* SSLv3, TLS alert, Client hello (1):
curl: (60) SSL certificate problem: unable to get local issuer certificate
More details here: http://curl.haxx.se/docs/sslcerts.html

curl performs SSL certificate verification by default, using a "bundle"
 of Certificate Authority (CA) public keys (CA certs). If the default
 bundle file isn't adequate, you can specify an alternate file
 using the --cacert option.
If this HTTPS server uses a certificate signed by a CA represented in
 the bundle, the certificate verification probably failed due to a
 problem with the certificate (it might be expired, or the name might
 not match the domain name in the URL).
If you'd like to turn off curl's verification of the certificate, use
 the -k (or --insecure) option.

Of course I don't want to ignore certification, I'd like to solve the issue.

My curl version:

$ curl --version
curl 7.38.0 (x86_64-pc-linux-gnu) libcurl/7.38.0 OpenSSL/1.0.2k zlib/1.2.8 libidn/1.29 libssh2/1.4.3 librtmp/2.3
Protocols: dict file ftp ftps gopher http https imap imaps ldap ldaps pop3 pop3s rtmp rtsp scp sftp smtp smtps telnet tftp
Features: AsynchDNS IDN IPv6 Largefile GSS-API SPNEGO NTLM NTLM_WB SSL libz TLS-SRP

Body:
From the -v output looks like it is getting to the correct folder but unable to get a cert

* successfully set certificate verify locations:
*   CAfile: none
  CApath: /etc/ssl/certs

Try doing this to update the current CA list.

cd /etc/ssl/certs
sudo wget http://curl.haxx.se/ca/cacert.pem

I think curl looks into the .pem file and not the .crt file.  Also see this thread https://serverfault.com/questions/151157/ubuntu-10-04-curl-how-do-i-fix-update-the-ca-bundle


问:
Format text in string as hh:mm:ss, hours only when needed
I'd like to format some text in a string. So if I input the text 0759, it should format it to 07:59 (minutes and seconds).

Same it should work like this (pseudocode)

input 759 -> output 07:59

input 10545 -> output 01:05:45 (hours, minutes, seconds)

input 5 -> output 00:05

I thought about using string.Format() but I as a newbie I don't really know how to do that.

Thanks!

答:
```<code>List<string> inputs = new List<string> { "78", "10545", "5" };
IEnumerable<TimeSpan> timeSpans = inputs
    .Select(i => TryParseTimeSpan(i))
    .Where(ts => ts.HasValue)
    .Select(ts => ts.Value);
foreach (TimeSpan ts in timeSpans)
    Console.WriteLine(ts.ToString());
</code>```


问:
Swift - Whitespace count in a string
How do you get the count of the empty space within text?

It would be more helpful to me if explained with an example.

答:
If you want to consider other whitespace characters (not only space) use regular expression:

```<code>let string = "How to get count of the empty space in text,Like how we get character count like wise i need empty space count in a text, It would be more helpful if explained with an example."

let regex = try! NSRegularExpression(pattern: "\\s")
let numberOfWhitespaceCharacters = regex.numberOfMatches(in: string, range: NSRange(location: 0, length: string.utf16.count))
</code>```

Regular expression \\s considers tab, cr, lf and space

Title: Swift - Whitespace count in a string

Body:
If you want to consider other whitespace characters (not only space) use regular expression:

let string = "How to get count of the empty space in text,Like how we get character count like wise i need empty space count in a text, It would be more helpful if explained with an example."

let regex = try! NSRegularExpression(pattern: "\\s")
let numberOfWhitespaceCharacters = regex.numberOfMatches(in: string, range: NSRange(location: 0, length: string.utf16.count))

Regular expression \\s considers tab, cr, lf and space


问:
sqlite3.OperationalError python
so what i'am basically trying to do is getting data from a from developed with pyqt and insert it into a database, the problem is with my ID column,this is the code i'am using to insert the data to the database :

```<code>connection.execute("INSERT INTO UTILISATEURS VALUES (?,?,?,?,?,?) ",(fullname,email,cin,address,phonenumber,ribnumber))
</code>```

i always get this error :

```<code>sqlite3.OperationalError: table UTILISATEURS has 7 columns but 6 values were supplied
</code>```

when i enter a query to insert into the table directly from sqlite cli i get the results desired without needing to insert the ID it automatically autoincrements

here is the output of the .schema command :

```<code>sqlite> .schema
CREATE TABLE ADMINSS(USERNAME TEXT NOT NULL,PASSWORD TEXT);
CREATE TABLE UTILISATEURS(ID INTEGER PRIMARY KEY,FULLNAME TEXT NOT NULL,EMAIL INT NOT NULL,CIN INTEGER,ADDRESS CHAR(50),PHONE INTEGER,RIB INTEGER);
</code>```

答:
okay i accepted the previous answer but with a slight modification :

```<code>connection.execute("INSERT INTO UTILISATEURS (FULLNAME, EMAIL, CIN, ADDRESS, PHONE, RIB) VALUES (?,?,?,?,?,?) ", (str(fullname), str(email), str(cin), str(address), str(phonenumber), str(ribnumber)))
</code>```

this worked for turns out i should parse to string the values i got from my text box in the form.

Title: sqlite3.OperationalError python

Body:
so what i'am basically trying to do is getting data from a from developed with pyqt and insert it into a database, the problem is with my ID column,this is the code i'am using to insert the data to the database :

connection.execute("INSERT INTO UTILISATEURS VALUES (?,?,?,?,?,?) ",(fullname,email,cin,address,phonenumber,ribnumber))

i always get this error :

sqlite3.OperationalError: table UTILISATEURS has 7 columns but 6 values were supplied

when i enter a query to insert into the table directly from sqlite cli i get the results desired without needing to insert the ID it automatically autoincrements

here is the output of the .schema command :

sqlite> .schema
CREATE TABLE ADMINSS(USERNAME TEXT NOT NULL,PASSWORD TEXT);
CREATE TABLE UTILISATEURS(ID INTEGER PRIMARY KEY,FULLNAME TEXT NOT NULL,EMAIL INT NOT NULL,CIN INTEGER,ADDRESS CHAR(50),PHONE INTEGER,RIB INTEGER);

Body:
okay i accepted the previous answer but with a slight modification :

connection.execute("INSERT INTO UTILISATEURS (FULLNAME, EMAIL, CIN, ADDRESS, PHONE, RIB) VALUES (?,?,?,?,?,?) ", (str(fullname), str(email), str(cin), str(address), str(phonenumber), str(ribnumber)))

this worked for turns out i should parse to string the values i got from my text box in the form.


问:
WooCommerce Subscriptions - Get product of a specific subscription
Is there a way to get from $product from $subscription?

Thanks to this post, I know that from $subscription I can get $order:

```<code>$order = $subscription->order;
</code>```

Is this also possible?

```<code>$product = $subscription->product;
</code>```

Or:

```<code>$product = $order->product;
</code>```

答:
Yes, if you have a "subscription ID" you can get an object like this:

```<code>$subscription = new WC_Subscription( $the_id );
</code>```

When you already have $subscription object:

```<code>$related_orders_ids_array = $subscription->get_related_orders();
</code>```

Then loop through array of related orders.

```<code>foreach ( $related_orders_ids_array as $order_id ) {

    $order = new WC_Order( $order_id );
    $items = $order->get_items();
</code>```

then if you loop through order items, you can access product information:

```<code>    foreach ( $items as $product ) {

        var_dump( $product );

    }

}
</code>```

Body:
Is there a way to get from $product from $subscription?

Thanks to this post, I know that from $subscription I can get $order:

$order = $subscription->order;

Is this also possible?

$product = $subscription->product;

Or:

$product = $order->product;

Body:
Yes, if you have a "subscription ID" you can get an object like this:

$subscription = new WC_Subscription( $the_id );

When you already have $subscription object:

$related_orders_ids_array = $subscription->get_related_orders();

Then loop through array of related orders.

foreach ( $related_orders_ids_array as $order_id ) {

    $order = new WC_Order( $order_id );
    $items = $order->get_items();

then if you loop through order items, you can access product information:

    foreach ( $items as $product ) {

        var_dump( $product );

    }

}


问:
Binding onchange event using JS (Syntax error)
I've recently been spending some time playing with javascript event listeners in an attempt to learn a little more. However I've kinda hit a road block.

I appear to be getting a syntax error, SyntaxError: expected expression, got keyword 'if'.

The Question

If someone could elaborate and explain my mistake to me, I would be thankful. See the Js Fiddle for a more complete example of what I'm tryign to accomplish.

I've attempted to read up a bit more using MDN (This Article Imparticular) as highlighted by the console. However I'm failing to understand, my error and how it coinsides with this article.

```<code>function myFunction() {

  // Text field element.
  var a = document.getElementsByName('field-one')[0];

  // Checkbox element.
  var b = document.getElementById('box-2');

  // Select Element
  var c = document.getElementById('dept');

  // Bind onchange event.
  c.setAttribute('onchange', myFunction()),

  if (b.checked) {
    a.disabled = false;
    a.placeholder = 'Enter Your Full Name.';

  } else {
    a.disabled = true;
    a.placeholder = 'Not Applicable.';
  }

}

function myFunction()
</code>```

JS FIDDLE

Any help with this would be much appreciated.

Regards,

-B.

EDIT TUE 4 JULY

I ended up completely reworking this to try and get things a little smoother. With some help from you all I was able to clarify I few things.

especially the key points highlighted by, @Kind User & @Shaminder S Aujla.

You have used comma instead of semicolon.

If you want to call the function, use just the name of the function.

Don't call the function while binding it.

Calling it like myFunction(); will throw "Too much recursion error".

The resulting change is shown below and you can also see my finished fiddle here;

```<code>window.addEventListener('load', function() {

  // Select Element
  var c = document.getElementById('dept');
  // Text field element.
  var a = document.getElementsByName('field-one')[0];

  // Bind onchange event.
  c.onchange = function() {

    if (this.options[this.selectedIndex].value == 3) {
      a.disabled = false;
      a.placeholder = 'Enter Your Full Name.';
    } else {
      a.disabled = true;
      a.placeholder = 'Not Applicable.';
    }
  }
})
</code>```

Thanks again all,
really appreciate it. :)

Regards,
- B.

答:
You have a syntax error in your code.
This:

```<code> // Bind onchange event.
  c.setAttribute('onchange', myFunction()),
</code>```

Please change to this:

```<code>// Bind onchange event.
  c.setAttribute('onchange', myFunction);
</code>```

Also, when calling function, omit the keyword function:
So, call it like this:

```<code>myFunction();
</code>```

Body:
I've recently been spending some time playing with javascript event listeners in an attempt to learn a little more. However I've kinda hit a road block.

I appear to be getting a syntax error, SyntaxError: expected expression, got keyword 'if'.

The Question

If someone could elaborate and explain my mistake to me, I would be thankful. See the Js Fiddle for a more complete example of what I'm tryign to accomplish.

I've attempted to read up a bit more using MDN (This Article Imparticular) as highlighted by the console. However I'm failing to understand, my error and how it coinsides with this article.

function myFunction() {

  // Text field element.
  var a = document.getElementsByName('field-one')[0];

  // Checkbox element.
  var b = document.getElementById('box-2');

  // Select Element
  var c = document.getElementById('dept');

  // Bind onchange event.
  c.setAttribute('onchange', myFunction()),

  if (b.checked) {
    a.disabled = false;
    a.placeholder = 'Enter Your Full Name.';

  } else {
    a.disabled = true;
    a.placeholder = 'Not Applicable.';
  }

}

function myFunction()

JS FIDDLE

Any help with this would be much appreciated.

Regards,

-B.

EDIT TUE 4 JULY

I ended up completely reworking this to try and get things a little smoother. With some help from you all I was able to clarify I few things.

especially the key points highlighted by, @Kind User & @Shaminder S Aujla.

You have used comma instead of semicolon.

If you want to call the function, use just the name of the function.

Don't call the function while binding it.

Calling it like myFunction(); will throw "Too much recursion error".

The resulting change is shown below and you can also see my finished fiddle here;

window.addEventListener('load', function() {

  // Select Element
  var c = document.getElementById('dept');
  // Text field element.
  var a = document.getElementsByName('field-one')[0];

  // Bind onchange event.
  c.onchange = function() {

    if (this.options[this.selectedIndex].value == 3) {
      a.disabled = false;
      a.placeholder = 'Enter Your Full Name.';
    } else {
      a.disabled = true;
      a.placeholder = 'Not Applicable.';
    }
  }
})

Thanks again all,
really appreciate it. :)

Regards,
- B.

Body:
You have a syntax error in your code.
This:

 // Bind onchange event.
  c.setAttribute('onchange', myFunction()),

Please change to this:

// Bind onchange event.
  c.setAttribute('onchange', myFunction);

Also, when calling function, omit the keyword function:
So, call it like this:

myFunction();