问:
Angular 2 + CLI : Error in Maximum call stack size exceeded
I have a problem with my Ng2 project for 3 - 4 days.

Versions.

@angular/cli: 1.0.0-rc.2

node: 6.9.2

os: win32 x64

@angular/common: 2.4.9

@angular/compiler: 2.4.9

@angular/core: 2.4.9

@angular/forms: 2.4.9

@angular/http: 2.4.9

@angular/platform-browser: 2.4.9

@angular/platform-browser-dynamic: 2.4.9

@angular/router: 3.4.9

@angular/cli: 1.0.0-rc.2

@angular/compiler-cli: 2.4.9

Repro steps.

I run ng serv / ng test or ng build and i have : "ERROR in Maximum call stack size exceeded"

The log given by the failure.

After "ng serve"

```<code>$ ng serve
** NG Live Development Server is running on http://localhost:4200 **
Hash: a73c4ecdb8222366629e
Time: 16536ms
chunk    {0} polyfills.bundle.js, polyfills.bundle.js.map (polyfills) 405 kB {5} [initial] [rendered]
chunk    {1} main.bundle.js, main.bundle.js.map (main) 41.1 kB {4} [initial] [rendered]
chunk    {2} styles.bundle.js, styles.bundle.js.map (styles) 149 kB {5} [initial] [rendered]
chunk    {3} scripts.bundle.js, scripts.bundle.js.map (scripts) 244 kB {5} [initial] [rendered]
chunk    {4} vendor.bundle.js, vendor.bundle.js.map (vendor) 2.75 MB [initial] [rendered]
chunk    {5} inline.bundle.js, inline.bundle.js.map (inline) 0 bytes [entry] [rendered]

ERROR in Maximum call stack size exceeded
webpack: Failed to compile.
</code>```

After I save one time and all is alright :

```<code>$ ng serve
** NG Live Development Server is running on http://localhost:4200 **
Hash: a73c4ecdb8222366629e
Time: 16536ms
chunk    {0} polyfills.bundle.js, polyfills.bundle.js.map (polyfills) 405 kB {5} [initial] [rendered]
chunk    {1} main.bundle.js, main.bundle.js.map (main) 41.1 kB {4} [initial] [rendered]
chunk    {2} styles.bundle.js, styles.bundle.js.map (styles) 149 kB {5} [initial] [rendered]
chunk    {3} scripts.bundle.js, scripts.bundle.js.map (scripts) 244 kB {5} [initial] [rendered]
chunk    {4} vendor.bundle.js, vendor.bundle.js.map (vendor) 2.75 MB [initial] [rendered]
chunk    {5} inline.bundle.js, inline.bundle.js.map (inline) 0 bytes [entry] [rendered]

ERROR in Maximum call stack size exceeded
webpack: Failed to compile.
webpack: Compiling...
Hash: 02fd7618c3e2de3db52e
Time: 9915ms
chunk    {0} 0.chunk.js, 0.chunk.js.map 926 kB {1} {2} {3} {5} [rendered]
chunk    {1} 1.chunk.js, 1.chunk.js.map 397 kB {0} {2} {3} {5} [rendered]
chunk    {2} 2.chunk.js, 2.chunk.js.map 33.1 kB {0} {1} {3} {5} [rendered]
chunk    {3} 3.chunk.js, 3.chunk.js.map 2.96 kB {0} {1} {2} {5} [rendered]
chunk    {4} polyfills.bundle.js, polyfills.bundle.js.map (polyfills) 405 kB {9} [initial] [rendered]
chunk    {5} main.bundle.js, main.bundle.js.map (main) 41.1 kB {8} [initial] [rendered]
chunk    {6} styles.bundle.js, styles.bundle.js.map (styles) 149 kB {9} [initial] [rendered]
chunk    {7} scripts.bundle.js, scripts.bundle.js.map (scripts) 244 kB {9} [initial] [rendered]
chunk    {8} vendor.bundle.js, vendor.bundle.js.map (vendor) 2.75 MB [initial] [rendered]
chunk    {9} inline.bundle.js, inline.bundle.js.map (inline) 0 bytes [entry] [rendered]
webpack: Compiled successfully.
</code>```

And for "ng test" is same.

Any idea to resolve this ?

答:
The best way i found to debug this is :

```<code>ng serve --aot
</code>```

It will exit building if any error is found with an understandable error.

Body:
I have a problem with my Ng2 project for 3 - 4 days.

Versions.

@angular/cli: 1.0.0-rc.2

node: 6.9.2

os: win32 x64

@angular/common: 2.4.9

@angular/compiler: 2.4.9

@angular/core: 2.4.9

@angular/forms: 2.4.9

@angular/http: 2.4.9

@angular/platform-browser: 2.4.9

@angular/platform-browser-dynamic: 2.4.9

@angular/router: 3.4.9

@angular/cli: 1.0.0-rc.2

@angular/compiler-cli: 2.4.9

Repro steps.

I run ng serv / ng test or ng build and i have : "ERROR in Maximum call stack size exceeded"

The log given by the failure.

After "ng serve"

$ ng serve
** NG Live Development Server is running on http://localhost:4200 **
Hash: a73c4ecdb8222366629e
Time: 16536ms
chunk    {0} polyfills.bundle.js, polyfills.bundle.js.map (polyfills) 405 kB {5} [initial] [rendered]
chunk    {1} main.bundle.js, main.bundle.js.map (main) 41.1 kB {4} [initial] [rendered]
chunk    {2} styles.bundle.js, styles.bundle.js.map (styles) 149 kB {5} [initial] [rendered]
chunk    {3} scripts.bundle.js, scripts.bundle.js.map (scripts) 244 kB {5} [initial] [rendered]
chunk    {4} vendor.bundle.js, vendor.bundle.js.map (vendor) 2.75 MB [initial] [rendered]
chunk    {5} inline.bundle.js, inline.bundle.js.map (inline) 0 bytes [entry] [rendered]

ERROR in Maximum call stack size exceeded
webpack: Failed to compile.

After I save one time and all is alright :

$ ng serve
** NG Live Development Server is running on http://localhost:4200 **
Hash: a73c4ecdb8222366629e
Time: 16536ms
chunk    {0} polyfills.bundle.js, polyfills.bundle.js.map (polyfills) 405 kB {5} [initial] [rendered]
chunk    {1} main.bundle.js, main.bundle.js.map (main) 41.1 kB {4} [initial] [rendered]
chunk    {2} styles.bundle.js, styles.bundle.js.map (styles) 149 kB {5} [initial] [rendered]
chunk    {3} scripts.bundle.js, scripts.bundle.js.map (scripts) 244 kB {5} [initial] [rendered]
chunk    {4} vendor.bundle.js, vendor.bundle.js.map (vendor) 2.75 MB [initial] [rendered]
chunk    {5} inline.bundle.js, inline.bundle.js.map (inline) 0 bytes [entry] [rendered]

ERROR in Maximum call stack size exceeded
webpack: Failed to compile.
webpack: Compiling...
Hash: 02fd7618c3e2de3db52e
Time: 9915ms
chunk    {0} 0.chunk.js, 0.chunk.js.map 926 kB {1} {2} {3} {5} [rendered]
chunk    {1} 1.chunk.js, 1.chunk.js.map 397 kB {0} {2} {3} {5} [rendered]
chunk    {2} 2.chunk.js, 2.chunk.js.map 33.1 kB {0} {1} {3} {5} [rendered]
chunk    {3} 3.chunk.js, 3.chunk.js.map 2.96 kB {0} {1} {2} {5} [rendered]
chunk    {4} polyfills.bundle.js, polyfills.bundle.js.map (polyfills) 405 kB {9} [initial] [rendered]
chunk    {5} main.bundle.js, main.bundle.js.map (main) 41.1 kB {8} [initial] [rendered]
chunk    {6} styles.bundle.js, styles.bundle.js.map (styles) 149 kB {9} [initial] [rendered]
chunk    {7} scripts.bundle.js, scripts.bundle.js.map (scripts) 244 kB {9} [initial] [rendered]
chunk    {8} vendor.bundle.js, vendor.bundle.js.map (vendor) 2.75 MB [initial] [rendered]
chunk    {9} inline.bundle.js, inline.bundle.js.map (inline) 0 bytes [entry] [rendered]
webpack: Compiled successfully.

And for "ng test" is same.

Any idea to resolve this ?

Body:
The best way i found to debug this is :

ng serve --aot

It will exit building if any error is found with an understandable error.


来源: stackexchange

问:
How can I mock a void method exception using JMockit
I have a problem when trying to mock void method exception.

```<code>    @Test
public void throwInternalServerException() throws Exception {
    new NonStrictExpectations() {{
        mockedClassInstance.voidMethod("abc", "def");
        result = new ServiceException();
    }};

    mockMvc.perform(post("/someRestApi/"))
            .andExpect(status().isInternalServerError());
</code>```

In the codes above, its success if i replace params "abc" and "def" with anyString

I tried the solution of this question but it does not work.

Any solution?

I used library : jmockit and spring-test.

答: The keyword anystring is used in the scenario, when whatever be the parameters(in this case, 'abc' and 'def'), it will throw the exception.

ContentLicense: CC BY-SA 3.0

Body:
I have a problem when trying to mock void method exception.

    @Test
public void throwInternalServerException() throws Exception {
    new NonStrictExpectations() {{
        mockedClassInstance.voidMethod("abc", "def");
        result = new ServiceException();
    }};

    mockMvc.perform(post("/someRestApi/"))
            .andExpect(status().isInternalServerError());

In the codes above, its success if i replace params "abc" and "def" with anyString

I tried the solution of this question but it does not work.

Any solution?

I used library : jmockit and spring-test.


问:
Justifying text inside a TextView in android
So, as most of you know, there is no text justifying inside a TextView in Android. So, I built a custom TextView to get around the problem. However, for some reason, sometimes punctuation marks break the line for some reason in some devices. I tested on an LG G3 and emulator (Nexus 4 running latest version) and a comma "," for instance breaks the justification on the LG G3 but not on the emulator.

If I add a Padding start and end (or left and right) of at least 2, the problem is solved. This looks very arbitrary to me.

Basically, my logic was that in order to justify the text, I would need to know the width of the TextView itself, construct the text into lines that are at maximum that length. Then, by finding the number of spaces in the line and the remaining empty space, stretch the " " (space) characters to be scaled according to remaining pixels (or, space in the view).

It works almost perfectly, and most of the time it supports RTL text as well.

here're some pictures of the text (a simple lorem impsum) with and without the offending marks (first one is on emulator nexus 4 running 7.1.1, second one is on LG G3 running v5.0)

Here's the code:

```<code>public class DTextView extends AppCompatTextView {

    private boolean justify;

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

    public DTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    public DTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(attrs);
    }

    private void setJustify(boolean justify) {
        this.justify = justify;
        if (justify) {
            justify();
        }
    }

    private void init(@Nullable AttributeSet attrs) {
        TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.DTextView, 0, 0);
        justify = ta.getBoolean(R.styleable.DTextView_justify, false);

        ta.recycle();
    }

    private SpannableStringBuilder justifyText() {

        String[] words = getText().toString().split(" ");
        setText("");

        int maxLineWidth = getWidth() - getPaddingLeft() - getPaddingRight();

        SpannableStringBuilder justifiedTextSpannable = new SpannableStringBuilder();

        //This will build the new text with the lines rearranged so that they will have a width
        //bigger than the View's own width
        ArrayList<String> lines = new ArrayList<>(0);
        String line = "";
        for (String word : words) {
            if (getWordWidth(line + word) < maxLineWidth) {
                line += word + " ";
            } else {
                line = line.substring(0, line.length() - 1);
                lines.add(line);
                line = word + " ";
            }
        }
        //Add the last line
        lines.add(line);

        for (int i = 0; i < lines.size() - 1; i++) {
            justifiedTextSpannable.append(justifyLine(lines.get(i), maxLineWidth));
            justifiedTextSpannable.append("\n");
        }

        justifiedTextSpannable.append(lines.get(lines.size() - 1));

        return justifiedTextSpannable;
    }

    private SpannableString justifyLine(String line, float maxWidth) {

        SpannableString sLine = new SpannableString(line);
        float spaces = line.split(" ").length - 1;

        float spaceCharSize = getWordWidth(" ");
        float emptySpace = maxWidth - getWordWidth(line);
        float newSpaceSize = (emptySpace / spaces) + spaceCharSize;
        float scaleX = newSpaceSize / spaceCharSize;

        for (int i = 0; i < line.length(); i++) {
            if (line.charAt(i) == ' ') {
                sLine.setSpan(new ScaleXSpan(scaleX), i, i + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }

        return sLine;
    }

    private void justify() {
        justify = false;
        setText(justifyText());
        invalidate();
    }

    private float getWordWidth(String word) {
        return getPaint().measureText(word);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (!justify)
            super.onDraw(canvas);
        else
            justify();
    }
}
</code>```

I would very much appreciate anyone that can shed some light on this.

答:
Try this way to justify text, it works for me

```<code>public class MainActivity extends Activity {

    private JustifiedTextView mJTv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mJTv=(JustifiedTextView) findViewById(R.id.activity_main_jtv_text);
        mJTv.setText(getResources().getString(R.string.test));
        mJTv.setTextSize(TypedValue.COMPLEX_UNIT_SP,20);
        mJTv.setLineSpacing(15);
        mJTv.setBackgroundColor(Color.RED);
        mJTv.setAlignment(Align.LEFT);
        mJTv.setTypeFace(Typeface.createFromAsset(getAssets(), "fonts/naskh_bold.ttf"));

    }
}
</code>```

XML

```<code><ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main_jsv"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ir.noghteh.JustifiedTextView
        android:id="@+id/activity_main_jtv_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:padding="25dp"
        xmlns:noghteh="http://noghteh.ir"
        noghteh:text="@string/hello_world"
        noghteh:textColor="@color/text"
        noghteh:textSize="18sp"
       >
    </ir.noghteh.JustifiedTextView>

</ScrollView>
</code>```

https://github.com/navabi/JustifiedTextView

https://github.com/ufo22940268/android-justifiedtextview

https://github.com/PareshMayani/Android-JustifyText

Body:
So, as most of you know, there is no text justifying inside a TextView in Android. So, I built a custom TextView to get around the problem. However, for some reason, sometimes punctuation marks break the line for some reason in some devices. I tested on an LG G3 and emulator (Nexus 4 running latest version) and a comma "," for instance breaks the justification on the LG G3 but not on the emulator.

If I add a Padding start and end (or left and right) of at least 2, the problem is solved. This looks very arbitrary to me.

Basically, my logic was that in order to justify the text, I would need to know the width of the TextView itself, construct the text into lines that are at maximum that length. Then, by finding the number of spaces in the line and the remaining empty space, stretch the " " (space) characters to be scaled according to remaining pixels (or, space in the view).

It works almost perfectly, and most of the time it supports RTL text as well.

here're some pictures of the text (a simple lorem impsum) with and without the offending marks (first one is on emulator nexus 4 running 7.1.1, second one is on LG G3 running v5.0)

Here's the code:

public class DTextView extends AppCompatTextView {

    private boolean justify;

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

    public DTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    public DTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(attrs);
    }

    private void setJustify(boolean justify) {
        this.justify = justify;
        if (justify) {
            justify();
        }
    }

    private void init(@Nullable AttributeSet attrs) {
        TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.DTextView, 0, 0);
        justify = ta.getBoolean(R.styleable.DTextView_justify, false);

        ta.recycle();
    }

    private SpannableStringBuilder justifyText() {

        String[] words = getText().toString().split(" ");
        setText("");

        int maxLineWidth = getWidth() - getPaddingLeft() - getPaddingRight();

        SpannableStringBuilder justifiedTextSpannable = new SpannableStringBuilder();

        //This will build the new text with the lines rearranged so that they will have a width
        //bigger than the View's own width
        ArrayList<String> lines = new ArrayList<>(0);
        String line = "";
        for (String word : words) {
            if (getWordWidth(line + word) < maxLineWidth) {
                line += word + " ";
            } else {
                line = line.substring(0, line.length() - 1);
                lines.add(line);
                line = word + " ";
            }
        }
        //Add the last line
        lines.add(line);

        for (int i = 0; i < lines.size() - 1; i++) {
            justifiedTextSpannable.append(justifyLine(lines.get(i), maxLineWidth));
            justifiedTextSpannable.append("\n");
        }

        justifiedTextSpannable.append(lines.get(lines.size() - 1));

        return justifiedTextSpannable;
    }

    private SpannableString justifyLine(String line, float maxWidth) {

        SpannableString sLine = new SpannableString(line);
        float spaces = line.split(" ").length - 1;

        float spaceCharSize = getWordWidth(" ");
        float emptySpace = maxWidth - getWordWidth(line);
        float newSpaceSize = (emptySpace / spaces) + spaceCharSize;
        float scaleX = newSpaceSize / spaceCharSize;

        for (int i = 0; i < line.length(); i++) {
            if (line.charAt(i) == ' ') {
                sLine.setSpan(new ScaleXSpan(scaleX), i, i + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }

        return sLine;
    }

    private void justify() {
        justify = false;
        setText(justifyText());
        invalidate();
    }

    private float getWordWidth(String word) {
        return getPaint().measureText(word);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (!justify)
            super.onDraw(canvas);
        else
            justify();
    }
}

I would very much appreciate anyone that can shed some light on this.

Body:
Try this way to justify text, it works for me

public class MainActivity extends Activity {

    private JustifiedTextView mJTv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mJTv=(JustifiedTextView) findViewById(R.id.activity_main_jtv_text);
        mJTv.setText(getResources().getString(R.string.test));
        mJTv.setTextSize(TypedValue.COMPLEX_UNIT_SP,20);
        mJTv.setLineSpacing(15);
        mJTv.setBackgroundColor(Color.RED);
        mJTv.setAlignment(Align.LEFT);
        mJTv.setTypeFace(Typeface.createFromAsset(getAssets(), "fonts/naskh_bold.ttf"));

    }
}

XML

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main_jsv"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ir.noghteh.JustifiedTextView
        android:id="@+id/activity_main_jtv_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:padding="25dp"
        xmlns:noghteh="http://noghteh.ir"
        noghteh:text="@string/hello_world"
        noghteh:textColor="@color/text"
        noghteh:textSize="18sp"
       >
    </ir.noghteh.JustifiedTextView>

</ScrollView>

https://github.com/navabi/JustifiedTextView

https://github.com/ufo22940268/android-justifiedtextview

https://github.com/PareshMayani/Android-JustifyText


问:
I need this code with dynamicly
I have a header menu and i do not want to add for each menu link in switch case like this, how can i do it dynamic...</p>

```<code>var sections = $(".href a");
var content = $("#load");

sections.click(function(){
    switch(this.id){
        case ('/p/settings/header-settings'):
            $(content).load('/p/settings/header-settings #load');
            window.history.pushState('user', 'user', '/p/settings/header-settings');
            break;
        case ('/p/settings/site-verifications'):
            $(content).load('/p/settings/site-verifications #load');
            window.history.pushState('user', 'user', '/p/settings/site-verifications');
            break;
        case ('/p/settings/analysis-settings'):
            $(content).load('/p/settings/analysis-settings #load');
            window.history.pushState('user', 'user', '/p/settings/header-settings');
            break;
        default:
            $(content).load('/p #load' );
            break;
    }
});
</code>```

答:
Directly pass the id with respected place instead of switch .And do with on() for dynamically append element .Its will perform depend on your id

var sections = $(".href a");
var content = $("#load");

sections.on('click', function() {
  var id = this.id;
  if(condition) //add with some  false condition as you wish for go to  default statement s
 {
  $(content).load('/p #load' );
 }else{
  $(content).load(id + ' #load');
  window.history.pushState('user', 'user', id);
  }
});```

Title: I need this code with dynamicly

Body:
I have a header menu and i do not want to add for each menu link in switch case like this, how can i do it dynamic...

var sections = $(".href a");
var content = $("#load");

sections.click(function(){
    switch(this.id){
        case ('/p/settings/header-settings'):
            $(content).load('/p/settings/header-settings #load');
            window.history.pushState('user', 'user', '/p/settings/header-settings');
            break;
        case ('/p/settings/site-verifications'):
            $(content).load('/p/settings/site-verifications #load');
            window.history.pushState('user', 'user', '/p/settings/site-verifications');
            break;
        case ('/p/settings/analysis-settings'):
            $(content).load('/p/settings/analysis-settings #load');
            window.history.pushState('user', 'user', '/p/settings/header-settings');
            break;
        default:
            $(content).load('/p #load' );
            break;
    }
});


问:
SQL Query for list within select where field = value and otherfield = othervalue
I need to fudge an existing SQL Server procedure rather quickly. It's a bit of a hack job but needs must.

I need for the following to return a list of voucher codes and invoice numbers rather than just one row of data where the comment is (in the WHERE clause):

```<code>SELECT TOP 10
    IH.INH_Voucher AS [ID], IH.COY_ID AS COY_ID,
    IH.INH_DateSupInv AS ORD_UpdatedOn,
    V.VES_ID, V.VES_IMOnumber, IH.INH_Order,
    IH.INH_ID AS ORD_ID, IH.INH_INDID
FROM
    InvoiceHDR IH (NOLOCK)
INNER JOIN
    VESSACCOMP VA ON IH.COY_ID = VA.COY_ID
INNER JOIN
    Vessel V ON VA.VES_ID =  V.VES_ID
WHERE
    v.VSS_ID IN ('01') AND
    (IH.INH_Status >= 20  AND IH.INH_Status <= 40) AND
    --IH.INH_Voucher = '170CH' AND IH.INH_SupInv = '1532' NEED LIST
    IH.INH_INDID IS NOT NULL
</code>```

So I would need

```<code>Voucher = '1700CH' AND SupInv = '1235' AND
Voucher = '180CH' AND SupInv = '1111' AND
</code>```

And so on for many matching VoucherCodes and InvoiceCodes.

I hope this is clear?

Thanks.

答:
You can apply the following WHERE clause to your query:::</p>

```<code>WHERE
    v.VSS_ID IN ('01') AND
    (IH.INH_Status BETWEEN 20 AND 40) AND
    ((IH.INH_Voucher = '170CH' AND IH.INH_SupInv = '1532')
    OR (IH.INH_Voucher = '180CH' AND IH.INH_SupInv = '1111'))
    AND IH.INH_INDID IS NOT NULL
</code>```

Body:
I need to fudge an existing SQL Server procedure rather quickly. It's a bit of a hack job but needs must.

I need for the following to return a list of voucher codes and invoice numbers rather than just one row of data where the comment is (in the WHERE clause):

SELECT TOP 10
    IH.INH_Voucher AS [ID], IH.COY_ID AS COY_ID,
    IH.INH_DateSupInv AS ORD_UpdatedOn,
    V.VES_ID, V.VES_IMOnumber, IH.INH_Order,
    IH.INH_ID AS ORD_ID, IH.INH_INDID
FROM
    InvoiceHDR IH (NOLOCK)
INNER JOIN
    VESSACCOMP VA ON IH.COY_ID = VA.COY_ID
INNER JOIN
    Vessel V ON VA.VES_ID =  V.VES_ID
WHERE
    v.VSS_ID IN ('01') AND
    (IH.INH_Status >= 20  AND IH.INH_Status <= 40) AND
    --IH.INH_Voucher = '170CH' AND IH.INH_SupInv = '1532' NEED LIST
    IH.INH_INDID IS NOT NULL

So I would need

Voucher = '1700CH' AND SupInv = '1235' AND
Voucher = '180CH' AND SupInv = '1111' AND

And so on for many matching VoucherCodes and InvoiceCodes.

I hope this is clear?

Thanks.

Body:
You can apply the following WHERE clause to your query:::

WHERE
    v.VSS_ID IN ('01') AND
    (IH.INH_Status BETWEEN 20 AND 40) AND
    ((IH.INH_Voucher = '170CH' AND IH.INH_SupInv = '1532')
    OR (IH.INH_Voucher = '180CH' AND IH.INH_SupInv = '1111'))
    AND IH.INH_INDID IS NOT NULL


问:
How to transform log4net config like web.config?
From my .csproj file:

```<code><Content Include="log4net.config">
  <SubType>Designer</SubType>
</Content>
<Content Include="log4net.Release.config">
  <DependentUpon>log4net.config</DependentUpon>
</Content>
<Content Include="log4net.Debug.config">
  <DependentUpon>log4net.config</DependentUpon>
</Content>
<Content Include="log4net.Live.config">
  <DependentUpon>log4net.config</DependentUpon>
</Content>
<Content Include="log4net.Demo.config">
  <DependentUpon>log4net.config</DependentUpon>
</Content>
</code>```

At the bottom of my .csproj file:

```<code>  <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
  <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" />
    <Target Name="AfterCompile" Condition="exists('log4net.$(Configuration).config')">
      <TransformXml Source="log4net.config"
        Destination="$(IntermediateOutputPath)$(TargetFileName).config"
        Transform="log4net.$(Configuration).config" />
      <ItemGroup>
        <AppConfigWithTargetPath Remove="log4net.config"/>
        <AppConfigWithTargetPath Include="$(IntermediateOutputPath)$(TargetFileName).config">
          <TargetPath>$(TargetFileName).config</TargetPath>
        </AppConfigWithTargetPath>
      </ItemGroup>
    </Target>
</code>```

From log4net.config

```<code><connectionString name="ConnName"
value="Data Source=localhost\sqlexpress;Initial Catalog=localdb;Persist Security Info=True;Integrated Security=SSPI;" />
</code>```

From log4net.Live.config (removed sensitive data)

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
    <connectionString name="ConnName" value="Data Source=127.0.0.1;Initial Catalog=DBName;Persist Security Info=True;User ID=userid;Password=pword"
        providerName="System.Data.SqlClient" xdt:Transform="Replace" xdt:Locator="Match(name)" />
</configuration>
</code>```

I checked msbuild output and I see that it transformed my web.config correctly, but I see no output for it transforming log4net.  Also, when I check the log4net.config file after publish, it has the original connection string.

What am I doing wrong :)?

Thanks!

Update

I had some errors in the code that msbuild were outputting as warnings that I didn't see.
I fixed those and now I get some output from MSBuild:

AfterCompile:   Transforming Source
  File: log4net.config
      Applying Transform File: log4net.Live.config
      Output File: obj\Live\Common.UI.Web.dll.config

  Transformation succeeded

This is still a problem, because the file should be named log4net.config, not Common.UI.Web.dll.config...

For whatever reason

$(TargetFileName)

is taking on the name of the .csproj file name.  If I replace it with just log4net, then it outputs correctly

Update

File is stuck in obj folder and is not getting picked up when publishing.

答:
ms007's answer nearly got me there though I was getting an access denied issue on the file as the build server had set it to read only. Here is my solution. </p>

```<code>  <Target Name="ApplyLoggingConfiguration" BeforeTargets="BeforeBuild" Condition="Exists('log4net.$(Configuration).config')">

    <TransformXml Source="log4net.config"
                  Transform="log4net.$(Configuration).config"
                  Destination="temp_log4net.config" />
    <Copy SourceFiles="temp_log4net.config"
          DestinationFiles="log4net.config"
          OverwriteReadOnlyFiles="True" />

    <Delete Files="temp_log4net.config" />
  </Target>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
From my .csproj file:

<Content Include="log4net.config">
  <SubType>Designer</SubType>
</Content>
<Content Include="log4net.Release.config">
  <DependentUpon>log4net.config</DependentUpon>
</Content>
<Content Include="log4net.Debug.config">
  <DependentUpon>log4net.config</DependentUpon>
</Content>
<Content Include="log4net.Live.config">
  <DependentUpon>log4net.config</DependentUpon>
</Content>
<Content Include="log4net.Demo.config">
  <DependentUpon>log4net.config</DependentUpon>
</Content>

At the bottom of my .csproj file:

  <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
  <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" />
    <Target Name="AfterCompile" Condition="exists('log4net.$(Configuration).config')">
      <TransformXml Source="log4net.config"
        Destination="$(IntermediateOutputPath)$(TargetFileName).config"
        Transform="log4net.$(Configuration).config" />
      <ItemGroup>
        <AppConfigWithTargetPath Remove="log4net.config"/>
        <AppConfigWithTargetPath Include="$(IntermediateOutputPath)$(TargetFileName).config">
          <TargetPath>$(TargetFileName).config</TargetPath>
        </AppConfigWithTargetPath>
      </ItemGroup>
    </Target>

From log4net.config

<connectionString name="ConnName"
value="Data Source=localhost\sqlexpress;Initial Catalog=localdb;Persist Security Info=True;Integrated Security=SSPI;" />

From log4net.Live.config (removed sensitive data)

<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
    <connectionString name="ConnName" value="Data Source=127.0.0.1;Initial Catalog=DBName;Persist Security Info=True;User ID=userid;Password=pword"
        providerName="System.Data.SqlClient" xdt:Transform="Replace" xdt:Locator="Match(name)" />
</configuration>

I checked msbuild output and I see that it transformed my web.config correctly, but I see no output for it transforming log4net.  Also, when I check the log4net.config file after publish, it has the original connection string.

What am I doing wrong :)?

Thanks!

Update

I had some errors in the code that msbuild were outputting as warnings that I didn't see.
I fixed those and now I get some output from MSBuild:

AfterCompile:   Transforming Source
  File: log4net.config
      Applying Transform File: log4net.Live.config
      Output File: obj\Live\Common.UI.Web.dll.config

  Transformation succeeded

This is still a problem, because the file should be named log4net.config, not Common.UI.Web.dll.config...

For whatever reason

$(TargetFileName)

is taking on the name of the .csproj file name.  If I replace it with just log4net, then it outputs correctly

Update

File is stuck in obj folder and is not getting picked up when publishing.

Body:
ms007's answer nearly got me there though I was getting an access denied issue on the file as the build server had set it to read only. Here is my solution.

  <Target Name="ApplyLoggingConfiguration" BeforeTargets="BeforeBuild" Condition="Exists('log4net.$(Configuration).config')">

    <TransformXml Source="log4net.config"
                  Transform="log4net.$(Configuration).config"
                  Destination="temp_log4net.config" />
    <Copy SourceFiles="temp_log4net.config"
          DestinationFiles="log4net.config"
          OverwriteReadOnlyFiles="True" />

    <Delete Files="temp_log4net.config" />
  </Target>


问:
How to get selected TabBar item?
I have went through some SO question and found this :

```<code>NSLog(@"selected tab index => %d",self.tabBarController.tabBar.selectedItem.tag);
</code>```

However this is always return 0.
What am I doing wrong?

my code in AppDelegate :

```<code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    // Assign tab bar item with titles
    UITabBarController *tabBarController = (UITabBarController *)self.window.rootViewController;
    UITabBar *tabBar = tabBarController.tabBar;
    UITabBarItem *tabBarItem1 = [tabBar.items objectAtIndex:0];
    UITabBarItem *tabBarItem2 = [tabBar.items objectAtIndex:1];
    UITabBarItem *tabBarItem3 = [tabBar.items objectAtIndex:2];
    return YES;
}
</code>```

Edit :

I would like to do something like this :

```<code>if(self.tabBarController.tabBar.selectedItem.tag == 0)
{
    [[UITabBar appearance] setSelectedImageTintColor:[UIColor orangeColor]];
}
else     if(self.tabBarController.tabBar.selectedItem.tag == 1)
{
    [[UITabBar appearance] setSelectedImageTintColor:[UIColor blueColor]];
}
</code>```

答:
The original question asked how to get/set the UITabBarItem using the TAG. I don't see an actual answer here.

Tag IS the better value to use particularly if you wish to save or "remember" the value so as to be able to restore the "last" selected tab in a future session. The index of any viewController on the TabBar can change if the user re-arranges tabs from the More menu, while tag will not if the App is properly designed.

To get the tag for the currently selected TabBarItem:

```<code>_tabBarController.tabBar.selectedItem.tag;
</code>```

To restore/set it from a value:

```<code>unsigned lastSelectedIndex = [[userSettings objectForKey:SavedTabLastViewedKey] unsignedIntValue];
for(UIViewController *vc in _tabBarController.viewControllers) {
    if(vc.tabBarItem.tag == lastSelectedIndex) {
        _tabBarController.selectedViewController = vc;
        break;
    }
}
</code>```

Title: How to get selected TabBar item?

Body:
I have went through some SO question and found this :

NSLog(@"selected tab index => %d",self.tabBarController.tabBar.selectedItem.tag);

However this is always return 0.
What am I doing wrong?

my code in AppDelegate :

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    // Assign tab bar item with titles
    UITabBarController *tabBarController = (UITabBarController *)self.window.rootViewController;
    UITabBar *tabBar = tabBarController.tabBar;
    UITabBarItem *tabBarItem1 = [tabBar.items objectAtIndex:0];
    UITabBarItem *tabBarItem2 = [tabBar.items objectAtIndex:1];
    UITabBarItem *tabBarItem3 = [tabBar.items objectAtIndex:2];
    return YES;
}

Edit :

I would like to do something like this :

if(self.tabBarController.tabBar.selectedItem.tag == 0)
{
    [[UITabBar appearance] setSelectedImageTintColor:[UIColor orangeColor]];
}
else     if(self.tabBarController.tabBar.selectedItem.tag == 1)
{
    [[UITabBar appearance] setSelectedImageTintColor:[UIColor blueColor]];
}

Body:
The original question asked how to get/set the UITabBarItem using the TAG. I don't see an actual answer here.

Tag IS the better value to use particularly if you wish to save or "remember" the value so as to be able to restore the "last" selected tab in a future session. The index of any viewController on the TabBar can change if the user re-arranges tabs from the More menu, while tag will not if the App is properly designed.

To get the tag for the currently selected TabBarItem:

_tabBarController.tabBar.selectedItem.tag;

To restore/set it from a value:

unsigned lastSelectedIndex = [[userSettings objectForKey:SavedTabLastViewedKey] unsignedIntValue];
for(UIViewController *vc in _tabBarController.viewControllers) {
    if(vc.tabBarItem.tag == lastSelectedIndex) {
        _tabBarController.selectedViewController = vc;
        break;
    }
}


问:
How to create a service in Python in Windows?
I have found http://code.activestate.com/recipes/576451-how-to-create-a-windows-service-in-python/

But that service does nothing. How can I use that service for running specific Python file?

答:
You can put your business code in SvcDoRun. The sample at your link just logs a message every three seconds. Just don't forget to check self.hWaitStop periodically.

Sometimes it is convenient to create a worker thread and do all work on that thread, or maybe start a child process. An additional complication in this case is that you have to think about synchronization.


问:
Key Value Pair in C Language
I am new to C programming and I am trying to create a key value structure as in Perl Programming. I saw one solution like :-

```<code>struct key_value
{
   int key;
   char* value;
};

struct key_value kv;

kv.key = 1;
kv.value = "foo";
</code>```

But I don't know how to access these values from this structure. Can someone enlight on this ?

答:
Your code already have the method to acess the values.

```<code>kv.key = 1
kv.value = "foo"
</code>```

To get the values assigned is simple

```<code>kv.key
kv.value
</code>```

It is a simple struct, if you wanna something like python dict you will need to implement a hash struct which will be more complicated.

Title: Key Value Pair in C Language

Body:
I am new to C programming and I am trying to create a key value structure as in Perl Programming. I saw one solution like :-

struct key_value
{
   int key;
   char* value;
};

struct key_value kv;

kv.key = 1;
kv.value = "foo";

But I don't know how to access these values from this structure. Can someone enlight on this ?

Body:
Your code already have the method to acess the values.

kv.key = 1
kv.value = "foo"

To get the values assigned is simple

kv.key
kv.value

It is a simple struct, if you wanna something like python dict you will need to implement a hash struct which will be more complicated.


问:
App thinning for video resources on iOS
I'm developing an universal iOS app and it has lot of video resources. In order to reduce the size of the app I would like to apply app thinning. I know that it's possible to do it with image resources but I haven't found any documentation about how to it with video resources. In other words, I would like to have video in different resolutions for iPhone and iPad devices.

Is it possible to do it with video resources?

Thanks a lot

答:
I think there is no way currently to decrease size of the video assets drastically.
You can look into On Demand Resources if it fits the bill.</p>

Title: App thinning for video resources on iOS


问:
Javascript, Open a tab, run a script then close it and move onto different tabs
So My whole plan is to, have a link which I will then enter, the tab is then opened and then a javascript script is run which will select a drop down, after it has done this then the tab is closed. I will need this because I open around 50 tabs, but the first ones load and then it takes a very long time to load all of them.

For example,

Open a tab: such as stack overflow.com once the page has fully loaded, I need it to run the script "document.getElementsByClassName("blah blah")[0].click();" and then close the tab and move onto the next, which will continue about 50 tabs.

Thanks :)

T

答:
You could create the instances using JavaScript. It'd be analog to this:
How to refresh another page using javascript without opening the same page in a new tab</p>


问:
Casting hex string to signed int results in different values in different platforms
I am dealing with an edge case in a program that I want to be multi-platform. Here is the extract of the problem:

```<code>#include <stdio.h>
#include <string.h>

void print_bits(size_t const size, void const * const ptr){
    unsigned char *b = (unsigned char*) ptr;
    unsigned char byte;
    int i, j;

    for (i=size-1;i>=0;i--)
    {
        for (j=7;j>=0;j--)
        {
            byte = (b[i] >> j) & 1;
            printf("%u", byte);
        }
    }
    puts("");
}

int main() {

char* ascii = "0x80000000";
int myint = strtol(ascii, NULL, 16);

printf("%s to signed int is %d and bits are:\t", ascii, myint);
print_bits(sizeof myint, &myint);

return 0;
}
</code>```

So when I compile with GCC on Linux I get this output:

```<code>0x80000000 to signed int is -2147483648 and bits are:   10000000000000000000000000000000
</code>```

On a Windows, using MSVC and MinGW I get:

```<code>0x80000000 to signed int is 2147483647 and bits are:    01111111111111111111111111111111
</code>```

I think the GCC outputs the correct expected values. My question is, where does this difference come from and how to make sure that on all compilers I get the correct result?

UPDATE

The reason behind this code is, I have to check if the MSB (bit #31) of the HEX value is 0 or 1. Then, I have to get the unsigned integer value of the next 7 bits (#30 to #24) result (in case of 0x80000000these 7 bits should result in 0:

```<code>    int msb_is_set = myint & 1;
    uint8_t next_7_bits;

next_7_bits = myint >> 24; //fine on GCC, outputs 0 for the next 7 bits
#ifdef WIN32 //If I do not do this, next_7_bit will be 127 on Windows instead of 0
    if(msb_is_set )
        next_7_bits = myint >> 1;
#endif
</code>```

P.S. This is on the same machine (i5 64bit)

答:
Don't do this:

```<code>#ifdef __GCC__
</code>```

because a compiler switch might change the way things work.  Better to do something like:

In some header somewhere:

```<code>#ifdef __GCC__
#define FEATURE_SHIFT_RIGHT_24
#endif
#ifdef __MSVC__
#define FEATURE_SHIFT_RIGHT_1
#endif
</code>```

Then in your main code:

```<code>#ifdef FEATURE_SHIFT_RIGHT_24
next_7_bits = myint >> 24;
#endif
#ifdef FEATURE_SHIFT_RIGHT_1
   if(msb_is_set )
     next_7_bits = myint >> 1;
#endif
</code>```

Your code should handle the implementation details, and the header should check which implementation is required by which compiler.

This separates out the code required from detecting which method is required for this compiler.   In your header you can do more complex detection of compiler features.

e.g.

```<code>#ifdef __GCC__ && __GCCVERION__ > 1.23
</code>```

etc

Body:
I am dealing with an edge case in a program that I want to be multi-platform. Here is the extract of the problem:

#include <stdio.h>
#include <string.h>

void print_bits(size_t const size, void const * const ptr){
    unsigned char *b = (unsigned char*) ptr;
    unsigned char byte;
    int i, j;

    for (i=size-1;i>=0;i--)
    {
        for (j=7;j>=0;j--)
        {
            byte = (b[i] >> j) & 1;
            printf("%u", byte);
        }
    }
    puts("");
}

int main() {

char* ascii = "0x80000000";
int myint = strtol(ascii, NULL, 16);

printf("%s to signed int is %d and bits are:\t", ascii, myint);
print_bits(sizeof myint, &myint);

return 0;
}

So when I compile with GCC on Linux I get this output:

0x80000000 to signed int is -2147483648 and bits are:   10000000000000000000000000000000

On a Windows, using MSVC and MinGW I get:

0x80000000 to signed int is 2147483647 and bits are:    01111111111111111111111111111111

I think the GCC outputs the correct expected values. My question is, where does this difference come from and how to make sure that on all compilers I get the correct result?

UPDATE

The reason behind this code is, I have to check if the MSB (bit #31) of the HEX value is 0 or 1. Then, I have to get the unsigned integer value of the next 7 bits (#30 to #24) result (in case of 0x80000000these 7 bits should result in 0:

    int msb_is_set = myint & 1;
    uint8_t next_7_bits;

next_7_bits = myint >> 24; //fine on GCC, outputs 0 for the next 7 bits
#ifdef WIN32 //If I do not do this, next_7_bit will be 127 on Windows instead of 0
    if(msb_is_set )
        next_7_bits = myint >> 1;
#endif

P.S. This is on the same machine (i5 64bit)

Body:
Don't do this:

#ifdef __GCC__

because a compiler switch might change the way things work.  Better to do something like:

In some header somewhere:

#ifdef __GCC__
#define FEATURE_SHIFT_RIGHT_24
#endif
#ifdef __MSVC__
#define FEATURE_SHIFT_RIGHT_1
#endif

Then in your main code:

#ifdef FEATURE_SHIFT_RIGHT_24
next_7_bits = myint >> 24;
#endif
#ifdef FEATURE_SHIFT_RIGHT_1
   if(msb_is_set )
     next_7_bits = myint >> 1;
#endif

Your code should handle the implementation details, and the header should check which implementation is required by which compiler.

This separates out the code required from detecting which method is required for this compiler.   In your header you can do more complex detection of compiler features.

e.g.

#ifdef __GCC__ && __GCCVERION__ > 1.23

etc


问:
Pandas - Merge Two Dataframes - sum across column
I am trying to merge two dataframes (call them DF1 & DF2) that basically look like the below.  My goal is:

I want open/close/low/high to all come from DF1.

I want numEvents and Volume = DF1 + DF2.

In cases where DF2 has rows that don't exist in DF1, I want open/close/low/high to be NaN (so I can later backfill them), and numEvents and Volume to come from DF2 as is.

Any help is much appreciated!

答:
use pd.merge:

it's outer join since you want data from both dfs.

pd.merge([A,B],how='outer', on=<mutual_key>)


问:
twilio rest API for event registration and listening
I'm using twilio rest API to implement a chat iOS app in objective-c. Though twilio has iOS SDK, I'm required to use rest API only. My question is does anyone know how to use twilio rest API for event registration and listening, such as message sending?</p>

答:
Twilio developer evangelist here.

The Twilio Programmable Chat API uses webhooks to notify your application of incoming messages. Note though that webhooks are not fired for events that are initiated from the REST API. Since you are in control of sending messages via the REST API you should be able to notify other parts of your application when you do so too.


问:
How to avoid lookup overhead in python with full-qualified names to avoid circular imports problems
To avoid circular imports, one can use import x and then use x.func each time.  (cf. Circular (or cyclic) imports in Python ). (In my case, I have no other choice actually)

However, when x is for example a.b.c.d.e, then you get a non-negligible overhead (in addition to the readability problems), especially if your function is called repetitively. I would like to know if there is some kind of mechanism to define shortcuts like E = a.b.c.d.e when the imports are resolved ? (or something to avoid the lookup eachtime)

Note : on pypy, there is no performance differences but on CPython, you can get ×2 improvement between a.A() and a.b.c.d.e.f.g.h.A()

EDIT
about the import ... as ... solution,
this is the trace I get (I think it will be clearer than any explication I could give) :

```<code>  File "MyApp/__init__.py", line 3, in <module>
    import MyApp.core
  File "MyApp/core.py", line 3, in <module>
    import MyApp.formatters.ASCIIFormatter as _F
  File "MyApp/formatters/__init__.py", line 2, in <module>
    import MyApp.formatters.ASCIIFormatter as ASCIIFormatter
  File "MyApp/formatters/ASCIIFormatter.py", line 2, in <module>
    import MyApp.core as _C
AttributeError: module 'MyApp' has no attribute 'core'
</code>```

答:
You can set an alias when importing a module:

```<code>import a.b.c.d.e as E
</code>```

The code you posted would work as well, but it's not as pretty:

```<code>import a.b.c.d.e
E = a.b.c.d.e
</code>```

Body:
To avoid circular imports, one can use import x and then use x.func each time.  (cf. Circular (or cyclic) imports in Python ). (In my case, I have no other choice actually)

However, when x is for example a.b.c.d.e, then you get a non-negligible overhead (in addition to the readability problems), especially if your function is called repetitively. I would like to know if there is some kind of mechanism to define shortcuts like E = a.b.c.d.e when the imports are resolved ? (or something to avoid the lookup eachtime)

Note : on pypy, there is no performance differences but on CPython, you can get ×2 improvement between a.A() and a.b.c.d.e.f.g.h.A()

EDIT
about the import ... as ... solution,
this is the trace I get (I think it will be clearer than any explication I could give) :

  File "MyApp/__init__.py", line 3, in <module>
    import MyApp.core
  File "MyApp/core.py", line 3, in <module>
    import MyApp.formatters.ASCIIFormatter as _F
  File "MyApp/formatters/__init__.py", line 2, in <module>
    import MyApp.formatters.ASCIIFormatter as ASCIIFormatter
  File "MyApp/formatters/ASCIIFormatter.py", line 2, in <module>
    import MyApp.core as _C
AttributeError: module 'MyApp' has no attribute 'core'

Body:
You can set an alias when importing a module:

import a.b.c.d.e as E

The code you posted would work as well, but it's not as pretty:

import a.b.c.d.e
E = a.b.c.d.e


问:
C++ interface without virtual functions
I was wondering how we can declare an interface in C++ without using virtual functions. After some internet searching I put together this solution:

```<code>#include <type_traits>

using namespace std;

// Definition of a type trait to check if a class defines a member function "bool foo(bool)"
template<typename T, typename = void>
struct has_foo : false_type { };

template<typename T>
struct has_foo<T, typename enable_if<is_same<bool, decltype(std::declval<T>().foo(bool()))>::value, void>::type> : true_type { };

// Definition of a type trait to check if a class defines a member function "void bar()"
template<typename T, typename = void>
struct has_bar : false_type { };

template<typename T>
struct has_bar<T, typename enable_if<is_same<void, decltype(std::declval<T>().bar())>::value, void>::type> : true_type { };

// Class defining the interface
template <typename T>
class Interface{
public:
  Interface(){
    static_assert(has_foo<T>::value == true, "member function foo not implemented");
    static_assert(has_bar<T>::value == true, "member function bar not implemented");
  }
};

// Interface implementation
class Implementation:Interface<Implementation>{
public:
  // If the following member functions are not declared a compilation error is returned by the compiler
  bool foo(bool in){return !in;}
  void bar(){}
};

int main(){}
</code>```

I'm planning to use this design strategy in a project where I will use static polymorphism only.
The C++ standard I will use in the project is C++11.

What do you think are the pros and cons of this approach?

What improvements can be made on the code I proposed?

EDIT 1:
I just realised that inheriting from Interface is not needed. This code could also be used:

```<code>class Implementation{
  Interface<Implementation> unused;
public:
  bool foo(bool in){return !in;}
  void bar(){}
};
</code>```

EDIT 2-3:
One major difference between the static_assert solution (with or without CRTP) and the standard CRTP is that the CRTP does not guarantee that the derived class implements all the interface members. E.g., the following code compiles correctly:

```<code>#include <type_traits>
using namespace std;

template< typename T>
class Interface{
public:
  bool foo(bool in){
    return static_cast<T*>(this)->foo(in);
  }
  void bar(){
    static_cast<T*>(this)->bar();
  }
};

class Implementation: public Interface<Implementation>{
public:
//    bool foo(bool in){return !in;}
//    void bar(){}
};

int main(){}
</code>```

An error about a missing member function will be returned by the compiler only when the functions foo or bar will be required.

The way I see it, the static_assert solution feels more like an interface declaration than CRTP alone.

答:
It appears that you want to implement concepts (lite). You may want to read the article before attempting an implementation.

Absent compiler support, you can partially implement this idea. Your static_assert idea is a known way to express interface requirements.

Consider the Sortable example from the link. You can create a class template Sortable, use static_assert to assert all kind of thinks about the template parameter. You explain to your users that they need to implement a certain cet of methods, and to enforce that set is implemented, they need to make use of Sortable<TheirClass> one way or another.

In order to express, right in a function declaration. the idea that your function requires a Sortable, you will have to resort to something like this:

```<code>template <typename Container>
auto doSomethingWithSortable (Container&) -> std::enable_if<Implements<Container, Sortable>>::type;
</code>```

Title: C++ interface without virtual functions

Body:
I was wondering how we can declare an interface in C++ without using virtual functions. After some internet searching I put together this solution:

#include <type_traits>

using namespace std;

// Definition of a type trait to check if a class defines a member function "bool foo(bool)"
template<typename T, typename = void>
struct has_foo : false_type { };

template<typename T>
struct has_foo<T, typename enable_if<is_same<bool, decltype(std::declval<T>().foo(bool()))>::value, void>::type> : true_type { };

// Definition of a type trait to check if a class defines a member function "void bar()"
template<typename T, typename = void>
struct has_bar : false_type { };

template<typename T>
struct has_bar<T, typename enable_if<is_same<void, decltype(std::declval<T>().bar())>::value, void>::type> : true_type { };

// Class defining the interface
template <typename T>
class Interface{
public:
  Interface(){
    static_assert(has_foo<T>::value == true, "member function foo not implemented");
    static_assert(has_bar<T>::value == true, "member function bar not implemented");
  }
};

// Interface implementation
class Implementation:Interface<Implementation>{
public:
  // If the following member functions are not declared a compilation error is returned by the compiler
  bool foo(bool in){return !in;}
  void bar(){}
};

int main(){}

I'm planning to use this design strategy in a project where I will use static polymorphism only.
The C++ standard I will use in the project is C++11.

What do you think are the pros and cons of this approach?

What improvements can be made on the code I proposed?

EDIT 1:
I just realised that inheriting from Interface is not needed. This code could also be used:

class Implementation{
  Interface<Implementation> unused;
public:
  bool foo(bool in){return !in;}
  void bar(){}
};

EDIT 2-3:
One major difference between the static_assert solution (with or without CRTP) and the standard CRTP is that the CRTP does not guarantee that the derived class implements all the interface members. E.g., the following code compiles correctly:

#include <type_traits>
using namespace std;

template< typename T>
class Interface{
public:
  bool foo(bool in){
    return static_cast<T*>(this)->foo(in);
  }
  void bar(){
    static_cast<T*>(this)->bar();
  }
};

class Implementation: public Interface<Implementation>{
public:
//    bool foo(bool in){return !in;}
//    void bar(){}
};

int main(){}

An error about a missing member function will be returned by the compiler only when the functions foo or bar will be required.

The way I see it, the static_assert solution feels more like an interface declaration than CRTP alone.

Body:
It appears that you want to implement concepts (lite). You may want to read the article before attempting an implementation.

Absent compiler support, you can partially implement this idea. Your static_assert idea is a known way to express interface requirements.

Consider the Sortable example from the link. You can create a class template Sortable, use static_assert to assert all kind of thinks about the template parameter. You explain to your users that they need to implement a certain cet of methods, and to enforce that set is implemented, they need to make use of Sortable<TheirClass> one way or another.

In order to express, right in a function declaration. the idea that your function requires a Sortable, you will have to resort to something like this:

template <typename Container>
auto doSomethingWithSortable (Container&) -> std::enable_if<Implements<Container, Sortable>>::type;


问:
How to copy one hundred files from folder to folder?
I have one million files in one folder, I want to copy just one hundred files from them in another folder: </p>

```<code>import os
import shutil

dir_src = ("/Big_Folder")
dir_dst = ("/Small_Folder")

for filename in os.listdir(dir_src):
    shutil.copy( dir_src + filename, dir_dst)
    print(filename)
</code>```

<p>This script copy for me all files, how to copy just 100000 files please? </p>

答:
Simply slice the list you want to iterate over:</p>

```<code>for filename in os.listdir(dir_src)[:100]:
    ...
</code>```

Body:
I have one million files in one folder, I want to copy just one hundred files from them in another folder:

import os
import shutil

dir_src = ("/Big_Folder")
dir_dst = ("/Small_Folder")

for filename in os.listdir(dir_src):
    shutil.copy( dir_src + filename, dir_dst)
    print(filename)

This script copy for me all files, how to copy just 100000 files please?

Body:
Simply slice the list you want to iterate over:

for filename in os.listdir(dir_src)[:100]:
    ...


问:
How to check if process is running on Red Hat Linux?
I've been using a modified class I found to check if another instance of the same process is already running, the problem is that the method of checking for the process adds another instance of the same process.

When my application starts, a new process ID is created and is visible with:

```<code>ps -A | grep "AppName"
</code>```

With this I get a since entry returned, I then check for another instance of the application using:

```<code>QString strCMD = "ps -A | grep \"" + mcstrAppName + "\"";
QProcess objProc;
objProc.start("bash", QStringList() << "-c" << strCMD);

if ( objProc.waitForStarted() != true || objProc.waitForFinished() != true ) {
    mcpobjApp->exit(cleanExit(-1, "Unable to determine if another instance is running!"));
    return;
}
</code>```

As soon as the 'start' method is called another instance of the same application appears in the process table, again, verified with:

```<code>ps -A | grep "AppName"
</code>```

Two entries now appear each with a different PID.  I've also tried:

```<code>QString strOptions = "-A | grep \"" + mcstrAppName + "\"";
QProcess objProc;
objProc.start("ps", QStringList() << strOptions);
</code>```

The result is the same, two entries in process table.

Is there a way to check the process table for another instance without adding an additional instance?

答:
The actual solution I used, which I wrote myself, prototype: clsSingleInstance.h:

```<code>class clsSingleInstance : public QObject {
Q_OBJECT

public:
    explicit clsSingleInstance(const QString& strAppName, QApplication* pobjApp);

public slots:
    void check();

private:
    const int mcintDelay = 3000;
    const QString mcstrAppName;

    qint64 mint64PID;
    QApplication const* mcpobjApp;
    QTimer* mptmrCheck;

    Q_DISABLE_COPY(clsSingleInstance);
};
</code>```

Implementation, clsSingleInstance.cpp:

```<code>    #include "clsSingleInstance.h"
    /**
     * @brief clsSingleInstance::clsSingleInstance
     * @param strAppName : The application name as it will appear in the process list
     * @param pobjApp : Pointer to the applicaiton instance
     */
    clsSingleInstance::clsSingleInstance(const QString& strAppName
                                        ,QApplication* pobjApp)
                                        :QObject(pobjApp)
                                        ,mcstrAppName(strAppName)
                                        ,mcpobjApp(pobjApp) {
    //Save the process ID
        mint64PID = mcpobjApp->applicationPid();
    //Run check now to determine if another instance is running
        check();
    //Set-up timer to check for another instance regularly
        mptmrCheck = new QTimer(this);

        if ( mptmrCheck != NULL ) {
            connect(mptmrCheck, SIGNAL(timeout()), this, SLOT(check()));
            mptmrCheck->start(mcintDelay);
        }
    }
    /**
     * @brief clsSingleInstance::check
     * Checks application instances running
     */
    void clsSingleInstance::check() {
        const QString cstrCheckFile = clsMainWin::mcszConfigPath
                                        + mcstrAppName + ".pid";
        QFile objPID(cstrCheckFile);

        if ( objPID.exists() == true ) {
    //Check the file date / time stamp
            QDateTime dtCreated = QFileInfo(cstrCheckFile).created()
                     ,dtNow = QDateTime::currentDateTime();
            qint64 int64Created = dtCreated.toMSecsSinceEpoch()
                  ,int64Now = dtNow.toMSecsSinceEpoch()
                  ,int64Diff = int64Now - int64Created;
    //Is the file current and being updated?
            if ( int64Diff < (mcintDelay * 2) ) {
    //PID file is live, read it
                if ( objPID.open(QIODevice::ReadOnly) == true ) {
    //PID file exists, it should only contain a single ID
                    QByteArray arybytContent = objPID.readAll();
                    QString strContent = arybytContent.trimmed();
                    objPID.close();

                    if ( strContent.toLongLong() != mint64PID ) {
                        qInfo("Another instance already present...");
                        exit(EXIT_FAILURE);
                    }
                }
            }
        }
    //Create / update PID file
        if ( objPID.open(QIODevice::WriteOnly) == true ) {
            QString strPID = QString::number(mint64PID);
            objPID.write(strPID.toLatin1());
            objPID.close();
        }
    }
</code>```

Body:
I've been using a modified class I found to check if another instance of the same process is already running, the problem is that the method of checking for the process adds another instance of the same process.

When my application starts, a new process ID is created and is visible with:

ps -A | grep "AppName"

With this I get a since entry returned, I then check for another instance of the application using:

QString strCMD = "ps -A | grep \"" + mcstrAppName + "\"";
QProcess objProc;
objProc.start("bash", QStringList() << "-c" << strCMD);

if ( objProc.waitForStarted() != true || objProc.waitForFinished() != true ) {
    mcpobjApp->exit(cleanExit(-1, "Unable to determine if another instance is running!"));
    return;
}

As soon as the 'start' method is called another instance of the same application appears in the process table, again, verified with:

ps -A | grep "AppName"

Two entries now appear each with a different PID.  I've also tried:

QString strOptions = "-A | grep \"" + mcstrAppName + "\"";
QProcess objProc;
objProc.start("ps", QStringList() << strOptions);

The result is the same, two entries in process table.

Is there a way to check the process table for another instance without adding an additional instance?

Body:
The actual solution I used, which I wrote myself, prototype: clsSingleInstance.h:

class clsSingleInstance : public QObject {
Q_OBJECT

public:
    explicit clsSingleInstance(const QString& strAppName, QApplication* pobjApp);

public slots:
    void check();

private:
    const int mcintDelay = 3000;
    const QString mcstrAppName;

    qint64 mint64PID;
    QApplication const* mcpobjApp;
    QTimer* mptmrCheck;

    Q_DISABLE_COPY(clsSingleInstance);
};

Implementation, clsSingleInstance.cpp:

    #include "clsSingleInstance.h"
    /**
     * @brief clsSingleInstance::clsSingleInstance
     * @param strAppName : The application name as it will appear in the process list
     * @param pobjApp : Pointer to the applicaiton instance
     */
    clsSingleInstance::clsSingleInstance(const QString& strAppName
                                        ,QApplication* pobjApp)
                                        :QObject(pobjApp)
                                        ,mcstrAppName(strAppName)
                                        ,mcpobjApp(pobjApp) {
    //Save the process ID
        mint64PID = mcpobjApp->applicationPid();
    //Run check now to determine if another instance is running
        check();
    //Set-up timer to check for another instance regularly
        mptmrCheck = new QTimer(this);

        if ( mptmrCheck != NULL ) {
            connect(mptmrCheck, SIGNAL(timeout()), this, SLOT(check()));
            mptmrCheck->start(mcintDelay);
        }
    }
    /**
     * @brief clsSingleInstance::check
     * Checks application instances running
     */
    void clsSingleInstance::check() {
        const QString cstrCheckFile = clsMainWin::mcszConfigPath
                                        + mcstrAppName + ".pid";
        QFile objPID(cstrCheckFile);

        if ( objPID.exists() == true ) {
    //Check the file date / time stamp
            QDateTime dtCreated = QFileInfo(cstrCheckFile).created()
                     ,dtNow = QDateTime::currentDateTime();
            qint64 int64Created = dtCreated.toMSecsSinceEpoch()
                  ,int64Now = dtNow.toMSecsSinceEpoch()
                  ,int64Diff = int64Now - int64Created;
    //Is the file current and being updated?
            if ( int64Diff < (mcintDelay * 2) ) {
    //PID file is live, read it
                if ( objPID.open(QIODevice::ReadOnly) == true ) {
    //PID file exists, it should only contain a single ID
                    QByteArray arybytContent = objPID.readAll();
                    QString strContent = arybytContent.trimmed();
                    objPID.close();

                    if ( strContent.toLongLong() != mint64PID ) {
                        qInfo("Another instance already present...");
                        exit(EXIT_FAILURE);
                    }
                }
            }
        }
    //Create / update PID file
        if ( objPID.open(QIODevice::WriteOnly) == true ) {
            QString strPID = QString::number(mint64PID);
            objPID.write(strPID.toLatin1());
            objPID.close();
        }
    }


问:
What is the difference between predict and svmclassify?
I tried the following code

```<code>data =  [27    9   0
    11.6723281  28.93422177 0
    25  9   0
    23  8   0
    5.896096039 23.97745722 1
    21  6   0
    21.16823369 5.292058423 0
    4.242640687 13.43502884 1
    22  6   0];
    Attributes = data(:,1:2);
    Classes = data(:,3);
    train = [1 3 4 5 6 7];
    test = [2 8 9];
    %%# Train
   SVMModel = fitcsvm(Classes(train),Attributes(train,:))
   classOrder = SVMModel.ClassNames
   sv = SVMModel.SupportVectors;
   figure
   gscatter(train(:,1),train(:,2),Classes)
   hold on
   plot(train(:,1),train(:,2),'ko','MarkerSize',10)
   legend('good','bad','Support Vector')
   hold off
</code>```

I tried both predict and svmclassify; but it returns an error. What is the basic difference between these two functions?

```<code> [label,score] = predict(SVMModel,test);
 label           = svmclassify(SVMModel, test);
</code>```

答:
First off, there's quite a big note on top of the documentation page on svmclassify:

svmclassify will be removed in a future release. See fitcsvm, ClassificationSVM, and CompactClassificationSVM instead.

MATLAB is a bit vague in its naming of functions, as there's loads of functions named predict, using different schemes and algorithms. I suspect you'll want to use the one for SVMs. This should return the same result as svmclassify, but I think that either something went wrong in determining which predict MATLAB decided to use, or that predict has a newer algorithm than the unsupported svmclassify, hence a different output may result.

The conclusion is that you should use the newest functions to be able to run your code in future releases and get the newest algorithms. MATLAB will choose the correct version of predict based on what kind of input structure you feed it.

Body:
I tried the following code

data =  [27    9   0
    11.6723281  28.93422177 0
    25  9   0
    23  8   0
    5.896096039 23.97745722 1
    21  6   0
    21.16823369 5.292058423 0
    4.242640687 13.43502884 1
    22  6   0];
    Attributes = data(:,1:2);
    Classes = data(:,3);
    train = [1 3 4 5 6 7];
    test = [2 8 9];
    %%# Train
   SVMModel = fitcsvm(Classes(train),Attributes(train,:))
   classOrder = SVMModel.ClassNames
   sv = SVMModel.SupportVectors;
   figure
   gscatter(train(:,1),train(:,2),Classes)
   hold on
   plot(train(:,1),train(:,2),'ko','MarkerSize',10)
   legend('good','bad','Support Vector')
   hold off

I tried both predict and svmclassify; but it returns an error. What is the basic difference between these two functions?

 [label,score] = predict(SVMModel,test);
 label           = svmclassify(SVMModel, test);


问:
How can I make a java program always running?
How can I make a java program such that it is always running on the system (such as a daemon or service), but only allow one instance of the program to run? I would like it to start either when I run the program or when the system starts (either is fine).</p>

答:
For First part of your Question you need to make  a thread running continuously,

for second part of your question  look here


问:
How to split columns into two sets per type?
I have a CSV input file. We read that using the following

```<code>val rawdata = spark.
  read.
  format("csv").
  option("header", true).
  option("inferSchema", true).
  load(filename)
</code>```

This neatly reads the data and builds the schema.

The next step is to split the columns into String and Integer columns. How?

If the following is the schema of my dataset...

```<code>scala> rawdata.printSchema
root
 |-- ID: integer (nullable = true)
 |-- First Name: string (nullable = true)
 |-- Last Name: string (nullable = true)
 |-- Age: integer (nullable = true)
 |-- DailyRate: integer (nullable = true)
 |-- Dept: string (nullable = true)
 |-- DistanceFromHome: integer (nullable = true)
</code>```

I'd like to split this into two variables (StringCols, IntCols) where:

StringCols should have "First Name","Last Name","Dept"

IntCols should have "ID","Age","DailyRate","DistanceFromHome"

This is what I have tried :

```<code>val names = rawdata.schema.fieldNames
val types = rawdata.schema.fields.map(r => r.dataType)
</code>```

Now in types, I would like to loop and find all StringType and lookup up in names for the column name, similarly for IntegerType.

答:
Here you go, you can filter your columns by type using the underlying schema and the dataType

```<code>import org.apache.spark.sql.types.{IntegerType, StringType}

val stringCols = df.schema.filter(c => c.dataType == StringType).map(_.name)
val intCols = df.schema.filter(c => c.dataType == IntegerType).map(_.name)

val dfOfString = df.select(stringCols.head, stringCols.tail : _*)
val dfOfInt = df.select(intCols.head, intCols.tail : _*)
</code>```

Body:
I have a CSV input file. We read that using the following

val rawdata = spark.
  read.
  format("csv").
  option("header", true).
  option("inferSchema", true).
  load(filename)

This neatly reads the data and builds the schema.

The next step is to split the columns into String and Integer columns. How?

If the following is the schema of my dataset...

scala> rawdata.printSchema
root
 |-- ID: integer (nullable = true)
 |-- First Name: string (nullable = true)
 |-- Last Name: string (nullable = true)
 |-- Age: integer (nullable = true)
 |-- DailyRate: integer (nullable = true)
 |-- Dept: string (nullable = true)
 |-- DistanceFromHome: integer (nullable = true)

I'd like to split this into two variables (StringCols, IntCols) where:

StringCols should have "First Name","Last Name","Dept"

IntCols should have "ID","Age","DailyRate","DistanceFromHome"

This is what I have tried :

val names = rawdata.schema.fieldNames
val types = rawdata.schema.fields.map(r => r.dataType)

Now in types, I would like to loop and find all StringType and lookup up in names for the column name, similarly for IntegerType.

Body:
Here you go, you can filter your columns by type using the underlying schema and the dataType

import org.apache.spark.sql.types.{IntegerType, StringType}

val stringCols = df.schema.filter(c => c.dataType == StringType).map(_.name)
val intCols = df.schema.filter(c => c.dataType == IntegerType).map(_.name)

val dfOfString = df.select(stringCols.head, stringCols.tail : _*)
val dfOfInt = df.select(intCols.head, intCols.tail : _*)


问:
Haxe abstracts - Can I implicitly cast an array when using @:from?
I'm attempting to treat an array of one type as an array of another (abstract) type. It works fine when I use the underlying type of the abstract. But when I attempt implicit conversion using another type (defined using @:from keyword), I get a build failure.

It works if I use an explicit cast, but I'm wondering - is there any way around this / something I'm missing?

In the example below, I get the build failure Array<Int> should be Array<StringAbstract>

```<code>class Test {
    static function main() {
        var test:String = "Hello World";
        print(test); //this works

        var testArr:Array<String> = ["Hello", "World"];
        printArray(testArr); //this works (using underlying type)

        var testInt:Int = 10;
        print(testInt); //this works

        var testIntArr:Array<Int> = [1, 2, 3];
        printArray(cast testIntArr);  //this works (explicit cast)
        printArray(testIntArr);  //build failure (using @:from)
    }

    static function print(s:StringAbstract) {
        trace(s);
    }

    static function printArray(arr:Array<StringAbstract>) {
        trace(arr);
    }
}

abstract StringAbstract(String) from String to String {
    inline function new(s:String) {
        this = s;
    }

    @:from
    static public function fromInt(i:Int) {
        return new StringAbstract(Std.string(i));
    }
}
</code>```

Follow Up

Taking suggestions from Gama11 and Justinfront, I defined an abstract to convert arrays to arrays of my abstract type. But now I'm running into a different issue - as soon as I declare a @:from function, it breaks code that used to work.

Specifically, I used to be able to call my function with "mixed" types that were implicitly converted to the abstract (e.g. printArray([1, "2", 3]);).

But as soon as I added a @:from function to convert from a different type of array (Array<Int> in this case), that functionality broke, with the error Arrays of mixed types are only allowed if the type is forced to Array<Dynamic>.

Curious if anyone knows why this would be (example: https://try.haxe.org/#65D03).

```<code>class Test {
    static function main() {
        var testMixedArr:Array<StringAbstract> = [1, "2", 3];
        printArray(testMixedArr); //this works
        printArray([1, "2", 3]); //this doesn't work, unless I remove "fromIntArray" function
    }

    static function printArray(arr:StringAbstractArray) {trace(arr);}
}

abstract StringAbstractArray(Array<StringAbstract>) from Array<StringAbstract> to Array<StringAbstract> {
    inline function new(s:Array<StringAbstract>) {
        this = s;
    }

    @:from
    static public function fromIntArray(intArr:Array<Int>) {
        return new StringAbstractArray(Lambda.array( Lambda.map( intArr, function(i: Int):StringAbstract {
            return i; } )));
    }
}
</code>```

答:
Follow up
This works on try haxe, are you sure you need to even be doing this?

```<code> class Test {
    static function main() {
        var testMixedArr:Array<StringAbstract> = [1, "2", 3];
        printArray(testMixedArr); //this works
        printArray(new StringAbstractArray([1, "2", 3]));
    }

    static function printArray(arr:StringAbstractArray) {
        trace(arr);
    }

}

 abstract StringAbstractArray(Array<StringAbstract>) from Array<StringAbstract> to Array<StringAbstract> {
    inline public function new(s:Array<StringAbstract>) {
        this = s;
    }

    @:from
    static public function fromIntArray(intArr:Array<Int>) {
    return new StringAbstractArray(Lambda.array( Lambda.map( intArr, function(i: Int):StringAbstract {
        return i; } )));
    }
}

abstract StringAbstract(String) from String to String {
    inline function new(s:String) {
       this = s;
    }

    @:from
    static function fromInt(i:Int) {
        return new StringAbstract(Std.string(i));
    }
}
</code>```

here:

http://try-haxe.mrcdk.com/#ED866

Body:
I'm attempting to treat an array of one type as an array of another (abstract) type. It works fine when I use the underlying type of the abstract. But when I attempt implicit conversion using another type (defined using @:from keyword), I get a build failure.

It works if I use an explicit cast, but I'm wondering - is there any way around this / something I'm missing?

In the example below, I get the build failure Array<Int> should be Array<StringAbstract>

class Test {
    static function main() {
        var test:String = "Hello World";
        print(test); //this works

        var testArr:Array<String> = ["Hello", "World"];
        printArray(testArr); //this works (using underlying type)

        var testInt:Int = 10;
        print(testInt); //this works

        var testIntArr:Array<Int> = [1, 2, 3];
        printArray(cast testIntArr);  //this works (explicit cast)
        printArray(testIntArr);  //build failure (using @:from)
    }

    static function print(s:StringAbstract) {
        trace(s);
    }

    static function printArray(arr:Array<StringAbstract>) {
        trace(arr);
    }
}

abstract StringAbstract(String) from String to String {
    inline function new(s:String) {
        this = s;
    }

    @:from
    static public function fromInt(i:Int) {
        return new StringAbstract(Std.string(i));
    }
}

Follow Up

Taking suggestions from Gama11 and Justinfront, I defined an abstract to convert arrays to arrays of my abstract type. But now I'm running into a different issue - as soon as I declare a @:from function, it breaks code that used to work.

Specifically, I used to be able to call my function with "mixed" types that were implicitly converted to the abstract (e.g. printArray([1, "2", 3]);).

But as soon as I added a @:from function to convert from a different type of array (Array<Int> in this case), that functionality broke, with the error Arrays of mixed types are only allowed if the type is forced to Array<Dynamic>.

Curious if anyone knows why this would be (example: https://try.haxe.org/#65D03).

class Test {
    static function main() {
        var testMixedArr:Array<StringAbstract> = [1, "2", 3];
        printArray(testMixedArr); //this works
        printArray([1, "2", 3]); //this doesn't work, unless I remove "fromIntArray" function
    }

    static function printArray(arr:StringAbstractArray) {trace(arr);}
}

abstract StringAbstractArray(Array<StringAbstract>) from Array<StringAbstract> to Array<StringAbstract> {
    inline function new(s:Array<StringAbstract>) {
        this = s;
    }

    @:from
    static public function fromIntArray(intArr:Array<Int>) {
        return new StringAbstractArray(Lambda.array( Lambda.map( intArr, function(i: Int):StringAbstract {
            return i; } )));
    }
}

Body:
Follow up
This works on try haxe, are you sure you need to even be doing this?

 class Test {
    static function main() {
        var testMixedArr:Array<StringAbstract> = [1, "2", 3];
        printArray(testMixedArr); //this works
        printArray(new StringAbstractArray([1, "2", 3]));
    }

    static function printArray(arr:StringAbstractArray) {
        trace(arr);
    }

}

 abstract StringAbstractArray(Array<StringAbstract>) from Array<StringAbstract> to Array<StringAbstract> {
    inline public function new(s:Array<StringAbstract>) {
        this = s;
    }

    @:from
    static public function fromIntArray(intArr:Array<Int>) {
    return new StringAbstractArray(Lambda.array( Lambda.map( intArr, function(i: Int):StringAbstract {
        return i; } )));
    }
}

abstract StringAbstract(String) from String to String {
    inline function new(s:String) {
       this = s;
    }

    @:from
    static function fromInt(i:Int) {
        return new StringAbstract(Std.string(i));
    }
}

here:

http://try-haxe.mrcdk.com/#ED866


问:
How can I get a Material SplitView in an ajax page? - Framework7
So I'm trying to make it so you go to a settings page from the main page kind of like the Settings tablet app on Android or iOS where it's a split view (Example of what happens down below). However I'm constantly running into trouble where I can't seem to get it to work. It always looks like it's on a single page. I tried using views in JavaScript, I tried rearranging HTML, I tried many combinations just to get it to work, however I can never get it to work. If you need anything else to get a broader picture, let me know.

Here's the page hierarchy:
Root dashboard page > Settings Button > Settings SplitView

Thanks in advance!

答:
You don't have tried to add left-view and right-view class with the data-view attribute ?

for more information read the views doc and have a look to the  split-view example


问:
iOS - Presenting a view controller from a presented view controller changes its height
I've a custom transition between two controller that works close to the iOS mail app, which one stays on top of the other with some implemented scrolling behavior.

If I present a new view controller from the Presented view controller which isn't full screen sized, and then I dismiss this new presented view controller, the previous Presented view controller changes its height and then resizes itself.

I know this might be a little confusing but check the gif example below.

As you can see, If I present this custom image picker and then dismiss it, the view controller which presented it warps to full screen and then resizes to the initial value.

How can I prevent this from happening? I want the ViewController which presents the image picker keeps its height.

After the dismiss you can see the resize happening.

Setting the presenting view controllers size

Since it's a UIViewControllerAnimatedTransitioning I create a custom presentation and the size it's set has it's own identity

```<code>class CustomPresentationController: UIPresentationController {

    override init(presentedViewController: UIViewController, presenting presentingViewController: UIViewController!) {
        super.init(presentedViewController: presentedViewController, presenting: presentingViewController)
    }

    override var frameOfPresentedViewInContainerView: CGRect {
        let containerBounds = self.containerView?.bounds
        let origin = CGPoint(x: 0.0, y: ((containerBounds?.size.height)! * 0.05))
        let size = CGSize(width: (containerBounds?.size.width)! , height: ((containerBounds?.size.height)! * 0.95))
        // Applies the attributes
        let presentedViewFrame: CGRect = CGRect(origin: origin, size: size)
        return presentedViewFrame
    }

    override func containerViewWillLayoutSubviews() {
        presentedView?.frame = frameOfPresentedViewInContainerView
    }
}
</code>```

Any hint?
thanks

答:
I think that is where the issue is. You are forcing the frame size which is not working out. You should use something like preferredContentSize.

You can simply add this to the viewDidLoad of your CustomPresentationController.

Alternatively you may also try modalPresentationStyle as "Over Current Context"

You can refer very good examples of how you can keep some part of VC as transparent here

Body:
I've a custom transition between two controller that works close to the iOS mail app, which one stays on top of the other with some implemented scrolling behavior.

If I present a new view controller from the Presented view controller which isn't full screen sized, and then I dismiss this new presented view controller, the previous Presented view controller changes its height and then resizes itself.

I know this might be a little confusing but check the gif example below.

As you can see, If I present this custom image picker and then dismiss it, the view controller which presented it warps to full screen and then resizes to the initial value.

How can I prevent this from happening? I want the ViewController which presents the image picker keeps its height.

After the dismiss you can see the resize happening.

Setting the presenting view controllers size

Since it's a UIViewControllerAnimatedTransitioning I create a custom presentation and the size it's set has it's own identity

class CustomPresentationController: UIPresentationController {

    override init(presentedViewController: UIViewController, presenting presentingViewController: UIViewController!) {
        super.init(presentedViewController: presentedViewController, presenting: presentingViewController)
    }

    override var frameOfPresentedViewInContainerView: CGRect {
        let containerBounds = self.containerView?.bounds
        let origin = CGPoint(x: 0.0, y: ((containerBounds?.size.height)! * 0.05))
        let size = CGSize(width: (containerBounds?.size.width)! , height: ((containerBounds?.size.height)! * 0.95))
        // Applies the attributes
        let presentedViewFrame: CGRect = CGRect(origin: origin, size: size)
        return presentedViewFrame
    }

    override func containerViewWillLayoutSubviews() {
        presentedView?.frame = frameOfPresentedViewInContainerView
    }
}

Any hint?
thanks


问:
Extracting content using JSOUP
I'm having trouble extracting web content using Jsoup. The problem is that- I'm getting more than what I needed !. Here is the format of web content..

```<code><td>
 <ul>
  <li>
       <b>
        Title
        </b>
     contents
        <p>
           <a href="www.somesite.com"><b>LinkText</b></a>
        </p>
  </li>
 </ul>
</td>
</code>```

I'm trying to extract title , content and linkText seperately..
Taking LinkText wasn't tough . I used this code to take that data

```<code>String title = "";
Elements elements;
Document document = Jsoup.connect(url).get();
elements = document.select("td ul li p a");
for (Element e : elements)
title += "\n" + e.text() + "\n\n";
</code>```

When I tries to take the Content with this code.

```<code>String content = "";
Elements elements;
Document document = Jsoup.connect(url).get();
elements = document.select("td ul li");
for (Element e : elements)
content += "\n" + e.text() + "\n\n";
</code>```

I'm getting everything. (Title, Content, LinkText). The reason for this problem is because all three items are inside
 .So it is returing every texts inside.. So , how can I get them as distinct Strings. I also want to get the Link- www.www.somesite.com along with the data..

答:
According to the Jsoup documentation the text() method gets combined text of selected element and all its children.

What you should to do is to use the ownText() method which gets ONLY the text owned by selected element.

Answering your second question: to get the href attribute of  tag use: element.attr("href").

Whole thing should look as follows:

```<code>Document document = Jsoup.connect(url).get();
String title = document.select("td ul li b").first().text();
String content = document.select("td ul li").first().ownText();
Element linkEl = document.select("td ul li p a").first();
String href = linkEl.attr("href");
String link = linkEl.text();
</code>```

See:

https://jsoup.org/apidocs/org/jsoup/nodes/Element.html#ownText--

https://jsoup.org/apidocs/org/jsoup/nodes/Node.html#attr-java.lang.String-

Title: Extracting content using JSOUP

Body:
I'm having trouble extracting web content using Jsoup. The problem is that- I'm getting more than what I needed !. Here is the format of web content..

        Title

     contents

           LinkText

I'm trying to extract title , content and linkText seperately..
Taking LinkText wasn't tough . I used this code to take that data

String title = "";
Elements elements;
Document document = Jsoup.connect(url).get();
elements = document.select("td ul li p a");
for (Element e : elements)
title += "\n" + e.text() + "\n\n";

When I tries to take the Content with this code.

String content = "";
Elements elements;
Document document = Jsoup.connect(url).get();
elements = document.select("td ul li");
for (Element e : elements)
content += "\n" + e.text() + "\n\n";

I'm getting everything. (Title, Content, LinkText). The reason for this problem is because all three items are inside
 .So it is returing every texts inside.. So , how can I get them as distinct Strings. I also want to get the Link- www.www.somesite.com along with the data..

Body:
According to the Jsoup documentation the text() method gets combined text of selected element and all its children.

What you should to do is to use the ownText() method which gets ONLY the text owned by selected element.

Answering your second question: to get the href attribute of <a> tag use: element.attr("href").

Whole thing should look as follows:

Document document = Jsoup.connect(url).get();
String title = document.select("td ul li b").first().text();
String content = document.select("td ul li").first().ownText();
Element linkEl = document.select("td ul li p a").first();
String href = linkEl.attr("href");
String link = linkEl.text();

See:

https://jsoup.org/apidocs/org/jsoup/nodes/Element.html#ownText--

https://jsoup.org/apidocs/org/jsoup/nodes/Node.html#attr-java.lang.String-


问:
switch tabs from viewpager
I have implemented tab layout design and i want to switch to a different tab whenever someone clicks on an image in a viewpager. My research has concluded that a click event is registered on the viewpager adapter however i cannot find a way to grab the id of the tab layout from the adapter.Below is my view pager adapter code:

```<code>    public class BooksPagerAdapter extends PagerAdapter {
    private Context mContext;
    ViewPager viewPager;
    private ViewPager pager = null;
    ImageView image1;
    private int images[] = {R.drawable.lagers11, R.drawable.stout11, R.drawable.malts11, R.drawable.lagers11, R.drawable.stout11, R.drawable.malts11};
    public BooksPagerAdapter(Context context) {
        mContext = context;
    }

    @Override
    public Object instantiateItem(ViewGroup container, final int position) {
        LayoutInflater inflater = LayoutInflater.from(mContext);
        RelativeLayout relativeLayout = (RelativeLayout) ViewGroup.inflate(mContext, R.layout.tab_layout, null);
        View itemView = inflater.inflate(R.layout.shop_books, container, false);

        ImageView image1 = (ImageView) itemView.findViewById(R.id.image);
        image1.setImageResource(images[position]);
        itemView.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){
                //this will log the page number that was click
                Toast.makeText(mContext, position + " pagess", Toast.LENGTH_SHORT).show();

            }
        });
        ((ViewPager) container).addView(itemView);
        return itemView;

    }

    @Override
    public void destroyItem(ViewGroup container, int position,
                            Object object) {
        container.removeView((View) object);
    }

    @Override
    public int getCount() {
        return (6);
    }

    @Override
    public float getPageWidth(int position) {
        return (0.3f);
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return (view == object);
    }}
</code>```

show_books layout

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<ImageView
android:id="@+id/image"
android:layout_width="wrap_content"
android:padding="2dp"
android:layout_height="100dp" />
</FrameLayout>
</code>```

tab layout

```<code><RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/shattered"
android:orientation="vertical">
<android.support.design.widget.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/qb"
android:elevation="6dp"
app:tabGravity="fill"
app:tabIndicatorColor="#ffffff"
app:tabIndicatorHeight="3dp"
app:tabMode="scrollable"
app:tabSelectedTextColor="@color/tabSelectedTextColor"
app:tabTextColor="@color/tabTextColor">
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:id="@+id/viewpagertabs"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/tabs">
</android.support.v4.view.ViewPager>
</RelativeLayout>
</code>```

答:
Simple, in OnClick of image you should try this

```<code>viewPager.setCurrentItem(pageNumber);
</code>```

Title: switch tabs from viewpager

Body:
I have implemented tab layout design and i want to switch to a different tab whenever someone clicks on an image in a viewpager. My research has concluded that a click event is registered on the viewpager adapter however i cannot find a way to grab the id of the tab layout from the adapter.Below is my view pager adapter code:

    public class BooksPagerAdapter extends PagerAdapter {
    private Context mContext;
    ViewPager viewPager;
    private ViewPager pager = null;
    ImageView image1;
    private int images[] = {R.drawable.lagers11, R.drawable.stout11, R.drawable.malts11, R.drawable.lagers11, R.drawable.stout11, R.drawable.malts11};
    public BooksPagerAdapter(Context context) {
        mContext = context;
    }

    @Override
    public Object instantiateItem(ViewGroup container, final int position) {
        LayoutInflater inflater = LayoutInflater.from(mContext);
        RelativeLayout relativeLayout = (RelativeLayout) ViewGroup.inflate(mContext, R.layout.tab_layout, null);
        View itemView = inflater.inflate(R.layout.shop_books, container, false);

        ImageView image1 = (ImageView) itemView.findViewById(R.id.image);
        image1.setImageResource(images[position]);
        itemView.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){
                //this will log the page number that was click
                Toast.makeText(mContext, position + " pagess", Toast.LENGTH_SHORT).show();

            }
        });
        ((ViewPager) container).addView(itemView);
        return itemView;

    }

    @Override
    public void destroyItem(ViewGroup container, int position,
                            Object object) {
        container.removeView((View) object);
    }

    @Override
    public int getCount() {
        return (6);
    }

    @Override
    public float getPageWidth(int position) {
        return (0.3f);
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return (view == object);
    }}

show_books layout

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<ImageView
android:id="@+id/image"
android:layout_width="wrap_content"
android:padding="2dp"
android:layout_height="100dp" />
</FrameLayout>

tab layout

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/shattered"
android:orientation="vertical">
<android.support.design.widget.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/qb"
android:elevation="6dp"
app:tabGravity="fill"
app:tabIndicatorColor="#ffffff"
app:tabIndicatorHeight="3dp"
app:tabMode="scrollable"
app:tabSelectedTextColor="@color/tabSelectedTextColor"
app:tabTextColor="@color/tabTextColor">
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:id="@+id/viewpagertabs"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/tabs">
</android.support.v4.view.ViewPager>
</RelativeLayout>

Body:
Simple, in OnClick of image you should try this

viewPager.setCurrentItem(pageNumber);


问:
how to break a line java script
i am setting a text of a h4 through java script what i want to do is add new line here's the code

```<code>$("#description").text("for CCAET and has received significant international scientific recognition. <br /> \n Dr. Armogan has also been responsible for many surgical firsts in retina and cataract management.");
</code>```

now i tried it with multiple solutions but still not working here's another one

```<code>$("#description").text("or CCAET and has received significant international scientific recognition.Dr. Armogan has also been responsible for many surgical firsts in retina and cataract management."+
                        "abc"+
                         "def");
</code>```

any help?

答:
use html function with ``` tag.it will preserve your raw html .</p>

<code>$("#description").html("```for CCAET and has received significant international scientific recognition. <br /> \n Dr. Armogan has also been responsible for many surgical firsts in retina and cataract management.```");
</code>```

Title: how to break a line java script

Body:
i am setting a text of a h4 through java script what i want to do is add new line here's the code

$("#description").text("for CCAET and has received significant international scientific recognition.
 \n Dr. Armogan has also been responsible for many surgical firsts in retina and cataract management.");

now i tried it with multiple solutions but still not working here's another one

$("#description").text("or CCAET and has received significant international scientific recognition.Dr. Armogan has also been responsible for many surgical firsts in retina and cataract management."+
                        "abc"+
                         "def");

any help?

Body:
use html function with
 tag.it will preserve your raw html .

$("#description").html("<pre>for CCAET and has received significant international scientific recognition. <br /> \n Dr. Armogan has also been responsible for many surgical firsts in retina and cataract management.</pre>");


问:
What is the difference between interfaces with function properties like "f()" and "f: () =>"?
Consider next A and B interfaces:

```<code>interface A {f(): number}
interface B {f: () => number}
</code>```

I've tried next things:

```<code>var a: A = {f: function() {return 1}}
var a: A = {f: () => 1}
var b: B = {f: function() {return 1}}
var b: B = {f: () => 1}
</code>```

Looks like the same.

答:
They are the same. They are just two different notations. Your interfaces say that there must be a property f, which is a function with no parameters returning a number.

{f: function() {return 1}} and {f: () => 1} are two ways to implement this interface. The only difference is that the second one makes use of an arrow function. This is mostly syntatic sugar, but differs slightly by the use of the this keyword.

Body:
Consider next A and B interfaces:

interface A {f(): number}
interface B {f: () => number}

I've tried next things:

var a: A = {f: function() {return 1}}
var a: A = {f: () => 1}
var b: B = {f: function() {return 1}}
var b: B = {f: () => 1}

Looks like the same.