问:
How to use selector to tint ImageView?
I want to tint my tabhost's icons using XML, instead of doing it programmatically (I wasn't able to do that anyway)...

I found this thread on SO: Android imageview change tint to simulate button click

That seems to be a pretty good solution, but I wasn't able to adapt it correctly in my project... I did the following changes:

```<code>public class TintableImageView extends ImageView {
    private ColorStateList tint;

    public TintableImageView(Context context) {
        super(context);
    }

    //this is the constructor that causes the exception
    public TintableImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs, 0);
    }

    public TintableImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context, attrs, defStyle);
    }

    //here, obtainStyledAttributes was asking for an array
    private void init(Context context, AttributeSet attrs, int defStyle) {
        TypedArray a = context.obtainStyledAttributes(attrs, new int[]{R.styleable.TintableImageView_tint}, defStyle, 0);
        tint = a.getColorStateList(R.styleable.TintableImageView_tint);
        a.recycle();
    }

    @Override
    protected void drawableStateChanged() {
        super.drawableStateChanged();
        if (tint != null && tint.isStateful())
            updateTintColor();
    }

    public void setColorFilter(ColorStateList tint) {
        this.tint = tint;
        super.setColorFilter(tint.getColorForState(getDrawableState(), 0));
    }

    private void updateTintColor() {
        int color = tint.getColorForState(getDrawableState(), 0);
        setColorFilter(color);
    }

}
</code>```

I also wasn't able to reference @drawable/selector.xml at android:tint, so I did this at colors.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="azulPadrao">#2e7cb4</color>
<drawable name="tab_icon_selector">@drawable/tab_icon_selector</drawable>
</resources>
</code>```

My selector:

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

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" android:tint="#007AFF" />
<item android:state_focused="true" android:tint="#007AFF" />
<item android:state_pressed="true" android:tint="#007AFF" />
<item android:tint="#929292" />
</selector>
</code>```

My tab layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:orientation="vertical" android:id="@+id/TabLayout"
          android:layout_width="fill_parent" android:layout_height="fill_parent"
          android:gravity="center" android:background="@drawable/tab_bg_selector">

<com.myapp.TintableImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageView" android:layout_gravity="center" android:tint="@drawable/tab_icon_selector"/>
<TextView android:id="@+id/TabTextView" android:text="Text"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content" android:textColor="@drawable/tab_text_selector"
          android:textSize="10dip"
          android:textStyle="bold" android:layout_marginTop="2dip"/>

</LinearLayout>
</code>```

Any suggestions? Thanks in advance

EDIT

I was getting a NumberFormatException for using android:tint, when the correct was app:tint (after setting xmlns:app="http://schemas.android.com/apk/res/com.myapp")... but now I think I'm using my selector in a wrong way, because the icons are all black, no matter the state...
I've tried setting <drawable name="tab_icon_selector">@drawable/tab_icon_selector</drawable> from within colors.xml, didn't work

答:
I agree with @Dreaming in Code and I will give an example.

ic_up_small

```<code><selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:color="@color/comment_count_selected_color" android:state_selected="true" />
    <item android:color="@color/comment_count_text_color"/>

</selector>
</code>```

layout/item_post_count_info.xml

```<code><android.support.v7.widget.AppCompatImageView
    android:id="@+id/post_upvote_icon"
    android:layout_width="14dp"
    android:layout_height="14dp"
    android:layout_marginLeft="17dp"
    app:srcCompat="@drawable/ic_up_small"
    app:tint="@color/post_up_color"/>
</code>```

Attention: We should use app:tint instead of android:tint.

My support library version is 26.0.2.

app/build.gradle

```<code>implementation 'com.android.support:appcompat-v7:26.0.2'
implementation 'com.android.support:support-core-utils:26.0.2'
implementation 'com.android.support:support-annotations:26.0.2'
implementation 'com.android.support:support-v4:26.0.2'
implementation 'com.android.support:design:26.0.2'
</code>```

If we use android:tint, it will crash and the log is like this:

E/AndroidRuntime: FATAL EXCEPTION: main
                                                                    android.view.InflateException: Binary XML file line #0: Error
  inflating class
                                                                        at android.view.LayoutInflater.createView(LayoutInflater.java:613)
                                                                        at
  android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:687)
                                                                        at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
                                                                        at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
                                                                        at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
                                                                        at
  com.opera.six.viewholder.post.PostCountInfoViewHolder$1.create(PostCountInfoViewHolder.java:29)
                                                                        at
  com.opera.six.viewholder.post.PostCountInfoViewHolder$1.create(PostCountInfoViewHolder.java:25)
                                                                        at
  com.opera.six.collection.CollectionAdapter.onCreateViewHolder(CollectionAdapter.java:39)
                                                                        at
  com.opera.six.collection.CollectionAdapter.onCreateViewHolder(CollectionAdapter.java:19)
                                                                        at
  android.support.v7.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:6493)
                                                                        at
  android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5680)
                                                                        at
  android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5563)
                                                                        at
  android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5559)
                                                                        at
  android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2229)
                                                                        at
  android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1556)
                                                                        at
  android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1516)
                                                                        at
  android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:608)
                                                                        at
  android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3693)
                                                                        at
  android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3410)
                                                                        at
  android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3962)
                                                                        at android.view.View.layout(View.java:13754)
                                                                        at android.view.ViewGroup.layout(ViewGroup.java:4364)
                                                                        at
  android.support.v4.widget.SwipeRefreshLayout.onLayout(SwipeRefreshLayout.java:610)
                                                                        at android.view.View.layout(View.java:13754)
                                                                        at android.view.ViewGroup.layout(ViewGroup.java:4364)
                                                                        at
  android.support.design.widget.HeaderScrollingViewBehavior.layoutChild(HeaderScrollingViewBehavior.java:132)
                                                                        at
  android.support.design.widget.ViewOffsetBehavior.onLayoutChild(ViewOffsetBehavior.java:42)
                                                                        at
  android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onLayoutChild(AppBarLayout.java:1361)
                                                                        at
  android.support.design.widget.CoordinatorLayout.onLayout(CoordinatorLayout.java:869)
                                                                        at android.view.View.layout(View.java:13754)
                                                                        at android.view.ViewGroup.layout(ViewGroup.java:4364)
                                                                        at android.support.v4.view.ViewPager.onLayout(ViewPager.java:1767)
                                                                        at android.view.View.layout(View.java:13754)
                                                                        at android.view.ViewGroup.layout(ViewGroup.java:4364)
                                                                        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1649)
                                                                        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1507)
                                                                        at android.widget.LinearLayout.onLayout(LinearLayout.java:1420)
                                                                        at android.view.View.layout(View.java:13754)
                                                                        at android.view.ViewGroup.layout(ViewGroup.java:4364)
                                                                        at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
                                                                        at android.view.View.layout(View.java:13754)
                                                                        at android.view.ViewGroup.layout(ViewGroup.java:4364)
                                                                        at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
                                                                        at android.view.View.layout(View.java:13754)
                                                                        at android.view.ViewGroup.layout(ViewGroup.java:4364)
                                                                        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1649)
                                                                        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1507)
                                                                        at android.widget.LinearLayout.onLayout(LinearLayout.java:1420)
                                                                        at android.view.View.layout(View.java:13754)
                                                                        at android.view.ViewGroup.layout(ViewGroup.java:4364)
                                                                        at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
                                                                        at android.view.View.layout(View.java:13754)
                                                                        at android.view.ViewGroup.layout(ViewGroup.java:4364)
                                                                        at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
                                                                        at android.view.View.layout(View.java:13754)
                                                                        at android.view.ViewGroup.layout(Vi

ContentLicense: CC BY-SA 4.0

Title: How to use selector to tint ImageView?

Body:
I want to tint my tabhost's icons using XML, instead of doing it programmatically (I wasn't able to do that anyway)...

I found this thread on SO: Android imageview change tint to simulate button click

That seems to be a pretty good solution, but I wasn't able to adapt it correctly in my project... I did the following changes:

public class TintableImageView extends ImageView {
    private ColorStateList tint;

    public TintableImageView(Context context) {
        super(context);
    }

    //this is the constructor that causes the exception
    public TintableImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs, 0);
    }

    public TintableImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context, attrs, defStyle);
    }

    //here, obtainStyledAttributes was asking for an array
    private void init(Context context, AttributeSet attrs, int defStyle) {
        TypedArray a = context.obtainStyledAttributes(attrs, new int[]{R.styleable.TintableImageView_tint}, defStyle, 0);
        tint = a.getColorStateList(R.styleable.TintableImageView_tint);
        a.recycle();
    }

    @Override
    protected void drawableStateChanged() {
        super.drawableStateChanged();
        if (tint != null && tint.isStateful())
            updateTintColor();
    }

    public void setColorFilter(ColorStateList tint) {
        this.tint = tint;
        super.setColorFilter(tint.getColorForState(getDrawableState(), 0));
    }

    private void updateTintColor() {
        int color = tint.getColorForState(getDrawableState(), 0);
        setColorFilter(color);
    }

}

I also wasn't able to reference @drawable/selector.xml at android:tint, so I did this at colors.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="azulPadrao">#2e7cb4</color>
<drawable name="tab_icon_selector">@drawable/tab_icon_selector</drawable>
</resources>

My selector:

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

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" android:tint="#007AFF" />
<item android:state_focused="true" android:tint="#007AFF" />
<item android:state_pressed="true" android:tint="#007AFF" />
<item android:tint="#929292" />
</selector>

My tab layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:orientation="vertical" android:id="@+id/TabLayout"
          android:layout_width="fill_parent" android:layout_height="fill_parent"
          android:gravity="center" android:background="@drawable/tab_bg_selector">

<com.myapp.TintableImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageView" android:layout_gravity="center" android:tint="@drawable/tab_icon_selector"/>
<TextView android:id="@+id/TabTextView" android:text="Text"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content" android:textColor="@drawable/tab_text_selector"
          android:textSize="10dip"
          android:textStyle="bold" android:layout_marginTop="2dip"/>

</LinearLayout>

Any suggestions? Thanks in advance

EDIT

I was getting a NumberFormatException for using android:tint, when the correct was app:tint (after setting xmlns:app="http://schemas.android.com/apk/res/com.myapp")... but now I think I'm using my selector in a wrong way, because the icons are all black, no matter the state...
I've tried setting <drawable name="tab_icon_selector">@drawable/tab_icon_selector</drawable> from within colors.xml, didn't work

Body:
I agree with @Dreaming in Code and I will give an example.

ic_up_small

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:color="@color/comment_count_selected_color" android:state_selected="true" />
    <item android:color="@color/comment_count_text_color"/>

</selector>

layout/item_post_count_info.xml

<android.support.v7.widget.AppCompatImageView
    android:id="@+id/post_upvote_icon"
    android:layout_width="14dp"
    android:layout_height="14dp"
    android:layout_marginLeft="17dp"
    app:srcCompat="@drawable/ic_up_small"
    app:tint="@color/post_up_color"/>

Attention: We should use app:tint instead of android:tint.

My support library version is 26.0.2.

app/build.gradle

implementation 'com.android.support:appcompat-v7:26.0.2'
implementation 'com.android.support:support-core-utils:26.0.2'
implementation 'com.android.support:support-annotations:26.0.2'
implementation 'com.android.support:support-v4:26.0.2'
implementation 'com.android.support:design:26.0.2'

If we use android:tint, it will crash and the log is like this:

E/AndroidRuntime: FATAL EXCEPTION: main
                                                                    android.view.InflateException: Binary XML file line #0: Error
  inflating class
                                                                        at android.view.LayoutInflater.createView(LayoutInflater.java:613)
                                                                        at
  android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:687)
                                                                        at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
                                                                        at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
                                                                        at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
                                                                        at
  com.opera.six.viewholder.post.PostCountInfoViewHolder$1.create(PostCountInfoViewHolder.java:29)
                                                                        at
  com.opera.six.viewholder.post.PostCountInfoViewHolder$1.create(PostCountInfoViewHolder.java:25)
                                                                        at
  com.opera.six.collection.CollectionAdapter.onCreateViewHolder(CollectionAdapter.java:39)
                                                                        at
  com.opera.six.collection.CollectionAdapter.onCreateViewHolder(CollectionAdapter.java:19)
                                                                        at
  android.support.v7.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:6493)
                                                                        at
  android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5680)
                                                                        at
  android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5563)
                                                                        at
  android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5559)
                                                                        at
  android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2229)
                                                                        at
  android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1556)
                                                                        at
  android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1516)
                                                                        at
  android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:608)
                                                                        at
  android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3693)
                                                                        at
  android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3410)
                                                                        at
  android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3962)
                                                                        at android.view.View.layout(View.java:13754)
                                                                        at android.view.ViewGroup.layout(ViewGroup.java:4364)
                                                                        at
  android.support.v4.widget.SwipeRefreshLayout.onLayout(SwipeRefreshLayout.java:610)
                                                                        at android.view.View.layout(View.java:13754)
                                                                        at android.view.ViewGroup.layout(ViewGroup.java:4364)
                                                                        at
  android.support.design.widget.HeaderScrollingViewBehavior.layoutChild(HeaderScrollingViewBehavior.java:132)
                                                                        at
  android.support.design.widget.ViewOffsetBehavior.onLayoutChild(ViewOffsetBehavior.java:42)
                                                                        at
  android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onLayoutChild(AppBarLayout.java:1361)
                                                                        at
  android.support.design.widget.CoordinatorLayout.onLayout(CoordinatorLayout.java:869)
                                                                        at android.view.View.layout(View.java:13754)
                                                                        at android.view.ViewGroup.layout(ViewGroup.java:4364)
                                                                        at android.support.v4.view.ViewPager.onLayout(ViewPager.java:1767)
                                                                        at android.view.View.layout(View.java:13754)
                                                                        at android.view.ViewGroup.layout(ViewGroup.java:4364)
                                                                        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1649)
                                                                        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1507)
                                                                        at android.widget.LinearLayout.onLayout(LinearLayout.java:1420)
                                                                        at android.view.View.layout(View.java:13754)
                                                                        at android.view.ViewGroup.layout(ViewGroup.java:4364)
                                                                        at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
                                                                        at android.view.View.layout(View.java:13754)
                                                                        at android.view.ViewGroup.layout(ViewGroup.java:4364)
                                                                        at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
                                                                        at android.view.View.layout(View.java:13754)
                                                                        at android.view.ViewGroup.layout(ViewGroup.java:4364)
                                                                        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1649)
                                                                        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1507)
                                                                        at android.widget.LinearLayout.onLayout(LinearLayout.java:1420)
                                                                        at android.view.View.layout(View.java:13754)
                                                                        at android.view.ViewGroup.layout(ViewGroup.java:4364)
                                                                        at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
                                                                        at android.view.View.layout(View.java:13754)
                                                                        at android.view.ViewGroup.layout(ViewGroup.java:4364)
                                                                        at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
                                                                        at android.view.View.layout(View.java:13754)
                                                                        at android.view.ViewGroup.layout(Vi


来源: stackexchange

问:
C# Nullable Equality Operations, Why does null <= null resolve as false?
Why is it that in .NET

```<code>null >= null
</code>```

resolves as false, but

```<code>null == null
</code>```

resolves as true?

In other words, why isn't null >= null equivalent to null > null || null == null?

Does anyone have the official answer?

答:
This isn't the "official" answer, it's my best guess. But if you're dealing with nullable ints and comparing them, you most likely always want the comparison to return false if you're dealing with two "int?"s that are null. That way if it returns true, you can be sure you've actually compared two integers, not two null values. It just removes the need for a separate null check.

That said, it is potentially confusing if it's not the behaviour you expect!

ContentLicense: CC BY-SA 3.0

Body:
Why is it that in .NET

null >= null

resolves as false, but

null == null

resolves as true?

In other words, why isn't null >= null equivalent to null > null || null == null?

Does anyone have the official answer?

ContentLicense: CC BY-SA 2.5


问:
insert into / copy data from table to same with some changing value PL-SQL
```<code>BEGIN
  FOR i IN (select * from Mpl_Form_Responses t  WHERE t.form_ID = 1944 and t.response_id > 15) LOOP
    INSERT INTO Mpl_Form_Responses
      (Form_Id, Response_Id,remarks, Userid)
    VALUES
      (7399, i.RESPONSE_ID,i.remarks, i.userid);
  END LOOP;
END;
</code>```

anyone know why its not working

答:
You dont need PL/SQL for this:</p>

```<code>  INSERT INTO mpl_form_responses
        (form_id
        ,response_id
        ,remarks
        ,userid)

   SELECT 7399 as form_id
         ,response_id
         ,remarks
         ,userid
     FROM mpl_form_responses t
    WHERE t.form_id = 1944
      AND t.response_id > 15
</code>```

Body:
BEGIN
  FOR i IN (select * from Mpl_Form_Responses t  WHERE t.form_ID = 1944 and t.response_id > 15) LOOP
    INSERT INTO Mpl_Form_Responses
      (Form_Id, Response_Id,remarks, Userid)
    VALUES
      (7399, i.RESPONSE_ID,i.remarks, i.userid);
  END LOOP;
END;

anyone know why its not working

Body:
You dont need PL/SQL for this:

  INSERT INTO mpl_form_responses
        (form_id
        ,response_id
        ,remarks
        ,userid)

   SELECT 7399 as form_id
         ,response_id
         ,remarks
         ,userid
     FROM mpl_form_responses t
    WHERE t.form_id = 1944
      AND t.response_id > 15


问:
Inheritance from Tkinter Frame in varying implementations
I'm fairly new to python and try to build a simple GUI following an object oriented approach. Therefor I let my widget classes inherit from tk.Frame and create an application controller to build the GUI.

My application contains the following two files:

mainModule.py

```<code># coding: utf8
from testPackage import myGUI
import Tkinter as tk

root = tk.Tk()  # Main window
my_gui = myGUI.MainApplication(root)
root.mainloop()  # Hold window open until we close it
</code>```

myGUI.py

```<code># coding: utf8
import Tkinter as tk

# Application initializer
class MainApplication(tk.Frame):
    def __init__(self, master):
         self.master = master
         tk.Frame.__init__(self, master)
         self.configure_gui()
         self.pack()    # <--- CODE IN QUESTION
         self.create_widgets()

    def configure_gui(self):
        self.master.title("Any title")
        self.master.geometry('800x600')
        self.master.minsize(600, 100)

    def create_widgets(self):
        self.main_window = MainWindow(self)
        self.main_window.pack()

# Main Data Window
class MainWindow(tk.Frame):
     def __init__(self, master):
         self.master = master
         tk.Frame.__init__(self, master)
         self.main_window = tk.Label(self, text="This is a test")
         self.main_window.pack(side="top", fill="x")
</code>```

Initially running my code without self.pack() (marked as #Code in question) in the MainApplication class definition gave me only the root basic window without the Label created from MainWindow class.

As simple as the answer may be but why?

I used a few sources to get into the topic inbefore and some of them didn't use any geometry manager on the root window (or i'm to inexpierienced to see it. Source below for examples).

Source:

https://www.begueradj.com/tkinter-best-practices.html

http://python-textbok.readthedocs.io/en/latest/Introduction_to_GUI_Programming.html#putting-it-all-together

Tkinter example code for multiple windows, why won't buttons load correctly?

Only after reading following answers regarding widget creation I came aware of the missing part:

Best way to structure a tkinter application

creating a custom widget in tkinter

Figuring that pack() on initialization would be the same as

```<code>MainApplication(root).pack(side="top", fill="both", expand=True)
</code>```

or

```<code>Example(root).place(x=0, y=0, relwidth=1, relheight=1)
</code>```

for a grid based layout.

I guess it's a very simple or obvious element i don't see relating to inheritance but i'm not entirely sure why have to pack() the MainApplication Frame and furthermore why it seems to work for example without this step.

答:
Because MainWindow inherits from Frame, it is itself a frame. If you never call pack, place, or grid on it, it will be invisible. This is no different than if you created a button or scrollbar or any other widget and then don't call one of those methods on it.

Since all of the other widgets are a children of this frame, they will be invisible since their parent is invisible.

Somewhat unrelated to the question being asked, self.pack() is a code smell. Generally speaking, a class should never call pack, place or grid on itself. This tightly couples itself to the caller (meaning, this widget has to know that the caller is using one of those methods).

In other words, if you decide that MainApplication wants to switch from pack to grid for all of its children, you can't just update MainApplication, you also have to update MainWindow. In this case, the root window has only one child so the problem is fairly small, but by doing it this way you are starting a bad practice that will eventually cause you problems.

The rule of thumb is that the function that creates a widget should be responsible for adding it to the screen. That means that it would be better to do it like this:

```<code>root = tk.Tk()
my_gui = myGUI.MainApplication(root)
my_gui.pack(fill="both", expand=True)
</code>```

You would then need to remove self.pack() from MainApplication.__init__.

You also have some very misleading code that might be contributing to the confusion. Take a look at this code:

```<code># Main Data Window
class MainWindow(tk.Frame):
     def __init__(self, master):
         ...
         self.main_window = tk.Label(self, text="This is a test")
         self.main_window.pack(side="top", fill="x")
</code>```

Notice how you have a class named MainWindow. Within that you have a label that is named self.main_window, but self.main_window is not a MainWindow. This is especially confusing since the function that creates MainWindow also creates an instance variable named self.main_window.

You might want to consider renaming this label to be something else (eg: self.label, self.greeting, etc).

Body:
I'm fairly new to python and try to build a simple GUI following an object oriented approach. Therefor I let my widget classes inherit from tk.Frame and create an application controller to build the GUI.

My application contains the following two files:

mainModule.py

# coding: utf8
from testPackage import myGUI
import Tkinter as tk

root = tk.Tk()  # Main window
my_gui = myGUI.MainApplication(root)
root.mainloop()  # Hold window open until we close it

myGUI.py

# coding: utf8
import Tkinter as tk

# Application initializer
class MainApplication(tk.Frame):
    def __init__(self, master):
         self.master = master
         tk.Frame.__init__(self, master)
         self.configure_gui()
         self.pack()    # <--- CODE IN QUESTION
         self.create_widgets()

    def configure_gui(self):
        self.master.title("Any title")
        self.master.geometry('800x600')
        self.master.minsize(600, 100)

    def create_widgets(self):
        self.main_window = MainWindow(self)
        self.main_window.pack()

# Main Data Window
class MainWindow(tk.Frame):
     def __init__(self, master):
         self.master = master
         tk.Frame.__init__(self, master)
         self.main_window = tk.Label(self, text="This is a test")
         self.main_window.pack(side="top", fill="x")

Initially running my code without self.pack() (marked as #Code in question) in the MainApplication class definition gave me only the root basic window without the Label created from MainWindow class.

As simple as the answer may be but why?

I used a few sources to get into the topic inbefore and some of them didn't use any geometry manager on the root window (or i'm to inexpierienced to see it. Source below for examples).

Source:

https://www.begueradj.com/tkinter-best-practices.html

http://python-textbok.readthedocs.io/en/latest/Introduction_to_GUI_Programming.html#putting-it-all-together

Tkinter example code for multiple windows, why won't buttons load correctly?

Only after reading following answers regarding widget creation I came aware of the missing part:

Best way to structure a tkinter application

creating a custom widget in tkinter

Figuring that pack() on initialization would be the same as

MainApplication(root).pack(side="top", fill="both", expand=True)

or

Example(root).place(x=0, y=0, relwidth=1, relheight=1)

for a grid based layout.

I guess it's a very simple or obvious element i don't see relating to inheritance but i'm not entirely sure why have to pack() the MainApplication Frame and furthermore why it seems to work for example without this step.

Body:
Because MainWindow inherits from Frame, it is itself a frame. If you never call pack, place, or grid on it, it will be invisible. This is no different than if you created a button or scrollbar or any other widget and then don't call one of those methods on it.

Since all of the other widgets are a children of this frame, they will be invisible since their parent is invisible.

Somewhat unrelated to the question being asked, self.pack() is a code smell. Generally speaking, a class should never call pack, place or grid on itself. This tightly couples itself to the caller (meaning, this widget has to know that the caller is using one of those methods).

In other words, if you decide that MainApplication wants to switch from pack to grid for all of its children, you can't just update MainApplication, you also have to update MainWindow. In this case, the root window has only one child so the problem is fairly small, but by doing it this way you are starting a bad practice that will eventually cause you problems.

The rule of thumb is that the function that creates a widget should be responsible for adding it to the screen. That means that it would be better to do it like this:

root = tk.Tk()
my_gui = myGUI.MainApplication(root)
my_gui.pack(fill="both", expand=True)

You would then need to remove self.pack() from MainApplication.__init__.

You also have some very misleading code that might be contributing to the confusion. Take a look at this code:

# Main Data Window
class MainWindow(tk.Frame):
     def __init__(self, master):
         ...
         self.main_window = tk.Label(self, text="This is a test")
         self.main_window.pack(side="top", fill="x")

Notice how you have a class named MainWindow. Within that you have a label that is named self.main_window, but self.main_window is not a MainWindow. This is especially confusing since the function that creates MainWindow also creates an instance variable named self.main_window.

You might want to consider renaming this label to be something else (eg: self.label, self.greeting, etc).


问:
js async/await throws error on using this keyword
So, here's the code

```<code>let x = await this.storeFileName(fileName);
</code>```

So, I've declared the storeFileName function as async and I'm also returning a promise and everything till here is fine. But I'm getting an error that says :

SyntaxError: Unexpected token this which is pointing to the 'this' followed by the await keyword

Btw I'm using an ES6 class and the this keyword refers to the object of that class.

It works without the await keyword but if I put await it throws an error.

What am I doing wrong? Everything seems correct. Can someone throw some light on me.

UPDATE :

These are the two functions.

```<code>   async encodeName(x){
     return new Promise((resolve,reject)=>{
        const cipher = crypto.createCipher('aes192', this.PASSWORD);
        let encrypted = cipher.update(x,'utf8', 'hex');
        encrypted += cipher.final('hex');
        if(encrypted.length>240){
         let x = await this.storeFileName(encrypted);
         resolve(`@Fn ${x}`);
      }
      resolve(encrypted);
     });
   }

   async storeFileName(x){
     return new Promise((resolve,reject)=>{
      let doc = { encName: x };
      filesDb = new db(`${this.mntpnt}/__CORE_rigel.pro/x100.db`);
      filesDb.insert(doc,(err,newdoc)=>{
        err?reject():resolve(newdoc._id);
      });
     });
   }
</code>```

Btw, I'm doing this on node.js

UPDATE 2 :

Here is the error message

```<code>A JavaScript error occurred in the main process
Uncaught Exception:
/home/teja/Documents/Rigel/components/diskEncryptor.js:32
        let x = await this.storeFileName(encrypted);
                      ^^^^
SyntaxError: Unexpected token this
    at createScript (vm.js:53:10)
    at Object.runInThisContext (vm.js:95:10)
    at Module._compile (module.js:543:28)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/home/teja/Documents/Rigel/index.js:4:23)
</code>```

答:
You cannot use await in the executor function of the new Promise constructor that is not declared async. And you should not anyway!

Use

```<code>async encodeName(x) {
  // no Promise constructor here!
  const cipher = crypto.createCipher('aes192', this.PASSWORD);
  let encrypted = cipher.update(x, 'utf8', 'hex');
  encrypted += cipher.final('hex');
  if (encrypted.length > 240) {
    let x = await this.storeFileName(encrypted);
    return `@Fn ${x}`);
  }
  return encrypted;
}
storeFileName(x) {
  // no unnecessary async here
  return new Promise((resolve, reject) => {
    let doc = { encName: x };
    filesDb = new db(`${this.mntpnt}/__CORE_rigel.pro/x100.db`);
    filesDb.insert(doc, (err, newdoc) => {
      err ? reject(err) : resolve(newdoc._id);
    });
  });
}
</code>```

Body:
So, here's the code

let x = await this.storeFileName(fileName);

So, I've declared the storeFileName function as async and I'm also returning a promise and everything till here is fine. But I'm getting an error that says :

SyntaxError: Unexpected token this which is pointing to the 'this' followed by the await keyword

Btw I'm using an ES6 class and the this keyword refers to the object of that class.

It works without the await keyword but if I put await it throws an error.

What am I doing wrong? Everything seems correct. Can someone throw some light on me.

UPDATE :

These are the two functions.

   async encodeName(x){
     return new Promise((resolve,reject)=>{
        const cipher = crypto.createCipher('aes192', this.PASSWORD);
        let encrypted = cipher.update(x,'utf8', 'hex');
        encrypted += cipher.final('hex');
        if(encrypted.length>240){
         let x = await this.storeFileName(encrypted);
         resolve(`@Fn ${x}`);
      }
      resolve(encrypted);
     });
   }

   async storeFileName(x){
     return new Promise((resolve,reject)=>{
      let doc = { encName: x };
      filesDb = new db(`${this.mntpnt}/__CORE_rigel.pro/x100.db`);
      filesDb.insert(doc,(err,newdoc)=>{
        err?reject():resolve(newdoc._id);
      });
     });
   }

Btw, I'm doing this on node.js

UPDATE 2 :

Here is the error message

A JavaScript error occurred in the main process
Uncaught Exception:
/home/teja/Documents/Rigel/components/diskEncryptor.js:32
        let x = await this.storeFileName(encrypted);
                      ^^^^
SyntaxError: Unexpected token this
    at createScript (vm.js:53:10)
    at Object.runInThisContext (vm.js:95:10)
    at Module._compile (module.js:543:28)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/home/teja/Documents/Rigel/index.js:4:23)

Body:
You cannot use await in the executor function of the new Promise constructor that is not declared async. And you should not anyway!

Use

async encodeName(x) {
  // no Promise constructor here!
  const cipher = crypto.createCipher('aes192', this.PASSWORD);
  let encrypted = cipher.update(x, 'utf8', 'hex');
  encrypted += cipher.final('hex');
  if (encrypted.length > 240) {
    let x = await this.storeFileName(encrypted);
    return `@Fn ${x}`);
  }
  return encrypted;
}
storeFileName(x) {
  // no unnecessary async here
  return new Promise((resolve, reject) => {
    let doc = { encName: x };
    filesDb = new db(`${this.mntpnt}/__CORE_rigel.pro/x100.db`);
    filesDb.insert(doc, (err, newdoc) => {
      err ? reject(err) : resolve(newdoc._id);
    });
  });
}


问:
Oracle SQL Count Grouping by without repeating records in previous days
I need to count the distinct WO grouping by day, but not counting the WO that were already in previous days. And sum the LABOR column grouping by day also.

SAMPLE:

```<code>DAY   WO     LABOR
6   379157    3
9   379157    5
10  379404    8
10  379362    8
19  386118    10
24  386547    2
25  388711    8
25  386547    5
30  386547    1
</code>```

RESULTS

```<code>DAY   WO    LABOR
6      1    3
9      0    5
10     2    16
19     1    10
24     1    2
25     1    13
30     0    1
</code>```

Thanks a lot for your help

答:
This works for the given set of data:</p>

```<code>SELECT day ,SUM( CASE WHEN t>0  THEN 1 ELSE 0 END) wo, SUM(labor) labor
FROM  (
        SELECT a.day ,a.wo-LAG(a.wo,1,0) OVER (ORDER BY a.wo ) AS  t,labor FROM
     my_test a )

GROUP BY  day
ORDER BY day
</code>```

Body:
I need to count the distinct WO grouping by day, but not counting the WO that were already in previous days. And sum the LABOR column grouping by day also.

SAMPLE:

DAY   WO     LABOR
6   379157    3
9   379157    5
10  379404    8
10  379362    8
19  386118    10
24  386547    2
25  388711    8
25  386547    5
30  386547    1

RESULTS

DAY   WO    LABOR
6      1    3
9      0    5
10     2    16
19     1    10
24     1    2
25     1    13
30     0    1

Thanks a lot for your help

Body:
This works for the given set of data:

SELECT day ,SUM( CASE WHEN t>0  THEN 1 ELSE 0 END) wo, SUM(labor) labor
FROM  (
        SELECT a.day ,a.wo-LAG(a.wo,1,0) OVER (ORDER BY a.wo ) AS  t,labor FROM
     my_test a )

GROUP BY  day
ORDER BY day


问:
How do I get checkbox value in a sheet?
I have multiple checkboxes called cBox1, cBox2 etc in a sheet called 'Images'.

I have three sheets: Data Table, Images, Data (respectively). Images contains two images with various checkboxes, a textbox and a button. When I click the button, the code gets value from the textbox and checkboxes and insert values into a table in the Data sheet.

I am trying to get whether a checkbox is checked or not with the below code:

```<code>If ThisWorkbook.Worksheets(2).Shapes("cBox1").OLEFormat.Object.Value = 0 Then
    totalOfWeldsInOrder = totalOfWeldsInOrder + 1
    s1 = 0
    notInOrder = True
End If
</code>```

However, the value never changes.

How can I get the checked value of the checkboxes?

I have also tried the below, with no success:

```<code>If ThisWorkbook.Worksheets(2).Shapes("cBox1").OLEFormat.Object.Value = -4146 Then
    totalOfWeldsInOrder = totalOfWeldsInOrder + 1
    s1 = 0
    notInOrder = True
End If
</code>```

And Also

```<code>If Sheet2.Shapes("cBox1").ControlFormat.Value = xlOff Then
   ......
End If
</code>```

EDIT:

```<code>If ThisWorkbook.Worksheets(2).cBox1.Value = 0 Then
    totalOfWeldsInOrder = totalOfWeldsInOrder + 1
    s1 = 0
    notInOrder = True
End If
</code>```

returns:

答:
There is a simple solution to your problem:

Use an Active-X Checkbox. Under Developmenttools tab in the menu bar there is: "Insert" it lets you insert two kinds of checkboxes, two kinds of every control strucutre infact. One is an active-x component which is more recent and the other ones are just for backwards compatibility reasons. So never use anything else then Active-X components. Then the code can be used as followed:

```<code>If ThisWorkbook.Worksheets(2).Checkbox1.Value = False Then
    totalOfWeldsInOrder = totalOfWeldsInOrder + 1
    s1 = 0
    notInOrder = True
End If
</code>```

The Checkbox name "CheckBox1" can be changed by showing and editing it's properties so it might also be called "okbox" this name will then replace CheckBox1 in your code.

Title: How do I get checkbox value in a sheet?

Body:
I have multiple checkboxes called cBox1, cBox2 etc in a sheet called 'Images'.

I have three sheets: Data Table, Images, Data (respectively). Images contains two images with various checkboxes, a textbox and a button. When I click the button, the code gets value from the textbox and checkboxes and insert values into a table in the Data sheet.

I am trying to get whether a checkbox is checked or not with the below code:

If ThisWorkbook.Worksheets(2).Shapes("cBox1").OLEFormat.Object.Value = 0 Then
    totalOfWeldsInOrder = totalOfWeldsInOrder + 1
    s1 = 0
    notInOrder = True
End If

However, the value never changes.

How can I get the checked value of the checkboxes?

I have also tried the below, with no success:

If ThisWorkbook.Worksheets(2).Shapes("cBox1").OLEFormat.Object.Value = -4146 Then
    totalOfWeldsInOrder = totalOfWeldsInOrder + 1
    s1 = 0
    notInOrder = True
End If

And Also

If Sheet2.Shapes("cBox1").ControlFormat.Value = xlOff Then
   ......
End If

EDIT:

If ThisWorkbook.Worksheets(2).cBox1.Value = 0 Then
    totalOfWeldsInOrder = totalOfWeldsInOrder + 1
    s1 = 0
    notInOrder = True
End If

returns:

Body:
There is a simple solution to your problem:

Use an Active-X Checkbox. Under Developmenttools tab in the menu bar there is: "Insert" it lets you insert two kinds of checkboxes, two kinds of every control strucutre infact. One is an active-x component which is more recent and the other ones are just for backwards compatibility reasons. So never use anything else then Active-X components. Then the code can be used as followed:

If ThisWorkbook.Worksheets(2).Checkbox1.Value = False Then
    totalOfWeldsInOrder = totalOfWeldsInOrder + 1
    s1 = 0
    notInOrder = True
End If

The Checkbox name "CheckBox1" can be changed by showing and editing it's properties so it might also be called "okbox" this name will then replace CheckBox1 in your code.


问:
Postfix: Setup corret certificate chain
I can't for the life of me figure out what I'm doing wrong here.
I can't get TLS to work properly on my Postfix-server.

I have a wildcard certificate from Thawte and I have put the wildcard and intermediate certificate in the same file. This is my main.cf:

```<code>smtpd_banner = $myhostname ESMTP $mail_name (Debian/GNU)
inet_interfaces = all
inet_protocols = ipv4
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128 192.165.199.0/24
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
myorigin = /etc/mailname
biff = no

smtpd_use_tls=yes
smtpd_tls_security_level = may
smtpd_tls_key_file = /etc/postfix/cert/device.key
smtpd_tls_cert_file = /etc/postfix/cert/device.crt
smtpd_tls_CAfile = /etc/postfix/cert/rootCA.pem
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtp_use_tls = yes
smtp_tls_security_level = may
smtp_tls_loglevel = 1
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache

smtpd_relay_restrictions = permit_mynetworks,permit_sasl_authenticated,defer_unauth_destination
smtpd_recipient_restrictions = permit_sasl_authenticated, permit_mynetworks, reject_unauth_destination
smtpd_sasl_local_domain = $myhostname
smtpd_sasl_auth_enable = yes
smtpd_sasl_security_options = noanonymous
broken_sasl_auth_clients = yes
</code>```

and this is my certificate file (I didn't paste the entire certificate).

```<code>-----BEGIN CERTIFICATE-----
MIIGsDCCBZigAwIBAgIQSgo15k4YWfFlAngSiZuLETANBgkqhkiG9w0BAQsFADBD
MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMdGhhd3RlLCBJbmMuMR0wGwYDVQQDExR0
...........Wildcard certificate............
gjgbXl6MjrVSj6FfDNJFjemtNRyHVEG+pOIE3s2bdxbW0GyKUu4Xv1lhs81AbriG
cCtxINchiAgsWURmK1oq8ebScFpgv30UWEpdkyToAjSbl1wq
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
MIIE3DCCA8SgAwIBAgIQPiM0Wu0sClF7Jt7UgB0QqjANBgkqhkiG9w0BAQsFADCB
rjELMAkGA1UEBhMCVVMxFTATBgNVBAoTDHRoYXd0ZSwgSW5jLjEoMCYGA1UECxMf
......Intermediate certificate........
Hi36v6dJog2X9ZbC6WzUzUcLi4oBi9v6z5J1Lt4+p3O1/gNRp0LDx0JrqW++9iDh
jr+fCY7lCOiSk3c+SUScf+l5nf9Lr+A4VzQNXxEyEpKpYYiBpR74oPBFWoZxIIWF
-----END CERTIFICATE-----
</code>```

When I run openssl s_client -connect smtp-out.domain.com:587 -starttls smtp

I get messages like these:

unable to get local issuer certificate

unable to verify the first certificate

certificate not trusted

```<code>Certificate chain
0 s:/C=SE/ST=State/L=City/O=Company/OU=INC/CN=*.domain.com
   i:/C=US/O=thawte, Inc./CN=thawte SHA256 SSL CA
 1 s:/C=US/O=thawte, Inc./OU=Domain Validated SSL/CN=thawte DV SSL SHA256 CA
   i:/C=US/O=thawte, Inc./OU=Certification Services Division/OU=(c) 2008 thawte, Inc. - For authorized use only/CN=thawte Primary Root CA - G3
</code>```

What do I have to do to get this working properly?
Obviously I'm missing something but I can't figure out what.

Also I get this in the log:

```<code>warning: TLS library problem: error:14094418:SSL routines:SSL3_READ_BYTES:tlsv1 alert unknown ca:s3_pkt.c:1315:SSL alert number 48:
</code>```

答:
I hate to answer my own question but I just found this wonderful site

I generated a correct chain with root certificate and used that instead and not it works.

Title: Postfix: Setup corret certificate chain

Body:
I can't for the life of me figure out what I'm doing wrong here.
I can't get TLS to work properly on my Postfix-server.

I have a wildcard certificate from Thawte and I have put the wildcard and intermediate certificate in the same file. This is my main.cf:

smtpd_banner = $myhostname ESMTP $mail_name (Debian/GNU)
inet_interfaces = all
inet_protocols = ipv4
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128 192.165.199.0/24
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
myorigin = /etc/mailname
biff = no

smtpd_use_tls=yes
smtpd_tls_security_level = may
smtpd_tls_key_file = /etc/postfix/cert/device.key
smtpd_tls_cert_file = /etc/postfix/cert/device.crt
smtpd_tls_CAfile = /etc/postfix/cert/rootCA.pem
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtp_use_tls = yes
smtp_tls_security_level = may
smtp_tls_loglevel = 1
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache

smtpd_relay_restrictions = permit_mynetworks,permit_sasl_authenticated,defer_unauth_destination
smtpd_recipient_restrictions = permit_sasl_authenticated, permit_mynetworks, reject_unauth_destination
smtpd_sasl_local_domain = $myhostname
smtpd_sasl_auth_enable = yes
smtpd_sasl_security_options = noanonymous
broken_sasl_auth_clients = yes

and this is my certificate file (I didn't paste the entire certificate).

-----BEGIN CERTIFICATE-----
MIIGsDCCBZigAwIBAgIQSgo15k4YWfFlAngSiZuLETANBgkqhkiG9w0BAQsFADBD
MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMdGhhd3RlLCBJbmMuMR0wGwYDVQQDExR0
...........Wildcard certificate............
gjgbXl6MjrVSj6FfDNJFjemtNRyHVEG+pOIE3s2bdxbW0GyKUu4Xv1lhs81AbriG
cCtxINchiAgsWURmK1oq8ebScFpgv30UWEpdkyToAjSbl1wq
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
MIIE3DCCA8SgAwIBAgIQPiM0Wu0sClF7Jt7UgB0QqjANBgkqhkiG9w0BAQsFADCB
rjELMAkGA1UEBhMCVVMxFTATBgNVBAoTDHRoYXd0ZSwgSW5jLjEoMCYGA1UECxMf
......Intermediate certificate........
Hi36v6dJog2X9ZbC6WzUzUcLi4oBi9v6z5J1Lt4+p3O1/gNRp0LDx0JrqW++9iDh
jr+fCY7lCOiSk3c+SUScf+l5nf9Lr+A4VzQNXxEyEpKpYYiBpR74oPBFWoZxIIWF
-----END CERTIFICATE-----

When I run openssl s_client -connect smtp-out.domain.com:587 -starttls smtp

I get messages like these:

unable to get local issuer certificate

unable to verify the first certificate

certificate not trusted

Certificate chain
0 s:/C=SE/ST=State/L=City/O=Company/OU=INC/CN=*.domain.com
   i:/C=US/O=thawte, Inc./CN=thawte SHA256 SSL CA
 1 s:/C=US/O=thawte, Inc./OU=Domain Validated SSL/CN=thawte DV SSL SHA256 CA
   i:/C=US/O=thawte, Inc./OU=Certification Services Division/OU=(c) 2008 thawte, Inc. - For authorized use only/CN=thawte Primary Root CA - G3

What do I have to do to get this working properly?
Obviously I'm missing something but I can't figure out what.

Also I get this in the log:

warning: TLS library problem: error:14094418:SSL routines:SSL3_READ_BYTES:tlsv1 alert unknown ca:s3_pkt.c:1315:SSL alert number 48:


问:
Want to Include CKeditor in Angular 2
I am using ng2-admin theme. I have created two folder Landingpage1 and LandingPage2 in src/app/pages folder structure.

Now I have created two separate module in two separate folder:

1. landingPage1.module.ts

```<code>  @NgModule({
    imports: [
        NgaModule,
        CommonModule,
        FormsModule,
        CKEditorModule,
        routing
    ],
    declarations: [
        LandingPage1,
        Ckeditor,
    ]
})
</code>```

2. landingPage2.module.ts

```<code>  @NgModule({
    imports:[
        ReactiveFormsModule,
        FormsModule,
        NgaModule,
        CommonModule,
        CKEditorModule,
        routing
    ],
    declarations:[
         LandingPage2,
         Ckeditor,
    ]
})
</code>```

When I using the Ckeditor in two component file then I getting following error:

Error: Type Ckeditor is part of the declarations of 2 modules: LandingPage1Module and LandingPage2Module! Please consider moving Ckeditor to a higher module that imports LandingPage1Module and LandingPage2Module. You can also create a new NgModule that exports and includes Ckeditor then import that NgModule in LandingPage1Module and LandingPage2Module.

I have imported Ckeditor on app.module.ts file but doesn't work.

答:
Remove Ckeditor from declarations in landingPage1.module.ts and landingPage2.module.ts.

Just keep it inside where you are importing those 2 modules , if app.module.ts then add there.

Proper solution to this is create a commonModule named EditorCommonModule

```<code>@NgModule({
    imports: [
        CKEditorModule
    ],
    exports: [
        CKEditorModule
    ],
    declarations: [],
    providers: [],
})
export class EditorCommonModule { }
</code>```

Then just import this EditorCommonModule wherever you need the ckEditor.

Remove CKEditorModule and Ckeditor from every where.

Title: Want to Include CKeditor in Angular 2

Body:
I am using ng2-admin theme. I have created two folder Landingpage1 and LandingPage2 in src/app/pages folder structure.

Now I have created two separate module in two separate folder:

1. landingPage1.module.ts

  @NgModule({
    imports: [
        NgaModule,
        CommonModule,
        FormsModule,
        CKEditorModule,
        routing
    ],
    declarations: [
        LandingPage1,
        Ckeditor,
    ]
})

2. landingPage2.module.ts

  @NgModule({
    imports:[
        ReactiveFormsModule,
        FormsModule,
        NgaModule,
        CommonModule,
        CKEditorModule,
        routing
    ],
    declarations:[
         LandingPage2,
         Ckeditor,
    ]
})

When I using the Ckeditor in two component file then I getting following error:

Error: Type Ckeditor is part of the declarations of 2 modules: LandingPage1Module and LandingPage2Module! Please consider moving Ckeditor to a higher module that imports LandingPage1Module and LandingPage2Module. You can also create a new NgModule that exports and includes Ckeditor then import that NgModule in LandingPage1Module and LandingPage2Module.

I have imported Ckeditor on app.module.ts file but doesn't work.

Body:
Remove Ckeditor from declarations in landingPage1.module.ts and landingPage2.module.ts.

Just keep it inside where you are importing those 2 modules , if app.module.ts then add there.

Proper solution to this is create a commonModule named EditorCommonModule

@NgModule({
    imports: [
        CKEditorModule
    ],
    exports: [
        CKEditorModule
    ],
    declarations: [],
    providers: [],
})
export class EditorCommonModule { }

Then just import this EditorCommonModule wherever you need the ckEditor.

Remove CKEditorModule and Ckeditor from every where.


问:
Iterate through an array of var chained variables in jQuery
I have a simple function in javascript that hides all css divs on page load:

```<code>function hideAllDivs() {
    var a5 = jQuery('.a5'),
        a2 = jQuery('.a2'),
        b2 = jQuery('.b2'),
        hd3 = jQuery('.hd3'),
        hd6 = jQuery('.hd6');

    a5.hide();
    a2.hide();
    b2.hide();
    hd3.hide();
    hd6.hide();
}
</code>```

As you can see I have to go through each one by one to hide them. Is there a way to store these into an array and just iterate through them all at once? That way if I add a new var chained query, I don't have to then go further down the function and manually hide it?

Any help would be greatly appreciated.

答:
You can just use a single selector:

```<code>jQuery('.a5, .a2, .b2, .hd3, .hd6').hide();
</code>```

Alternatively, you might want to consider creating a new class that you apply to elements you want to hide, and just hide that single class - depends on your overall structure, but that way you don't need to come back and edit this function ever again, just apply that class where needed.

Body:
I have a simple function in javascript that hides all css divs on page load:

function hideAllDivs() {
    var a5 = jQuery('.a5'),
        a2 = jQuery('.a2'),
        b2 = jQuery('.b2'),
        hd3 = jQuery('.hd3'),
        hd6 = jQuery('.hd6');

    a5.hide();
    a2.hide();
    b2.hide();
    hd3.hide();
    hd6.hide();
}

As you can see I have to go through each one by one to hide them. Is there a way to store these into an array and just iterate through them all at once? That way if I add a new var chained query, I don't have to then go further down the function and manually hide it?

Any help would be greatly appreciated.

Body:
You can just use a single selector:

jQuery('.a5, .a2, .b2, .hd3, .hd6').hide();

Alternatively, you might want to consider creating a new class that you apply to elements you want to hide, and just hide that single class - depends on your overall structure, but that way you don't need to come back and edit this function ever again, just apply that class where needed.


问:
Django saving to Foreign field
I'm trying to save an Item based on the Foreign Key Primary Key for topCategory and middleCategory.

models.py

```<code>class MiddleCategory(models.Model):
    title = models.CharField(max_length=50)
    slug = models.SlugField()
    def __str__(self):
        return self.title

class TopCategory(models.Model):
    title = models.CharField(max_length=50)
    slug = models.SlugField()
    middleCategory = models.ManyToManyField(MiddleCategory)
    def __str__(self):
        return self.title

# Item
class Product(models.Model):
    title = models.CharField(max_length=500, db_index=True)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    brand = models.CharField(max_length=100)
#     brand_id = models.IntegerField()
    retailer = models.CharField(max_length=255)
    image = models.CharField(max_length=1000)
    url = models.URLField(max_length=800, unique=True, default='')
    model_numbers = models.BigIntegerField(default=0)
    description = models.CharField(max_length=500)

    featured = models.CharField(max_length=255, db_index=True, default='NO')
    timestamp = models.DateTimeField(auto_now=True)

    topCategory = models.ForeignKey(TopCategory)
    middleCategory = models.ForeignKey(MiddleCategory)

    def __str__(self):
        return self.title
</code>```

In my script I'm saving like this:

```<code>            Product(title=title,
                    price=price,
                    brand=brand,
                    retailer=retailer,
                    image=image,
                    url=url,
                    description=description,

                    midCategory=midCategory,
                    topCategory=topCategory
                    ).save()
</code>```

This is the error I am getting:

ValueError: Cannot assign "'1'": "Product.topCategory" must be a "TopCategory" instance.

答:
You can get instance of TopCategory

```<code>instance = TopCategory.objects.get(id=topCategory)
</code>```

then

```<code>Product(title=title,
                    price=price,
                    brand=brand,
                    retailer=retailer,
                    image=image,
                    url=url,
                    description=description,
                    midCategory=midCategory,
                    topCategory=instance
                    ).save()
</code>```

Title: Django saving to Foreign field

Body:
I'm trying to save an Item based on the Foreign Key Primary Key for topCategory and middleCategory.

models.py

class MiddleCategory(models.Model):
    title = models.CharField(max_length=50)
    slug = models.SlugField()
    def __str__(self):
        return self.title

class TopCategory(models.Model):
    title = models.CharField(max_length=50)
    slug = models.SlugField()
    middleCategory = models.ManyToManyField(MiddleCategory)
    def __str__(self):
        return self.title

# Item
class Product(models.Model):
    title = models.CharField(max_length=500, db_index=True)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    brand = models.CharField(max_length=100)
#     brand_id = models.IntegerField()
    retailer = models.CharField(max_length=255)
    image = models.CharField(max_length=1000)
    url = models.URLField(max_length=800, unique=True, default='')
    model_numbers = models.BigIntegerField(default=0)
    description = models.CharField(max_length=500)

    featured = models.CharField(max_length=255, db_index=True, default='NO')
    timestamp = models.DateTimeField(auto_now=True)

    topCategory = models.ForeignKey(TopCategory)
    middleCategory = models.ForeignKey(MiddleCategory)

    def __str__(self):
        return self.title

In my script I'm saving like this:

            Product(title=title,
                    price=price,
                    brand=brand,
                    retailer=retailer,
                    image=image,
                    url=url,
                    description=description,

                    midCategory=midCategory,
                    topCategory=topCategory
                    ).save()

This is the error I am getting:

ValueError: Cannot assign "'1'": "Product.topCategory" must be a "TopCategory" instance.

Body:
You can get instance of TopCategory

instance = TopCategory.objects.get(id=topCategory)

then

Product(title=title,
                    price=price,
                    brand=brand,
                    retailer=retailer,
                    image=image,
                    url=url,
                    description=description,
                    midCategory=midCategory,
                    topCategory=instance
                    ).save()


问:
Scala Authorization header - Akka HTTP IllegalArgumentException
I'm trying in Scala to make a request to send a user/pass:

```<code>def makeRequestWithRadiusHeader(header: String) = {
    val urlEncHeaderVal = java.net.URLEncoder.encode(s"Basic $header", "utf-8")
    val request = exampleNmsRequest() ~> addHeader("Authorization", urlEncHeaderVal)

    makeRequest(request)
  }
</code>```

where header is "user:password" and on addHeader I get an error like this:

```<code>java.lang.IllegalArgumentException: Illegal HTTP header 'Authorization': Invalid input '%', expected token68-start, '=', OWS or 'EOI' (line 1, column 11): Basic+user%3Apassword
</code>```

If I try without encoding, I get the same error with ':'

答:
I've solved it giving to the function makeRequestWithRadiusHeader a base64 converted parameter.

```<code>val validRadiusHeader = BaseEncoding.base64().encode("aladdin:OpenSesame".getBytes(Charsets.UTF_8))
val response = makeRequestWithRadiusHeader(validRadiusHeader)
</code>```

This way it works fine. It is the way Basic access authentication works.

Body:
I'm trying in Scala to make a request to send a user/pass:

def makeRequestWithRadiusHeader(header: String) = {
    val urlEncHeaderVal = java.net.URLEncoder.encode(s"Basic $header", "utf-8")
    val request = exampleNmsRequest() ~> addHeader("Authorization", urlEncHeaderVal)

    makeRequest(request)
  }

where header is "user:password" and on addHeader I get an error like this:

java.lang.IllegalArgumentException: Illegal HTTP header 'Authorization': Invalid input '%', expected token68-start, '=', OWS or 'EOI' (line 1, column 11): Basic+user%3Apassword

If I try without encoding, I get the same error with ':'

Body:
I've solved it giving to the function makeRequestWithRadiusHeader a base64 converted parameter.

val validRadiusHeader = BaseEncoding.base64().encode("aladdin:OpenSesame".getBytes(Charsets.UTF_8))
val response = makeRequestWithRadiusHeader(validRadiusHeader)

This way it works fine. It is the way Basic access authentication works.


问:
How to better structure an Array of Arrays in JSON
In the following JSON object:

```<code>var employees = { "accounting" : [   // accounting is an array in employees.
                                { "firstName" : "John",  // First element
                                  "lastName"  : "Doe",
                                  "age"       : 23 },

                                { "firstName" : "Mary",  // Second Element
                                  "lastName"  : "Smith",
                                  "age"       : 32 }
                              ], // End "accounting" array.
              "sales"       : [ // Sales is another array in employees.
                                { "firstName" : "Sally", // First Element
                                  "lastName"  : "Green",
                                  "age"       : 27 },

                                { "firstName" : "Jim",   // Second Element
                                  "lastName"  : "Galley",
                                  "age"       : 41 }
                              ] // End "sales" Array.
            } // End Employees
</code>```

How do I restructure the object so I can access each employee first name like this:

```<code>employees[0].firstName
employees[1].firstName
// etc
</code>```

答:
You can't pivot this like that.  Either you move the department as a key in the employee object or you have to access it like employees.accounting[0].firstName.

If you insist on accessing the employee as employees[index], you have to restructure it to:

```<code>var employees = [
  { "firstName" : "John", "lastName" : "Doe", "age" : 23, "department" : "accounting" },
  { "firstName" : "...", ..., "department" : "accounting" },
  ... and so on.
];
</code>```

and introduce a different way to filter by department.

maybe create a function that loop through the employees array, and copy each element that match the filter into a new array object and return it.

```<code>function getAllEmployeesFilteredBy(filterName, filterValue, empArray)
{
  var result = [];
  for (var i=0; i < empArray.length; i++) {
    if (empArray[i][filterName] === filterValue)
      //by ref
      result[result.length] = empArray[i];

      //or if you prefer by value (different object altogether)
      //result[result.length] = { "firstName" : empArray[i].firstName, "lastName" : empArray[i].lastName, ... }
  }
  return result;
}
</code>```

Body:
In the following JSON object:

var employees = { "accounting" : [   // accounting is an array in employees.
                                { "firstName" : "John",  // First element
                                  "lastName"  : "Doe",
                                  "age"       : 23 },

                                { "firstName" : "Mary",  // Second Element
                                  "lastName"  : "Smith",
                                  "age"       : 32 }
                              ], // End "accounting" array.
              "sales"       : [ // Sales is another array in employees.
                                { "firstName" : "Sally", // First Element
                                  "lastName"  : "Green",
                                  "age"       : 27 },

                                { "firstName" : "Jim",   // Second Element
                                  "lastName"  : "Galley",
                                  "age"       : 41 }
                              ] // End "sales" Array.
            } // End Employees

How do I restructure the object so I can access each employee first name like this:

employees[0].firstName
employees[1].firstName
// etc

Body:
You can't pivot this like that.  Either you move the department as a key in the employee object or you have to access it like employees.accounting[0].firstName.

If you insist on accessing the employee as employees[index], you have to restructure it to:

var employees = [
  { "firstName" : "John", "lastName" : "Doe", "age" : 23, "department" : "accounting" },
  { "firstName" : "...", ..., "department" : "accounting" },
  ... and so on.
];

and introduce a different way to filter by department.

maybe create a function that loop through the employees array, and copy each element that match the filter into a new array object and return it.

function getAllEmployeesFilteredBy(filterName, filterValue, empArray)
{
  var result = [];
  for (var i=0; i < empArray.length; i++) {
    if (empArray[i][filterName] === filterValue)
      //by ref
      result[result.length] = empArray[i];

      //or if you prefer by value (different object altogether)
      //result[result.length] = { "firstName" : empArray[i].firstName, "lastName" : empArray[i].lastName, ... }
  }
  return result;
}


问:
REST and spring-mvc
Since REST based controller methods only return objects ( not views ) to the client based on the request, how can I show view to my user ? Or maybe better question what is a good way to combine spring-mvc web app with REST, so my user always get the answer, not in just ( for example ) JSON format, but also with the view ?

So far as I understood, REST based controller would be perfectly fitting to the mobile app ( for example twitter ), where views are handled inside the app and the only thing server has to worry about is to pass the right object to the right request. But what about the web app ?

I might be wrong in several things ( correct me if I am ), since I am trying to understand REST and I am still learning.

答:
This method returns a view

```<code>@RequestMapping("/home")
String home(Model model) {
    return "home";  // resources\templates\home.html
}
</code>```

This method Returns String

```<code>@RequestMapping(value = "/home")
@ResponseBody
public String home() {
    return "Success";
}
</code>```

Title: REST and spring-mvc

Body:
This method returns a view

@RequestMapping("/home")
String home(Model model) {
    return "home";  // resources\templates\home.html
}

This method Returns String

@RequestMapping(value = "/home")
@ResponseBody
public String home() {
    return "Success";
}


问:
Rx scan(), cannot generate observable from seed and another observable
I have a seed value Triangle (Bool) and an observable that emits values Circle (Int). My intention is to generate a new observable (Triangle, Circle)  each time a value is emitted from that observable, transforming the Triangle value negating the current value. This is my marble diagram:

But I cannot achieve it, and I don't know if scan is the correct operator. This is my code:

```<code>typealias Triangle = Bool
typealias Circle = Int

func scan() {
    let triangle: Triangle = false
    circleObservable
        .scan(triangle, accumulator: ({ (triangle, circle) -> (Triangle, Circle) in
            return (!triangle, circle)
        }))
}
</code>```

This generates a compiler error:

Cannot convert value of type '(Triangle, Circle) -> (Triangle,
  Circle)' (aka '(Bool, Int) -> (Bool, Int)') to expected argument type
  '(_, _) -> _'

Thanks!

答:
```<code>circleObservable.scan((Triangle(false), Circle()), accumulator: { lastValue, circle -> (Triangle, Circle) in (!lastValue.0, circle) })
</code>```

Or simpler:

```<code>typealias Triangle = Bool
typealias Circle = Int

func scan(circle: Observable<Circle>) -> Observable<(Triangle, Circle)> {
    return circle.scan((Triangle(false), Circle())) { (!$0.0, $1) }
}
</code>```

Body:
I have a seed value Triangle (Bool) and an observable that emits values Circle (Int). My intention is to generate a new observable (Triangle, Circle)  each time a value is emitted from that observable, transforming the Triangle value negating the current value. This is my marble diagram:

But I cannot achieve it, and I don't know if scan is the correct operator. This is my code:

typealias Triangle = Bool
typealias Circle = Int

func scan() {
    let triangle: Triangle = false
    circleObservable
        .scan(triangle, accumulator: ({ (triangle, circle) -> (Triangle, Circle) in
            return (!triangle, circle)
        }))
}

This generates a compiler error:

Cannot convert value of type '(Triangle, Circle) -> (Triangle,
  Circle)' (aka '(Bool, Int) -> (Bool, Int)') to expected argument type
  '(_, _) -> _'

Thanks!

Body:
circleObservable.scan((Triangle(false), Circle()), accumulator: { lastValue, circle -> (Triangle, Circle) in (!lastValue.0, circle) })

Or simpler:

typealias Triangle = Bool
typealias Circle = Int

func scan(circle: Observable<Circle>) -> Observable<(Triangle, Circle)> {
    return circle.scan((Triangle(false), Circle())) { (!$0.0, $1) }
}


问:
Output of gulp-sass is .scss files not css files
I'm trying to compile some .scss files into css using gulp. gulpfile.js:

```<code>var gulp = require("gulp");
var sass = require("gulp-sass");

gulp.task("sass",
function() {
    return gulp.src("app/assets/sass/*.scss")
     .pipe(sass({
                includePaths: [
                    "govuk_modules/govuk_frontend_toolkit/stylesheets/",
                    "govuk_modules/govuk_template/assets/stylesheet/",
                    "govuk_modules/govuk-elements-sass/"
         ]
        }).pipe(gulp.dest("./wwwroot/stylesheets/")));
});
</code>```

I'm using Visual Studio 2017 and when I run the sass task in task explorer, I get the expected files output into the destination folder, however, they are .scss files and not the expected .css files.

There are some 20+ files in total in the paths, and these do get compiled in to 4 files but like I say, are .scss not css.

Any ideas?

答:
There's a problem with the closing of your first pipe, you should close it before starting the pipe for gulp.dest.

By doing so the files should be compiled to css and not scss.

```<code>.pipe(sass({
    includePaths: [
        "govuk_modules/govuk_frontend_toolkit/stylesheets/",
        "govuk_modules/govuk_template/assets/stylesheet/",
        "govuk_modules/govuk-elements-sass/"
    ]
})).pipe(gulp.dest("./wwwroot/stylesheets/"));
</code>```

Body:
I'm trying to compile some .scss files into css using gulp. gulpfile.js:

var gulp = require("gulp");
var sass = require("gulp-sass");

gulp.task("sass",
function() {
    return gulp.src("app/assets/sass/*.scss")
     .pipe(sass({
                includePaths: [
                    "govuk_modules/govuk_frontend_toolkit/stylesheets/",
                    "govuk_modules/govuk_template/assets/stylesheet/",
                    "govuk_modules/govuk-elements-sass/"
         ]
        }).pipe(gulp.dest("./wwwroot/stylesheets/")));
});

I'm using Visual Studio 2017 and when I run the sass task in task explorer, I get the expected files output into the destination folder, however, they are .scss files and not the expected .css files.

There are some 20+ files in total in the paths, and these do get compiled in to 4 files but like I say, are .scss not css.

Any ideas?

Body:
There's a problem with the closing of your first pipe, you should close it before starting the pipe for gulp.dest.

By doing so the files should be compiled to css and not scss.

.pipe(sass({
    includePaths: [
        "govuk_modules/govuk_frontend_toolkit/stylesheets/",
        "govuk_modules/govuk_template/assets/stylesheet/",
        "govuk_modules/govuk-elements-sass/"
    ]
})).pipe(gulp.dest("./wwwroot/stylesheets/"));


问:
Spring Data 1.11.7 No property existsBy
Good morning!

My Spring application doesn't seem to detect existsBy projections

```<code>Caused by: org.springframework.data.mapping.PropertyReferenceException: No property existsById found for type Planet!
at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:77)
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:329)
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:309)
at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:272)
</code>```

Code in the repository

public boolean existsByIdAndOwnerId(Long planetId, Integer ownerId);

Spring version: 4.3.12.RELEASE

Hibernate version: 5.2.12.Final

Spring Data JPA version: 1.11.7.RELEASE

Thanks in advance!

答: If you are extending CrudRepository<T, ID> in your repository it provides existById(ID) which takes id as parameter and returns Boolean based on db entry's existence. For your case you can do like this: public boolean findByIdAndOwnerId(Long planetId, Integer ownerId);

Title: Spring Data 1.11.7 No property existsBy

Body:
Good morning!

My Spring application doesn't seem to detect existsBy projections

Caused by: org.springframework.data.mapping.PropertyReferenceException: No property existsById found for type Planet!
at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:77)
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:329)
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:309)
at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:272)

Code in the repository

public boolean existsByIdAndOwnerId(Long planetId, Integer ownerId);

Spring version: 4.3.12.RELEASE

Hibernate version: 5.2.12.Final

Spring Data JPA version: 1.11.7.RELEASE

Thanks in advance!


问:
Factoring a number in Java - Homework
As several other questions have asked on this forum, how would you go about finding the factors of a number.

Note: I have tried to understand what other people have written, please do not rehash already given answers

My code works as of right now but, for example the number 6 returns:
6.0 factored by 1.0 is 6.000
6.0 factored by 2.0 is 3.000
6.0 factored by 3.0 is 2.000
6.0 factored by 4.0 is 1.500
6.0 factored by 5.0 is 1.200
6.0 factored by 6.0 is 1.000

Is there a way to remove all the decimal numbers?
I thought somehting about a "for" statement, but I don't really know how to use them.

Current Code:

```<code>public class Factoring {

public static void main(String[] args) {
    double input;
    double factor = 1;
    double factorNum;

    System.out.println("This application calculates every factor of a given number!"
            + "\nPlease enter a number: ");
    input = TextIO.getlnDouble();

    System.out.println("Original Number: " + input);

    while (input >= factor){
        factorNum = input / factor;

        System.out.print("\n" + input + " factored by " + factor + " is ");
        System.out.printf("%.3f", factorNum);
        factor++;
    }
}

}
</code>```

答:
I stored the factors in ArrayList</p>

```<code>          int s = /* Your number or get from user */;
    ArrayList<Integer>integers = new ArrayList<>();
    for (int i = 1 ; i <= s ; i++){
        if(s%i == 0){
         integers.add(i);
           /* just for printing the factors */ System.out.println(i);
        }
    }
</code>```

Title: Factoring a number in Java - Homework

Body:
As several other questions have asked on this forum, how would you go about finding the factors of a number.

Note: I have tried to understand what other people have written, please do not rehash already given answers

My code works as of right now but, for example the number 6 returns:
6.0 factored by 1.0 is 6.000
6.0 factored by 2.0 is 3.000
6.0 factored by 3.0 is 2.000
6.0 factored by 4.0 is 1.500
6.0 factored by 5.0 is 1.200
6.0 factored by 6.0 is 1.000

Is there a way to remove all the decimal numbers?
I thought somehting about a "for" statement, but I don't really know how to use them.

Current Code:

public class Factoring {

public static void main(String[] args) {
    double input;
    double factor = 1;
    double factorNum;

    System.out.println("This application calculates every factor of a given number!"
            + "\nPlease enter a number: ");
    input = TextIO.getlnDouble();

    System.out.println("Original Number: " + input);

    while (input >= factor){
        factorNum = input / factor;

        System.out.print("\n" + input + " factored by " + factor + " is ");
        System.out.printf("%.3f", factorNum);
        factor++;
    }
}

}

Body:
I stored the factors in ArrayList

          int s = /* Your number or get from user */;
    ArrayList<Integer>integers = new ArrayList<>();
    for (int i = 1 ; i <= s ; i++){
        if(s%i == 0){
         integers.add(i);
           /* just for printing the factors */ System.out.println(i);
        }
    }


问:
Joinable group video chat rooms using Quickblox
I am currently developing an iOS application which requires users to join video chat rooms, very similar to how Houseparty and Airtime works. However, I don't know where to start, nor what third party service I should use in order to incorporate this in my app. From what I can find online, Quickblox seem to be one of the best, but on the other hand, it seems to only offer "video calls", meaning that in order to start a group video chat, you have to call users, in contrast to how for example Houseparty works where you can join a room without accepting a call. This issue even seems to state that it is not even possible to do this at all. My question is therefore, is it possible to use Quickblox in order to develop an application that allows users to have video group chats, without ever calling someone and instead allow them to join the video group chat sporadically? If not, which third party service makes this possible? </p>

答:
Regular calls in quick blox are implemented as a peer to peer calls. The feature you need is conference call . Quick blox have custom enterprise solution with the usage of server-side, it provide call with 10 to 15 users but in the enterprise tier . Check Out link below.

Quick blox


问:
Android JNI FindClass not finding R.id
I am trying to find the value for a resource id. The first step of loading R class fails:

```<code>jclass rcl = (*env).FindClass("my/package/R$id");
</code>```

the value of rcl is NULL.  I tried

```<code>jclass rcl = (*env).FindClass("my/package/R/id");
</code>```

which also returns null.

Finding other classes such as MainActivity working fine. Using NDK15. What could be wrong?

Output of javap:
http://siara.cc/output.txt

EDITED:
On changing class name to just my/package/R, I find the following line in the adb log:

```<code>exception: java.lang.ClassNotFoundException: Didn't find class "my.package.R" on path: DexPathList[[zip file "/data/app/my.package-1/base.apk"],nativeLibraryDirectories=[/data/app/my.package-1/lib/arm, /system/fake-libs, /data/app/my.package-1/base.apk!/lib/armeabi-v7a, /system/lib, /vendor/lib, /system/vendor/lib]]
</code>```

答:
The problem was solved by adding proguard rule like this:

```<code>-keep class my.package.R$* { *; }
</code>```

It appears that proguard obfuscates R class as well.

Title: Android JNI FindClass not finding R.id

Body:
I am trying to find the value for a resource id. The first step of loading R class fails:

jclass rcl = (*env).FindClass("my/package/R$id");

the value of rcl is NULL.  I tried

jclass rcl = (*env).FindClass("my/package/R/id");

which also returns null.

Finding other classes such as MainActivity working fine. Using NDK15. What could be wrong?

Output of javap:
http://siara.cc/output.txt

EDITED:
On changing class name to just my/package/R, I find the following line in the adb log:

exception: java.lang.ClassNotFoundException: Didn't find class "my.package.R" on path: DexPathList[[zip file "/data/app/my.package-1/base.apk"],nativeLibraryDirectories=[/data/app/my.package-1/lib/arm, /system/fake-libs, /data/app/my.package-1/base.apk!/lib/armeabi-v7a, /system/lib, /vendor/lib, /system/vendor/lib]]

Body:
The problem was solved by adding proguard rule like this:

-keep class my.package.R$* { *; }

It appears that proguard obfuscates R class as well.


问:
How to get my web text below my logo and navbar?
I'm trying to build a simple web page. It has a logo in the upper left corner, and on the same line to the right is a navbar. That all works fine. The problem is that I want to then have text below the logo & navbar (full width). No matter what I try, the text starts in the same line as the logo and navbar. How can I force the text to start below the logo & navbar?

Here's the html:

```<code><!doctype html>
<html>
    <head>
        <link rel="stylesheet" href="Temp.css" type="text/css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    </head>
    <body>
        <div class="logo" style="display:inline;">
            <a href="Temp.html">
                <img src="robert-half-technology-logo-600(40).gif"/>
            </a>
        </div>

        <nav class="navbar  navbar-fixed-top">
            <div class="container-fluid">
                <ul class="nav navbar-nav pull-right">
                    <li class="active"><a href="#" style="color:black;">Home</a></li>
                    <li><a href="Temp_AboutUs.html" style="color:black;">About Us</a></li>
                    <li><a href="Temp_Careers.html" style="color:black;">Careers</a></li>
                    <li><a href="Temp_ContactUs.html" style="color:black;">Contact Us</a></li>
                </ul>
            </div><br/><br/>
        </nav>
        <div class="container">
            <div class="row">
                <div class="col-md-8">
                    <h1>About Us</h1>
                    <p class="normaltext">
                        Founded in 1948, Robert Half has a long company history of innovation, always guided by high ethical standards and the belief that finding the right fit for a client and candidate creates an engaged and energized workforce.
                    </p>
                    <p class="normaltext">
                        We pioneered the idea of professional staffing services nearly 70 years ago and, as the needs of businesses have evolved, so have we. In 1986, when current leadership acquired the Robert Half business from founder Bob Half, the staffing industry was much different than it is today. Our leadership team saw potential in moving toward a more specialized staffing approach and began placing temporary workers at higher skill levels. Our clients and candidates found value in professional-level staffing, which is why we launched a series of temporary professional staffing divisions in the finance and accounting, legal, creative and marketing, technology and administrative fields. And in 2002, we again saw opportunity and introduced Protiviti, a global independent risk consulting and internal audit service, to support companies as they faced more stringent financial reporting and disclosure practices under new regulations such as Sarbanes-Oxley.
                    </p>
                    <p class="normaltext">
                        Explore Robert Half’s history, learn about our leadership and accolades and see how we have found opportunity in innovation to create a $5 billion professional services organization.
                    </p>
                    <h2>1940s: The beginning</h2>
                    <table style="width:100%" class="normaltext">
                        <tr>
                            <td>1948</td>
                            <td>Robert Half founded by Bob and Maxine Half.</td>
                        </tr>
                    </table>
                    <h2>1960s: High ethical standards become a cornerstone</h2>
                    <table style="width:100%" class="normaltext">
                        <tr>
                            <td>1963</td>
                            <td style="padding-left:20px;">Bob Half speaks out against discriminatory recruiting and staffing practices in a letter to the Association of Personnel Agencies of New York.</td>
                        </tr>
                    </table>
                    <h2>1970s: A decade of firsts</h2>
                    <table style="width:100%" class="normaltext">
                        <tr>
                            <td>1973</td>
                            <td style="padding-left:20px">Robert Half opens its first international location in London.</td>
                        </tr>
                        <tr>
                            <td>1973</td>
                            <td style="padding-left:20px;">Accountemps, the first of many professional staffing divisions, is launched, thus beginning Robert Half’s specialized approach to temporary staffing.</td>
                        </tr>
                    </table>
                </div>
            </div>
        </div>
    </body>

</html>
</code>```

And here's the css:

```<code>ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
}

li {
    float: left;
}

a {
    display: block;
    padding: 8px;
    background-color: #dddddd;
}

.logo {
    position: fixed;
    z-index: 2000;
}

.video {
position: fixed;
top: 50%;
left: 50%;
min-width: 100%;
min-height: 100%;
z-index: -100;
-ms-transform: translateX(-50%) translateY(-50%);
-moz-transform: translateX(-50%) translateY(-50%);
-webkit-transform: translateX(-50%) translateY(-50%);
transform: translateX (-50%) translateY(-50%);
}

h1 {
    text-align:center;
    color:#a01b35;
}

.normaltext {
    font-size: 18px;
    font-family: "Futura BT W01 Book",OpenSansRegular,"Open Sans Regular",sans-serif;
    line-height: 1.25;
}
</code>```

答:
Give margin-top to the container as much as need to accomodate Header height and give top:0px css to .logo class.</p>

```<code>.container {
    width: 1170px;
    margin-top: 100px;
}

.logo{
   position: fixed;
   z-index: 2000;
   top: 0px;
}
</code>```

Body:
I'm trying to build a simple web page. It has a logo in the upper left corner, and on the same line to the right is a navbar. That all works fine. The problem is that I want to then have text below the logo & navbar (full width). No matter what I try, the text starts in the same line as the logo and navbar. How can I force the text to start below the logo & navbar?

Here's the html:

<!doctype html>

        <link rel="stylesheet" href="Temp.css" type="text/css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

Home

About Us

Careers

Contact Us

About Us

                        Founded in 1948, Robert Half has a long company history of innovation, always guided by high ethical standards and the belief that finding the right fit for a client and candidate creates an engaged and energized workforce.

                        We pioneered the idea of professional staffing services nearly 70 years ago and, as the needs of businesses have evolved, so have we. In 1986, when current leadership acquired the Robert Half business from founder Bob Half, the staffing industry was much different than it is today. Our leadership team saw potential in moving toward a more specialized staffing approach and began placing temporary workers at higher skill levels. Our clients and candidates found value in professional-level staffing, which is why we launched a series of temporary professional staffing divisions in the finance and accounting, legal, creative and marketing, technology and administrative fields. And in 2002, we again saw opportunity and introduced Protiviti, a global independent risk consulting and internal audit service, to support companies as they faced more stringent financial reporting and disclosure practices under new regulations such as Sarbanes-Oxley.

                        Explore Robert Half’s history, learn about our leadership and accolades and see how we have found opportunity in innovation to create a $5 billion professional services organization.

1940s: The beginning

                            1948
                            Robert Half founded by Bob and Maxine Half.

1960s: High ethical standards become a cornerstone

                            1963
                            Bob Half speaks out against discriminatory recruiting and staffing practices in a letter to the Association of Personnel Agencies of New York.

1970s: A decade of firsts

                            1973
                            Robert Half opens its first international location in London.

                            1973
                            Accountemps, the first of many professional staffing divisions, is launched, thus beginning Robert Half’s specialized approach to temporary staffing.

And here's the css:

ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
}

li {
    float: left;
}

a {
    display: block;
    padding: 8px;
    background-color: #dddddd;
}

.logo {
    position: fixed;
    z-index: 2000;
}

.video {
position: fixed;
top: 50%;
left: 50%;
min-width: 100%;
min-height: 100%;
z-index: -100;
-ms-transform: translateX(-50%) translateY(-50%);
-moz-transform: translateX(-50%) translateY(-50%);
-webkit-transform: translateX(-50%) translateY(-50%);
transform: translateX (-50%) translateY(-50%);
}

h1 {
    text-align:center;
    color:#a01b35;
}

.normaltext {
    font-size: 18px;
    font-family: "Futura BT W01 Book",OpenSansRegular,"Open Sans Regular",sans-serif;
    line-height: 1.25;
}

Body:
Give margin-top to the container as much as need to accomodate Header height and give top:0px css to .logo class.

.container {
    width: 1170px;
    margin-top: 100px;
}

.logo{
   position: fixed;
   z-index: 2000;
   top: 0px;
}


问:
How to process massive number of images from download URL using EMR
I have a text file with image urls separated with line break for each.

I want to process these massive amount of images by saving to S3 bucket and process them with nodejs.

How is it possible to use EMR to do this if not what would be a better solution?

答:
You could consider using S3 + Lambda. Depending upon how many images you want to download, of course, and what you need to do with them. You could run a Node process on an EC2 instance (or your local machine even) that reads the text file, fetches each of the images and puts each one on S3. You can create a trigger on S3 so that when any new items are put into a bucket, it calls an AWS Lambda function. The Lambda function can then process the image as you want. The restriction here is that Lambda has a 5 minute maximum execution time, so it depends upon what you really need to do with the image. If the processing takes less than this time, then it should be OK.

This is relatively simple, and fast as it will create as many Lambda instances as needed to cope with the load.

Probably a reasonable idea to model this to cost it out to make sure it fits within your budget: https://aws.amazon.com/lambda/pricing/.