问:
how to handle OverflowException in C#?
I need to handle OverflowException in method mul().

```<code>class B
{
    short a, b;
    public B(short a, short b) { this.a = a; this.b = b; }
    public short mul()
    {
        try
        {
            return checked((short)(a * b));
        }
        catch (OverflowException exc) { Console.WriteLine(exc); }
    }
}

class MainClass
{
    public static void Main(string[] args)
    {
        B m1 = new B(1000, 500);
        m1.mul();
    }
}
</code>```

But the above code gives the following error :Error CS0161: 'B.mul()': not all code paths return a value (CS0161)

What can I do to fix it?

答:
Please, do not mix logic and UI; just put try {} catch {} to its proper place and everything will be clear:

```<code>class B
{
    ...

    // Logic: multiply with possible Overflow exception
    // Let us be nice and document the exception
    ///<exception cref="System.OverflowException">
    ///When a or (and) b are too large
    ///</exception>
    public short mul()
    {
        // Do we know how to process the exception at the place?
        // No. There're many reasonable responses:
        // - stop execution
        // - use some special/default value (e.g. -1, short.MaxValue)
        // - switch to class C which operates with int (or BigInteger) etc.
        // That's why we don't catch exception here
        return checked((short)(a * b));
    }
}
</code>```

...

```<code>class MainClass
{
    // UI: perform operation and show the result on the console
    public static void Main(string[] args)
    {
        B m1 = new B(1000, 500);

        try
        {
            m1.mul();
        }
        catch (OverflowException exc)
        {
            // Proper place to catch the exception: only here, at UI,
            // we know what to do with the exception:
            // we should print out the exception on the Console
            Console.WriteLine(exc);
        }
    }
}
</code>```

Title: how to handle OverflowException in C#?

Body:
I need to handle OverflowException in method mul().

class B
{
    short a, b;
    public B(short a, short b) { this.a = a; this.b = b; }
    public short mul()
    {
        try
        {
            return checked((short)(a * b));
        }
        catch (OverflowException exc) { Console.WriteLine(exc); }
    }
}

class MainClass
{
    public static void Main(string[] args)
    {
        B m1 = new B(1000, 500);
        m1.mul();
    }
}

But the above code gives the following error :Error CS0161: 'B.mul()': not all code paths return a value (CS0161)

What can I do to fix it?

Body:
Please, do not mix logic and UI; just put try {} catch {} to its proper place and everything will be clear:

class B
{
    ...

    // Logic: multiply with possible Overflow exception
    // Let us be nice and document the exception
    ///<exception cref="System.OverflowException">
    ///When a or (and) b are too large
    ///</exception>
    public short mul()
    {
        // Do we know how to process the exception at the place?
        // No. There're many reasonable responses:
        // - stop execution
        // - use some special/default value (e.g. -1, short.MaxValue)
        // - switch to class C which operates with int (or BigInteger) etc.
        // That's why we don't catch exception here
        return checked((short)(a * b));
    }
}

...

class MainClass
{
    // UI: perform operation and show the result on the console
    public static void Main(string[] args)
    {
        B m1 = new B(1000, 500);

        try
        {
            m1.mul();
        }
        catch (OverflowException exc)
        {
            // Proper place to catch the exception: only here, at UI,
            // we know what to do with the exception:
            // we should print out the exception on the Console
            Console.WriteLine(exc);
        }
    }
}


来源: stackexchange

问:
jQuery dropdown menu using prepend trigger
I am trying to use jQuery to prepend a trigger to a menu then have that trigger toggle child elements. The code below doesn't open the sub menus when using jQuery prepend, can any one suggest a fix?

HTML

```<code><ul>
  <li class="menu-item-has-children">Item 1</li>
    <ul class="sub-menu">
      <li>Sub Item 1</li>
      <li>Sub Item 2</li>
      <li class="menu-item-has-children">Sub Item 3</li>
        <ul class="sub-menu">
          <li>Sub Sub Item 1</li>
          <li>Sub Sub Item 2</li>
          <li>Sub Sub Item 3</li>
          <li>Sub Sub Item 4</li>
          <li>Sub Sub Item 5</li>
        </ul>
      <li>Sub Item 4</li>
      <li>Sub Item 5</li>
    </ul>
</ul>
</code>```

CSS

```<code>ul li {
 list-style-type:none;
}
.open {
  width:20px;
  height:20px;
  background-color:red;
  color:#fff;
  display:block;
  cursor:pointer;
  text-align:center;
}
.sub-menu {
  display:none;
}
</code>```

JS

```<code>jQuery(document).ready(function() {
jQuery('.menu-item-has-children').prepend ('<a class="open">+</a>');
    jQuery('.open').click(function () {
        jQuery(this).next('.sub-menu').toggle();
  });
});
</code>```

JS FIDDLE

Thanks!

答:
The issue with your code is not the JS but your HTML.

As Joseph Marikle stated: Your ul

permitted content zero or more
 elements, which in turn often
  contain nested
 or
 elements.

must not have any child-elements other than li.

In your case the element .open does not have a sibling therefor.next() will not find .sub-menu.

If you move your inner ul inside the li.menu-item-has-children you JS works just fine:

jQuery(document).ready(function() {
  jQuery('.menu-item-has-children').prepend('+');
  jQuery('.open').click(function() {
    jQuery(this).next('.sub-menu').toggle();
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>ul li {
  list-style-type: none;
}

.open {
  width: 20px;
  height: 20px;
  background-color: red;
  color: #fff;
  display: block;
  cursor: pointer;
  text-align: center;
}

.sub-menu {
  display: none;
}</code>```

Item 1

Sub Item 1

Sub Item 3

Sub Sub Item 1

Sub Item 4

```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to use jQuery to prepend a trigger to a menu then have that trigger toggle child elements. The code below doesn't open the sub menus when using jQuery prepend, can any one suggest a fix?

HTML

Item 1

Sub Item 1

Sub Item 2

Sub Item 3

Sub Sub Item 1

Sub Sub Item 2

Sub Sub Item 3

Sub Sub Item 4

Sub Sub Item 5

Sub Item 4

Sub Item 5

CSS

ul li {
 list-style-type:none;
}
.open {
  width:20px;
  height:20px;
  background-color:red;
  color:#fff;
  display:block;
  cursor:pointer;
  text-align:center;
}
.sub-menu {
  display:none;
}

JS

jQuery(document).ready(function() {
jQuery('.menu-item-has-children').prepend ('+');
    jQuery('.open').click(function () {
        jQuery(this).next('.sub-menu').toggle();
  });
});

JS FIDDLE

Thanks!

Body:
The issue with your code is not the JS but your HTML.

As Joseph Marikle stated: Your ul

permitted content zero or more <li> elements, which in turn often
  contain nested <ol> or <ul> elements.

must not have any child-elements other than li.

In your case the element .open does not have a sibling therefor.next() will not find .sub-menu.

If you move your inner ul inside the li.menu-item-has-children you JS works just fine:

jQuery(document).ready(function() {
  jQuery('.menu-item-has-children').prepend('<a class="open">+</a>');
  jQuery('.open').click(function() {
    jQuery(this).next('.sub-menu').toggle();
  });
});

ul li {
  list-style-type: none;
}

.open {
  width: 20px;
  height: 20px;
  background-color: red;
  color: #fff;
  display: block;
  cursor: pointer;
  text-align: center;
}

.sub-menu {
  display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li class="menu-item-has-children">Item 1
    <ul class="sub-menu">
      <li>Sub Item 1</li>
      <li class="menu-item-has-children">Sub Item 3
        <ul class="sub-menu">
          <li>Sub Sub Item 1</li>
        </ul>
      </li>
      <li>Sub Item 4</li>
    </ul>
  </li>
</ul>


问:
Update opinion error Netlogo. (Beginner)
I'm trying to build a Netlogo model in which nodes in a network update their opinions based on the opinions (or 'participation) of others to whom they are linked in the network.

I made the following engine to update opinions

```<code>    to go
 ask turtles [
set new-external-motivation (labda * external-motivation - ( 1 - labda ) * ( 1 - lpr ))]

  tick
end

to lpr
 ask turtles [
 set local-participation-rate ( (sum [participation] of link-neighbors) / (count link-neighbors) )
end
</code>```

where labda is a slider variable that dictates the degree to which individuals use new participation information in their decisions and where lpr is the 'local participation rate' of the nodes the turtle is linked with. Each turtle has a participation variable which is either 0 or 1.

However, I'm getting the error "- expected 1 input on the right, a number" with the '1 - lpr' section of the code highlighted.

I'm not sure what wrong. Anyone who can help?

答:
It looks like lpr should be a reporter. Also, note that lpr is being called from inside the ask turtles in go. So you don't want to call ask turtles inside lpr as well; the way you have it, all turtles are asking all turtles to run the code in lpr, which is not what you want.

Perhaps you meant something like this:

```<code>to-report lpr
  report ( (sum [participation] of link-neighbors) / (count link-neighbors) )
end
</code>```

Body:
I'm trying to build a Netlogo model in which nodes in a network update their opinions based on the opinions (or 'participation) of others to whom they are linked in the network.

I made the following engine to update opinions

    to go
 ask turtles [
set new-external-motivation (labda * external-motivation - ( 1 - labda ) * ( 1 - lpr ))]

  tick
end

to lpr
 ask turtles [
 set local-participation-rate ( (sum [participation] of link-neighbors) / (count link-neighbors) )
end

where labda is a slider variable that dictates the degree to which individuals use new participation information in their decisions and where lpr is the 'local participation rate' of the nodes the turtle is linked with. Each turtle has a participation variable which is either 0 or 1.

However, I'm getting the error "- expected 1 input on the right, a number" with the '1 - lpr' section of the code highlighted.

I'm not sure what wrong. Anyone who can help?

Body:
It looks like lpr should be a reporter. Also, note that lpr is being called from inside the ask turtles in go. So you don't want to call ask turtles inside lpr as well; the way you have it, all turtles are asking all turtles to run the code in lpr, which is not what you want.

Perhaps you meant something like this:

to-report lpr
  report ( (sum [participation] of link-neighbors) / (count link-neighbors) )
end


问:
Default property for class in delphi 7
I'd like to ask on how to set default property in a delphi 7 class? So it can be accesed by just writing >> class := '..'; << that's if the default property set to text. so we dont have to write class.text := '..';</p>

答:
You can't do that because it leads to ambiguous situation.

For example, you have a class:

```<code>type
  TMyClass = class
  public
    property MyProperty: TMyClass read FMyProperty; default;
  end;
var
  a, b : TMyClass;

begin
  // ...
  a := b; // Do we assign to a or to MyProperty
  // ...
end;
</code>```

It could have worked for other (basic) types but its still confusing. Besides, its just a few extra characters to type.

ContentLicense: CC BY-SA 2.5

Title: Default property for class in delphi 7

Body:
You can't do that because it leads to ambiguous situation.

For example, you have a class:

type
  TMyClass = class
  public
    property MyProperty: TMyClass read FMyProperty; default;
  end;
var
  a, b : TMyClass;

begin
  // ...
  a := b; // Do we assign to a or to MyProperty
  // ...
end;

It could have worked for other (basic) types but its still confusing. Besides, its just a few extra characters to type.


问:
Add a child view to a parent layout with the same bounds
In a RelativeLayout I have 2 buttons: button and button2. These 3 itself lie inside the root view which is also a RelativeLayout.

What I am trying to accomplish here is that when button is clicked button2 should be removed from the inner RelativeLayout(its id is otherLayout) and get added to the root View which is rootView but with the same bounds as it was in the inner layout.

Here is my XML and Java code:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/rootView"
    tools:context="com.test.testproject.MainActivity">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/otherLayout"
        >
        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:layout_marginStart="53dp"
            android:layout_marginTop="94dp"
            android:text="One" />

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@+id/button"
            android:layout_marginStart="76dp"
            android:layout_toEndOf="@+id/button"
            android:text="Two" />

    </RelativeLayout>

</RelativeLayout>
</code>```

Java Code

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

    Button button,button2;

    int mLeft,mRight,mTop,mBottom;
    RelativeLayout otherLayout;
    RelativeLayout rootView;
    ViewGroup childParent;
    int[] mBounds = new int[2];

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

        button = (Button) findViewById(R.id.button);
        button2 = (Button) findViewById(R.id.button2);
//        rootView = (RelativeLayout) findViewById(R.id.rootView);
        rootView = (RelativeLayout) findViewById(R.id.rootView);
        otherLayout = (RelativeLayout) findViewById(R.id.otherLayout);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Rect r = new Rect();

                button2.getLocalVisibleRect(r);
//                button2.getDrawingRect(r);
//                ((ViewGroup)button2.getParent()).offsetDescendantRectToMyCoords(button2, r);

                mLeft = r.left;
                mRight = r.right;
                mBottom = r.bottom;
                mTop = r.top;

                childParent = (ViewGroup) button2.getParent();

                ((ViewGroup)button2.getParent()).removeView(button2);

                Handler mHandler = new Handler(Looper.getMainLooper());

                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {

                        button2.setTop(mTop);
                        button2.setLeft(mLeft);
                        button2.setBottom(mBottom);
                        button2.setRight(mRight);

/*
                        button2.setX(mBounds[1]);
                        button2.setY(mBounds[0]);*/

                        ((ViewGroup)rootView).addView(button2);
                    }
                },1000);

            }
        });

    }
}
</code>```

I tried a different methods but would work. I used getLocalVisibleRect(), getDrawingRect() and all (You can see in the commented code).

So how do I achieve this? Remember, that the requirement is that the View residing in the inner layout and after adding to root should have the same bounds and params and the position on screen also must not change.

答:
I think that your issue may be with the layout parameters of button2. Probably the easiest way to approach this is to capture the position of button2 in the layout and set up new layout parameters. mLeft and mTop to be the left and top margins.

A simplified onCreate method is below, but I am curious about why this would be useful.

Also take a look at these caveats. The document for View specifies why setTop, etc. should not be called outside the layout system. (See here.)

setTop

void setTop (int top)

Sets the top position of this view relative to its parent. This method is meant to be called by the layout system and should not generally be called otherwise, because the property may be changed at any time by the layout.

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    Button button;

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button = (Button) findViewById(R.id.button);
    button2 = (Button) findViewById(R.id.button2);
    rootView = (RelativeLayout) findViewById(R.id.rootView);
    otherLayout = (RelativeLayout) findViewById(R.id.otherLayout);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            RelativeLayout.LayoutParams params;
            int top = button2.getTop();
            int left = button2.getLeft();

            ((ViewGroup) button2.getParent()).removeView(button2);
            params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            params.setMargins(left, top, 0, 0);
            button2.setLayoutParams(params);
            rootView.addView(button2);
        }
    });
}
</code>```

Body:
In a RelativeLayout I have 2 buttons: button and button2. These 3 itself lie inside the root view which is also a RelativeLayout.

What I am trying to accomplish here is that when button is clicked button2 should be removed from the inner RelativeLayout(its id is otherLayout) and get added to the root View which is rootView but with the same bounds as it was in the inner layout.

Here is my XML and Java code:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/rootView"
    tools:context="com.test.testproject.MainActivity">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/otherLayout"
        >
        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:layout_marginStart="53dp"
            android:layout_marginTop="94dp"
            android:text="One" />

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@+id/button"
            android:layout_marginStart="76dp"
            android:layout_toEndOf="@+id/button"
            android:text="Two" />

    </RelativeLayout>

</RelativeLayout>

Java Code

public class MainActivity extends AppCompatActivity {

    Button button,button2;

    int mLeft,mRight,mTop,mBottom;
    RelativeLayout otherLayout;
    RelativeLayout rootView;
    ViewGroup childParent;
    int[] mBounds = new int[2];

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

        button = (Button) findViewById(R.id.button);
        button2 = (Button) findViewById(R.id.button2);
//        rootView = (RelativeLayout) findViewById(R.id.rootView);
        rootView = (RelativeLayout) findViewById(R.id.rootView);
        otherLayout = (RelativeLayout) findViewById(R.id.otherLayout);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Rect r = new Rect();

                button2.getLocalVisibleRect(r);
//                button2.getDrawingRect(r);
//                ((ViewGroup)button2.getParent()).offsetDescendantRectToMyCoords(button2, r);

                mLeft = r.left;
                mRight = r.right;
                mBottom = r.bottom;
                mTop = r.top;

                childParent = (ViewGroup) button2.getParent();

                ((ViewGroup)button2.getParent()).removeView(button2);

                Handler mHandler = new Handler(Looper.getMainLooper());

                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {

                        button2.setTop(mTop);
                        button2.setLeft(mLeft);
                        button2.setBottom(mBottom);
                        button2.setRight(mRight);

/*
                        button2.setX(mBounds[1]);
                        button2.setY(mBounds[0]);*/

                        ((ViewGroup)rootView).addView(button2);
                    }
                },1000);

            }
        });

    }
}

I tried a different methods but would work. I used getLocalVisibleRect(), getDrawingRect() and all (You can see in the commented code).

So how do I achieve this? Remember, that the requirement is that the View residing in the inner layout and after adding to root should have the same bounds and params and the position on screen also must not change.

Body:
I think that your issue may be with the layout parameters of button2. Probably the easiest way to approach this is to capture the position of button2 in the layout and set up new layout parameters. mLeft and mTop to be the left and top margins.

A simplified onCreate method is below, but I am curious about why this would be useful.

Also take a look at these caveats. The document for View specifies why setTop, etc. should not be called outside the layout system. (See here.)

setTop

void setTop (int top)

Sets the top position of this view relative to its parent. This method is meant to be called by the layout system and should not generally be called otherwise, because the property may be changed at any time by the layout.

@Override
protected void onCreate(Bundle savedInstanceState) {
    Button button;

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button = (Button) findViewById(R.id.button);
    button2 = (Button) findViewById(R.id.button2);
    rootView = (RelativeLayout) findViewById(R.id.rootView);
    otherLayout = (RelativeLayout) findViewById(R.id.otherLayout);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            RelativeLayout.LayoutParams params;
            int top = button2.getTop();
            int left = button2.getLeft();

            ((ViewGroup) button2.getParent()).removeView(button2);
            params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            params.setMargins(left, top, 0, 0);
            button2.setLayoutParams(params);
            rootView.addView(button2);
        }
    });
}


问:
Send notification to users when product is created in OctoberCMS?
I have a plugin that creates a product and I want to send a notification email to all users when a new product has been created, how do i approach this?</p>

答:
You could use Events

Fire an event when the product is created and Listen to the respective event to send notification mail to the users.

```<code>Event::fire('product.create', [$product]);
</code>```

Register the listener within the boot method of the plugin

```<code>public function boot()
{
    Event::listen('product.create', function ($product) {

       // Send Mail to subscribed users

    });
}
</code>```

Body:
You could use Events

Fire an event when the product is created and Listen to the respective event to send notification mail to the users.

Event::fire('product.create', [$product]);

Register the listener within the boot method of the plugin

public function boot()
{
    Event::listen('product.create', function ($product) {

       // Send Mail to subscribed users

    });
}


问:
How do I annotate types in a for-loop?
I want to annotate a type of a variable in a for-loop. I tried this but it didn't work:

for i: int in range(5):
    pass
```
<p>What I expect is working autocomplete in PyCharm 2016.3.2, but using
pre-annotation didn't work:</p>
<pre class="lang-py prettyprint-override"><code>i: int
for i in range(5):
    pass
</code>```

P.S. Pre-annotation works for PyCharm >= 2017.1.

答:
None of the responses here were useful, except to say that you can't. Even the accepted answer uses syntax from the PEP 526 document, which isn't valid python syntax. If you try to type in

```<code>x: int
</code>```

You'll see it's a syntax error.

Here is a useful workaround:

```<code>for __x in range(5):
    x = __x  # type: int
    print(x)
</code>```

Do your work with x. PyCharm recognizes its type, and autocomplete works.

ContentLicense: CC BY-SA 4.0

Title: How do I annotate types in a for-loop?

Body:
I want to annotate a type of a variable in a for-loop. I tried this but it didn't work:

for i: int in range(5):
    pass

What I expect is working autocomplete in PyCharm 2016.3.2, but using
pre-annotation didn't work:

i: int
for i in range(5):
    pass

P.S. Pre-annotation works for PyCharm >= 2017.1.

Body:
None of the responses here were useful, except to say that you can't. Even the accepted answer uses syntax from the PEP 526 document, which isn't valid python syntax. If you try to type in

x: int

You'll see it's a syntax error.

Here is a useful workaround:

for __x in range(5):
    x = __x  # type: int
    print(x)

Do your work with x. PyCharm recognizes its type, and autocomplete works.


问:
Create-react-app with codesplitting and await
In this article on official react website, I can clearly see that using await to dynamically import the module is allowed, yet when I try to do it (exactly like in the example) in my code an error is what I get:

```<code>Syntax error: await is a reserved word (11:31)
</code>```

What am I missing?

EDIT

Code just for convenience:

```<code>class App extends Component {
    state = {
        lazyComponent: null
    }
    componentDidMount() {
        const { default: Message } = await import('./Message.js');
        this.setState({
            lazyComponent: <Message />
        })
    }
    render() {
        return (
            <div className="App">
                <p>Let's start!</p>
                {this.state.lazyComponent || <p>Loading...</p> }
            </div>
        );
    }
}

export default App;
</code>```

答: You missed the async word before componentDidMount(), it is shown in the link you provided

Body:
In this article on official react website, I can clearly see that using await to dynamically import the module is allowed, yet when I try to do it (exactly like in the example) in my code an error is what I get:

Syntax error: await is a reserved word (11:31)

What am I missing?

EDIT

Code just for convenience:

class App extends Component {
    state = {
        lazyComponent: null
    }
    componentDidMount() {
        const { default: Message } = await import('./Message.js');
        this.setState({
            lazyComponent: <Message />
        })
    }
    render() {
        return (

Let's start!

                {this.state.lazyComponent ||
Loading...
 }

        );
    }
}

export default App;


问:
I cannot figure out why my variable is out of range
I am getting an error in my python code. This is the code

```<code>binary=[]
bits=int(input("How many bits do you want to have?   >>"))
numOfCombos=2**bits
lenOfPart=numOfCombos/2
x=0
y=0
z=0
while x!=numOfCombos:
    binary.insert(x,[])
    x+=1
x=0
while x!=lenOfPart:
    binary[x].insert(0,"0")
    x+=1
while x!=lenOfPart*2:
    binary[x].insert(0,"1")
    x+=1
x=0
p=0
while x!=bits:
    lenOfPart=lenOfPart/2
    while z!=len(binary)-1:
        while p!=lenOfPart:
            binary[y].insert(len(binary[y]),"0")
            y+=1
            p+=1
        p=0
        while p!=lenOfPart:
            binary[y].insert(len(binary[y]),"1")
            y+=1
            p+=1
        p=0
        z+=1
    y=0
    x+=1

print(numOfCombos)
print(len(binary))
print(binary)
</code>```

I am getting an error that reads

```<code>How many bits do you want to have?   >>3
Traceback (most recent call last):
  File "C:/Users/#####/AppData/Local/Programs/Python/Python36-32/binarygen.py", line 24, in <module>
    binary[y].insert(len(binary[y]),"0")
IndexError: list index out of range
</code>```

I do not understand why my variables are not working. I have tested all the things I can think of. If you have any advice, please respond as soon as possible. If you think that the entire program is wrong, please insert a working version into your answer. The purpose of the program is to generate all the possible binary combinations for a given number of bits. Thank you for your time and help.

答: The loop was stopping at the wrong time. Instead of stopping at bits I needed it to stop at bits-1.

Body:
I am getting an error in my python code. This is the code

binary=[]
bits=int(input("How many bits do you want to have?   >>"))
numOfCombos=2**bits
lenOfPart=numOfCombos/2
x=0
y=0
z=0
while x!=numOfCombos:
    binary.insert(x,[])
    x+=1
x=0
while x!=lenOfPart:
    binary[x].insert(0,"0")
    x+=1
while x!=lenOfPart*2:
    binary[x].insert(0,"1")
    x+=1
x=0
p=0
while x!=bits:
    lenOfPart=lenOfPart/2
    while z!=len(binary)-1:
        while p!=lenOfPart:
            binary[y].insert(len(binary[y]),"0")
            y+=1
            p+=1
        p=0
        while p!=lenOfPart:
            binary[y].insert(len(binary[y]),"1")
            y+=1
            p+=1
        p=0
        z+=1
    y=0
    x+=1

print(numOfCombos)
print(len(binary))
print(binary)

I am getting an error that reads

How many bits do you want to have?   >>3
Traceback (most recent call last):
  File "C:/Users/#####/AppData/Local/Programs/Python/Python36-32/binarygen.py", line 24, in <module>
    binary[y].insert(len(binary[y]),"0")
IndexError: list index out of range

I do not understand why my variables are not working. I have tested all the things I can think of. If you have any advice, please respond as soon as possible. If you think that the entire program is wrong, please insert a working version into your answer. The purpose of the program is to generate all the possible binary combinations for a given number of bits. Thank you for your time and help.


问:
How do I create a condition that will not display a field if the field is empty?
I am using advanced custom fields (ACF). I would like to not display the ACF  repeater field the_sub_field('feature_image_post'); if the field is empty. I wrapped the field in a div and wrote a display = none using CSS if the field is empty but I'm sure there is a better way of doing this. My logic doesn't seem to work.

```<code> <?php

        // check if the repeater field has rows of data

        if( have_rows('repeat_field') ):

          // loop through the rows of data
            while ( have_rows('repeat_field') ) : the_row();

                // display a sub field value

                echo '<span class="place-name">';
                  the_sub_field('place_name');
                echo '</span>';

      if (!empty (get_sub_field('feature_image_post')))  {

       echo '<div class="post-feature" style="display:block;">';
       echo the_sub_field('feature_image_post');
       echo '</div>';

      }

      else {
       echo '<div class="post-feature" style="display:none;">'
       echo the_sub_field('feature_image_post');
       echo '</div>';

      }
            endwhile;

        else :

            // no rows found

        endif;
</code>```

答:
There's no need for an else statement here. If the field hasn't been set then you simply don't show anything.

My approach would be to use get_sub_field() and assign the result to a variable as part of the conditional.

The default return value for an image in ACF is an array of values so I'm going to assume that's what you have.

Example:

```<code>if ( $feature_image_post = get_sub_field( 'feature_image_post' ) )  {
    echo '<div class="post-feature">';
    printf( '<img src="%s" alt="%s" />', esc_url( $feature_image_post['url'] ), esc_attr( $feature_image_post['title'] ) );
    echo '</div>';
}
</code>```

One final point to raise is the difference between get_sub_field() and the_sub_field(). In your original code you were trying to echo the_sub_field(). get_... will return a value whereas the_... will output it making echo redundant in that context.

Body:
I am using advanced custom fields (ACF). I would like to not display the ACF  repeater field the_sub_field('feature_image_post'); if the field is empty. I wrapped the field in a div and wrote a display = none using CSS if the field is empty but I'm sure there is a better way of doing this. My logic doesn't seem to work.

 <?php

        // check if the repeater field has rows of data

        if( have_rows('repeat_field') ):

          // loop through the rows of data
            while ( have_rows('repeat_field') ) : the_row();

                // display a sub field value

                echo '';
                  the_sub_field('place_name');
                echo '';

      if (!empty (get_sub_field('feature_image_post')))  {

       echo '
';
       echo the_sub_field('feature_image_post');
       echo '
';

      }

      else {
       echo '
'
       echo the_sub_field('feature_image_post');
       echo '
';

      }
            endwhile;

        else :

            // no rows found

        endif;

Body:
There's no need for an else statement here. If the field hasn't been set then you simply don't show anything.

My approach would be to use get_sub_field() and assign the result to a variable as part of the conditional.

The default return value for an image in ACF is an array of values so I'm going to assume that's what you have.

Example:

if ( $feature_image_post = get_sub_field( 'feature_image_post' ) )  {
    echo '<div class="post-feature">';
    printf( '<img src="%s" alt="%s" />', esc_url( $feature_image_post['url'] ), esc_attr( $feature_image_post['title'] ) );
    echo '</div>';
}

One final point to raise is the difference between get_sub_field() and the_sub_field(). In your original code you were trying to echo the_sub_field(). get_... will return a value whereas the_... will output it making echo redundant in that context.


问:
Merging different SQL scripts into one script
I have 3 query scripts that are working on the same table; one is counting total number of rows, another one is counting total number of duplicated rows and the other one is counting total number of distinct (unique) rows.

To count the total number of rows:

```<code>select count(*) as total_rows from <table_name>
</code>```

To count the duplicated rows:

```<code>select COUNT (<column_name>) as total_duplicate from <table_name> group by (<column_name>) HAVING count(<column_name>) > 1
</code>```

To count the unique rows:

```<code>select COUNT(DISTINCT <column_name>) as total_unique from <table_name>
</code>```

I am trying to merge all 3 into a single script. I am able to do it for total count and unique count; But, I am not sure how to include the duplicated count query since it has a group by statement.

Any idea please.

答:
You could union these together:</p>

```<code> select count(*) as count_total
        'total_rows' as count_type
 from <table_name>

 union

 select count (<column_name>)as count_total
        'total_duplicate' as count_type
 from <table_name>
 group by (<column_name>)
 HAVING count(<column_name>) > 1

 union

 select COUNT(DISTINCT <column_name>) as count_total
        'total_unique' as count type
 from <table_name>
</code>```

Body:
I have 3 query scripts that are working on the same table; one is counting total number of rows, another one is counting total number of duplicated rows and the other one is counting total number of distinct (unique) rows.

To count the total number of rows:

select count(*) as total_rows from <table_name>

To count the duplicated rows:

select COUNT (<column_name>) as total_duplicate from <table_name> group by (<column_name>) HAVING count(<column_name>) > 1

To count the unique rows:

select COUNT(DISTINCT <column_name>) as total_unique from <table_name>

I am trying to merge all 3 into a single script. I am able to do it for total count and unique count; But, I am not sure how to include the duplicated count query since it has a group by statement.

Any idea please.

Body:
You could union these together:

 select count(*) as count_total
        'total_rows' as count_type
 from <table_name>

 union

 select count (<column_name>)as count_total
        'total_duplicate' as count_type
 from <table_name>
 group by (<column_name>)
 HAVING count(<column_name>) > 1

 union

 select COUNT(DISTINCT <column_name>) as count_total
        'total_unique' as count type
 from <table_name>


问:
Unwanted comma-separated arguments to Spring controller method
I'm seeing a strange problem with a Spring MVC controller.  This method is intended to set the password.  It takes two form parameters "password" and "confirmPassword".  The first time the form is called, this works fine-- the fields are passed to the method.

The problem occurs when the form is submitted a second time.  If the form is incorrectly filled out the first time, the user is correctly sent back to the form page and prompted to enter the password again.  However the arguments to the method are incorrect on the second try.  The arguments are a comma separated list which includes the first form entry concatenated with the second.

Example:

First form post with field "password" has a value of "abc".  Method argument "password" has value "abc".

Second form post with field "password" and a value of "xyz".  Method argument "password" has value "xyz,abc".

The Spring MVC docs don't indicate much useful.  Somehow the old form post is remembered and included. Anyone have experience in solving this?

Controller method is below:

```<code>@RequestMapping(value = "/account/reset", method = RequestMethod.POST)
public String resetPassword(@RequestParam("password") String password,
        @RequestParam("confirmPassword") String confirmPassword,
        @RequestParam("hash") String hash, ModelMap model) throws EncryptionException
{
    String userName = stringEncrypterService.decrypt(hash);
    User user = userService.findUserByPath(userName);

    if (!password.equals(confirmPassword))
    {
        model.put("hash", hash);
        model.put("user", user);
        model.put("error",
                "The two passwords you entered below do not match. Please try again.");

        return "users/resetPassword";
    }

    userService.updatePassword(user, password);
    emailService.sendUserInfoChange(user);
    return "redirect:/session/signin?passwordReset=true";
}
</code>```

Update.  Several responders have suggested that perhaps the problematic posts have extra URL parameters or hidden form fields resulting in duplicate field names.  I confirmed with Fiddler that this is not the case.  Here's the raw request from the third try. (slightly edited to remove session cookie).

```<code>POST http://wintest.foriodev.com/simulate/account/reset/ HTTP/1.1
Host: wintest.foriodev.com
Connection: keep-alive
Referer: http://wintest.foriodev.com/simulate/account/reset/
Content-Length: 73
Cache-Control: max-age=0
Origin: http://wintest.foriodev.com
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.133 Safari/534.16
Content-Type: application/x-www-form-urlencoded
Accept: application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
Cookie: AUTOLOGIN_TOKEN=xyz; SIMULATE_WORKER=wintest; JSESSIONID=xyz;

password=a&hash=xyz&confirmPassword=a&save=Reset+Password
</code>```

答: In my case, I had associated hidden field with a path that was unused. Removing the hidden field helped me resolve the issue.</p>

Body:
I'm seeing a strange problem with a Spring MVC controller.  This method is intended to set the password.  It takes two form parameters "password" and "confirmPassword".  The first time the form is called, this works fine-- the fields are passed to the method.

The problem occurs when the form is submitted a second time.  If the form is incorrectly filled out the first time, the user is correctly sent back to the form page and prompted to enter the password again.  However the arguments to the method are incorrect on the second try.  The arguments are a comma separated list which includes the first form entry concatenated with the second.

Example:

First form post with field "password" has a value of "abc".  Method argument "password" has value "abc".

Second form post with field "password" and a value of "xyz".  Method argument "password" has value "xyz,abc".

The Spring MVC docs don't indicate much useful.  Somehow the old form post is remembered and included. Anyone have experience in solving this?

Controller method is below:

@RequestMapping(value = "/account/reset", method = RequestMethod.POST)
public String resetPassword(@RequestParam("password") String password,
        @RequestParam("confirmPassword") String confirmPassword,
        @RequestParam("hash") String hash, ModelMap model) throws EncryptionException
{
    String userName = stringEncrypterService.decrypt(hash);
    User user = userService.findUserByPath(userName);

    if (!password.equals(confirmPassword))
    {
        model.put("hash", hash);
        model.put("user", user);
        model.put("error",
                "The two passwords you entered below do not match. Please try again.");

        return "users/resetPassword";
    }

    userService.updatePassword(user, password);
    emailService.sendUserInfoChange(user);
    return "redirect:/session/signin?passwordReset=true";
}

Update.  Several responders have suggested that perhaps the problematic posts have extra URL parameters or hidden form fields resulting in duplicate field names.  I confirmed with Fiddler that this is not the case.  Here's the raw request from the third try. (slightly edited to remove session cookie).

POST http://wintest.foriodev.com/simulate/account/reset/ HTTP/1.1
Host: wintest.foriodev.com
Connection: keep-alive
Referer: http://wintest.foriodev.com/simulate/account/reset/
Content-Length: 73
Cache-Control: max-age=0
Origin: http://wintest.foriodev.com
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.133 Safari/534.16
Content-Type: application/x-www-form-urlencoded
Accept: application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
Cookie: AUTOLOGIN_TOKEN=xyz; SIMULATE_WORKER=wintest; JSESSIONID=xyz;

password=a&hash=xyz&confirmPassword=a&save=Reset+Password


问:
Extend Div Into Parent Without Negative Margins
I would like to have a child div extend to be the same width as it's parent's parent. So with HTML structure like this:

```<code><div class="pp">
  <div class="p">
    <p>
    Some text
    </p>
    <div class="c">
      This is the thingy!
    </div>
    <p>
    Some more text
    </p>
  </div>
</div>
</code>```

I would like div.c to extend to the borders of div.pp.

I know this is possible with negative margins, but in my situation I am not aware of the margins of div.pp beforehand. I'm aware I could write some JavaScript to do this, but I am interested in a CSS only solution. I'm also aware that changing the structure of the HTML could solve this problem, however that is also not an option.

Here is fiddle illustrating the HTML and some helpful CSS:

https://jsfiddle.net/y37mLkzu/1/

There is an example there of fixing this with negative margins.

答:
I am not sure if this will work in your situation, but it is the only other way without using a fixed minus margin and only using pure CSS. I have added :before and :after to .c and absolute positioned them at either side of the .c element. I have also added overflow hidden to the .pp wrapper to cut off the excess absolute positioned elements.

p {
  margin:0;
}
.pp {
  padding: 0 6px 0 6px;
  width: 100px;
  background-color: black;
  overflow: hidden;
}
.p {
  background-color:white;
}
.c {
  background-color:red;
  position: relative;
}
.c:before, .c:after {
  content:"";
  position: absolute;
  top:0;
  background: red;
  height:100%;
  width:100%;
}
.c:before {
  left:-100%;
}
.c:after {
  right:-100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="pp">
  <div class="p">
    <p>
    Some text
    </p>
    <div class="c">
      This is the thingy!
    </div>
    <p>
    Some more text
    </p>
  </div>
</div></code>```

Body:
I would like to have a child div extend to be the same width as it's parent's parent. So with HTML structure like this:

    Some text

      This is the thingy!

    Some more text

I would like div.c to extend to the borders of div.pp.

I know this is possible with negative margins, but in my situation I am not aware of the margins of div.pp beforehand. I'm aware I could write some JavaScript to do this, but I am interested in a CSS only solution. I'm also aware that changing the structure of the HTML could solve this problem, however that is also not an option.

Here is fiddle illustrating the HTML and some helpful CSS:

https://jsfiddle.net/y37mLkzu/1/

There is an example there of fixing this with negative margins.

Body:
I am not sure if this will work in your situation, but it is the only other way without using a fixed minus margin and only using pure CSS. I have added :before and :after to .c and absolute positioned them at either side of the .c element. I have also added overflow hidden to the .pp wrapper to cut off the excess absolute positioned elements.

p {
  margin:0;
}
.pp {
  padding: 0 6px 0 6px;
  width: 100px;
  background-color: black;
  overflow: hidden;
}
.p {
  background-color:white;
}
.c {
  background-color:red;
  position: relative;
}
.c:before, .c:after {
  content:"";
  position: absolute;
  top:0;
  background: red;
  height:100%;
  width:100%;
}
.c:before {
  left:-100%;
}
.c:after {
  right:-100%;
}

<div class="pp">
  <div class="p">
    <p>
    Some text
    </p>
    <div class="c">
      This is the thingy!
    </div>
    <p>
    Some more text
    </p>
  </div>
</div>


问:
VBA/Excel - find path for saving a file, but only match a certain part of the path
I'd like to save a file in the following example folder:

C:\MainFolder\Subfolder1\Subfolder2\Subfolder3_A_abc_123

There are other subfolders in the folder where I'd like the file be saved, like:

Subfolder_B_xyz_456

Subfolder_C_rst_789

etc

The thing is that I want to find a folder on the the path all the way up to: "Subfolder3_", the "A" will be fetched from a range in a sheet and the "_abc_123", I do not want to match.

Does anyone have a clever FSO example or other creative sollution? I'm new to programming so any suggestion is appreciated.

Thanks on advance.

PythonStyle

Updated question to ho1:

This is the code:

```<code>Sub Create_WorkB_Input()

Dim wbBook1 As Workbook
Dim wbBook2 As Workbook
Dim shTemp1 As Worksheet
Dim shTemp2 As Worksheet
Dim shTemp_admin As Worksheet
Dim shTSSR_inp1 As Worksheet
Dim shTSSR_inp2 As Worksheet
Dim strVersion As String
Dim strPrep As String
Dim Datecr As Date
Dim strComment As String
Dim intBatch As Integer
Dim strSiteID As String
Dim strClusterID As String
Dim strPath As String
Dim fso As New FileSystemObject
Dim flds As Folders
Dim f As Folder

Set wbBook1 = Workbooks("Name_Input_TEMPLATE_v4.0.xls")
Set wbBook2 = Workbooks("Name_Input_To_xxx.xlsm")
Set shTemp1 = Workbooks("Name_Input_TEMPLATE_v4.0.xls").Sheets("TSSR_Input_sh1")
Set shTemp2 = Workbooks("Name_Input_TEMPLATE_v4.0.xls").Sheets("TSSR_Input_sh2")
Set shTSSR_inp1 = Workbooks("Name_Input_To_xxx.xlsm").Sheets("xxx")
Set shTSSR_inp2 = Workbooks("Name_Input_To_xxx.xlsm").Sheets("yyy")
Set shTemp_admin = Workbooks("Name_Input_TEMPLATE_v4.0.xls").Sheets("www")

shTSSR_inp1.UsedRange.Copy

shTemp1.Paste

shTSSR_inp2.UsedRange.Copy

shTemp2.Paste

intBatch = shTemp1.Range("AQ2").Value
strSiteID = shTemp1.Range("A2").Value
strClusterID = shTemp1.Range("B2").Value
strComment = InputBox(Prompt:="Insert comments.", Title:="INSERT COMMENTS", Default:="New site - batch " & intBatch & " ref email fr Me dato")

With shTemp_admin
    .Range("A18").FormulaR1C1 = "4.0"
    .Range("B18").Value = "John Doe"
    .Range("C18").Value = Date
    .Range("D18").Value = strComment
End With

strPath = "D:\Path_to_folder\folder1\folder2\folder3\folder4"

Set flds = fso.GetFolder(strPath & "\Folder5_Input_Batch_" & intBatch & "*")

For Each f In flds

    If f.Name Like strPath Then

        wbBook1.SaveAs Filename:="" + strPath + "\" + "TSSR_Input_" + strClusterID + "_" + strSiteID + "_v4.0.xls", _
                FileFormat:=xlNormal, _
                Password:="", _
                WriteResPassword:="", _
                ReadOnlyRecommended:=False, _
                CreateBackup:=False

    End If

Next

End Sub
</code>```

I am getting error at this line :

```<code>Set flds = fso.GetFolder(strPath & "\Folder5_Input_Batch_" & intBatch & "*")
</code>```

Could you please have a look at it?
The names of folders and workbooks are changed so they might not make any sense. Only the folder part is important.

Thanks in advance.

Rgds

P

答:
You could just loop through all the subdirectories and for each directory you compare it with the path you want to find. Something like this pseudo code should work:

```<code>For each dir in SubDirectories
  Dim lookingFor as String
  lookingFor = "Subfolder3_" & yourVariable & "*"
  If dir.Name Like lookingFor Then ' Note the use of the Like operator here so that it sees the * as a wildcard
    ' This is the right one
  End If
Next
</code>```

An other, similar, option would be to use regular expressions which are more powerful than Like, but I don't think you'd need that. However, just in case, you can find information about it here: How to Use Regular Expressions in Visual Basic

Body:
I'd like to save a file in the following example folder:

C:\MainFolder\Subfolder1\Subfolder2\Subfolder3_A_abc_123

There are other subfolders in the folder where I'd like the file be saved, like:

Subfolder_B_xyz_456

Subfolder_C_rst_789

etc

The thing is that I want to find a folder on the the path all the way up to: "Subfolder3_", the "A" will be fetched from a range in a sheet and the "_abc_123", I do not want to match.

Does anyone have a clever FSO example or other creative sollution? I'm new to programming so any suggestion is appreciated.

Thanks on advance.

PythonStyle

Updated question to ho1:

This is the code:

Sub Create_WorkB_Input()

Dim wbBook1 As Workbook
Dim wbBook2 As Workbook
Dim shTemp1 As Worksheet
Dim shTemp2 As Worksheet
Dim shTemp_admin As Worksheet
Dim shTSSR_inp1 As Worksheet
Dim shTSSR_inp2 As Worksheet
Dim strVersion As String
Dim strPrep As String
Dim Datecr As Date
Dim strComment As String
Dim intBatch As Integer
Dim strSiteID As String
Dim strClusterID As String
Dim strPath As String
Dim fso As New FileSystemObject
Dim flds As Folders
Dim f As Folder

Set wbBook1 = Workbooks("Name_Input_TEMPLATE_v4.0.xls")
Set wbBook2 = Workbooks("Name_Input_To_xxx.xlsm")
Set shTemp1 = Workbooks("Name_Input_TEMPLATE_v4.0.xls").Sheets("TSSR_Input_sh1")
Set shTemp2 = Workbooks("Name_Input_TEMPLATE_v4.0.xls").Sheets("TSSR_Input_sh2")
Set shTSSR_inp1 = Workbooks("Name_Input_To_xxx.xlsm").Sheets("xxx")
Set shTSSR_inp2 = Workbooks("Name_Input_To_xxx.xlsm").Sheets("yyy")
Set shTemp_admin = Workbooks("Name_Input_TEMPLATE_v4.0.xls").Sheets("www")

shTSSR_inp1.UsedRange.Copy

shTemp1.Paste

shTSSR_inp2.UsedRange.Copy

shTemp2.Paste

intBatch = shTemp1.Range("AQ2").Value
strSiteID = shTemp1.Range("A2").Value
strClusterID = shTemp1.Range("B2").Value
strComment = InputBox(Prompt:="Insert comments.", Title:="INSERT COMMENTS", Default:="New site - batch " & intBatch & " ref email fr Me dato")

With shTemp_admin
    .Range("A18").FormulaR1C1 = "4.0"
    .Range("B18").Value = "John Doe"
    .Range("C18").Value = Date
    .Range("D18").Value = strComment
End With

strPath = "D:\Path_to_folder\folder1\folder2\folder3\folder4"

Set flds = fso.GetFolder(strPath & "\Folder5_Input_Batch_" & intBatch & "*")

For Each f In flds

    If f.Name Like strPath Then

        wbBook1.SaveAs Filename:="" + strPath + "\" + "TSSR_Input_" + strClusterID + "_" + strSiteID + "_v4.0.xls", _
                FileFormat:=xlNormal, _
                Password:="", _
                WriteResPassword:="", _
                ReadOnlyRecommended:=False, _
                CreateBackup:=False

    End If

Next

End Sub

I am getting error at this line :

Set flds = fso.GetFolder(strPath & "\Folder5_Input_Batch_" & intBatch & "*")

Could you please have a look at it?
The names of folders and workbooks are changed so they might not make any sense. Only the folder part is important.

Thanks in advance.

Rgds

P

Body:
You could just loop through all the subdirectories and for each directory you compare it with the path you want to find. Something like this pseudo code should work:

For each dir in SubDirectories
  Dim lookingFor as String
  lookingFor = "Subfolder3_" & yourVariable & "*"
  If dir.Name Like lookingFor Then ' Note the use of the Like operator here so that it sees the * as a wildcard
    ' This is the right one
  End If
Next

An other, similar, option would be to use regular expressions which are more powerful than Like, but I don't think you'd need that. However, just in case, you can find information about it here: How to Use Regular Expressions in Visual Basic


问:
Jenkinsfile with user input with variable in choices
I want to use new Jenkinsfile for new job.

I have jenkinsfile wich I have in solo repository:

I get branches from another gitlab repository by git ls-remote in bash. And I store them in variables: branch1, branch2, brach3....

Then I want to use these variables in user input choices

```<code>script {
  env.BRANCHDEPLOY = input message: 'User input required',
  ok: 'Deploy!',
  parameters: [choice(name: 'Branch to deploy', choices: '${branch1}\n${branch2}\n${branch3}', description: 'What branch you wont deploy?')]
}
echo "${env.BRANCHDEPLOY}"
</code>```

Then I will use ${env.BRANCHDEPLOY} for git to deploy selected branch.

Problem is that I can't get to work it with variables in user choice.

I just need to let user choose branch what he wants deploy from another gitlab repository.

答:
Did you try something like that, you should be able to pass tha var.</p>

```<code>parameters {
    string(branchName: 'feature_x')
}
scm {
    checkout(
      branches: [[name: '*/$branchName']],
....

 }
</code>```

Body:
I want to use new Jenkinsfile for new job.

I have jenkinsfile wich I have in solo repository:

I get branches from another gitlab repository by git ls-remote in bash. And I store them in variables: branch1, branch2, brach3....

Then I want to use these variables in user input choices

script {
  env.BRANCHDEPLOY = input message: 'User input required',
  ok: 'Deploy!',
  parameters: [choice(name: 'Branch to deploy', choices: '${branch1}\n${branch2}\n${branch3}', description: 'What branch you wont deploy?')]
}
echo "${env.BRANCHDEPLOY}"

Then I will use ${env.BRANCHDEPLOY} for git to deploy selected branch.

Problem is that I can't get to work it with variables in user choice.

I just need to let user choose branch what he wants deploy from another gitlab repository.

Body:
Did you try something like that, you should be able to pass tha var.

parameters {
    string(branchName: 'feature_x')
}
scm {
    checkout(
      branches: [[name: '*/$branchName']],
....

 }


问:
why HDP install mysql while I have chose existing mysql
I am installing HDP 2.6 via Ambari 2.5.0.3,the error shows in Hive client install.the error logs:

resource_management.core.exceptions.ExecutionFailed: Execution of '/usr/bin/zypper --quiet install --auto-agree-with-licenses --no-confirm mysql-client' returned 4. Problem: mysql-community-client-5.7.17-1.sles11.x86_64 conflicts with namespace:otherproviders(mysql-client) provided by mysql-client-5.5.31-0.7.10.x86_64
 Solution 1: Following actions will be done:
  deinstallation of mysql-community-client-5.7.17-1.sles11.x86_64
  deinstallation of mysql-community-server-5.7.17-1.sles11.x86_64
 Solution 2: do not install mysql-client-5.5.31-0.7.10.x86_64

Choose from above solutions by number or cancel [1/2/c] (c): c```

I have chose exisiting mysql database,why ambari still try to install ?
or is there anyway to choose the "2" in above option?

答:
You installed mysql from a non-default system repository. Ambari does not check if packages are already installed, it just installs packages for every service during cluster deployment (or when adding a service/host).

Package dependencies are defined at metainfo.xml files. You may try to find the relevant Ambari service metainfo file and play around service dependency definition. It looks like

```<code>    <osSpecific>
      <osFamily>suse</osFamily>
      <packages>
        <package>
          <name>mysql-client</name>
        </package>
      </packages>
    </osSpecific>
</code>```

metainfo.xml files may be located at two locations. Make sure to choose the right file.

default service metainfo /var/lib/ambari-server/resources/common-services/<service name>/<service version>/metainfo.xml

per-stack overrides /var/lib/ambari-server/resources/stacks/<stack id>/<stack version>/services/<service name>/metainfo.xml

Don't forget to restart ambari-server! It reads service definitions on start.

There is an attachment to related EPIC that explains the logic of inheritance https://issues.apache.org/jira/browse/AMBARI-7201

Body:
I am installing HDP 2.6 via Ambari 2.5.0.3,the error shows in Hive client install.the error logs:

resource_management.core.exceptions.ExecutionFailed: Execution of '/usr/bin/zypper --quiet install --auto-agree-with-licenses --no-confirm mysql-client' returned 4. Problem: mysql-community-client-5.7.17-1.sles11.x86_64 conflicts with namespace:otherproviders(mysql-client) provided by mysql-client-5.5.31-0.7.10.x86_64
 Solution 1: Following actions will be done:
  deinstallation of mysql-community-client-5.7.17-1.sles11.x86_64
  deinstallation of mysql-community-server-5.7.17-1.sles11.x86_64
 Solution 2: do not install mysql-client-5.5.31-0.7.10.x86_64

Choose from above solutions by number or cancel [1/2/c] (c): c

I have chose exisiting mysql database,why ambari still try to install ?
or is there anyway to choose the "2" in above option?

Body:
You installed mysql from a non-default system repository. Ambari does not check if packages are already installed, it just installs packages for every service during cluster deployment (or when adding a service/host).

Package dependencies are defined at metainfo.xml files. You may try to find the relevant Ambari service metainfo file and play around service dependency definition. It looks like

    <osSpecific>
      <osFamily>suse</osFamily>
      <packages>
        <package>
          <name>mysql-client</name>
        </package>
      </packages>
    </osSpecific>

metainfo.xml files may be located at two locations. Make sure to choose the right file.

default service metainfo /var/lib/ambari-server/resources/common-services/<service name>/<service version>/metainfo.xml

per-stack overrides /var/lib/ambari-server/resources/stacks/<stack id>/<stack version>/services/<service name>/metainfo.xml

Don't forget to restart ambari-server! It reads service definitions on start.

There is an attachment to related EPIC that explains the logic of inheritance https://issues.apache.org/jira/browse/AMBARI-7201


问:
Loop through dropdown webdriver
How would I loop through 9 selections in drop down list ... say for instance it has 9 different values how would I make it go through all of them using select?

Ex. Values were
Red
Blue
Green
Purple

So far I have

```<code>for (int i=0; i<4; i++){

        WebElement ClubDropDown = driver.findElement(By.id("tenantList"));

        Select CDropdown = new Select(ClubDropDown);

// This is the part I'm stuck on how to make it loop through the drop downs and preform the defined public void cases

         OpenMp(); // This is one of my public void test cases
    }
</code>```

答:
in Java8

```<code>Select cDropdown = new Select(ClubDropDown);
cDropdown.getOptions().forEach(el -> {
                //do something
});
</code>```

P.S. start variable names from lower case letter  ClubDropDown -> clubDropDown

Title: Loop through dropdown webdriver

Body:
How would I loop through 9 selections in drop down list ... say for instance it has 9 different values how would I make it go through all of them using select?

Ex. Values were
Red
Blue
Green
Purple

So far I have

for (int i=0; i<4; i++){

        WebElement ClubDropDown = driver.findElement(By.id("tenantList"));

        Select CDropdown = new Select(ClubDropDown);

// This is the part I'm stuck on how to make it loop through the drop downs and preform the defined public void cases

         OpenMp(); // This is one of my public void test cases
    }

Body:
in Java8

Select cDropdown = new Select(ClubDropDown);
cDropdown.getOptions().forEach(el -> {
                //do something
});

P.S. start variable names from lower case letter  ClubDropDown -> clubDropDown


问:
Error when trying to send transactional email from template using sendGrid
I'm trying to send a transactional email via node using sendGrid. Below is an example of my code.

```<code>        const subject = 'Email subject';
        const templateId = 'templateId';
        const sg = require('sendgrid')(secret);
        const request = sg.emptyRequest({
            method: 'POST',
            path: '/v3/mail/send',
            body: {
                "personalizations": [
                    {
                        "bcc": userEmails,
                        "substitutions": {
                            "-userName-": userDetails.name,
                            "-productPrice-": productDetails.price,
                            "-productUrl-": productDetails.url,
                            "-productPercentageDrop-": productDetails.percentageDrop,
                            "-productName-": productDetails.name,
                            "-productOriginalPrice-": productDetails.origPrice,
                            "-productDroppedPrice-": productDetails.dropPrice,
                            "-productImageUrl-": productDetails.imageUrl
                        },
                        "subject": subject.substring(0, 75)
                    }
                ],
                "from": {
                    "email": "myemail",
                    "name": "myname"
                },
                "content": [
                    {
                        "type": "text/html"
                    }
                ],
                "template_id": templateId
            }
        });

        sg.API(request, function (error, response) {
            if (error) {

                console.log('Error response received');
            }
            console.log(response.body.errors);
        });
</code>```

But every time I run the code I get the following error message.

400
 message: 'Bad Request', field: null, help: null

Which isn't really that helpful when trying to find out why its erroring.

Body JSON being sent:

```<code>{
"host":"",
"method":"POST",
"path":"/v3/mail/send",
"headers":{

},
"body":{
    "personalizations":[
        {
            "bcc":[
                {
                    "email":"name1@hotmail.com",
                    "name":"name1"
                },
                {
                    "email":"name2@hotmail.com",
                    "name":"name2"
                }
            ],
            "substitutions":{
                "-productPrice-":189.5,
                "-productUrl-":"http://www.tesco.com/direct/humax-fvp-4000t500-m-smart-freeview-play-hd-digital-tv-recorder-with-wi-fi-500gb/483-1785.prd",
                "-productName-":"Tesco direct: Humax FVP-4000T/500 (M) Smart Freeview Play HD Digital TV Recorder with Wi-Fi - 500GB"
            },
            "subject":"Product Tesco direct: Humax FVP-4000T/500 (M) Smart Freeview Play HD Digita"
        }
    ],
    "from":{
        "email":"email@pricetracker.io",
        "name":"Pricetracker"
    },
    "content":[
        {
            "type":"text/html"
        }
    ],
    "template_id":"XXXXXX"
},
"queryParams":{

},
"test":false,
"port":""
</code>```

}

答:
don't know if this could still be helpful for you, but I've had some similar issues when using substitutions with Sendgrid. I'm using the sendgrid-php library, but internally it sends the same format. What I found was that all substitution values should be converted to string. For instance your value for productPrice should be like this:

```<code>"-productPrice-": "189.5",
</code>```

With quotes. In my case I had integers, and when I converted them to strings, all worked correctly.

Body:
I'm trying to send a transactional email via node using sendGrid. Below is an example of my code.

        const subject = 'Email subject';
        const templateId = 'templateId';
        const sg = require('sendgrid')(secret);
        const request = sg.emptyRequest({
            method: 'POST',
            path: '/v3/mail/send',
            body: {
                "personalizations": [
                    {
                        "bcc": userEmails,
                        "substitutions": {
                            "-userName-": userDetails.name,
                            "-productPrice-": productDetails.price,
                            "-productUrl-": productDetails.url,
                            "-productPercentageDrop-": productDetails.percentageDrop,
                            "-productName-": productDetails.name,
                            "-productOriginalPrice-": productDetails.origPrice,
                            "-productDroppedPrice-": productDetails.dropPrice,
                            "-productImageUrl-": productDetails.imageUrl
                        },
                        "subject": subject.substring(0, 75)
                    }
                ],
                "from": {
                    "email": "myemail",
                    "name": "myname"
                },
                "content": [
                    {
                        "type": "text/html"
                    }
                ],
                "template_id": templateId
            }
        });

        sg.API(request, function (error, response) {
            if (error) {

                console.log('Error response received');
            }
            console.log(response.body.errors);
        });

But every time I run the code I get the following error message.

400
 message: 'Bad Request', field: null, help: null

Which isn't really that helpful when trying to find out why its erroring.

Body JSON being sent:

{
"host":"",
"method":"POST",
"path":"/v3/mail/send",
"headers":{

},
"body":{
    "personalizations":[
        {
            "bcc":[
                {
                    "email":"name1@hotmail.com",
                    "name":"name1"
                },
                {
                    "email":"name2@hotmail.com",
                    "name":"name2"
                }
            ],
            "substitutions":{
                "-productPrice-":189.5,
                "-productUrl-":"http://www.tesco.com/direct/humax-fvp-4000t500-m-smart-freeview-play-hd-digital-tv-recorder-with-wi-fi-500gb/483-1785.prd",
                "-productName-":"Tesco direct: Humax FVP-4000T/500 (M) Smart Freeview Play HD Digital TV Recorder with Wi-Fi - 500GB"
            },
            "subject":"Product Tesco direct: Humax FVP-4000T/500 (M) Smart Freeview Play HD Digita"
        }
    ],
    "from":{
        "email":"email@pricetracker.io",
        "name":"Pricetracker"
    },
    "content":[
        {
            "type":"text/html"
        }
    ],
    "template_id":"XXXXXX"
},
"queryParams":{

},
"test":false,
"port":""

}

Body:
don't know if this could still be helpful for you, but I've had some similar issues when using substitutions with Sendgrid. I'm using the sendgrid-php library, but internally it sends the same format. What I found was that all substitution values should be converted to string. For instance your value for productPrice should be like this:

"-productPrice-": "189.5",

With quotes. In my case I had integers, and when I converted them to strings, all worked correctly.


问:
Insert image into jsp page
I am sorry that I need to ask this but I already spent three days trying to do this. I am buidling Java Web application and I want to include image to JSP page. Project name is realestates and I have Files folder inside realestates folder.

My code is like this:

```<code><img alt="govno" src="<%=request.getContextPath() + "/Files/kurac.jpg"%>" style="width: 400px; height: 300px;">
</code>```

This is what gets generated on page after I open it in browser:

```<code><img alt="govno" src="/realestates/Files/kurac.jpg" style="width: 400px; height: 300px;">
</code>```

BUT, image is not dispayed, only alt "govno" is written. I have tried many many paths (relative, absolute, changed folder structure million times and whatever I could think of and find on internet but nothing helped). Who would say that such a thing will be so hard to do???

Folder structure on Tomcat server after deployment is:

```<code>webapps
 - realestates
   |- WEB-INF
   |- Files
     |- kurac.jpg
</code>```

答:
I read your question and i have one solution for your problem you can use the INPUT STREAM for add an image in JSP page...

THIS IS JUST EXAMPLE...AND MAY HAVE ERROR BUT THIS IS THE WAY HOW TO INSERT IMAGE IN JSP...

```<code>Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection connection =
    DriverManager.getConnection(connectionURL, "user", "pass");

psmnt = connection.prepareStatement(
    "insert into save_image(user, image) values(?,?)");
psmnt.setString(1, username);

ImageIO.write(image, "png", new File("C://image.png"));
File imageFile = new File("C://image.png");
FileInputStream fis = new FileInputStream(imageFile);

psmnt.setBinaryStream(2, (InputStream)fis, (fis.length()));
int s = psmnt.executeUpdate();
</code>```

Title: Insert image into jsp page

Body:
I am sorry that I need to ask this but I already spent three days trying to do this. I am buidling Java Web application and I want to include image to JSP page. Project name is realestates and I have Files folder inside realestates folder.

My code is like this:

<img alt="govno" src="<%=request.getContextPath() + "/Files/kurac.jpg"%>" style="width: 400px; height: 300px;">

This is what gets generated on page after I open it in browser:

BUT, image is not dispayed, only alt "govno" is written. I have tried many many paths (relative, absolute, changed folder structure million times and whatever I could think of and find on internet but nothing helped). Who would say that such a thing will be so hard to do???

Folder structure on Tomcat server after deployment is:

webapps
 - realestates
   |- WEB-INF
   |- Files
     |- kurac.jpg

Body:
I read your question and i have one solution for your problem you can use the INPUT STREAM for add an image in JSP page...

THIS IS JUST EXAMPLE...AND MAY HAVE ERROR BUT THIS IS THE WAY HOW TO INSERT IMAGE IN JSP...

Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection connection =
    DriverManager.getConnection(connectionURL, "user", "pass");

psmnt = connection.prepareStatement(
    "insert into save_image(user, image) values(?,?)");
psmnt.setString(1, username);

ImageIO.write(image, "png", new File("C://image.png"));
File imageFile = new File("C://image.png");
FileInputStream fis = new FileInputStream(imageFile);

psmnt.setBinaryStream(2, (InputStream)fis, (fis.length()));
int s = psmnt.executeUpdate();


问:
Using a created extension method
Here's the method I created:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using MvcApplication1.Models;
using System.Text;

namespace MvcApplication1.HelperMethods
{
    public static class NavigationalMenu
    {
        public static string MyMenu(this HtmlHelper helper)
        {
            ProyectoFinalEntities x = new ProyectoFinalEntities();
            var categories = x.Categories;
            StringBuilder stringBuilder = new StringBuilder();
            foreach (Category c in categories)
            {
                stringBuilder.Append(helper.RouteLink(c.Name, "AuctionCategoryDetails", new { categoryName = c.Name }).ToString());
            }

            return stringBuilder.ToString();
        }
    }
}
</code>```

I was told that I could then use this extension method in my Views (right now, I'm using _layout.cshtml) by using the @Html keyword, like so:

```<code>@Html.MyMenu //doesn't appears to be in the available method selection.
</code>```

What's the reason why I can't call this method like that? Thanks for the help.

答: Add a using clause for MvcApplication1.HelperMethods

OwnerDisplayName: delete

Title: Using a created extension method

Body:
Here's the method I created:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using MvcApplication1.Models;
using System.Text;

namespace MvcApplication1.HelperMethods
{
    public static class NavigationalMenu
    {
        public static string MyMenu(this HtmlHelper helper)
        {
            ProyectoFinalEntities x = new ProyectoFinalEntities();
            var categories = x.Categories;
            StringBuilder stringBuilder = new StringBuilder();
            foreach (Category c in categories)
            {
                stringBuilder.Append(helper.RouteLink(c.Name, "AuctionCategoryDetails", new { categoryName = c.Name }).ToString());
            }

            return stringBuilder.ToString();
        }
    }
}

I was told that I could then use this extension method in my Views (right now, I'm using _layout.cshtml) by using the @Html keyword, like so:

@Html.MyMenu //doesn't appears to be in the available method selection.

What's the reason why I can't call this method like that? Thanks for the help.


问:
How to enforce data validation in Excel on a function executing a macro?
I'm compiling a database of companies and corresponding 3-letter acronyms. I have this macro that automatically generates an acronym when a new company is added to the database.

```<code>Function Abbv(pWorkRng As Range) As String
    Dim arr As Variant
    Dim xValue As String
    Dim output As String

    xValue = pWorkRng.Value
    arr = VBA.Split(Trim(xValue))

    For i = 0 To UBound(arr)
        output = output & VBA.Left(arr(i), 1) & ""
    Next

    output = Left(output, 3)
    Abbv = output
End Function
</code>```

I'm trying to enforce a data validation against inputting a duplicate entry so that any newly generated acronyms aren't the same as any previously existing acronyms (on the off chance that the initials of a newly added company are the same as an acronym already in the database).

This is the formula I have for preventing duplicate entries but it still allows auto-generated acronyms to be a duplicate.

```<code>=COUNTIF($D$1:$D$200,D1)=1
</code>```

How do I get this duplicate entry warning to prevent any auto-generated acronyms from being duplicates?

答:
Have a look at the WorksheetFunction.CountIf method

```<code>Application.WorksheetFunction.CountIf(Arg1, Arg2)
</code>```

Where …

Arg1 is the range of cells from which you want to count cells like Worksheets("Sheet1").Range("$D$1:$D$200") and

Arg is the criteria in the form of a number, expression, cell reference, or text that defines which cells will be counted: e.g. your Abbv.

Body:
I'm compiling a database of companies and corresponding 3-letter acronyms. I have this macro that automatically generates an acronym when a new company is added to the database.

Function Abbv(pWorkRng As Range) As String
    Dim arr As Variant
    Dim xValue As String
    Dim output As String

    xValue = pWorkRng.Value
    arr = VBA.Split(Trim(xValue))

    For i = 0 To UBound(arr)
        output = output & VBA.Left(arr(i), 1) & ""
    Next

    output = Left(output, 3)
    Abbv = output
End Function

I'm trying to enforce a data validation against inputting a duplicate entry so that any newly generated acronyms aren't the same as any previously existing acronyms (on the off chance that the initials of a newly added company are the same as an acronym already in the database).

This is the formula I have for preventing duplicate entries but it still allows auto-generated acronyms to be a duplicate.

=COUNTIF($D$1:$D$200,D1)=1

How do I get this duplicate entry warning to prevent any auto-generated acronyms from being duplicates?

Body:
Have a look at the WorksheetFunction.CountIf method

Application.WorksheetFunction.CountIf(Arg1, Arg2)

Where …

Arg1 is the range of cells from which you want to count cells like Worksheets("Sheet1").Range("$D$1:$D$200") and

Arg is the criteria in the form of a number, expression, cell reference, or text that defines which cells will be counted: e.g. your Abbv.


问:
How to connect to weather API using requests?
I am trying to learn Requests and practicing by connecting to the weather API.  But for some reason I can't get it to work?  It is clear the weather API is wanting the param in a certain way that I cannot seem to figure out how it translates to Requests.

Here is my code:

```<code>r = requests.get('http://api.openweathermap.org/data/2.5/weather', q={'Anderson'})
</code>```

Here is the link to the API page:
https://openweathermap.org/current

I see the weather pages wants the param in terms of q = city, but the error I get is:

```<code>TypeError: request() got an unexpected keyword argument 'q'
</code>```

Also here the the Requests page that I am referring to: http://docs.python-requests.org/en/master/

Thanks for the help!

答:
Try changing your call to the one that follows (by adding the api key to the params):

```<code>r = requests.get('http://api.openweathermap.org/data/2.5/weather', params={'q': 'Anderson', 'APPID': YOUR_API_KEY})
</code>```

Body:
I am trying to learn Requests and practicing by connecting to the weather API.  But for some reason I can't get it to work?  It is clear the weather API is wanting the param in a certain way that I cannot seem to figure out how it translates to Requests.

Here is my code:

r = requests.get('http://api.openweathermap.org/data/2.5/weather', q={'Anderson'})

Here is the link to the API page:
https://openweathermap.org/current

I see the weather pages wants the param in terms of q = city, but the error I get is:

TypeError: request() got an unexpected keyword argument 'q'

Also here the the Requests page that I am referring to: http://docs.python-requests.org/en/master/

Thanks for the help!

Body:
Try changing your call to the one that follows (by adding the api key to the params):

r = requests.get('http://api.openweathermap.org/data/2.5/weather', params={'q': 'Anderson', 'APPID': YOUR_API_KEY})


问:
Async Thread.CurrentThread.CurrentCulture in .net-4.6
Because of the following information from microsoft, I updated my code a bit. It sounds like they updated the currentculture to something I could use.

For apps that target the .NET Framework 4.6 and later versions,
  CultureInfo.CurrentCulture and CultureInfo.CurrentUICulture are stored
  in a thread's ExecutionContext, which flows across asynchronous
  operations.
  (source: https://msdn.microsoft.com/en-us/library/dn833123(v=vs.110).aspx)

```<code>using System;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("start " + Thread.CurrentThread.CurrentCulture.ToString() + " " + Thread.CurrentThread.ManagedThreadId);
        RunAsync().Wait();
        Console.WriteLine("Finish " + Thread.CurrentThread.CurrentCulture.ToString() + " " + Thread.CurrentThread.ManagedThreadId);
        Console.ReadKey();
    }

    static async Task RunAsync()
    {
        Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("de-DE");

        Console.WriteLine("1 " + Thread.CurrentThread.CurrentCulture.ToString() + " " + Thread.CurrentThread.ManagedThreadId);
        string cultureInTask = string.Empty;

        await Task.Run(() => cultureInTask = Thread.CurrentThread.CurrentCulture.ToString() + " " + Thread.CurrentThread.ManagedThreadId).ConfigureAwait(true);

        Console.WriteLine("2 " + cultureInTask);
        string twoA = await TestMethodAsync();
        Console.WriteLine("2a " + twoA + " " + Thread.CurrentThread.ManagedThreadId);
        Console.WriteLine("3 " + Thread.CurrentThread.CurrentCulture.ToString() + " " + Thread.CurrentThread.ManagedThreadId);
    }

    public static async Task<string> TestMethodAsync()
    {
        Console.WriteLine("2s " + Thread.CurrentThread.CurrentCulture.ToString() + " " + Thread.CurrentThread.ManagedThreadId);
        return await Task.Run(() =>
        {
            return System.Threading.Thread.CurrentThread.CurrentUICulture.ToString() + " " + Thread.CurrentThread.ManagedThreadId;
        });
    }
}
</code>```

Output:

```<code>start en-US 1
1 de-DE 1
2 de-DE 3
2s de-DE 3
2a en-US 4 4
3 de-DE 4
Finish en-US 1
</code>```

But why is 2a returning en-US and not de-DE? Is it because the executionContext is different? If so, how can I stay in the same execution context?

答: CurrentCulture and CurrentUICulture are independent properties. You're only setting CurrentCulture, and you're reporting that everywhere except for 2a, which reports CurrentUICulture. If you use the same property consistently throughout the code (either property should be fine), it'll give you the expected results.

Body:
Because of the following information from microsoft, I updated my code a bit. It sounds like they updated the currentculture to something I could use.

For apps that target the .NET Framework 4.6 and later versions,
  CultureInfo.CurrentCulture and CultureInfo.CurrentUICulture are stored
  in a thread's ExecutionContext, which flows across asynchronous
  operations.
  (source: https://msdn.microsoft.com/en-us/library/dn833123(v=vs.110).aspx)

using System;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("start " + Thread.CurrentThread.CurrentCulture.ToString() + " " + Thread.CurrentThread.ManagedThreadId);
        RunAsync().Wait();
        Console.WriteLine("Finish " + Thread.CurrentThread.CurrentCulture.ToString() + " " + Thread.CurrentThread.ManagedThreadId);
        Console.ReadKey();
    }

    static async Task RunAsync()
    {
        Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("de-DE");

        Console.WriteLine("1 " + Thread.CurrentThread.CurrentCulture.ToString() + " " + Thread.CurrentThread.ManagedThreadId);
        string cultureInTask = string.Empty;

        await Task.Run(() => cultureInTask = Thread.CurrentThread.CurrentCulture.ToString() + " " + Thread.CurrentThread.ManagedThreadId).ConfigureAwait(true);

        Console.WriteLine("2 " + cultureInTask);
        string twoA = await TestMethodAsync();
        Console.WriteLine("2a " + twoA + " " + Thread.CurrentThread.ManagedThreadId);
        Console.WriteLine("3 " + Thread.CurrentThread.CurrentCulture.ToString() + " " + Thread.CurrentThread.ManagedThreadId);
    }

    public static async Task<string> TestMethodAsync()
    {
        Console.WriteLine("2s " + Thread.CurrentThread.CurrentCulture.ToString() + " " + Thread.CurrentThread.ManagedThreadId);
        return await Task.Run(() =>
        {
            return System.Threading.Thread.CurrentThread.CurrentUICulture.ToString() + " " + Thread.CurrentThread.ManagedThreadId;
        });
    }
}

Output:

start en-US 1
1 de-DE 1
2 de-DE 3
2s de-DE 3
2a en-US 4 4
3 de-DE 4
Finish en-US 1

But why is 2a returning en-US and not de-DE? Is it because the executionContext is different? If so, how can I stay in the same execution context?


问:
.htaccess: Invalid command 'Allow', perhaps misspelled or defined by a module not included in the server configuration
The Apache version that I used in my local machine is 2.4, when I accessed the url of my application in the browser, I got this error.

```<code>/var/www/app/public/.htaccess: Invalid command 'Allow', perhaps misspelled or defined by a module not included in the server configuration
</code>```

This is the content of my .htaccess file:

```<code>SetEnvIf Request_URI ^/SOME_ENPOINT/ noauth=1
SetEnvIf Request_URI ^/auth/ noauth=1

AuthUserFile /var/www/app/.htpasswd
AuthType Basic
AuthName "APP Login"

Require valid-user
Allow from env=noauth
</code>```

I am thinking that I will remove this line of code below in .htaccess file.

```<code>Allow from env=noauth
</code>```

I already enabled the mod_env module of my apache server.

Is there way to solve this issue but using the environment variable noauth? Thanks :)

答: These are legacy access control directives. Either port Order, allow, and deny to "Require" or load the mod_access_compat module in your (non-htaccess) apache config.

Body:
The Apache version that I used in my local machine is 2.4, when I accessed the url of my application in the browser, I got this error.

/var/www/app/public/.htaccess: Invalid command 'Allow', perhaps misspelled or defined by a module not included in the server configuration

This is the content of my .htaccess file:

SetEnvIf Request_URI ^/SOME_ENPOINT/ noauth=1
SetEnvIf Request_URI ^/auth/ noauth=1

AuthUserFile /var/www/app/.htpasswd
AuthType Basic
AuthName "APP Login"

Require valid-user
Allow from env=noauth

I am thinking that I will remove this line of code below in .htaccess file.

Allow from env=noauth

I already enabled the mod_env module of my apache server.

Is there way to solve this issue but using the environment variable noauth? Thanks :)


问:
when I use use pipe when the command is stored in a string, the pipe will be recognized as '|', why?
I excute bash shell like this

```<code>cmd="cat tmp1.list tmp2.list | sort > tmp3.list"
$cmd
</code>```

the result is

```<code>sdas
qqq
cat: |: No such file or directory
cat: sort: No such file or directory
cat: >: No such file or directory
cat: tmp3.list: No such file or directory
enter code here
</code>```

I konw 'eval' can work
but I want to know why it can't

答:
Operator precedence happen before variable substitution.

For example :

```<code>$cmd | cat
</code>```

The command is splitted

```<code>$cmd -> | -> cat
</code>```

$cmd will be executed, then piped to cat

Then, your $cmd is replaced, but executed as a single command. It does not open a subshell for it.
So the first command is executed, and everything else is added as an argument to it.

Body:
I excute bash shell like this

cmd="cat tmp1.list tmp2.list | sort > tmp3.list"
$cmd

the result is

sdas
qqq
cat: |: No such file or directory
cat: sort: No such file or directory
cat: >: No such file or directory
cat: tmp3.list: No such file or directory
enter code here

I konw 'eval' can work
but I want to know why it can't

Body:
Operator precedence happen before variable substitution.

For example :

$cmd | cat

The command is splitted

$cmd -> | -> cat

$cmd will be executed, then piped to cat

Then, your $cmd is replaced, but executed as a single command. It does not open a subshell for it.
So the first command is executed, and everything else is added as an argument to it.


问:
Docker Compose host path error with nginx
I've a error when I run docker-compose up nginx with my host path :

ERROR: for nginx  Cannot start service nginx: oci runtime error: container_linux.go:247: starting container process caused "process_linux.go:359: container init caused \"rootfs_linux.go:54: mounting \\"/d/Sites/lfdwveille/app/config/docker/nginx.conf\\" to rootfs \\"/mnt/sda1/var/lib/docker/aufs/mnt/fce42187ef3ff6bcc0d5acf53a77d2218348a432063e2d5fe00b8ac945578f63\\" at \\"/mnt/sda1/var/lib/docker/aufs/mnt/fce42187ef3ff6bcc0d5acf53a77d2218348a432063e2d5fe00b8ac945578f63/etc/nginx/nginx.conf\\" caused \\"not a directory\\"\""

: Are you trying to mount a directory onto a file (or vice-versa)? Check if the specified host path exists and is the expected type

[31mERROR[0m: Encountered errors while bringing up the project.

The folder url is correct :( I don't know why nginx don't want mount folder and I've no problem with PHP and MySQL.

My setup :

Windows

docker-compose v1.9.0

docker 1.12

Error log :

container_linux.go:247: starting container process caused "process_linux.go:359: container init caused \"rootfs_linux.go:54: mounting \\"/d/Sites/lfdwveille/app/config/docker/nginx.conf\\" to rootfs \\"/mnt/sda1/var/lib/docker/aufs/mnt/fce42187ef3ff6bcc0d5acf53a77d2218348a432063e2d5fe00b8ac945578f63\\" at \\"/mnt/sda1/var/lib/docker/aufs/mnt/fce42187ef3ff6bcc0d5acf53a77d2218348a432063e2d5fe00b8ac945578f63/etc/nginx/nginx.conf\\" caused \\"not a directory\\"\""

Anyone have idea ?

Thank you !

答:
If you are using Docker Machine on Windows, docker has limited access to your Windows filesystem. By default Docker Machine tries to auto-share your C:\Users (Windows) directory.

Docker compose - share volume Nginx


问:
Changing functionality of back button on android
I want to change the functionality of back button for a particular bunch of code being active. Once its done how do i reset it to default.

I am using following piece of code:

```<code>@Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if(keyCode== KeyEvent.KEYCODE_BACK && issearchopen)
        {
            searchView.closeSearch();
        }

        else{

        }
        return true;
    }
</code>```

boolean issearchopen is true whenever my 'bunch' of code is active.

Thanks in advance

答:
It should look like this</p>

```<code>@Override
public void onBackPressed() {
   if(isSearchOpen){
     // do stuff
   } else {
      super.onBackPressed(); // default behaviour
   }
}
</code>```

Body:
I want to change the functionality of back button for a particular bunch of code being active. Once its done how do i reset it to default.

I am using following piece of code:

@Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if(keyCode== KeyEvent.KEYCODE_BACK && issearchopen)
        {
            searchView.closeSearch();
        }

        else{

        }
        return true;
    }

boolean issearchopen is true whenever my 'bunch' of code is active.

Thanks in advance

Body:
It should look like this

@Override
public void onBackPressed() {
   if(isSearchOpen){
     // do stuff
   } else {
      super.onBackPressed(); // default behaviour
   }
}


问:
SplitButton title with glyphicon + text
How can I make a title of a SplitButton with a glyphicon and tile just like classic button (crosshair).

Because when I try to do same as classic button with <Glyphicon glyph="screenshot" /> Crosshair it doesn't work so I tried {<Glyphicon glyph="retweet"/>}'ROI' or {<Glyphicon glyph="retweet"/>}+'ROI' or <Glyphicon glyph="retweet"/>+'ROI'

Nothing work.

Thanks in advance for your help.

答:
Just Put it inside your button tag like this: </p>

```<code><button><Glyphicon glyph="retweet"/> ROI</button>
</code>```

Title: SplitButton title with glyphicon + text

Body:
Just Put it inside your button tag like this:

<button><Glyphicon glyph="retweet"/> ROI</button>


问:
How to set MySQL database to 'Starting state' every hour
I have a WordPress demo site to let visitors try out some live plugins.

What I want is that the connected MySQL database refreshes every hour. Meaning: Going back to the clean starting state.

So every hour the demo site will be clean and fresh again without any data from demo users.

Is there a query via php that should be running or how can I manage this?

Hope you understand my question.

Many thanks in advance!

UPDATE:

I have create a cronjob and the job gets activated coz I'm receiving an email every time it gets extivated :)

But why is my sql file not executing? Any ideas?

```<code><?php

exec("mysql -u DB-USER -pDB-PASS DB-NAME < /home/users/XXXX/XXXX/yw-cronjobs/clean_demo_db.sql");

$to      = 'contact@XXXX.nl';
$subject = 'Demo Cron Executed';
$message = 'Cron job to reset demo has been executed';
$headers = 'From: admin@XXXX.nl' . "\r\n" .
'Reply-To: admin@XXXX.nl' . "\r\n" .
'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);

?>
</code>```

When I import the clean_demo_db.sql file in PHPMyAdmin it does what it should...

Am I missing something here?

答:
Take the mysqldump of your MySQL database. Schedule cronjob which puts the dump every hour.
For putting, you can use mysql -h<db_hostname> -u<db_username> -p<db_password> <databasename> < <mysqldump_file.sql>

If your server is linux, then schedule cron job using sudo crontab -e.

Body:
I have a WordPress demo site to let visitors try out some live plugins.

What I want is that the connected MySQL database refreshes every hour. Meaning: Going back to the clean starting state.

So every hour the demo site will be clean and fresh again without any data from demo users.

Is there a query via php that should be running or how can I manage this?

Hope you understand my question.

Many thanks in advance!

UPDATE:

I have create a cronjob and the job gets activated coz I'm receiving an email every time it gets extivated :)

But why is my sql file not executing? Any ideas?

<?php

exec("mysql -u DB-USER -pDB-PASS DB-NAME < /home/users/XXXX/XXXX/yw-cronjobs/clean_demo_db.sql");

$to      = 'contact@XXXX.nl';
$subject = 'Demo Cron Executed';
$message = 'Cron job to reset demo has been executed';
$headers = 'From: admin@XXXX.nl' . "\r\n" .
'Reply-To: admin@XXXX.nl' . "\r\n" .
'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);

?>

When I import the clean_demo_db.sql file in PHPMyAdmin it does what it should...

Am I missing something here?


问:
How do I redirect www.mypage.com/this/that to www.mypage.com in IIS
```<code><rule name="url rewrite"
                    stopProcessing="true">
                <match url="This/That/Something(.*)$" />
                <action type="Redirect"
                       url="" />
            </rule>
</code>```

What do i put in the in the action url to just have it redirect to the current domain.

trying to turn www.mypage.com/this/that/whatever.aspx to this www.mypage.com

答:
If you want to redirect to homepage, you can just use /. It will looks like that

```<code><rule name="url rewrite" stopProcessing="true">
    <match url="This/That/Something(.*)$" />
    <action type="Redirect" url="/" />
</rule>
</code>```

For ex. if you want to redirect to www.mypage.com/abc, you can use like that:

```<code><rule name="url rewrite" stopProcessing="true">
    <match url="This/That/Something(.*)$" />
    <action type="Redirect" url="/abc" />
</rule>
</code>```

In case if you want to redirect to another domain www.otherdomain.com, you should use it like that:

```<code><rule name="url rewrite" stopProcessing="true">
    <match url="This/That/Something(.*)$" />
    <action type="Redirect" url="http://www.otherdomain.com" />
</rule>
</code>```

Body:
<rule name="url rewrite"
                    stopProcessing="true">
                <match url="This/That/Something(.*)$" />
                <action type="Redirect"
                       url="" />
            </rule>

What do i put in the in the action url to just have it redirect to the current domain.

trying to turn www.mypage.com/this/that/whatever.aspx to this www.mypage.com

Body:
If you want to redirect to homepage, you can just use /. It will looks like that

<rule name="url rewrite" stopProcessing="true">
    <match url="This/That/Something(.*)$" />
    <action type="Redirect" url="/" />
</rule>

For ex. if you want to redirect to www.mypage.com/abc, you can use like that:

<rule name="url rewrite" stopProcessing="true">
    <match url="This/That/Something(.*)$" />
    <action type="Redirect" url="/abc" />
</rule>

In case if you want to redirect to another domain www.otherdomain.com, you should use it like that:

<rule name="url rewrite" stopProcessing="true">
    <match url="This/That/Something(.*)$" />
    <action type="Redirect" url="http://www.otherdomain.com" />
</rule>


问:
How can I shrink an image in HTML whilst maintaining its sharpness?
I have an image that I use many times. In several cases I want to shrink its size, but obviously it loses sharpness when I do this in HTML.

Is there a way to fix this? The image is located elsewhere and I can’t save it locally.

Thanks

答:
Firefox and Internet Explorer actually do have CSS properties that adjust the way images are rendered when resized via HTML attributes or CSS properties:

Firefox: image-rendering

Internet Explorer: -ms-interpolation-mode

These won’t work in other browsers, and may not work great in all (or any) versions of IE and Firefox.

But it might be worth experimenting with them as a fallback in case resizer.co causes any issues.