问:
replace more than white space with some value in python
I want to replace more than one white spaces from string with "@".
If one white space is there it should be intact but if there is more than one consecutive whitespace then it will keep one and append @. For example

```<code>s = "Hello how  are   you."
</code>```

would become

```<code>"Hello how @are @@you"
</code>```

答:
Python 2.7:

```<code>import re
s = "Hello how  are   you"
s = re.sub("(?<= ) ", "@" ,s)

print s
</code>```

Or, if you want to have only one @ signifying "multiple spaces", change to ("(?<= ) +", "@" ,s)

Explanation: The regex contains a positive lookbehind (?<= ) : it only finds spaces that are preceded by another space, but does not include the first space in the results. Because of that, when the results are replaced by an @, the first space remains intact (it is not preceded by another one), all the others are replaced in a one-by-one fashion by @.

Adding + to the main expression means that it will collect all multiple spaces except for the first one (due to positive lookbehind) and replace them with a single @.

This pattern will only get the " ", if you want to cover tabs, too, you'd need to change to \s

Body:
I want to replace more than one white spaces from string with "@".
If one white space is there it should be intact but if there is more than one consecutive whitespace then it will keep one and append @. For example

s = "Hello how  are   you."

would become

"Hello how @are @@you"

Body:
Python 2.7:

import re
s = "Hello how  are   you"
s = re.sub("(?<= ) ", "@" ,s)

print s

Or, if you want to have only one @ signifying "multiple spaces", change to ("(?<= ) +", "@" ,s)

Explanation: The regex contains a positive lookbehind (?<= ) : it only finds spaces that are preceded by another space, but does not include the first space in the results. Because of that, when the results are replaced by an @, the first space remains intact (it is not preceded by another one), all the others are replaced in a one-by-one fashion by @.

Adding + to the main expression means that it will collect all multiple spaces except for the first one (due to positive lookbehind) and replace them with a single @.

This pattern will only get the " ", if you want to cover tabs, too, you'd need to change to \s


来源: stackexchange

问:
Split a string but keep the Comma
I need to split a sentence string that keeps the non-whitespace such as . or ,. I need them to be included within the array string being split. Not in their own seperate array index.

```<code>const regex = /\W(?:\s)/g

function splitString (string) {
  return string.split(regex)
}

console.log(splitString("string one, string two, thing three, string four."))

// Output ["string one", "string two", "thing three", "string four."]
// Desired ["string one,", "string two,", "string three,", "string four."]
</code>```

答:
Perhaps using a match approach instead of a split approach:

```<code>"string one, string two, thing three, four four.".match(/\w+(?:\s\w+)*\W?/g);
// [ 'string one,', 'string two,', 'thing three,', 'four four.' ]
</code>```

or something more specific (this way you can easily choose one or several delimiter characters):

```<code>"string one, string two, thing three, four four.".match(/\S.*?(?![^,]),?/g);
</code>```

ContentLicense: CC BY-SA 3.0

Title: Split a string but keep the Comma

Body:
I need to split a sentence string that keeps the non-whitespace such as . or ,. I need them to be included within the array string being split. Not in their own seperate array index.

const regex = /\W(?:\s)/g

function splitString (string) {
  return string.split(regex)
}

console.log(splitString("string one, string two, thing three, string four."))

// Output ["string one", "string two", "thing three", "string four."]
// Desired ["string one,", "string two,", "string three,", "string four."]

Body:
Perhaps using a match approach instead of a split approach:

"string one, string two, thing three, four four.".match(/\w+(?:\s\w+)*\W?/g);
// [ 'string one,', 'string two,', 'thing three,', 'four four.' ]

or something more specific (this way you can easily choose one or several delimiter characters):

"string one, string two, thing three, four four.".match(/\S.*?(?![^,]),?/g);


问:
UITextField border color
I have really great wish to set my own color to UITextField border. But so far I could find out how to change the border line style only.

I've used background property to set background color in such way:

```<code>self.textField.backgroundColor = textFieldColor;
</code>```

But I have to change color of UITextField border too. And my question was about how to change the border color.

答:
If you use a TextField with rounded corners use this code:

```<code>    self.TextField.layer.cornerRadius=8.0f;
    self.TextField.layer.masksToBounds=YES;
    self.TextField.layer.borderColor=[[UIColor redColor]CGColor];
    self.TextField.layer.borderWidth= 1.0f;
</code>```

To remove the border:

```<code>self.TextField.layer.masksToBounds=NO;
self.TextField.layer.borderColor=[[UIColor clearColor]CGColor];
</code>```

Title: UITextField border color

Body:
I have really great wish to set my own color to UITextField border. But so far I could find out how to change the border line style only.

I've used background property to set background color in such way:

self.textField.backgroundColor = textFieldColor;

But I have to change color of UITextField border too. And my question was about how to change the border color.

Body:
If you use a TextField with rounded corners use this code:

    self.TextField.layer.cornerRadius=8.0f;
    self.TextField.layer.masksToBounds=YES;
    self.TextField.layer.borderColor=[[UIColor redColor]CGColor];
    self.TextField.layer.borderWidth= 1.0f;

To remove the border:

self.TextField.layer.masksToBounds=NO;
self.TextField.layer.borderColor=[[UIColor clearColor]CGColor];


问:
External Data Refresh Failed DATABASENAME Tfs_Analysis Work Item
i have excel reports accessing analysis database. they are uploaded to sharepoint.
After upload they dont work anymore.

secure store credentials for analysis database have been created. connection string in excel is the same as in the other working reports that where already there.
user for the reports is the sharepoint service account.
user has full access to tfs, sharepoint, tfs database server and analysis server

when refreshing the report on my pc trough sharepoint web portal, the graphs get empty. refreshing it on other PC's in the network, the error comes up.

any ideas?

答:
Apparently the cause for the error message was different date/time formats in the excel file and the server.

The file has TT.MM.JJ Germnan format, the server expects english format.


问:
JComboBox same entry multiple times
I've got a JComboBox that I'm passing an array of strings to. Some of the values are multiple times in that array. The combobox is rendered correctly, but I just can't select all the entries.

```<code>String[] entrys = {"A", "B", "C", "A"};
JComboBox combo = new JComboBox(entrys);
</code>```

In this example, I won't be able to select the second A because there is already an A earlier in the array.

```<code>combo.addItemListener(new ItemListener() {
    @Override
    public void itemStateChanged(ItemEvent e) {
        if(e.getStateChange() == ItemEvent.SELECTED)
            System.out.println(combo.getSelectedIndex());
    }
});
</code>```

If I press the second A it's still selecting the first one and printing 0.

What is the best way to get this to work?

Do I have to write a
custom ComboBox Model?

答:
So, basically, JComboBox is doing this in the getSelectedIndex method...

```<code>public int getSelectedIndex() {
    Object sObject = dataModel.getSelectedItem();
    int i,c;
    E obj;

    for ( i=0,c=dataModel.getSize();i<c;i++ ) {
        obj = dataModel.getElementAt(i);
        if ( obj != null && obj.equals(sObject) )
            return i;
    }
    return -1;
</code>```

This is why, when you select A, it's returning 0, because it finds a object matching the selected value at position 0. You need to generate a unique object wrapper around the values which will allow the comparison to select the correct value

Maybe something like...

```<code>public class Wrapper {
    private final String value;

    public Wrapper(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }

    // I personally prefer to use a custom cell renderer, but
    // for the sake of brevity, I'm using the toString method instead
    @Override
    public String toString() {
        return value;
    }

}
</code>```

Then we need to map the String values...

```<code>String[] entrys = {"A", "B", "C", "A"};
Wrapper[] wrappers = Arrays.stream(entrys).map((String t) -> new Wrapper(t)).toArray(Wrapper[]::new);
JComboBox<Wrapper> b = new JComboBox<>(wrappers);
</code>```

and we're all set.  Just remember, you're dealing with the Wrapper class, not Strings when you use getSelectedItem, so you'll need to unwrap them

Title: JComboBox same entry multiple times

Body:
I've got a JComboBox that I'm passing an array of strings to. Some of the values are multiple times in that array. The combobox is rendered correctly, but I just can't select all the entries.

String[] entrys = {"A", "B", "C", "A"};
JComboBox combo = new JComboBox(entrys);

In this example, I won't be able to select the second A because there is already an A earlier in the array.

combo.addItemListener(new ItemListener() {
    @Override
    public void itemStateChanged(ItemEvent e) {
        if(e.getStateChange() == ItemEvent.SELECTED)
            System.out.println(combo.getSelectedIndex());
    }
});

If I press the second A it's still selecting the first one and printing 0.

What is the best way to get this to work?

Do I have to write a
custom ComboBox Model?

Body:
So, basically, JComboBox is doing this in the getSelectedIndex method...

public int getSelectedIndex() {
    Object sObject = dataModel.getSelectedItem();
    int i,c;
    E obj;

    for ( i=0,c=dataModel.getSize();i<c;i++ ) {
        obj = dataModel.getElementAt(i);
        if ( obj != null && obj.equals(sObject) )
            return i;
    }
    return -1;

This is why, when you select A, it's returning 0, because it finds a object matching the selected value at position 0. You need to generate a unique object wrapper around the values which will allow the comparison to select the correct value

Maybe something like...

public class Wrapper {
    private final String value;

    public Wrapper(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }

    // I personally prefer to use a custom cell renderer, but
    // for the sake of brevity, I'm using the toString method instead
    @Override
    public String toString() {
        return value;
    }

}

Then we need to map the String values...

String[] entrys = {"A", "B", "C", "A"};
Wrapper[] wrappers = Arrays.stream(entrys).map((String t) -> new Wrapper(t)).toArray(Wrapper[]::new);
JComboBox<Wrapper> b = new JComboBox<>(wrappers);

and we're all set.  Just remember, you're dealing with the Wrapper class, not Strings when you use getSelectedItem, so you'll need to unwrap them


问:
Tablayout with Viewpager programatically creating is not working
Activity Class :

```<code>public class DynamicActivity extends AppCompatActivity{

    private LinearLayout mLinearLayout;
    private View mView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mLinearLayout = new LinearLayout(DynamicActivity.this);
        mLinearLayout.setOrientation(LinearLayout.VERTICAL);
        mLinearLayout.setLayoutParams(new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));

        TabLayout tabLayout = new TabLayout(DynamicActivity.this);
        tabLayout.setLayoutParams(new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT));
        tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
        tabLayout.setBackgroundColor(Color.CYAN);
        mLinearLayout.addView(tabLayout);

        ViewPager viewPager = new ViewPager(DynamicActivity.this);
        viewPager.setLayoutParams(new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT));
        viewPager.setBackgroundColor(Color.BLUE);
        mLinearLayout.addView(viewPager);

        ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
        viewPager.setAdapter(viewPagerAdapter);

        tabLayout.addTab(tabLayout.newTab());
        tabLayout.addTab(tabLayout.newTab());
        tabLayout.addTab(tabLayout.newTab());

        tabLayout.setupWithViewPager(viewPager);

        setContentView(mLinearLayout);
    }
}

**Adapter Class :**
public class ViewPagerAdapter extends FragmentStatePagerAdapter{
    public ViewPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return "Test";
    }

    @Override
    public Fragment getItem(int position) {
        return new TestFagment();
    }

    @Override
    public int getCount() {
        return 3;
    }
}
</code>```

Exception :

FATAL EXCEPTION: main

E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.locale.tablayoutdynamicsample, PID: 27084
                                                                                java.lang.IllegalStateException: ViewPager with adapter com.example.locale.tablayoutdynamicsample.ViewPagerAdapter@3b0e90d6 requires a view id
                                                                                at android.support.v4.app.FragmentStatePagerAdapter.startUpdate(FragmentStatePagerAdapter.java:87)
                                                                                at android.support.v4.view.ViewPager.populate(ViewPager.java:1148)
                                                                                at android.support.v4.view.ViewPager.populate(ViewPager.java:1116)
                                                                                at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1642)
                                                                                at android.view.View.measure(View.java:18580)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5827)
                                                                                at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1435)
                                                                                at android.widget.LinearLayout.measureVertical(LinearLayout.java:721)
                                                                                at android.widget.LinearLayout.onMeasure(LinearLayout.java:612)
                                                                                at android.view.View.measure(View.java:18580)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5827)
                                                                                at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
                                                                                at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)
                                                                                at android.view.View.measure(View.java:18580)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5827)
                                                                                at android.support.v7.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:393)
                                                                                at android.view.View.measure(View.java:18580)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5827)
                                                                                at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
                                                                                at android.view.View.measure(View.java:18580)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5827)
                                                                                at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1435)
                                                                                at android.widget.LinearLayout.measureVertical(LinearLayout.java:721)
                                                                                at android.widget.LinearLayout.onMeasure(LinearLayout.java:612)
                                                                                at android.view.View.measure(View.java:18580)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5827)
                                                                                at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
                                                                                at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2897)
                                                                                at android.view.View.measure(View.java:18580)
                                                                                at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2248)
                                                                                at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1306)
                                                                                at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1548)
                                                                                at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1191)
                                                                                at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6642)
                                                                                at android.view.Choreographer$CallbackRecord.run(Choreographer.java:777)
                                                                                at android.view.Choreographer.doCallbacks(Choreographer.java:590)
                                                                                at android.view.Choreographer.doFrame(Choreographer.java:560)
                                                                                at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:763)
                                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:145)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5951)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1388)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183)

答:
It says "VewPager with Adapter ViewPagerAdapter@3b0e90d6 requires a view id" so try this:

```<code>viewPager.setId(anyInteger);
</code>```

Body:
Activity Class :

public class DynamicActivity extends AppCompatActivity{

    private LinearLayout mLinearLayout;
    private View mView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mLinearLayout = new LinearLayout(DynamicActivity.this);
        mLinearLayout.setOrientation(LinearLayout.VERTICAL);
        mLinearLayout.setLayoutParams(new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));

        TabLayout tabLayout = new TabLayout(DynamicActivity.this);
        tabLayout.setLayoutParams(new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT));
        tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
        tabLayout.setBackgroundColor(Color.CYAN);
        mLinearLayout.addView(tabLayout);

        ViewPager viewPager = new ViewPager(DynamicActivity.this);
        viewPager.setLayoutParams(new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT));
        viewPager.setBackgroundColor(Color.BLUE);
        mLinearLayout.addView(viewPager);

        ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
        viewPager.setAdapter(viewPagerAdapter);

        tabLayout.addTab(tabLayout.newTab());
        tabLayout.addTab(tabLayout.newTab());
        tabLayout.addTab(tabLayout.newTab());

        tabLayout.setupWithViewPager(viewPager);

        setContentView(mLinearLayout);
    }
}

**Adapter Class :**
public class ViewPagerAdapter extends FragmentStatePagerAdapter{
    public ViewPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return "Test";
    }

    @Override
    public Fragment getItem(int position) {
        return new TestFagment();
    }

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

Exception :

FATAL EXCEPTION: main

E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.locale.tablayoutdynamicsample, PID: 27084
                                                                                java.lang.IllegalStateException: ViewPager with adapter com.example.locale.tablayoutdynamicsample.ViewPagerAdapter@3b0e90d6 requires a view id
                                                                                at android.support.v4.app.FragmentStatePagerAdapter.startUpdate(FragmentStatePagerAdapter.java:87)
                                                                                at android.support.v4.view.ViewPager.populate(ViewPager.java:1148)
                                                                                at android.support.v4.view.ViewPager.populate(ViewPager.java:1116)
                                                                                at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1642)
                                                                                at android.view.View.measure(View.java:18580)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5827)
                                                                                at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1435)
                                                                                at android.widget.LinearLayout.measureVertical(LinearLayout.java:721)
                                                                                at android.widget.LinearLayout.onMeasure(LinearLayout.java:612)
                                                                                at android.view.View.measure(View.java:18580)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5827)
                                                                                at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
                                                                                at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)
                                                                                at android.view.View.measure(View.java:18580)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5827)
                                                                                at android.support.v7.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:393)
                                                                                at android.view.View.measure(View.java:18580)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5827)
                                                                                at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
                                                                                at android.view.View.measure(View.java:18580)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5827)
                                                                                at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1435)
                                                                                at android.widget.LinearLayout.measureVertical(LinearLayout.java:721)
                                                                                at android.widget.LinearLayout.onMeasure(LinearLayout.java:612)
                                                                                at android.view.View.measure(View.java:18580)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5827)
                                                                                at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
                                                                                at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2897)
                                                                                at android.view.View.measure(View.java:18580)
                                                                                at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2248)
                                                                                at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1306)
                                                                                at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1548)
                                                                                at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1191)
                                                                                at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6642)
                                                                                at android.view.Choreographer$CallbackRecord.run(Choreographer.java:777)
                                                                                at android.view.Choreographer.doCallbacks(Choreographer.java:590)
                                                                                at android.view.Choreographer.doFrame(Choreographer.java:560)
                                                                                at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:763)
                                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:145)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5951)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1388)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183)

Body:
It says "VewPager with Adapter ViewPagerAdapter@3b0e90d6 requires a view id" so try this:

viewPager.setId(anyInteger);


问:
Match a set of characters from one table into the records of an other table
I have two tables (T-SQL):

```<code>tblInvalidCharactersList         tblMonthsRecords
+-----------+-----------+        +--------+-------------+
| CodePoint | Character |        | RecRef | Name        |
+-----------+-----------+        +--------+-------------+
|    38     |     &     |        | 21     | Firs> name  |
+-----------+-----------+        +--------+-------------+
|    64     |     @     |        | 89     | @Second name|
+-----------+-----------+        +--------+-------------+
|    62     |     >     |        | 321    | Third n«me  |
+-----------+-----------+        +--------+-------------+
|    171    |     «     |        | 381    | Fourth name |
+-----------+-----------+        +--------+-------------+
</code>```

I want to find those records of the tblMonthsRecords which have at least  one (or more) character(s) from the Character column of the tblInvalidCharactersList table.

I tried:

```<code>SELECT
    [RecRef],
    [Name]
FROM [tblMonthsRecords]
WHERE [Name] IN (SELECT Character FROM [tblInvalidCharactersList])
</code>```

and it returns no results at all.

I even tried the NOT IN clause and as you may guess, returns all records.

The reason why I am not hardcoding the characters list within a LIKE clause is because I want the list to be dynamically updated.

You can think the tblInvalidCharactersList as a characters "black list".

答:
I would use exists:

```<code>select mr.*
from tblMonthsRecords mr
where exists (select 1
              from tblInvalidCharactersList icl
              where charindex(icl.Character, mr.name) > 0
             );
</code>```

You don't seem to care about the actual invalid character.

Body:
I have two tables (T-SQL):

tblInvalidCharactersList         tblMonthsRecords
+-----------+-----------+        +--------+-------------+
| CodePoint | Character |        | RecRef | Name        |
+-----------+-----------+        +--------+-------------+
|    38     |     &     |        | 21     | Firs> name  |
+-----------+-----------+        +--------+-------------+
|    64     |     @     |        | 89     | @Second name|
+-----------+-----------+        +--------+-------------+
|    62     |     >     |        | 321    | Third n«me  |
+-----------+-----------+        +--------+-------------+
|    171    |     «     |        | 381    | Fourth name |
+-----------+-----------+        +--------+-------------+

I want to find those records of the tblMonthsRecords which have at least  one (or more) character(s) from the Character column of the tblInvalidCharactersList table.

I tried:

SELECT
    [RecRef],
    [Name]
FROM [tblMonthsRecords]
WHERE [Name] IN (SELECT Character FROM [tblInvalidCharactersList])

and it returns no results at all.

I even tried the NOT IN clause and as you may guess, returns all records.

The reason why I am not hardcoding the characters list within a LIKE clause is because I want the list to be dynamically updated.

You can think the tblInvalidCharactersList as a characters "black list".

Body:
I would use exists:

select mr.*
from tblMonthsRecords mr
where exists (select 1
              from tblInvalidCharactersList icl
              where charindex(icl.Character, mr.name) > 0
             );

You don't seem to care about the actual invalid character.


问:
How can I use bootstrap modal, toasty, etc. In aspnet core with angular 2 project?
I am using Angular2 in my existing ASP.NET Core MVC project. I am already using toasty, modals and other libraries in my MVC .cshtml views.

However, I couldn't make those work in my components. Is there any example teaching how to use them.

Tried ngModal and others but could not make it work

答:
this may help you, I use it in my own project.
https://ng-bootstrap.github.io/#/home </p>


问:
Python can't find the file pip.conf
I can't find the file pip.conf in the path ~/.config/pip/pip.conf  or the path ~/pip/pip.conf. My version of pip is 8.1.2

答:
As stated in the documentation, the default locations for Linux are:

per-user: $HOME/.config/pip/pip.conf

global: /etc/pip.conf

ContentLicense: CC BY-SA 4.0

Title: Python can't find the file pip.conf


问:
sending mail but no message-id
I am getting interesting rejections from my clients mail server when sending a mail with indy-10's tidMessage component saying:

550 Rejected: Message does not contain a Message-ID

I get this even when using indy's own demo app

http://www.indyproject.org/DemoDownloads/Indy_10_MailClient.zip

what do I do to fix this. thanks!

答:
It works with Indy9, maybe things haven't cahnged too much in 10:</p>

```<code>    procedure AddMsgID(AMsg: TIdMessage);
    var
      id: AnsiString;
    begin
      id := GenerateUniqueMsgID;
      AMsg.MsgId := id;
      AMsg.AddHeader('Message-ID=' + id);
      // AMsg.ExtraHeaders.Values['Message-ID'] := id;
    end; // AddMsgID
</code>```

ContentLicense: CC BY-SA 2.5

Title: sending mail but no message-id

Body:
It works with Indy9, maybe things haven't cahnged too much in 10:

    procedure AddMsgID(AMsg: TIdMessage);
    var
      id: AnsiString;
    begin
      id := GenerateUniqueMsgID;
      AMsg.MsgId := id;
      AMsg.AddHeader('Message-ID=' + id);
      // AMsg.ExtraHeaders.Values['Message-ID'] := id;
    end; // AddMsgID


问:
How to scale down right column in grid to max. 100% of left column?
I have two columns side by side in a bootstrap grid. I need to force the second column not to be higher than the first one. I know how to force the second column to get full height in dependance of the first column by using widespread method of display: table.
But how to manage the other way round? I prefer a solution using css, no js if possible.
The first one contains a responsive image, second one contains text.
If the text would need more space than the image, text should scroll.

```<code><div class="row">
<div class="col-xs-6 first">
    <img class="img-responsive" src="image/example.jpg" />
</div>
<div class="col-xs-6 second">
    <p>
        Some text lore ipsum etc etc<br />
        Some text lore ipsum etc etc<br />
        Some text lore ipsum etc etc<br />
        Some text lore ipsum etc etc<br />
        Some text lore ipsum etc etc<br />
        Some text lore ipsum etc etc<br />
        Some text lore ipsum etc etc<br />
        Some text lore ipsum etc etc<br />
        Some text lore ipsum etc etc<br />
    </p>
</div>
</code>```

答:
Here you can check this example

If you want to do height adjustment of text div related to image than you can go with the max-height property of css

You can increase and decrease max-height property as per your need.

And secondly give overflow-y: auto for scroll.

Hope this will helps you.

.second {
 max-height: 165px;
 overflow-y: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div class="row">
<div class="col-xs-6 first">
    <img class="img-responsive" src="https://dummyimage.com/600x400/000/fff" />
</div>
<div class="col-xs-6 second">
    <p>
        Some text lore ipsum etc etc<br />
        Some text lore ipsum etc etc<br />
        Some text lore ipsum etc etc<br />
        Some text lore ipsum etc etc<br />
        Some text lore ipsum etc etc<br />
        Some text lore ipsum etc etc<br />
        Some text lore ipsum etc etc<br />
        Some text lore ipsum etc etc<br />
        Some text lore ipsum etc etc<br />
    </p>
</div></code>```

Body:
I have two columns side by side in a bootstrap grid. I need to force the second column not to be higher than the first one. I know how to force the second column to get full height in dependance of the first column by using widespread method of display: table.
But how to manage the other way round? I prefer a solution using css, no js if possible.
The first one contains a responsive image, second one contains text.
If the text would need more space than the image, text should scroll.

        Some text lore ipsum etc etc

        Some text lore ipsum etc etc

        Some text lore ipsum etc etc

        Some text lore ipsum etc etc

        Some text lore ipsum etc etc

        Some text lore ipsum etc etc

        Some text lore ipsum etc etc

        Some text lore ipsum etc etc

        Some text lore ipsum etc etc

Body:
Here you can check this example

If you want to do height adjustment of text div related to image than you can go with the max-height property of css

You can increase and decrease max-height property as per your need.

And secondly give overflow-y: auto for scroll.

Hope this will helps you.

.second {
 max-height: 165px;
 overflow-y: auto;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div class="row">
<div class="col-xs-6 first">
    <img class="img-responsive" src="https://dummyimage.com/600x400/000/fff" />
</div>
<div class="col-xs-6 second">
    <p>
        Some text lore ipsum etc etc<br />
        Some text lore ipsum etc etc<br />
        Some text lore ipsum etc etc<br />
        Some text lore ipsum etc etc<br />
        Some text lore ipsum etc etc<br />
        Some text lore ipsum etc etc<br />
        Some text lore ipsum etc etc<br />
        Some text lore ipsum etc etc<br />
        Some text lore ipsum etc etc<br />
    </p>
</div>


问:
How can i describe table in cassandra database?
```<code>$describe = new Cassandra\SimpleStatement(<<<EOD
             describe keyspace.tablename
EOD
    );
    $session->execute($describe);
</code>```

i used above code but it is not working.
how can i fetch field name and it's data type from Cassandra table ?

答: Try desc table keyspace.tablename;

Body:
$describe = new Cassandra\SimpleStatement(<<<EOD
             describe keyspace.tablename
EOD
    );
    $session->execute($describe);

i used above code but it is not working.
how can i fetch field name and it's data type from Cassandra table ?

Body: Try desc table keyspace.tablename;


问:
PDO fetch obj with defined objectname
Similar too:

```<code>PDO::FETCH_CLASS | PDO::FETCH_CLASSTYPE
</code>```

I want to do the same with:

```<code>PDO::FETCH_OBJ
</code>```

Means I want to pick each row as an object named by the first value.

Example:

```<code>id name url
1  Test www.test.de
2  Test2 www.test2.de

Select name, id, url FROM whatever;

$processes = $result->fetchAll(PDO::FETCH_OBJ);
</code>```

returns the objects idexed from 0 - x

```<code>fetchAll(PDO::FETCH_ASSOC | PDO::FETCH_GROUP)
</code>```

Returns it nearly like I want just 2 downsides:

```<code>   test {
      0: [
        'id': 1,
        'src': 'www.test.de'
      ]
    }
</code>```

First is I want to keep name in the object (could douple select (select name, name ...) and I have the unecessary array inside.

So any idea how I get it to this:

```<code>test [
        'name': 'test',
        'id': 1,
        'src': 'www.test.de'
      ]
test2 [
        'name': 'test2',
        'id': 2,
        'src': 'www.test2.de'
]
</code>```

答:
You can use this:

$dbh = new PDO('mysql:dbname=my;host=localhost', 'root', '');

$sth = $dbh->prepare("SELECT name, id, name, url FROM data");
$sth->execute();

var_dump($sth->fetchAll(PDO::FETCH_OBJ | PDO::FETCH_GROUP | PDO::FETCH_UNIQUE));
```

<p>The output will be like this:</p>

```array(3) {
  'test 1' =>
  class stdClass#6 (3) {
    public $id =>
    string(1) "4"
    public $name =>
    string(6) "test 1"
    public $url =>
    string(13) "www.gmail.com"
  }
  'test 2' =>
  class stdClass#4 (3) {
    public $id =>
    string(1) "2"
    public $name =>
    string(6) "test 2"
    public $url =>
    string(14) "www.google.com"
  }
  'test 3' =>
  class stdClass#5 (3) {
    public $id =>
    string(1) "3"
    public $name =>
    string(6) "test 3"
    public $url =>
    string(21) "www.stackoverflow.com"
  }
}
```

<p>But be noticed: if you add duplicate values into the <code>name</code> column, you will get values of last record with the same name. In my example above I have table with this dataset:</p>

```select * from data;
+----+--------+-----------------------+
| id | name   | url                   |
+----+--------+-----------------------+
|  1 | test 1 | www.ya.ru             |
|  2 | test 2 | www.google.com        |
|  3 | test 3 | www.stackoverflow.com |
|  4 | test 1 | www.gmail.com         |
+----+--------+-----------------------+
4 rows in set (0,00 sec)
```

So you have data from record with ID = 4 in object named "test 1".

Title: PDO fetch obj with defined objectname

Body:
Similar too:

PDO::FETCH_CLASS | PDO::FETCH_CLASSTYPE

I want to do the same with:

PDO::FETCH_OBJ

Means I want to pick each row as an object named by the first value.

Example:

id name url
1  Test www.test.de
2  Test2 www.test2.de

Select name, id, url FROM whatever;

$processes = $result->fetchAll(PDO::FETCH_OBJ);

returns the objects idexed from 0 - x

fetchAll(PDO::FETCH_ASSOC | PDO::FETCH_GROUP)

Returns it nearly like I want just 2 downsides:

   test {
      0: [
        'id': 1,
        'src': 'www.test.de'
      ]
    }

First is I want to keep name in the object (could douple select (select name, name ...) and I have the unecessary array inside.

So any idea how I get it to this:

test [
        'name': 'test',
        'id': 1,
        'src': 'www.test.de'
      ]
test2 [
        'name': 'test2',
        'id': 2,
        'src': 'www.test2.de'
]

Body:
You can use this:

$dbh = new PDO('mysql:dbname=my;host=localhost', 'root', '');

$sth = $dbh->prepare("SELECT name, id, name, url FROM data");
$sth->execute();

var_dump($sth->fetchAll(PDO::FETCH_OBJ | PDO::FETCH_GROUP | PDO::FETCH_UNIQUE));

The output will be like this:

array(3) {
  'test 1' =>
  class stdClass#6 (3) {
    public $id =>
    string(1) "4"
    public $name =>
    string(6) "test 1"
    public $url =>
    string(13) "www.gmail.com"
  }
  'test 2' =>
  class stdClass#4 (3) {
    public $id =>
    string(1) "2"
    public $name =>
    string(6) "test 2"
    public $url =>
    string(14) "www.google.com"
  }
  'test 3' =>
  class stdClass#5 (3) {
    public $id =>
    string(1) "3"
    public $name =>
    string(6) "test 3"
    public $url =>
    string(21) "www.stackoverflow.com"
  }
}

But be noticed: if you add duplicate values into the name column, you will get values of last record with the same name. In my example above I have table with this dataset:

select * from data;
+----+--------+-----------------------+
| id | name   | url                   |
+----+--------+-----------------------+
|  1 | test 1 | www.ya.ru             |
|  2 | test 2 | www.google.com        |
|  3 | test 3 | www.stackoverflow.com |
|  4 | test 1 | www.gmail.com         |
+----+--------+-----------------------+
4 rows in set (0,00 sec)

So you have data from record with ID = 4 in object named "test 1".


问:
How to set visibility GONE of views for always with shared preferences in Fragment
I have some views in fragment under TabLayout. I want these views to be hidden with 'view.setVisibility' for always (till clearing app data or uninstalling) after a clicking a button. Can somebody help me please. I don't think this question needs any  code to show you.</p>

答: You can manage your UI with the SharedPreference. When your onCreateView of fragment is loaded you can check your SharedPreferenceview visible state and apply this flag to view visibility.


问:
Pandas, create new columns based on existing with repeated count
It's a bit complicated for explain, so I'll do my best. I have a pandas with two columns: hour (from 1 to 24) and value(corresponding to each hour). Dataset index is huge but column hour is repeated on that 24 hours basis (from 1 to 24). I am trying to create new 24 columns: value -1, value -2, value -3...value -24 that will correspond to each row and value from -1 hour, value from -2 hours(from above rows).

```<code>hour | value | value -1 | value -2 | value -3| ... | value - 24
1       10       0          0           0               0
2       11       10         0           0               0
3       12       11         10          0               0
4       13       12         11          10              0
...
24      32       31         30          29              0
1       33       32         31          30              10
2       34       33         32          31              11
and so on...
</code>```

All value numbers are for the example. As I said there are lots of rows, not only 24 for all hours in a day time but all following time series from 1 to 24 and etc.
Thanks in advance and may the force be with you!

答:
Is this what you need?

```<code>df = pd.DataFrame([[1,10],[2,11],
             [3,12],[4,13]], columns=['hour','value'])

for i in range(1, 24):
    df['value -' + str(i)] = df['value'].shift(i).fillna(0)
</code>```

result:

Body:
It's a bit complicated for explain, so I'll do my best. I have a pandas with two columns: hour (from 1 to 24) and value(corresponding to each hour). Dataset index is huge but column hour is repeated on that 24 hours basis (from 1 to 24). I am trying to create new 24 columns: value -1, value -2, value -3...value -24 that will correspond to each row and value from -1 hour, value from -2 hours(from above rows).

hour | value | value -1 | value -2 | value -3| ... | value - 24
1       10       0          0           0               0
2       11       10         0           0               0
3       12       11         10          0               0
4       13       12         11          10              0
...
24      32       31         30          29              0
1       33       32         31          30              10
2       34       33         32          31              11
and so on...

All value numbers are for the example. As I said there are lots of rows, not only 24 for all hours in a day time but all following time series from 1 to 24 and etc.
Thanks in advance and may the force be with you!

Body:
Is this what you need?

df = pd.DataFrame([[1,10],[2,11],
             [3,12],[4,13]], columns=['hour','value'])

for i in range(1, 24):
    df['value -' + str(i)] = df['value'].shift(i).fillna(0)

result:


问:
Delivery Pipeline View for Jenkins Pipelines in job dsl
How can I create a delivery pipeline view for jenkins pipeline using jobdsl.

All I could find was deliveryPipelineView, which isn't the same view, any information on this would be useful

答:
For me, the deliveryPipeLineView method create exactly a delivery pipeline view..

Here an exemple :

```<code>deliveryPipelineView('name-pipeline') {
   description('description-pipeline')
   pipelineInstances(1)
   showAggregatedPipeline()
   columns(1)
   sorting(Sorting.TITLE)
   updateInterval(2)
   enableStartBuild()
   enableManualTriggers()
   showAvatars()
   showChangeLog()
   pipelines {
    component('name', 'init-job')
   }
}
</code>```

See the doc on gitHub for more details : https://github.com/jenkinsci/job-dsl-plugin/wiki/Job-DSL-Commands

Body:
For me, the deliveryPipeLineView method create exactly a delivery pipeline view..

Here an exemple :

deliveryPipelineView('name-pipeline') {
   description('description-pipeline')
   pipelineInstances(1)
   showAggregatedPipeline()
   columns(1)
   sorting(Sorting.TITLE)
   updateInterval(2)
   enableStartBuild()
   enableManualTriggers()
   showAvatars()
   showChangeLog()
   pipelines {
    component('name', 'init-job')
   }
}

See the doc on gitHub for more details : https://github.com/jenkinsci/job-dsl-plugin/wiki/Job-DSL-Commands


问:
Using Linq to filter an array with bool properties true in to another array
I have an array of type Brick with each brick having an isBroken bool property. How can I use Linq to filter all bricks with isBroken = true into a new array?

答:
You can use the select method for this :

```<code>var theNewList = Brick.Where(b => b.isBroken).Select(b => new Brick
{
    //Populate new object
}).ToList() / .ToArray();
</code>```

Note that Select is used and not where to project the List into a new one.

Also, the .ToList()/ToArray() is to add the array to memory, you may not need it, .Select() return an IEnumerable.
It is possible to use Brik.Where(..).ToList(); as this would create a new List but the reference to the object inside the list would be the same, so again it  depands on your need.
And .Select() require using System.Linq;

Body:
You can use the select method for this :

var theNewList = Brick.Where(b => b.isBroken).Select(b => new Brick
{
    //Populate new object
}).ToList() / .ToArray();

Note that Select is used and not where to project the List into a new one.

Also, the .ToList()/ToArray() is to add the array to memory, you may not need it, .Select() return an IEnumerable.
It is possible to use Brik.Where(..).ToList(); as this would create a new List but the reference to the object inside the list would be the same, so again it  depands on your need.
And .Select() require using System.Linq;


问:
Docker: cd into directory using regular expressions
I have to build a Docker image and in the Dockerfile I have move into a directory whose name contains a dynamic id, e.g myfolder12345, that can become myfolder56789 in another build. As I don't know which can be this id everytime I do the build, I have tried to use regular expressions to achieve that.

I've tried with

```<code>WORKDIR myfolder*
</code>```

but the current directory remains /.
How can be solved?

答:
Having a non-deterministic content in a docker image is a bad idea.

You should rename the folder first, then the WORKDIR will be easier:

```<code># Supposing there is only one folder123 at each build
RUN mv /path/to/folder* /path/to/folder
WORKDIR /path/to/folder
</code>```

Body:
I have to build a Docker image and in the Dockerfile I have move into a directory whose name contains a dynamic id, e.g myfolder12345, that can become myfolder56789 in another build. As I don't know which can be this id everytime I do the build, I have tried to use regular expressions to achieve that.

I've tried with

WORKDIR myfolder*

but the current directory remains /.
How can be solved?

Body:
Having a non-deterministic content in a docker image is a bad idea.

You should rename the folder first, then the WORKDIR will be easier:

# Supposing there is only one folder123 at each build
RUN mv /path/to/folder* /path/to/folder
WORKDIR /path/to/folder


问:
JavaScript image banner timer HTML
I want to be able to make my image banner move on to the next image after a few seconds. I've tried a few things but nothing has worked. I believe I can use JavaScript to do this.

Any help will be much appreciated!

I'll put the code up:

```<code><div id = "imageBanner">
   <div id="slideshow-wrap">
        <input type="radio" id="button-1" name="controls"     checked="checked"/>
        <label for="button-1"></label>
        <input type="radio" id="button-2" name="controls"/>
        <label for="button-2"></label>
        <input type="radio" id="button-3" name="controls"/>
        <label for="button-3"></label>
        <input type="radio" id="button-4" name="controls"/>
        <label for="button-4"></label>
        <input type="radio" id="button-5" name="controls"/>
        <label for="button-5"></label>
        <label for="button-1" class="arrows" id="arrow-1">></label>
        <label for="button-2" class="arrows" id="arrow-2">></label>
        <label for="button-3" class="arrows" id="arrow-3">></label>
        <label for="button-4" class="arrows" id="arrow-4">></label>
        <label for="button-5" class="arrows" id="arrow-5">></label>
        <div id="slideshow-inner">
            <ul id = "slideshow">
                <li><img style="width:100%;" src="battlefield4.png" /></li>
                <li><img style="width:100%;" src="fifa12.png" /></li>
                <li><img style="width:100%;" src="spiderman.png" /></li>
                <li><img style="width:100%;" src="mario.png" /></li>
                <li><img style="width:100%;" src="wiifit.png" /></li>
            </ul>
        </div>
   </div>
</div>
</code>```

答:
```<code>JS CODE

$(function() {
var endDate = new Date();
endDate = new Date(2017, 12 - 1, 31);
$('#dcountdown').countdown({
until: endDate
});

$('#dclose').click(function() {
$(this).parent().slideUp();
});
});
</code>```

HTML CODE

```<code><div id="dbanner" class="change-color">
<div class="dcontent">
  [http://carrentalchennai.in/][1] <strong> South Indian Tour Packages </strong> [Google Authorised Reseller Chennai][1] by
         <code> [http://www.alphabetwebz.com/][1] </code> <span class="dtime"> [http://www.carrentalinchennai.com/][1]</span><span     id="dcountdown"></span>
  </div>
  <div id="dclose">close me!</div>

  </div>
</code>```

CSS CODE

```<code>  @import url(https://fonts.googleapis.com/css?family=Open+Sans:400,700,700italic);
  body {
    background-color: #000;
  }

  #dbanner {
    position: fixed;
    bottom: 0px;
    height: auto;
    width: 100%;
    padding: 30px 0 30px 0;
    color: #fff;
    text-align: center;
    font-family: "Open Sans";
    text-shadow: 1px 2px 2px rgba(0, 0, 0, 0.8);
  }

  .dcontent {
    padding: 0px 30px 0px 30px;
    font-size: 16px;
  }

  .dcontent strong {
    font-size: 30px;
    color: yellow;
    white-space: nowrap;
  }

  .dcontent code {
    font-size: 30px;
    padding: 2px 5px 2px 5px;
    color: #EED183;
    border: 1px dashed #EED183;
    background-color: #0C3D4C;
    white-space: nowrap;
  }

  .dtime {
    font-size: 18px;
    background-color: #FF2A2A;
    padding: 0 10px 0 10px;
    white-space: nowrap;
  }

  #dclose {
    position: absolute;
    font-size: 8px;
    height: 20px;
    line-height: 20px;
    top: 5px;
    right: 10px;
    color: #fff;
  }

  #dclose:hover {
    cursor: pointer;
  }

  .change-color {
    background-color: #107460;
    color: #FFF;
    text-align: center;
    animation-name: homeCycle;
    animation-duration: 6s;
    animation-direction: alternate;
    animation-iteration-count: infinite;
    -webkit-animation-name: homeCycle;
    -webkit-animation-duration: 6s;
    -webkit-animation-direction: alternate;
    -webkit-animation-iteration-count: infinite;
  }

  @keyframes homeCycle {
    0% {
      background-color: #727272;
    }
    25% {
      background-color: #86C14D;
    }
    50% {
      background-color: #0088CC;
    }
    75% {
      background-color: #0C3D4C;
    }
  }

  @-webkit-keyframes homeCycle {
    0% {
      background-color: #727272;
    }
    25% {
      background-color: #86C14D;
    }
    50% {
      background-color: #0088CC;
    }
    75% {
      background-color: #0C3D4C;
    }
  }

  .countdown-section {
    padding: 0 5px 0 5px;
  }

  .countdown-amount {
    padding: 0 5px 0 0;
  }

  .countdown-period {
    text-transform: uppercase;
  }

  .countdown-descr {}
</code>```

Title: JavaScript image banner timer HTML

Body:
I want to be able to make my image banner move on to the next image after a few seconds. I've tried a few things but nothing has worked. I believe I can use JavaScript to do this.

Any help will be much appreciated!

I'll put the code up:

        <input type="radio" id="button-1" name="controls"     checked="checked"/>

        <input type="radio" id="button-2" name="controls"/>

        <input type="radio" id="button-3" name="controls"/>

        <input type="radio" id="button-4" name="controls"/>

        <input type="radio" id="button-5" name="controls"/>

        >
        >
        >
        >
        >

Body:
JS CODE

$(function() {
var endDate = new Date();
endDate = new Date(2017, 12 - 1, 31);
$('#dcountdown').countdown({
until: endDate
});

$('#dclose').click(function() {
$(this).parent().slideUp();
});
});

HTML CODE

<div id="dbanner" class="change-color">
<div class="dcontent">
  [http://carrentalchennai.in/][1] <strong> South Indian Tour Packages </strong> [Google Authorised Reseller Chennai][1] by
         <code> [http://www.alphabetwebz.com/][1] </code> <span class="dtime"> [http://www.carrentalinchennai.com/][1]</span><span     id="dcountdown"></span>
  </div>
  <div id="dclose">close me!</div>

  </div>

CSS CODE

  @import url(https://fonts.googleapis.com/css?family=Open+Sans:400,700,700italic);
  body {
    background-color: #000;
  }

  #dbanner {
    position: fixed;
    bottom: 0px;
    height: auto;
    width: 100%;
    padding: 30px 0 30px 0;
    color: #fff;
    text-align: center;
    font-family: "Open Sans";
    text-shadow: 1px 2px 2px rgba(0, 0, 0, 0.8);
  }

  .dcontent {
    padding: 0px 30px 0px 30px;
    font-size: 16px;
  }

  .dcontent strong {
    font-size: 30px;
    color: yellow;
    white-space: nowrap;
  }

  .dcontent code {
    font-size: 30px;
    padding: 2px 5px 2px 5px;
    color: #EED183;
    border: 1px dashed #EED183;
    background-color: #0C3D4C;
    white-space: nowrap;
  }

  .dtime {
    font-size: 18px;
    background-color: #FF2A2A;
    padding: 0 10px 0 10px;
    white-space: nowrap;
  }

  #dclose {
    position: absolute;
    font-size: 8px;
    height: 20px;
    line-height: 20px;
    top: 5px;
    right: 10px;
    color: #fff;
  }

  #dclose:hover {
    cursor: pointer;
  }

  .change-color {
    background-color: #107460;
    color: #FFF;
    text-align: center;
    animation-name: homeCycle;
    animation-duration: 6s;
    animation-direction: alternate;
    animation-iteration-count: infinite;
    -webkit-animation-name: homeCycle;
    -webkit-animation-duration: 6s;
    -webkit-animation-direction: alternate;
    -webkit-animation-iteration-count: infinite;
  }

  @keyframes homeCycle {
    0% {
      background-color: #727272;
    }
    25% {
      background-color: #86C14D;
    }
    50% {
      background-color: #0088CC;
    }
    75% {
      background-color: #0C3D4C;
    }
  }

  @-webkit-keyframes homeCycle {
    0% {
      background-color: #727272;
    }
    25% {
      background-color: #86C14D;
    }
    50% {
      background-color: #0088CC;
    }
    75% {
      background-color: #0C3D4C;
    }
  }

  .countdown-section {
    padding: 0 5px 0 5px;
  }

  .countdown-amount {
    padding: 0 5px 0 0;
  }

  .countdown-period {
    text-transform: uppercase;
  }

  .countdown-descr {}


问:
Python threads all executing on a single core
I have a Python program that spawns many threads, runs 4 at a time, and each performs an expensive operation. Pseudocode:

```<code>for object in list:
    t = Thread(target=process, args=(object))
    # if fewer than 4 threads are currently running, t.start(). Otherwise, add t to queue
</code>```

But when the program is run, Activity Monitor in OS X shows that 1 of the 4 logical cores is at 100% and the others are at nearly 0. Obviously I can't force the OS to do anything but I've never had to pay attention to performance in multi-threaded code like this before so I was wondering if I'm just missing or misunderstanding something.

Thanks.

答:
Note that in many cases (and virtually all cases where your "expensive operation" is a calculation implemented in Python), multiple threads will not actually run concurrently due to Python's Global Interpreter Lock (GIL).

The GIL is an interpreter-level lock.
This lock prevents execution of
multiple threads at once in the Python
interpreter. Each thread that wants to
run must wait for the GIL to be
released by the other thread, which
means your multi-threaded Python
application is essentially single
threaded, right? Yes. Not exactly.
Sort of.

CPython uses what’s called “operating
system” threads under the covers,
which is to say each time a request to
make a new thread is made, the
interpreter actually calls into the
operating system’s libraries and
kernel to generate a new thread. This
is the same as Java, for example. So
in memory you really do have multiple
threads and normally the operating
system controls which thread is
scheduled to run. On a multiple
processor machine, this means you
could have many threads spread across
multiple processors, all happily
chugging away doing work.

However, while CPython does use
operating system threads (in theory
allowing multiple threads to execute
within the interpreter
simultaneously), the interpreter also
forces the GIL to be acquired by a
thread before it can access the
interpreter and stack and can modify
Python objects in memory all
willy-nilly. The latter point is why
the GIL exists: The GIL prevents
simultaneous access to Python objects
by multiple threads. But this does not
save you (as illustrated by the Bank
example) from being a lock-sensitive
creature; you don’t get a free ride.
The GIL is there to protect the
interpreters memory, not your sanity.

See the Global Interpreter Lock section of Jesse Noller's post for more details.

To get around this problem, check out Python's multiprocessing module.

multiple processes (with judicious use
of IPC) are[...] a much better
approach to writing apps for multi-CPU
boxes than threads.

-- Guido van Rossum (creator of Python)

Edit based on a comment from @spinkus:

If Python can't run multiple threads simultaneously, then why have threading at all?

Threads can still be very useful in Python when doing simultaneous operations that do not need to modify the interpreter's state. This includes many (most?) long-running function calls that are not in-Python calculations, such as I/O (file access or network requests)) and [calculations on Numpy arrays][6]. These operations release the GIL while waiting for a result, allowing the program to continue executing. Then, once the result is received, the thread must re-acquire the GIL in order to use that result in "Python-land"

Body:
I have a Python program that spawns many threads, runs 4 at a time, and each performs an expensive operation. Pseudocode:

for object in list:
    t = Thread(target=process, args=(object))
    # if fewer than 4 threads are currently running, t.start(). Otherwise, add t to queue

But when the program is run, Activity Monitor in OS X shows that 1 of the 4 logical cores is at 100% and the others are at nearly 0. Obviously I can't force the OS to do anything but I've never had to pay attention to performance in multi-threaded code like this before so I was wondering if I'm just missing or misunderstanding something.

Thanks.


答:
Is this what you are looking for?</p>

```<code>import pandas as pd
df = pd.DataFrame({'hour': list(range(24))*2,
                   'value': list(range(48))})

shift_cols_n = 10
for shift in range(1, shift_cols_n):
    new_columns_name = 'value - ' + str(shift)

    # Assuming that you don't have any NAs in your dataframe
    df[new_columns_name] = df['value'].shift(shift).fillna(0)

    # A safer (and a less simple) way, in case you have NAs in your dataframe
    df[new_columns_name] = df['value'].shift(shift)
    df.loc[:shift, new_columns_name] = 0

print(df.head(9))

   hour  value  value - 1  value - 2  value - 3  value - 4  value - 5  \
0     0      0        0.0        0.0        0.0        0.0        0.0
1     1      1        0.0        0.0        0.0        0.0        0.0
2     2      2        1.0        0.0        0.0        0.0        0.0
3     3      3        2.0        1.0        0.0        0.0        0.0
4     4      4        3.0        2.0        1.0        0.0        0.0
5     5      5        4.0        3.0        2.0        1.0        0.0
6     6      6        5.0        4.0        3.0        2.0        1.0
7     7      7        6.0        5.0        4.0        3.0        2.0
8     8      8        7.0        6.0        5.0        4.0        3.0

   value - 6  value - 7  value - 8  value - 9
0        0.0        0.0        0.0        0.0
1        0.0        0.0        0.0        0.0
2        0.0        0.0        0.0        0.0
3        0.0        0.0        0.0        0.0
4        0.0        0.0        0.0        0.0
5        0.0        0.0        0.0        0.0
6        0.0        0.0        0.0        0.0
7        1.0        0.0        0.0        0.0
8        2.0        1.0        0.0        0.0
</code>```

Title: Pandas, create new columns based on existing with repeated count

Body:
Is this what you are looking for?

import pandas as pd
df = pd.DataFrame({'hour': list(range(24))*2,
                   'value': list(range(48))})

shift_cols_n = 10
for shift in range(1, shift_cols_n):
    new_columns_name = 'value - ' + str(shift)

    # Assuming that you don't have any NAs in your dataframe
    df[new_columns_name] = df['value'].shift(shift).fillna(0)

    # A safer (and a less simple) way, in case you have NAs in your dataframe
    df[new_columns_name] = df['value'].shift(shift)
    df.loc[:shift, new_columns_name] = 0

print(df.head(9))

   hour  value  value - 1  value - 2  value - 3  value - 4  value - 5  \
0     0      0        0.0        0.0        0.0        0.0        0.0
1     1      1        0.0        0.0        0.0        0.0        0.0
2     2      2        1.0        0.0        0.0        0.0        0.0
3     3      3        2.0        1.0        0.0        0.0        0.0
4     4      4        3.0        2.0        1.0        0.0        0.0
5     5      5        4.0        3.0        2.0        1.0        0.0
6     6      6        5.0        4.0        3.0        2.0        1.0
7     7      7        6.0        5.0        4.0        3.0        2.0
8     8      8        7.0        6.0        5.0        4.0        3.0

   value - 6  value - 7  value - 8  value - 9
0        0.0        0.0        0.0        0.0
1        0.0        0.0        0.0        0.0
2        0.0        0.0        0.0        0.0
3        0.0        0.0        0.0        0.0
4        0.0        0.0        0.0        0.0
5        0.0        0.0        0.0        0.0
6        0.0        0.0        0.0        0.0
7        1.0        0.0        0.0        0.0
8        2.0        1.0        0.0        0.0


问:
How to hide overlay on mouse hover
Here is my code, what i want is to hide overlay after mouse hover, and what is happening is its staying active until i remove mouse hover on the image. is there any one can solve this problem

.upper {position: absolute; top: 50%; bottom: 0; left: 50%; transform: translate(-50%, -50%); width: 0; height: 0; overflow: hidden; background: #ddd; opacity: 0.5; transition: .2s ease; border-radius: 100%;}
.maine:hover .upper {width: 150%; height: 150%;}
.maine {position: relative; overflow: hidden;}
.upper:after {width 0; height: 0;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="col-md-2">
  <div class="maine">
    <img src="https://www.w3schools.com/howto/img_avatar.png" alt="Avatar" class="img-responsive">
    <div class="upper"> heading </div>
</div>
</div></code>```

答:
Here is the solution that you want and made without using @keyframes.

.maine {position: relative; overflow: hidden;}
.upper {position: absolute; top: 50%; bottom: 0; left: 50%; transform: translate(-50%, -50%); width: 0px; height: 0px; overflow: hidden; background: #ddd; transition-property: width, height; opacity: 0.5; transition: .4s ease; border-radius: 100%;}
.maine:hover .upper {width: 150%; height: 150%; opacity: 0; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="col-md-2">
  <div class="maine">
    <img src="https://www.w3schools.com/howto/img_avatar.png" alt="Avatar" class="img-responsive">
    <div class="upper"> heading </div>
</div>
</div></code>```

If you want to keep heading visible it should be a solution..!

.maine {position: relative; overflow: hidden;}
.upper {position: absolute; top: 50%; bottom: 0; left: 50%; transform: translate(-50%, -50%); width: 0px; height: 0px; overflow: hidden; background: #ddd; transition-property: width, height; opacity: 0.5; transition: .4s ease; border-radius: 100%;}
.maine:hover .upper {width: 150%; height: 150%; opacity: 0; }
.heading {position: absolute; top: 0px; left: 0px; width: 100%; height: 100%; padding-top: 30%; text-align: center; display: none; transition: all .2s linear !important;}
.maine:hover .heading {display: block;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="col-md-2">
  <div class="maine">
    <img src="https://www.w3schools.com/howto/img_avatar.png" alt="Avatar" class="img-responsive">
    <div class="upper"></div>
    <di class="heading"><h2>Heading</div>
</div>
</div></code>```

Title: How to hide overlay on mouse hover

Body:
Here is my code, what i want is to hide overlay after mouse hover, and what is happening is its staying active until i remove mouse hover on the image. is there any one can solve this problem

.upper {position: absolute; top: 50%; bottom: 0; left: 50%; transform: translate(-50%, -50%); width: 0; height: 0; overflow: hidden; background: #ddd; opacity: 0.5; transition: .2s ease; border-radius: 100%;}
.maine:hover .upper {width: 150%; height: 150%;}
.maine {position: relative; overflow: hidden;}
.upper:after {width 0; height: 0;}

 heading

Body:
Here is the solution that you want and made without using @keyframes.

.maine {position: relative; overflow: hidden;}
.upper {position: absolute; top: 50%; bottom: 0; left: 50%; transform: translate(-50%, -50%); width: 0px; height: 0px; overflow: hidden; background: #ddd; transition-property: width, height; opacity: 0.5; transition: .4s ease; border-radius: 100%;}
.maine:hover .upper {width: 150%; height: 150%; opacity: 0; }

<div class="col-md-2">
  <div class="maine">
    <img src="https://www.w3schools.com/howto/img_avatar.png" alt="Avatar" class="img-responsive">
    <div class="upper"> heading </div>
</div>
</div>

If you want to keep heading visible it should be a solution..!

.maine {position: relative; overflow: hidden;}
.upper {position: absolute; top: 50%; bottom: 0; left: 50%; transform: translate(-50%, -50%); width: 0px; height: 0px; overflow: hidden; background: #ddd; transition-property: width, height; opacity: 0.5; transition: .4s ease; border-radius: 100%;}
.maine:hover .upper {width: 150%; height: 150%; opacity: 0; }
.heading {position: absolute; top: 0px; left: 0px; width: 100%; height: 100%; padding-top: 30%; text-align: center; display: none; transition: all .2s linear !important;}
.maine:hover .heading {display: block;}

<div class="col-md-2">
  <div class="maine">
    <img src="https://www.w3schools.com/howto/img_avatar.png" alt="Avatar" class="img-responsive">
    <div class="upper"></div>
    <di class="heading"><h2>Heading</div>
</div>
</div>


问:
get title inside link tag in HTML using beautifulsoup
I am extracting data from https://data.gov.au/dataset?organization=reservebankofaustralia&_groups_limit=0&groups=business
and got output I wanted but now problem is: the output that I am getting is Business Support an... and Reserve Bank of Aus...., not complete text, I want to print the whole text not "......." for all. I replaced line 9 and 10 in answer by jezrael, please refer to Fetching content from html and write fetched content in a specific format in CSV with code
org = soup.find_all('a', {'class':'nav-item active'})[0].get('title')
groups = soup.find_all('a', {'class':'nav-item active'})[1].get('title')
. And I am running it separately and getting error: list index out of range. What should I use to extract complete sentences? I also tried :
org = soup.find_all('span',class_="filtered pill"), it gave answer of type string when I ran separately but could not run with whole code.

答:
All data with longer text are in attribut title, shorter are in text. So add double if:

```<code>for i in webpage_urls:
    wiki2 = i
    page= urllib.request.urlopen(wiki2)
    soup = BeautifulSoup(page, "lxml")

    lobbying = {}
    #always only 2 active li, so select first by [0]  and second by [1]
    l = soup.find_all('li', class_="nav-item active")

    org = l[0].a.get('title')
    if org == '':
        org = l[0].span.get_text()

    groups = l[1].a.get('title')
    if groups == '':
        groups = l[1].span.get_text()

    data2 = soup.find_all('h3', class_="dataset-heading")
    for element in data2:
        lobbying[element.a.get_text()] = {}
    data2[0].a["href"]
    prefix = "https://data.gov.au"
    for element in data2:
        lobbying[element.a.get_text()]["link"] = prefix + element.a["href"]
        lobbying[element.a.get_text()]["Organisation"] = org
        lobbying[element.a.get_text()]["Group"] = groups

        #print(lobbying)
        df = pd.DataFrame.from_dict(lobbying, orient='index') \
               .rename_axis('Titles').reset_index()
        dfs.append(df)
</code>```

```<code>df = pd.concat(dfs, ignore_index=True)
df1 = df.drop_duplicates(subset = 'Titles').reset_index(drop=True)

df1['Organisation'] = df1['Organisation'].str.replace('\(\d+\)', '')
df1['Group'] = df1['Group'].str.replace('\(\d+\)', '')
</code>```

```<code>print (df1.head())

                                              Titles  \
0                                     Banks – Assets
1  Consolidated Exposures – Immediate and Ultimat...
2  Foreign Exchange Transactions and Holdings of ...
3  Finance Companies and General Financiers – Sel...
4                   Liabilities and Assets – Monthly

                                                link  \
0           https://data.gov.au/dataset/banks-assets
1  https://data.gov.au/dataset/consolidated-expos...
2  https://data.gov.au/dataset/foreign-exchange-t...
3  https://data.gov.au/dataset/finance-companies-...
4  https://data.gov.au/dataset/liabilities-and-as...

                Organisation                            Group
0  Reserve Bank of Australia  Business Support and Regulation
1  Reserve Bank of Australia  Business Support and Regulation
2  Reserve Bank of Australia  Business Support and Regulation
3  Reserve Bank of Australia  Business Support and Regulation
4  Reserve Bank of Australia  Business Support and Regulation
</code>```

Body:
All data with longer text are in attribut title, shorter are in text. So add double if:

for i in webpage_urls:
    wiki2 = i
    page= urllib.request.urlopen(wiki2)
    soup = BeautifulSoup(page, "lxml")

    lobbying = {}
    #always only 2 active li, so select first by [0]  and second by [1]
    l = soup.find_all('li', class_="nav-item active")

    org = l[0].a.get('title')
    if org == '':
        org = l[0].span.get_text()

    groups = l[1].a.get('title')
    if groups == '':
        groups = l[1].span.get_text()

    data2 = soup.find_all('h3', class_="dataset-heading")
    for element in data2:
        lobbying[element.a.get_text()] = {}
    data2[0].a["href"]
    prefix = "https://data.gov.au"
    for element in data2:
        lobbying[element.a.get_text()]["link"] = prefix + element.a["href"]
        lobbying[element.a.get_text()]["Organisation"] = org
        lobbying[element.a.get_text()]["Group"] = groups

        #print(lobbying)
        df = pd.DataFrame.from_dict(lobbying, orient='index') \
               .rename_axis('Titles').reset_index()
        dfs.append(df)

df = pd.concat(dfs, ignore_index=True)
df1 = df.drop_duplicates(subset = 'Titles').reset_index(drop=True)

df1['Organisation'] = df1['Organisation'].str.replace('\(\d+\)', '')
df1['Group'] = df1['Group'].str.replace('\(\d+\)', '')

print (df1.head())

                                              Titles  \
0                                     Banks – Assets
1  Consolidated Exposures – Immediate and Ultimat...
2  Foreign Exchange Transactions and Holdings of ...
3  Finance Companies and General Financiers – Sel...
4                   Liabilities and Assets – Monthly

                                                link  \
0           https://data.gov.au/dataset/banks-assets
1  https://data.gov.au/dataset/consolidated-expos...
2  https://data.gov.au/dataset/foreign-exchange-t...
3  https://data.gov.au/dataset/finance-companies-...
4  https://data.gov.au/dataset/liabilities-and-as...

                Organisation                            Group
0  Reserve Bank of Australia  Business Support and Regulation
1  Reserve Bank of Australia  Business Support and Regulation
2  Reserve Bank of Australia  Business Support and Regulation
3  Reserve Bank of Australia  Business Support and Regulation
4  Reserve Bank of Australia  Business Support and Regulation


问:
how to make material2 tabs to use full page size
I want to create tab group having two tabs. Tab group should use the full page size and the individual tab should get equal width. Following is code that I am using

```<code><md-tab-group fxFlexFill>
    <md-tab>
        <ng-template md-tab-label>
            <md-icon>description</md-icon> Content Privileges
        </ng-template>
        Content Privileges
    </md-tab>
    <md-tab>
        <ng-template md-tab-label>
            <md-icon>flash_on</md-icon> Application Privileges
        </ng-template>
        Application Privileges
    </md-tab>
</md-tab-group>
</code>```

And here is the output of above

Tabs are not using the full width. And label icon and text is not aligned.

How can I do that?

答:
For alignment Problem: I just use vertical-align:middle; in md-icon and changed div with span. Its seems working.

```<code><div>
  <md-tab-group >
    <md-tab>
        <ng-template md-tab-label>
            <md-icon style="vertical-align:middle;">description</md-icon>
            <span class="title">Content Privileges</span>
        </ng-template>
        Content Privileges
    </md-tab>
    <md-tab>
        <ng-template md-tab-label>
            <md-icon style="vertical-align:middle;">flash_on</md-icon>
            <span class="title">Application Privileges</span>
        </ng-template>
        Application Privileges
    </md-tab>
  </md-tab-group>
</div>
</code>```

Body:
I want to create tab group having two tabs. Tab group should use the full page size and the individual tab should get equal width. Following is code that I am using

<md-tab-group fxFlexFill>
    <md-tab>
        <ng-template md-tab-label>
            <md-icon>description</md-icon> Content Privileges
        </ng-template>
        Content Privileges
    </md-tab>
    <md-tab>
        <ng-template md-tab-label>
            <md-icon>flash_on</md-icon> Application Privileges
        </ng-template>
        Application Privileges
    </md-tab>
</md-tab-group>

And here is the output of above

Tabs are not using the full width. And label icon and text is not aligned.

How can I do that?

Body:
For alignment Problem: I just use vertical-align:middle; in md-icon and changed div with span. Its seems working.

<div>
  <md-tab-group >
    <md-tab>
        <ng-template md-tab-label>
            <md-icon style="vertical-align:middle;">description</md-icon>
            <span class="title">Content Privileges</span>
        </ng-template>
        Content Privileges
    </md-tab>
    <md-tab>
        <ng-template md-tab-label>
            <md-icon style="vertical-align:middle;">flash_on</md-icon>
            <span class="title">Application Privileges</span>
        </ng-template>
        Application Privileges
    </md-tab>
  </md-tab-group>
</div>


问:
c# Serialport data received event handler
I am currently reading data from serialport using WPF. I am able to read data from serialport & write it in File using Binarywriter.

What Problem I am facing right now is:
I want to Analyse this data. I have developed one function which contains Use case structures to split the data which i read in serialport datahandler. Purpose is to Analyse captured data. But my program is just hanging on in receiving data from Serialport. Its not approaching down to Analyse the data.

This are few Options which i read from some Posts which may be a solution for my problem:

Backgroundworker: If yes then how i can fetch in my current program?

Threading: I tried it but its not working. My program is handing on writing the Bytes in the file & not going down to start the thread which i declared.

So can anybody suggest me a better option?

My code:

```<code>private void port_DataReceived(Object sender, SerialDataReceivedEventArgs e) {
  BinaryWriter writer=new BinaryWriter(File.Open("c:\\temp\\lbus2snifflog1.txt", FileMode.Append));
  int bytes=comport.Read(buffer, 0, 4096);
  for (int i=0;
  i < bytes;
  i++) {
    //writer.Write(buffer, 0, bytes);             // Write the data to the file on temp folder
    data.Enqueue(buffer[i]); // Enqueue data from the buffer
    writer.Write(buffer, 0, bytes);
  }
  //writer.Write(buffer, 0, bytes);
  writer.Flush(); // Send all remaining data to the writer
  writer.Close(); // Close the writer
  /*Initilaise the Thread for the Analysis*/
  Thread Analyser=new Thread(datacollection);
  Analyser.Start();
}
</code>```

答:
Edit
For your case, don't know if this is best approach, but this may work.

You have a ConcurrentDictionary in main thread. In BackgroundWorker thread you get the data from the ConcurrentDictionary. Then you report to main thread the processed data.

Here is a working scenario.

Example:

```<code>class MyClass
{
    private ConcurrentDictionary<int, string> serialPortsQueue =
        new ConcurrentDictionary<int, string>();

    private BackgroundWorker _worker;
    public MyClass()
    {
        _worker = new BackgroundWorker()
        {
            WorkerSupportsCancellation = true,
            WorkerReportsProgress = true
        };

        _worker.DoWork += DeviceDataAcquisition_DoWork;
        _worker.ProgressChanged += DeviceDataAcquisition_ProgressChanged;
        _worker.RunWorkerCompleted += DeviceDataAcquisition_RunWorkerCompleted;
        _worker.RunWorkerAsync();

        System.Diagnostics.Debug.WriteLine($"{DateTime.Now}: begin add first data");
        serialPortsQueue.TryAdd(1, "data 1");
        serialPortsQueue.TryAdd(2, "data 2");
        serialPortsQueue.TryAdd(3, "data 3");
        serialPortsQueue.TryAdd(4, "data 4");
        serialPortsQueue.TryAdd(5, "data 5");
        serialPortsQueue.TryAdd(6, "data 6");
        serialPortsQueue.TryAdd(7, "data 7");
        System.Diagnostics.Debug.WriteLine($"{DateTime.Now}: end add first data");
        Thread.Sleep(2000);
        System.Diagnostics.Debug.WriteLine($"{DateTime.Now}: begin add second data");
        serialPortsQueue.TryAdd(8, "data 8");
        System.Diagnostics.Debug.WriteLine($"{DateTime.Now}: end add second data");
    }

    private void DeviceDataAcquisition_DoWork(object sender, DoWorkEventArgs e)
    {
        // backgroundworker thread
        if (sender is BackgroundWorker worker)
        {
            //just demo propose
            int cnt = 0;

            while (true)
            {
                if (worker.CancellationPending)
                    break;

                if (serialPortsQueue.Count > 0)
                {
                    KeyValuePair<int, string> kv = serialPortsQueue.ElementAt(0);
                    serialPortsQueue.TryRemove(kv.Key, out string value);

                    //just demo propose
                    // Simulate some processing
                    Thread.Sleep(1000);

                    worker.ReportProgress(0, kv);

                    //just demo propose
                    cnt++;
                }

                //just demo propose
                if (cnt == 8)
                    break;
            }
        }
    }

    private void DeviceDataAcquisition_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        // main thread
        if (e.UserState is KeyValuePair<int, string> kv)
        {
            System.Diagnostics.Debug.WriteLine($"{DateTime.Now}: {kv.Key} -> {kv.Value}");
        }
    }

    private void DeviceDataAcquisition_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        if (sender is BackgroundWorker worker)
        {
            worker.DoWork -= DeviceDataAcquisition_DoWork;
            worker.ProgressChanged -= DeviceDataAcquisition_ProgressChanged;
            worker.RunWorkerCompleted -= DeviceDataAcquisition_RunWorkerCompleted;
            worker.Dispose(); // i think this does nothing...
            System.Diagnostics.Debug.WriteLine($"{DateTime.Now}: end backgroundworker");
        }
    }
}
</code>```

You can see in the window Output  -> Debug the results.

Hope this helps.

Body:
I am currently reading data from serialport using WPF. I am able to read data from serialport & write it in File using Binarywriter.

What Problem I am facing right now is:
I want to Analyse this data. I have developed one function which contains Use case structures to split the data which i read in serialport datahandler. Purpose is to Analyse captured data. But my program is just hanging on in receiving data from Serialport. Its not approaching down to Analyse the data.

This are few Options which i read from some Posts which may be a solution for my problem:

Backgroundworker: If yes then how i can fetch in my current program?

Threading: I tried it but its not working. My program is handing on writing the Bytes in the file & not going down to start the thread which i declared.

So can anybody suggest me a better option?

My code:

private void port_DataReceived(Object sender, SerialDataReceivedEventArgs e) {
  BinaryWriter writer=new BinaryWriter(File.Open("c:\\temp\\lbus2snifflog1.txt", FileMode.Append));
  int bytes=comport.Read(buffer, 0, 4096);
  for (int i=0;
  i < bytes;
  i++) {
    //writer.Write(buffer, 0, bytes);             // Write the data to the file on temp folder
    data.Enqueue(buffer[i]); // Enqueue data from the buffer
    writer.Write(buffer, 0, bytes);
  }
  //writer.Write(buffer, 0, bytes);
  writer.Flush(); // Send all remaining data to the writer
  writer.Close(); // Close the writer
  /*Initilaise the Thread for the Analysis*/
  Thread Analyser=new Thread(datacollection);
  Analyser.Start();
}

Body:
Edit
For your case, don't know if this is best approach, but this may work.

You have a ConcurrentDictionary in main thread. In BackgroundWorker thread you get the data from the ConcurrentDictionary. Then you report to main thread the processed data.

Here is a working scenario.

Example:

class MyClass
{
    private ConcurrentDictionary<int, string> serialPortsQueue =
        new ConcurrentDictionary<int, string>();

    private BackgroundWorker _worker;
    public MyClass()
    {
        _worker = new BackgroundWorker()
        {
            WorkerSupportsCancellation = true,
            WorkerReportsProgress = true
        };

        _worker.DoWork += DeviceDataAcquisition_DoWork;
        _worker.ProgressChanged += DeviceDataAcquisition_ProgressChanged;
        _worker.RunWorkerCompleted += DeviceDataAcquisition_RunWorkerCompleted;
        _worker.RunWorkerAsync();

        System.Diagnostics.Debug.WriteLine($"{DateTime.Now}: begin add first data");
        serialPortsQueue.TryAdd(1, "data 1");
        serialPortsQueue.TryAdd(2, "data 2");
        serialPortsQueue.TryAdd(3, "data 3");
        serialPortsQueue.TryAdd(4, "data 4");
        serialPortsQueue.TryAdd(5, "data 5");
        serialPortsQueue.TryAdd(6, "data 6");
        serialPortsQueue.TryAdd(7, "data 7");
        System.Diagnostics.Debug.WriteLine($"{DateTime.Now}: end add first data");
        Thread.Sleep(2000);
        System.Diagnostics.Debug.WriteLine($"{DateTime.Now}: begin add second data");
        serialPortsQueue.TryAdd(8, "data 8");
        System.Diagnostics.Debug.WriteLine($"{DateTime.Now}: end add second data");
    }

    private void DeviceDataAcquisition_DoWork(object sender, DoWorkEventArgs e)
    {
        // backgroundworker thread
        if (sender is BackgroundWorker worker)
        {
            //just demo propose
            int cnt = 0;

            while (true)
            {
                if (worker.CancellationPending)
                    break;

                if (serialPortsQueue.Count > 0)
                {
                    KeyValuePair<int, string> kv = serialPortsQueue.ElementAt(0);
                    serialPortsQueue.TryRemove(kv.Key, out string value);

                    //just demo propose
                    // Simulate some processing
                    Thread.Sleep(1000);

                    worker.ReportProgress(0, kv);

                    //just demo propose
                    cnt++;
                }

                //just demo propose
                if (cnt == 8)
                    break;
            }
        }
    }

    private void DeviceDataAcquisition_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        // main thread
        if (e.UserState is KeyValuePair<int, string> kv)
        {
            System.Diagnostics.Debug.WriteLine($"{DateTime.Now}: {kv.Key} -> {kv.Value}");
        }
    }

    private void DeviceDataAcquisition_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        if (sender is BackgroundWorker worker)
        {
            worker.DoWork -= DeviceDataAcquisition_DoWork;
            worker.ProgressChanged -= DeviceDataAcquisition_ProgressChanged;
            worker.RunWorkerCompleted -= DeviceDataAcquisition_RunWorkerCompleted;
            worker.Dispose(); // i think this does nothing...
            System.Diagnostics.Debug.WriteLine($"{DateTime.Now}: end backgroundworker");
        }
    }
}

You can see in the window Output  -> Debug the results.

Hope this helps.


问:
How to add tasks in the Queue dynamically in google app engine?
For e.g. can i do some thing like this ----
List of namespaces; so iterate over each namespace</p>

```<code>Queue queue = QueueFactory.getQueue("updateReservation-queue");
for(String name : namespaces){
   queue.add(TaskOptions.Builder.withUrl("/CheckExpiryDateTask").param("name", namespace));
}
</code>```

答: Yes, of course you can - is there something in particular you're having trouble with?</p>

Body:
For e.g. can i do some thing like this ----
List of namespaces; so iterate over each namespace

Queue queue = QueueFactory.getQueue("updateReservation-queue");
for(String name : namespaces){
   queue.add(TaskOptions.Builder.withUrl("/CheckExpiryDateTask").param("name", namespace));
}


问:
Spring Batch: How to get errors for all lines read?
I am using FlatFileItemReader to read a file. I plug in the DefaultLineMapper and my own custom FieldSetMapper (myMapper).

Currently in myMapper, when an error occurs I simply log it. I would like to accumulate all errors, for all lines in the file, and then save them to a file.

I was considering implementing my own Tasklet. But from what I've read, it is recommended to only do this if your step is not doing chunk-oriented processing.

Another option is to use either ItemListenerSupport or ItemReadListener and implement the onReadError() method. But if I do that, I'm not sure how I could have access to a global/shared object that holds a list of all errors, for all lines.

I've been going back and forth between these 2 options trying to get them to work, without much success. Any advice much appreciated.

***** EDIT *****

My code isn't anything non-standard I don't think. I define the errors log Job Param:

```<code>Map<String, JobParameter> jobParametersMap ...
jobParametersMap.put("errorsFile", new JobParameter(errorsFileURI));
</code>```

My xml config looks like this:

```<code><job ...>
  <step ...>
  <step id="import">
    <tasklet>
      <chunk reader="importReader" writer="importWriter" .../>
    </tasklet>
  </step>
</job>

<bean id="importReader" class="MyImportReader" scope="step">
  <property name="resource" .../>
  <property name="lineMapper">
    <bean class = "...DefaultLineMapper">
      ...
      <property name="fieldSetMapper" ref="importMapper"/>
    </bean>
  </property>
  <property name="errorsFile" value="#jobParameters['errorsFile']}"/>
</bean>

<bean id="importWriter" ...scope="step">
  ...
  <property name="errorsFile" value="#jobParameters['errorsFile']}"/>
</bean>
</code>```

The Reader class extends FlatFileItemReader and implements ItemReadListener. The writer implements BatchLoadableWriter and StepExecutionListener.

As you can see I pass the errorsFile to both the Reader and the Writer. The Writer has used the errorsFile for some time, whereas I just added it to the Reader. Both classes have a getter/setter for errorsFile.

The difference between them is that in the Writer, the @Overridden write() method validates and then writes all Items in the file. So all errors are written to the errorsFile at once. Also, if there are errors, a flag is set (hasErrors), and that flag's value is checked in the @Overridden afterStep() method. If it is true, ExitStatus.FAILED is returned.

Whereas with the Reader, the doRead() method is called once for each Item.   If there is an error, I can write it to the errorsFile, and I could set a flag like the Writer does. But the flag will be set only for that line/Item.

So let's say I import 10 lines. The first 5 have errors, the last 5 don't. When afterRead() is called, it will check the value of the flag for the last processed Item, which had no errors, so hasErrors will be false. Not good. Or perhaps it would be better to override onReadError(). But what would cause that method to be called, an error in the Mapper?

Something tells me implementing my own Reader, and/or having it implement ItemReadListener might not be the way to go about this. To me it seems I need to put some or all of this logic in the Reader's "parent" ... which would be ... a Tasklet? But I've read on SO and elsewhere on the net that implementing your own Tasklet to perform chunk processing isn't recommended; it should only be done for simple tasks.

I'm at a loss ...

答:
I think you should consider using the step and job scope. From your reader you can save the error details to these scopes and then reference the information at a later stage. I'd be careful about recording too much information here.

http://docs.spring.io/spring-batch/reference/html/configureStep.html#step-scope

You at the start of the job, generate and name an error file and save it to the job/step scope. If your Reader has an error, it can write details to the file. At the end of the process, you still have a reference to the error file name, with the recorded details.

Body:
I am using FlatFileItemReader to read a file. I plug in the DefaultLineMapper and my own custom FieldSetMapper (myMapper).

Currently in myMapper, when an error occurs I simply log it. I would like to accumulate all errors, for all lines in the file, and then save them to a file.

I was considering implementing my own Tasklet. But from what I've read, it is recommended to only do this if your step is not doing chunk-oriented processing.

Another option is to use either ItemListenerSupport or ItemReadListener and implement the onReadError() method. But if I do that, I'm not sure how I could have access to a global/shared object that holds a list of all errors, for all lines.

I've been going back and forth between these 2 options trying to get them to work, without much success. Any advice much appreciated.

***** EDIT *****

My code isn't anything non-standard I don't think. I define the errors log Job Param:

Map<String, JobParameter> jobParametersMap ...
jobParametersMap.put("errorsFile", new JobParameter(errorsFileURI));

My xml config looks like this:

<job ...>
  <step ...>
  <step id="import">
    <tasklet>
      <chunk reader="importReader" writer="importWriter" .../>
    </tasklet>
  </step>
</job>

<bean id="importReader" class="MyImportReader" scope="step">
  <property name="resource" .../>
  <property name="lineMapper">
    <bean class = "...DefaultLineMapper">
      ...
      <property name="fieldSetMapper" ref="importMapper"/>
    </bean>
  </property>
  <property name="errorsFile" value="#jobParameters['errorsFile']}"/>
</bean>

<bean id="importWriter" ...scope="step">
  ...
  <property name="errorsFile" value="#jobParameters['errorsFile']}"/>
</bean>

The Reader class extends FlatFileItemReader and implements ItemReadListener. The writer implements BatchLoadableWriter and StepExecutionListener.

As you can see I pass the errorsFile to both the Reader and the Writer. The Writer has used the errorsFile for some time, whereas I just added it to the Reader. Both classes have a getter/setter for errorsFile.

The difference between them is that in the Writer, the @Overridden write() method validates and then writes all Items in the file. So all errors are written to the errorsFile at once. Also, if there are errors, a flag is set (hasErrors), and that flag's value is checked in the @Overridden afterStep() method. If it is true, ExitStatus.FAILED is returned.

Whereas with the Reader, the doRead() method is called once for each Item.   If there is an error, I can write it to the errorsFile, and I could set a flag like the Writer does. But the flag will be set only for that line/Item.

So let's say I import 10 lines. The first 5 have errors, the last 5 don't. When afterRead() is called, it will check the value of the flag for the last processed Item, which had no errors, so hasErrors will be false. Not good. Or perhaps it would be better to override onReadError(). But what would cause that method to be called, an error in the Mapper?

Something tells me implementing my own Reader, and/or having it implement ItemReadListener might not be the way to go about this. To me it seems I need to put some or all of this logic in the Reader's "parent" ... which would be ... a Tasklet? But I've read on SO and elsewhere on the net that implementing your own Tasklet to perform chunk processing isn't recommended; it should only be done for simple tasks.

I'm at a loss ...