问:
Is this the fastest way to parse my XML into JavaScript objects using jQuery?
I have an XML file like this:

```<code><content>
    <box>
        <var1>A1</var1>
        <var2>B1</var2>
        <var3>C1</var3>
        <var4>D1</var4>
    </box>
    <box>
        <var1>A2</var1>
        <var2>B2</var2>
        <var3>C2</var3>
        <var4>D2</var4>
    </box>
    <box>
        <var1>A3</var1>
        <var2>B3</var2>
        <var3>C3</var3>
        <var4>D3</var4>
    </box>
</content>
</code>```

It has 500 box elements which I need to parse into JavaScript objects. I am using this code which works fine but I am a newbie and maybe I am missing something and would like to get suggestions if there is a better/faster way to do it:

```<code>var app = {
    //...
    box: [],

    init: function (file) {
        var that = this;

        $.ajax({
            type: "GET",
            url: file,
            dataType: "xml",
            success: function (xml) {
                $("box", xml).each(function (i) {
                    var e = $(this);
                    that.box[i] = new Box(i, {
                        var1: e.children("var1").text(),
                        var2: e.children("var2").text(),
                        var3: e.children("var3").text(),
                        var4: e.children("var4").text()
                    });
                });
            }
        });
    },
    //...
};
</code>```

Thanks in advance.

答:
Use JSON if at all possible. That way the browser will do the parsing for you and you won't have to do any post-processing.

JSON from the server

```<code>{"content":
  {"box": [
    {"var1": "A1",
     "var2": "B1",
     "var3": "C1",
     "var4": "D1"},
    {"var1": "A2",
     "var2": "B2",
     "var3": "C2",
     "var4": "D2"},
    {"var1": "A3",
     "var2": "B3",
     "var3": "C3",
     "var4": "D3"}]}}
</code>```

Client JavaScript

```<code>var app = {
    //...
    box: [],

    init: function (file) {
        var that = this;

        $.ajax({
            type: "GET",
            url: file,
            dataType: "json",
            success: function(result) {
              that.box = $.map(result.content.box, function(box, i) {
                return new Box(i, box);
              });
            }
        });
    },
    //...
};
</code>```

Body:
I have an XML file like this:

<content>
    <box>
        <var1>A1</var1>
        <var2>B1</var2>
        <var3>C1</var3>
        <var4>D1</var4>
    </box>
    <box>
        <var1>A2</var1>
        <var2>B2</var2>
        <var3>C2</var3>
        <var4>D2</var4>
    </box>
    <box>
        <var1>A3</var1>
        <var2>B3</var2>
        <var3>C3</var3>
        <var4>D3</var4>
    </box>
</content>

It has 500 box elements which I need to parse into JavaScript objects. I am using this code which works fine but I am a newbie and maybe I am missing something and would like to get suggestions if there is a better/faster way to do it:

var app = {
    //...
    box: [],

    init: function (file) {
        var that = this;

        $.ajax({
            type: "GET",
            url: file,
            dataType: "xml",
            success: function (xml) {
                $("box", xml).each(function (i) {
                    var e = $(this);
                    that.box[i] = new Box(i, {
                        var1: e.children("var1").text(),
                        var2: e.children("var2").text(),
                        var3: e.children("var3").text(),
                        var4: e.children("var4").text()
                    });
                });
            }
        });
    },
    //...
};

Thanks in advance.

Body:
Use JSON if at all possible. That way the browser will do the parsing for you and you won't have to do any post-processing.

JSON from the server

{"content":
  {"box": [
    {"var1": "A1",
     "var2": "B1",
     "var3": "C1",
     "var4": "D1"},
    {"var1": "A2",
     "var2": "B2",
     "var3": "C2",
     "var4": "D2"},
    {"var1": "A3",
     "var2": "B3",
     "var3": "C3",
     "var4": "D3"}]}}

Client JavaScript

var app = {
    //...
    box: [],

    init: function (file) {
        var that = this;

        $.ajax({
            type: "GET",
            url: file,
            dataType: "json",
            success: function(result) {
              that.box = $.map(result.content.box, function(box, i) {
                return new Box(i, box);
              });
            }
        });
    },
    //...
};


来源: stackexchange

问:
Nginx ldap require group
I have compiled and configured nginx to work with ldap and our ActiveDirectory. All works with this configuration:

```<code>ldap_server MyAD {
   url ldap://100.100.100.11:3268/DC=<mydomain>,DC=<myext>?sAMAccountName?sub?(objectClass=user);
    binddn "<user>";
    binddn_passwd <password>;
    group_attribute member;
    group_attribute_is_dn on;
    require valid_user;
  }
</code>```

My site require authentication and only users in ActiveDirectory can access.
Now I'm trying to allow only users that are in a specific ActiveDirectory group, but with no success, can anyone help me to fix the url query?

答: In addition to require valid_user, you can add require group "dn_of_the_group".

ContentLicense: CC BY-SA 3.0

Title: Nginx ldap require group

Body:
I have compiled and configured nginx to work with ldap and our ActiveDirectory. All works with this configuration:

ldap_server MyAD {
   url ldap://100.100.100.11:3268/DC=<mydomain>,DC=<myext>?sAMAccountName?sub?(objectClass=user);
    binddn "<user>";
    binddn_passwd <password>;
    group_attribute member;
    group_attribute_is_dn on;
    require valid_user;
  }

My site require authentication and only users in ActiveDirectory can access.
Now I'm trying to allow only users that are in a specific ActiveDirectory group, but with no success, can anyone help me to fix the url query?


问:
Excluding Image From the CSS of Animatable Property
I applied following CSS to the post article which affects a background change of color-

```<code> .post-article{
     background: green;
     -webkit-animation: mymove 15s;
 }
 @-webkit-keyframes mymove {
     from {background-color: green;}
     to {background-color: blue;}
 }
</code>```

Now, this article post contains am image and the CSS has affected the image, too! I want to selectively exclude this image class (which is .article img )from being affected due to this CSS. So, I used-

```<code>.post-article:not(.article img){
     background: green;
     -webkit-animation: mymove 15s;
 }
 @-webkit-keyframes mymove {
     from {background-color: green;}
     to {background-color: blue;}
 }
</code>```

But the desired change didn't occur and all elements continue to be affected. Any guidelines?

Minified versiion of HTML;

```<code><html>
<head>
<style>
.post-article {  width: 300px;
height: 200px;
background: green;
-webkit-animation: mymove 15s;
}
@-webkit-keyframes mymove {
from {background-color: green;}
to {background-color: blue;}
}

</style>
</head>
<body>

<div id="post-article"></div>

</body>
</html>
</code>```

答:
Add another div in-between, I think it should work :</p>

```<code><div>
    <img src="//placehold.it/400x200" />
    <div class="post-article">
        <p >lorem ipsum lorem ipsum lorem ipsum  lorem ipsum lorem ipsum</p>
    </div>
</div>
</code>```

Body:
I applied following CSS to the post article which affects a background change of color-

 .post-article{
     background: green;
     -webkit-animation: mymove 15s;
 }
 @-webkit-keyframes mymove {
     from {background-color: green;}
     to {background-color: blue;}
 }

Now, this article post contains am image and the CSS has affected the image, too! I want to selectively exclude this image class (which is .article img )from being affected due to this CSS. So, I used-

.post-article:not(.article img){
     background: green;
     -webkit-animation: mymove 15s;
 }
 @-webkit-keyframes mymove {
     from {background-color: green;}
     to {background-color: blue;}
 }

But the desired change didn't occur and all elements continue to be affected. Any guidelines?

Minified versiion of HTML;

Body:
Add another div in-between, I think it should work :

<div>
    <img src="//placehold.it/400x200" />
    <div class="post-article">
        <p >lorem ipsum lorem ipsum lorem ipsum  lorem ipsum lorem ipsum</p>
    </div>
</div>


问:
Count How Many Letters In A List With 'n' Input
Basically i wanted to know how to count the number of letters in a list, for example lets say i add the word 'EXAMPLE' to a list and then lets say i wanna find out how many times the letter 'e' is used given e as the user input how would i write it so it says there are 2 e's in the word 'EXAMPLE'.

So far i got

```<code>WordList = []
print("1. Enter A Word")
print("2. Check Letter Or Vowel Times")

userInput = input("Please Choose An Option: ")
if userInput == "1":
    wordInput = input("Please Enter A Word: ")
    WordList.append(wordInput.lower())
</code>```

答:
```<code>l = ['example']

def count(y):
    for x in l:
        return x.count(y)

count('e')
</code>```

Without using built-in function count()

```<code>l=list('example')

def count(y):
    cnt=0
    for x in l:
        if x == y:
            cnt+=1
    return cnt

print(count('e'))
</code>```

Body:
Basically i wanted to know how to count the number of letters in a list, for example lets say i add the word 'EXAMPLE' to a list and then lets say i wanna find out how many times the letter 'e' is used given e as the user input how would i write it so it says there are 2 e's in the word 'EXAMPLE'.

So far i got

WordList = []
print("1. Enter A Word")
print("2. Check Letter Or Vowel Times")

userInput = input("Please Choose An Option: ")
if userInput == "1":
    wordInput = input("Please Enter A Word: ")
    WordList.append(wordInput.lower())

Body:
l = ['example']

def count(y):
    for x in l:
        return x.count(y)

count('e')

Without using built-in function count()

l=list('example')

def count(y):
    cnt=0
    for x in l:
        if x == y:
            cnt+=1
    return cnt

print(count('e'))


问:
How to initiate a viewcontroller without presenting it?
I have a tab bar controller and a few other viewcontrollers outside the tab bar controller. I have this viewcontroller called "X" which is a part of the tab bar controller. I have another viewcontroller called "Y" which is not a part of the tab bar controller. Now i want to initiate X when im inside Y upon tapping a button without actually presenting it. I want X to become active and fire its viewdidload so that i can access X whenever i chose to do so. Is this possible. Im sorry if im not clear in explaining my quiestion. let me know if you need any other additional information.</p>

答:
Old question at this point, but I was looking for an answer myself just yesterday and managed to get it figured out.

Instantiate the ViewController, then call loadViewIfNeeded().

Example:

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let exampleVC = storyboard.instantiateViewController(withIdentifier: "ExampleViewController") as! ExampleViewController
exampleVC.loadViewIfNeeded()

If you want, you can then check if the view is loaded with:

```<code>exampleVC.isViewLoaded
</code>```

The ViewController is now all set up and ready for display when you decide to present it.

Body:
Old question at this point, but I was looking for an answer myself just yesterday and managed to get it figured out.

Instantiate the ViewController, then call loadViewIfNeeded().

Example:

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let exampleVC = storyboard.instantiateViewController(withIdentifier: "ExampleViewController") as! ExampleViewController
exampleVC.loadViewIfNeeded()

If you want, you can then check if the view is loaded with:

exampleVC.isViewLoaded

The ViewController is now all set up and ready for display when you decide to present it.


问:
iOS 11 prefersLargeTitles not updating until scroll
I implemented a basic UIViewController with a UITableView that's wrapped in a UINavigationController. I set prefersLargeTitles to true:

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    navigationController?.navigationBar.prefersLargeTitles = true
    navigationItem.title = "Coffees"
}
</code>```

However, the title stays small until I scroll the view, at which point it enlarges. I tried moving that call to where I create the UINavigationController, but there was no effect. I am sure the navigationController is not nil when I set prefersLargeTitles.

Should I be updating that property elsewhere? Or should I file a Radar?

Update:

This only seems to happen if my view contains a UITableView or is itself a UITableViewController

答:
I had the same issue only on one tableview ...

I had to set :

```<code>self.tableView.contentInsetAdjustmentBehavior = .never
</code>```

so that my tableview stop scrolling when uiviewcontroller was loaded.

It's the tableview automatic scrolling that makes the large title being hidden

Hope this helps

Body:
I implemented a basic UIViewController with a UITableView that's wrapped in a UINavigationController. I set prefersLargeTitles to true:

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    navigationController?.navigationBar.prefersLargeTitles = true
    navigationItem.title = "Coffees"
}

However, the title stays small until I scroll the view, at which point it enlarges. I tried moving that call to where I create the UINavigationController, but there was no effect. I am sure the navigationController is not nil when I set prefersLargeTitles.

Should I be updating that property elsewhere? Or should I file a Radar?

Update:

This only seems to happen if my view contains a UITableView or is itself a UITableViewController

Body:
I had the same issue only on one tableview ...

I had to set :

self.tableView.contentInsetAdjustmentBehavior = .never

so that my tableview stop scrolling when uiviewcontroller was loaded.

It's the tableview automatic scrolling that makes the large title being hidden

Hope this helps


问:
Scala matching high order function return value
Hello im trying to use case match with a high order function. if function return true do things same for false. Thank you.</p>

```<code>def funk(ls:List[Int],f:Int=>Boolean):List[Int]=
{
  f match
  {
    case true => do something
    case false => do somethingelse
  }
}
</code>```

答:
you have to execute the function and pass the return value to the match case as

```<code>def funk(ls:List[Int],f:Int=>Boolean):List[Int]=
{
  f(some integer value) match
  {
    case  true => return a list of integers
    case false => return a list of integers
  }
}
</code>```

for example

```<code>def funk(ls:List[Int],f:Int=>Boolean):List[Int]=
{
  f(ls(0)) match
  {
    case  true => List(1,2)
    case false => List(4,3)
  }
}
</code>```

Body:
Hello im trying to use case match with a high order function. if function return true do things same for false. Thank you.

def funk(ls:List[Int],f:Int=>Boolean):List[Int]=
{
  f match
  {
    case true => do something
    case false => do somethingelse
  }
}

Body:
you have to execute the function and pass the return value to the match case as

def funk(ls:List[Int],f:Int=>Boolean):List[Int]=
{
  f(some integer value) match
  {
    case  true => return a list of integers
    case false => return a list of integers
  }
}

for example

def funk(ls:List[Int],f:Int=>Boolean):List[Int]=
{
  f(ls(0)) match
  {
    case  true => List(1,2)
    case false => List(4,3)
  }
}


问:
How to handle event if window service killed
I have developed window service. I want to know how can I get notification if service is killed. Presently i am getting notification if service is stopped.

```<code>----service startup code---

inline void CServiceModule::Init(_ATL_OBJMAP_ENTRY* p, HINSTANCE h, UINT      nServiceNameID, const GUID* plibid)
{
    CComModule::Init(p, h, plibid);

    m_bService = TRUE;
    m_hInstance = h;

    if(m_szServiceName.size()==0)
    {
        string strServiceName = GetServiceName();
        m_szServiceName = strServiceName;
    }

    // set up the initial service status
    m_hServiceStatus = NULL;
    m_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
    m_status.dwCurrentState = SERVICE_STOPPED;
    m_status.dwControlsAccepted = SERVICE_ACCEPT_PRESHUTDOWN;
    m_status.dwWin32ExitCode = 0;
    m_status.dwServiceSpecificExitCode = 0;
    m_status.dwCheckPoint = 0;
    m_status.dwWaitHint = 0;
}

 ---Handler----
 inline void CServiceModule::Handler(DWORD dwOpcode)
 {
     switch (dwOpcode)
     {
        case SERVICE_CONTROL_SHUTDOWN:
        case SERVICE_CONTROL_STOP:
            SetServiceStatus(SERVICE_STOP_PENDING);
            PostThreadMessage(dwThreadID, WM_QUIT, 0, 0);
            break;
        case SERVICE_CONTROL_PAUSE:
            break;
        case SERVICE_CONTROL_CONTINUE:
            break;
        case SERVICE_CONTROL_INTERROGATE:
            break;
  /*    case SERVICE_CONTROL_SHUTDOWN:

        break;*/
        default:
            LogEvent(_T("Bad service request"));
    }
}
</code>```

I am getting notification SERVICE_CONTROL_STOP when service is stopped. Please suggest what handler should i used if service is killed.

答:
If it's killed, it's killed. It ends. Immediately. You don't get any signals.

However recent windows versions will never just kill a process if you select that in the task manager. They will first send a close signal (as if you had pressed Alt-F4) to the app to give it a chance to close gracefully. The app will only be terminated if it does not shut down in a specified time span.

Body:
I have developed window service. I want to know how can I get notification if service is killed. Presently i am getting notification if service is stopped.

----service startup code---

inline void CServiceModule::Init(_ATL_OBJMAP_ENTRY* p, HINSTANCE h, UINT      nServiceNameID, const GUID* plibid)
{
    CComModule::Init(p, h, plibid);

    m_bService = TRUE;
    m_hInstance = h;

    if(m_szServiceName.size()==0)
    {
        string strServiceName = GetServiceName();
        m_szServiceName = strServiceName;
    }

    // set up the initial service status
    m_hServiceStatus = NULL;
    m_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
    m_status.dwCurrentState = SERVICE_STOPPED;
    m_status.dwControlsAccepted = SERVICE_ACCEPT_PRESHUTDOWN;
    m_status.dwWin32ExitCode = 0;
    m_status.dwServiceSpecificExitCode = 0;
    m_status.dwCheckPoint = 0;
    m_status.dwWaitHint = 0;
}

 ---Handler----
 inline void CServiceModule::Handler(DWORD dwOpcode)
 {
     switch (dwOpcode)
     {
        case SERVICE_CONTROL_SHUTDOWN:
        case SERVICE_CONTROL_STOP:
            SetServiceStatus(SERVICE_STOP_PENDING);
            PostThreadMessage(dwThreadID, WM_QUIT, 0, 0);
            break;
        case SERVICE_CONTROL_PAUSE:
            break;
        case SERVICE_CONTROL_CONTINUE:
            break;
        case SERVICE_CONTROL_INTERROGATE:
            break;
  /*    case SERVICE_CONTROL_SHUTDOWN:

        break;*/
        default:
            LogEvent(_T("Bad service request"));
    }
}

I am getting notification SERVICE_CONTROL_STOP when service is stopped. Please suggest what handler should i used if service is killed.


问:
Set drawable resource ID in android:src for ImageView using data binding in Android
I'm trying to set drawable resource ID to android:src of ImageView using data binding

Here is my object:

```<code>public class Recipe implements Parcelable {
    public final int imageResource; // resource ID (e.g. R.drawable.some_image)
    public final String title;
    // ...

    public Recipe(int imageResource, String title /* ... */) {
        this.imageResource = imageResource;
        this.title = title;
    }

    // ...
}
</code>```

Here is my layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <data>
        <variable
            name="recipe"
            type="com.example.android.fivewaystocookeggs.Recipe" />
    </data>

    <!-- ... -->

    <ImageView
        android:id="@+id/recipe_image_view"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:scaleType="centerCrop"
        android:src="@{recipe.imageResource}" />

    <!-- ... -->

</layout>
</code>```

And finally, activity class:

```<code>// ...

public class RecipeActivity extends AppCompatActivity {

    public static final String RECIPE_PARCELABLE = "recipe_parcelable";
    private Recipe mRecipe;

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

        mRecipe = getIntent().getParcelableExtra(RECIPE_PARCELABLE);
        ActivityRecipeBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_recipe);
        binding.setRecipe(mRecipe);
    }

    // ...

}
</code>```

It doesn't display image at all. What am I doing wrong?

BTW, it was perfectly working with standard way:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_recipe);

    final ImageView recipeImageView = (ImageView) findViewById(R.id.recipe_image_view);
    recipeImageView.setImageResource(mRecipe.imageResource);

}
</code>```

答:
Never override standard SDK attributes when you create your own @BindingAdapter!

This is not a good approach for many reasons like:
it's gonna prevent obtaining benefits of new fixes on Android SDK update on that attribute. Also it might confuse developers and surely tricky for reusability (because it's un-exptected to be overrided )

you may use different namespace like:

```<code>custom:src="@{recipe.imageResource}"
</code>```

or

```<code>mybind:src="@{recipe.imageResource}"
</code>```

------ start Update 2.Jul.2018

Namespace is not recommended to be used, so better to rely on prefix or different name as:

```<code>app:custom_src="@{recipe.imageResource}"
</code>```

or

```<code>app:customSrc="@{recipe.imageResource}"
</code>```

------ end Update 2.Jul.2018

However, I would recommend different solution as:

```<code>android:src="@{ContextCompat.getDrawable(context, recipe.imageResource)}"
</code>```

context view is always available inside binding expression  @{ ... }

Body:
I'm trying to set drawable resource ID to android:src of ImageView using data binding

Here is my object:

public class Recipe implements Parcelable {
    public final int imageResource; // resource ID (e.g. R.drawable.some_image)
    public final String title;
    // ...

    public Recipe(int imageResource, String title /* ... */) {
        this.imageResource = imageResource;
        this.title = title;
    }

    // ...
}

Here is my layout:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <data>
        <variable
            name="recipe"
            type="com.example.android.fivewaystocookeggs.Recipe" />
    </data>

    <ImageView
        android:id="@+id/recipe_image_view"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:scaleType="centerCrop"
        android:src="@{recipe.imageResource}" />

</layout>

And finally, activity class:

// ...

public class RecipeActivity extends AppCompatActivity {

    public static final String RECIPE_PARCELABLE = "recipe_parcelable";
    private Recipe mRecipe;

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

        mRecipe = getIntent().getParcelableExtra(RECIPE_PARCELABLE);
        ActivityRecipeBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_recipe);
        binding.setRecipe(mRecipe);
    }

    // ...

}

It doesn't display image at all. What am I doing wrong?

BTW, it was perfectly working with standard way:

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

    final ImageView recipeImageView = (ImageView) findViewById(R.id.recipe_image_view);
    recipeImageView.setImageResource(mRecipe.imageResource);

}

Body:
Never override standard SDK attributes when you create your own @BindingAdapter!

This is not a good approach for many reasons like:
it's gonna prevent obtaining benefits of new fixes on Android SDK update on that attribute. Also it might confuse developers and surely tricky for reusability (because it's un-exptected to be overrided )

you may use different namespace like:

custom:src="@{recipe.imageResource}"

or

mybind:src="@{recipe.imageResource}"

------ start Update 2.Jul.2018

Namespace is not recommended to be used, so better to rely on prefix or different name as:

app:custom_src="@{recipe.imageResource}"

or

app:customSrc="@{recipe.imageResource}"

------ end Update 2.Jul.2018

However, I would recommend different solution as:

android:src="@{ContextCompat.getDrawable(context, recipe.imageResource)}"

context view is always available inside binding expression  @{ ... }

ContentLicense: CC BY-SA 4.0


问:
Why do these links exceed the width?
How can we explain that these links exceed the 200px width:

.small { background-color: red; width: 200px; }
.tag { background-color: rgba(0,0,0,.05); margin-right: 10px;  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="small">
2 January 2017#foooooo#foooooo#foooooo#foooooo#foooooo#foooooo
</div></code>```

whereas, if we add a newline after each , it doesn't:

.small { background-color: red; width: 200px; }
.tag { background-color: rgba(0,0,0,.05); margin-right: 10px;  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="small">
2 January 2017
#foooooo
#foooooo
#foooooo
#foooooo
#foooooo
#foooooo
</div></code>```

What is the usual good practice to not be trapped in such corner cases?

答:
Because there is no space between the a tags and browser can't break a tag in new line.you can use of word-wrap(more...) or word-break(more...) .

A) Use of word-wrap:

.small { background-color: red; width: 200px;word-wrap: break-word;};
.tag { background-color: rgba(0,0,0,.05); margin-right: 10px;  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="small">
2 January 2017#foooooo#foooooo#foooooo#foooooo#foooooo#foooooo
</div></code>```

B) Use of word-break:

.small { background-color: red; width: 200px;word-break: break-all;};
.tag { background-color: rgba(0,0,0,.05); margin-right: 10px;  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="small">
2 January 2017#foooooo#foooooo#foooooo#foooooo#foooooo#foooooo
</div></code>```

C) Other way is put a space between the a tags.

.small { background-color: red; width: 200px;};
.tag { background-color: rgba(0,0,0,.05); margin-right: 10px;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="small">
2 January 2017 #foooooo #foooooo #foooooo #foooooo #foooooo #foooooo
</div></code>```

Title: Why do these links exceed the width?

Body:
How can we explain that these links exceed the 200px width:

.small { background-color: red; width: 200px; }
.tag { background-color: rgba(0,0,0,.05); margin-right: 10px;  }

2 January 2017#foooooo#foooooo#foooooo#foooooo#foooooo#foooooo

whereas, if we add a newline after each , it doesn't:

.small { background-color: red; width: 200px; }
.tag { background-color: rgba(0,0,0,.05); margin-right: 10px;  }

2 January 2017
#foooooo
#foooooo
#foooooo
#foooooo
#foooooo
#foooooo

What is the usual good practice to not be trapped in such corner cases?

Body:
Because there is no space between the a tags and browser can't break a tag in new line.you can use of word-wrap(more...) or word-break(more...) .

A) Use of word-wrap:

.small { background-color: red; width: 200px;word-wrap: break-word;};
.tag { background-color: rgba(0,0,0,.05); margin-right: 10px;  }

<div class="small">
<a class="date" href="blah">2 January 2017</a><a class="tag" href="blah">#foooooo</a><a class="tag" href="blah">#foooooo</a><a class="tag" href="blah">#foooooo</a><a class="tag" href="blah">#foooooo</a><a class="tag" href="blah">#foooooo</a><a class="tag" href="blah">#foooooo</a>
</div>

B) Use of word-break:

.small { background-color: red; width: 200px;word-break: break-all;};
.tag { background-color: rgba(0,0,0,.05); margin-right: 10px;  }

<div class="small">
<a class="date" href="blah">2 January 2017</a><a class="tag" href="blah">#foooooo</a><a class="tag" href="blah">#foooooo</a><a class="tag" href="blah">#foooooo</a><a class="tag" href="blah">#foooooo</a><a class="tag" href="blah">#foooooo</a><a class="tag" href="blah">#foooooo</a>
</div>

C) Other way is put a space between the a tags.

.small { background-color: red; width: 200px;};
.tag { background-color: rgba(0,0,0,.05); margin-right: 10px;}

<div class="small">
<a class="date" href="blah">2 January 2017</a> <a class="tag" href="blah">#foooooo</a> <a class="tag" href="blah">#foooooo</a> <a class="tag" href="blah">#foooooo</a> <a class="tag" href="blah">#foooooo</a> <a class="tag" href="blah">#foooooo</a> <a class="tag" href="blah">#foooooo</a>
</div>


问:
Creating a custom bootstrap / bootloader in C#
We've decided to create a custom bootstrapper for our deployment solution. We are currently re-writing and re-designing our deployment strategy for all of our products. Sadly, none of us are deployment experts.

Here's what we have so far:

A. The MSI packages will be authored in InstallShield. We will use whatever feature Installshield offers (IIS integration, COM registration, Registry, etc). The dialog's created by InstallShield will not be used (that is what the bootstrapper is for). The MSIs will be installed silently.

B. Whenever we need to write CA's for stuff that InstallShield can't handle, we will be writing them in managed code (C#) using DTF. We will be creating a "Custom Action Framework" that will "standardize" how we use custom actions.

C. We will create a custom bootstrapper (the "setup.exe") in C# to "handle" the installation.

We have decided to go with a multiple MSI approach and use MSI transaction to "chain" the installation from the boostrapper (inspired from Office 2007 installer)

The boostrapper that we are envisioning to create is inspired from Visual Studio's and SQL Server's bootstrapper. The boostrapper will be responsible for the following:

Prerequisite installation: Each application require a pre-requisite. These pre-requisites are listed in an XML file placed on the same folder as the MSI (inspired from Office 2007 installer) along with other metadata. Depending on current state of the system, the boostrapper will decide which pre-requisite to be installed or not.

Feature selection: We are planning to structure the "internal" MSI's feature in such a way that it will not be appropriate to be displayed right away to the end-user. We will have feature labeled as "Core_Files", or "Vista_Only" or "64bit_Only". Depending on the metadata on the XML file (on item 1) and the target system, the bootstrapper will be responsible in "populating" a "feature tree" that the user can customize (also inspired from Office 2007 bootstrapper).

Pre-installation Checks: The bootstrapper will be responsible in checking if the system is ready to receive the installation. For instance, if a machine needs to reboot prior to installation or if the user needs to manually install a service pack, patch or a windows component. Anything that needs to be done that needs user intervention should be displayed here. Think of it as a check list (a listbox) with checks and exes. (Inspired from SQL server's bootstrapper). The "rules" will be written in C#.

Application Configuration: For application that needs to be "configured" prior to installation. These "parameters" (user configuration) will be passed to the respective MSI via MSI Properties.

Actual Installation: The bootstrapper will then perform the installation. Proper "transaction" should be observed when necessary. All "products" that should be grouped together shall be displayed as one product in Add/Remove Programs (by messing with the ARP entries). Also, proper progress shall be reported by each MSI being installed.

-- That's what we have so far.

I think there are a couple of out-of-the-box solutions for creating a custom bootstrapper like dotNetInstaller and BMG. We've look into it but it's not as flexible as we've hoped. There's also BURN but we're not sure if it's ready for primetime.

So here we are... we've decided to create our own custom bootstrapper.

Question:

Are we crazy? Shouldn't we be creating our own bootstrapper? Which ideas listed above are not realistic? Is there a better approach?

Any input regarding our situation will be greatly appreciated. Also, if you have any questions, please don't hesitate to ask.

答: Frankly, Burn isn't going to be done for at least a year.  You already have InstallShield and IMO it has the best off the shelf bootstrapper currently available.  I'd scope your requirements back and make it fit the box.   Pretty much everything I read from you can be done using InstallShield if you learn to push it to it's limits.</p>

ContentLicense: CC BY-SA 2.5


问:
get Metadata from Url using MetadataExtractor in C#
I have used following code but I can't get any response from that
I have faced exception from this like
'The given path's format is not supported.'

```<code>else if (Path.GetExtension(blobFilePath).ToLower() == ".jpg"  ||
         Path.GetExtension(blobFilePath).ToLower() == ".jpeg" ||
         Path.GetExtension(blobFilePath).ToLower() == ".gif"  ||
         Path.GetExtension(blobFilePath).ToLower() == ".png")
{
    filepath = blob.Uri.AbsoluteUri;
}

IEnumerable<MetadataExtractor.Directory> directories =
    ImageMetadataReader.ReadMetadata(filepath.ToString());
</code>```

Can you please help me out from this ?

Thanks

答:
The overload of ImageMetadataReader.ReadMetadata you're using expects a file system path. Using a URL won't work.

Instead, you must open the network stream and pass it. Assuming your URL uses HTTP or HTTPS, something like this should do it:

```<code>using (var client = new HttpClient())
using (var response = await client.GetAsync(url))
using (var content = response.Content)
using (var stream = await content.ReadAsStreamAsync())
{
    // NOTE passing a stream here, not a string
    var directories = ImageMetadataReader.ReadMetadata(stream);

    // ...
}
</code>```

Body:
I have used following code but I can't get any response from that
I have faced exception from this like
'The given path's format is not supported.'

else if (Path.GetExtension(blobFilePath).ToLower() == ".jpg"  ||
         Path.GetExtension(blobFilePath).ToLower() == ".jpeg" ||
         Path.GetExtension(blobFilePath).ToLower() == ".gif"  ||
         Path.GetExtension(blobFilePath).ToLower() == ".png")
{
    filepath = blob.Uri.AbsoluteUri;
}

IEnumerable<MetadataExtractor.Directory> directories =
    ImageMetadataReader.ReadMetadata(filepath.ToString());

Can you please help me out from this ?

Thanks

Body:
The overload of ImageMetadataReader.ReadMetadata you're using expects a file system path. Using a URL won't work.

Instead, you must open the network stream and pass it. Assuming your URL uses HTTP or HTTPS, something like this should do it:

using (var client = new HttpClient())
using (var response = await client.GetAsync(url))
using (var content = response.Content)
using (var stream = await content.ReadAsStreamAsync())
{
    // NOTE passing a stream here, not a string
    var directories = ImageMetadataReader.ReadMetadata(stream);

    // ...
}


问:
using express-validator as Express middle ware not working
I am using npm module [express-validator][1] to validate my query and body parameter. As in express , we can pass list of function as a middleware , I have created an separate file as validator. Here my code of the validator..

creditcard.validator.js

```<code>const { check, body , query ,oneOf, validationResult } = require('express-validator/check');

exports.post_credit_check =  [
    function(req,res,next) {
        body('firstName')
        .exists()
        .isAlphanumeric().withMessage('firstName should be alpanumeric')
        .isLength({min: 1 , max: 50}).withMessage('firstName should not be empty, should be more than one and less than 50 character')
        .trim();
        var errorValidation = validationResult(req);
        if ( errorValidation ) {
            return res.status(500).json({
                title: 'an error occured',
                error: errorValidation
            });
        }
        next()
    },

    function(req,res,next) {
    body('lastName')
    .exists()
    .isAlphanumeric().withMessage('lastName should be alpanumeric')
    .isLength({min: 1 , max: 50}).withMessage('lastName should not be empty, should be more than one and less than 50 character')
    .trim();
var errorValidation = validationResult(req);
            if ( errorValidation ) {
                return res.status(500).json({
                    title: 'an error occured',
                    error: errorValidation
                });
            }
            next()
        }
];
</code>```

Here my the route file where I am passing the middleware validator array

```<code>var express = require('express');
var router = express.Router();
var Creditcard =  require('../models/creditcard.model');
const { validationResult } = require('express-validator/check');
var validate = require('../models/creditcard.validate');

router.post('/creditcarddetails', validate.post_credit_check , function(req, res, next) {
          .................
}
</code>```

Though I am passing all middleware function in validate.post_credit_check, it not validating the body and not giving the error.

答:
I think that the check method is already a middleware and there is no need to call it inside another middleware, your code should be:</p>

```<code>exports.post_credit_check =  [
    body('firstName')
        .exists()
        .isAlphanumeric().withMessage('firstName should be alpanumeric')
        .isLength({min: 1 , max: 50}).withMessage('firstName should not be empty, should be more than one and less than 50 character')
        .trim(),
    function(req,res,next) {
        var errorValidation = validationResult(req);
        if ( errorValidation ) {
            return res.status(500).json({
                title: 'an error occured',
                error: errorValidation
            });
        }
        next()
    },
    body('lastName')
        .exists()
        .isAlphanumeric().withMessage('lastName should be alpanumeric')
        .isLength({min: 1 , max: 50}).withMessage('lastName should not be empty, should be more than one and less than 50 character')
        .trim(),
    function(req,res,next) {

        var errorValidation = validationResult(req);
        if ( errorValidation ) {
            return res.status(500).json({
                title: 'an error occured',
                error: errorValidation
            });
        }
        next()
    }
];
</code>```

Body:
I am using npm module [express-validator][1] to validate my query and body parameter. As in express , we can pass list of function as a middleware , I have created an separate file as validator. Here my code of the validator..

creditcard.validator.js

const { check, body , query ,oneOf, validationResult } = require('express-validator/check');

exports.post_credit_check =  [
    function(req,res,next) {
        body('firstName')
        .exists()
        .isAlphanumeric().withMessage('firstName should be alpanumeric')
        .isLength({min: 1 , max: 50}).withMessage('firstName should not be empty, should be more than one and less than 50 character')
        .trim();
        var errorValidation = validationResult(req);
        if ( errorValidation ) {
            return res.status(500).json({
                title: 'an error occured',
                error: errorValidation
            });
        }
        next()
    },

    function(req,res,next) {
    body('lastName')
    .exists()
    .isAlphanumeric().withMessage('lastName should be alpanumeric')
    .isLength({min: 1 , max: 50}).withMessage('lastName should not be empty, should be more than one and less than 50 character')
    .trim();
var errorValidation = validationResult(req);
            if ( errorValidation ) {
                return res.status(500).json({
                    title: 'an error occured',
                    error: errorValidation
                });
            }
            next()
        }
];

Here my the route file where I am passing the middleware validator array

var express = require('express');
var router = express.Router();
var Creditcard =  require('../models/creditcard.model');
const { validationResult } = require('express-validator/check');
var validate = require('../models/creditcard.validate');

router.post('/creditcarddetails', validate.post_credit_check , function(req, res, next) {
          .................
}

Though I am passing all middleware function in validate.post_credit_check, it not validating the body and not giving the error.

Body:
I think that the check method is already a middleware and there is no need to call it inside another middleware, your code should be:

exports.post_credit_check =  [
    body('firstName')
        .exists()
        .isAlphanumeric().withMessage('firstName should be alpanumeric')
        .isLength({min: 1 , max: 50}).withMessage('firstName should not be empty, should be more than one and less than 50 character')
        .trim(),
    function(req,res,next) {
        var errorValidation = validationResult(req);
        if ( errorValidation ) {
            return res.status(500).json({
                title: 'an error occured',
                error: errorValidation
            });
        }
        next()
    },
    body('lastName')
        .exists()
        .isAlphanumeric().withMessage('lastName should be alpanumeric')
        .isLength({min: 1 , max: 50}).withMessage('lastName should not be empty, should be more than one and less than 50 character')
        .trim(),
    function(req,res,next) {

        var errorValidation = validationResult(req);
        if ( errorValidation ) {
            return res.status(500).json({
                title: 'an error occured',
                error: errorValidation
            });
        }
        next()
    }
];


问:
How to get the origin URL from a "doPost" request on google apps script
I've been trying to identify the origin of a POST request made to a Google Apps Script doPost() content service;

```<code>function doPost(request) {
   // Something like this:
   var originURL = request.headers.URL; // http://myurl.com

}
</code>```

Since I have published it ("Deploy as web app"), to 'Anyone, even anonymous',
it has the following header:

```<code>access-control-allow-origin: *
</code>```

So I want to control it's access in my code.

Is it possible?

答:
We can not use direct post method in other aplication but you can use URL parameters passing try following.
Publishing script makes sure you have updated version and copy /exec link.
you can pass URL parameters like https://script../../exec?=para1=1012D.

More details Click Here

Body:
I've been trying to identify the origin of a POST request made to a Google Apps Script doPost() content service;

function doPost(request) {
   // Something like this:
   var originURL = request.headers.URL; // http://myurl.com

}

Since I have published it ("Deploy as web app"), to 'Anyone, even anonymous',
it has the following header:

access-control-allow-origin: *

So I want to control it's access in my code.

Is it possible?


问:
C Recursive search for a file in a folder and subfolders
My program is getting the input path from the user, and is looking for files with a name corresponding with a column from a .csv file where oldpath is the userinput path, and then i'm using get_between_delimiter in a while loop to get the name of the file i'm looking for from the first cell of each line in the .csv

What I can't figure out is how do I check all the subdirectories for that file if it does not exist in the base directory or right away, while keeping my program's functionality?

```<code>  strcpy(oldnp, oldpath);
  strcat(oldnp, "/");
  strcat(oldnp, get_between_delimiter(commande[cnt] , 0));
  strcat(oldnp, ".png");
  source = fopen(oldnp, "r");
  if ((source = fopen(oldnp, "r")) == NULL)
   file_found();
  else
   ;?
</code>```

答:
Use FindFirstFile to list all the files in a directory, then compare with each file. Or do a recursive search and search each sub directory.

You can adjust the "wildcard" also.

This example looks for "something.png" on "c:\\test", if it doesn't find it, it will look in sub directories of "c:\\test"

Make sure you don't do a recursive search on "C:\" because that's going to go through all the files on the drive.

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

int findfile_recursive(const char *folder, const char *filename, char *fullpath)
{
    char wildcard[MAX_PATH];
    sprintf(wildcard, "%s\\*", folder);
    WIN32_FIND_DATA fd;
    HANDLE handle = FindFirstFile(wildcard, &fd);
    if(handle == INVALID_HANDLE_VALUE) return 0;
    do
    {
        if(strcmp(fd.cFileName, ".") == 0 || strcmp(fd.cFileName, "..") == 0)
            continue;
        char path[MAX_PATH];
        sprintf(path, "%s\\%s", folder, fd.cFileName);

        if(_stricmp(fd.cFileName, filename) == 0)
            strcpy(fullpath, path);
        else if(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
            findfile_recursive(path, filename, fullpath);
        if(strlen(fullpath))
            break;
    } while(FindNextFile(handle, &fd));
    FindClose(handle);
    return strlen(fullpath);
}

int main(void)
{
    char fullpath[MAX_PATH] = { 0 };
    if(findfile_recursive("c:\\test", "something.png", fullpath))
        printf("found: %s\n", fullpath);
    return 0;
}
</code>```

Body:
My program is getting the input path from the user, and is looking for files with a name corresponding with a column from a .csv file where oldpath is the userinput path, and then i'm using get_between_delimiter in a while loop to get the name of the file i'm looking for from the first cell of each line in the .csv

What I can't figure out is how do I check all the subdirectories for that file if it does not exist in the base directory or right away, while keeping my program's functionality?

  strcpy(oldnp, oldpath);
  strcat(oldnp, "/");
  strcat(oldnp, get_between_delimiter(commande[cnt] , 0));
  strcat(oldnp, ".png");
  source = fopen(oldnp, "r");
  if ((source = fopen(oldnp, "r")) == NULL)
   file_found();
  else
   ;?

Body:
Use FindFirstFile to list all the files in a directory, then compare with each file. Or do a recursive search and search each sub directory.

You can adjust the "wildcard" also.

This example looks for "something.png" on "c:\\test", if it doesn't find it, it will look in sub directories of "c:\\test"

Make sure you don't do a recursive search on "C:\" because that's going to go through all the files on the drive.

#include <stdio.h>
#include <Windows.h>

int findfile_recursive(const char *folder, const char *filename, char *fullpath)
{
    char wildcard[MAX_PATH];
    sprintf(wildcard, "%s\\*", folder);
    WIN32_FIND_DATA fd;
    HANDLE handle = FindFirstFile(wildcard, &fd);
    if(handle == INVALID_HANDLE_VALUE) return 0;
    do
    {
        if(strcmp(fd.cFileName, ".") == 0 || strcmp(fd.cFileName, "..") == 0)
            continue;
        char path[MAX_PATH];
        sprintf(path, "%s\\%s", folder, fd.cFileName);

        if(_stricmp(fd.cFileName, filename) == 0)
            strcpy(fullpath, path);
        else if(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
            findfile_recursive(path, filename, fullpath);
        if(strlen(fullpath))
            break;
    } while(FindNextFile(handle, &fd));
    FindClose(handle);
    return strlen(fullpath);
}

int main(void)
{
    char fullpath[MAX_PATH] = { 0 };
    if(findfile_recursive("c:\\test", "something.png", fullpath))
        printf("found: %s\n", fullpath);
    return 0;
}


问:
In C language binary file io
if I input a binary file to array buf, why do I have to input it by (void*) ??
and why do I have to write it by (void*)?? please observe this code and please explain this code to me. (I just copy this code from my book)

```<code>int main(void) {
FILE * src = fopen("a.png", "rb");
FILE * des = fopen("b.png", "wb");

char buf[20];
int readCnt;

if (src == NULL || des == NULL) {
    puts("File open failed");
    return -1;
}

while (1) {
    readCnt = fread((void*)buf, 1, sizeof(buf), src);

    if (readCnt < sizeof(buf)) {
        if (feof(src) != 0) {
            fwrite((void*)buf, 1, readCnt, des);
            puts("File copy complete");
            break;
        }
        else
            puts("File copy Failed");

        break;
    }
    fwrite((void*)buf, 1, sizeof(buf), des);
}
fclose(src);
fclose(des);
return 0;
</code>```

}

答:
This should probably be a comment but i don't have the reputation for that. In your code:

if (src == NULL || des == NULL) {
      puts("File open failed");
      return -1;
  }

There is a chance that either src or des may have been opened correctly and therefore should have fclose(); called for it.

Something like:

```<code>if (src == NULL || des == NULL)
{
      if(src)
      {
        fclose(src);
      }
      if(des)
      {
        fclose(des);
      }
      puts("File open failed");
      return -1;
  }
</code>```

would be better.

Title: In C language binary file io

Body:
if I input a binary file to array buf, why do I have to input it by (void*) ??
and why do I have to write it by (void*)?? please observe this code and please explain this code to me. (I just copy this code from my book)

int main(void) {
FILE * src = fopen("a.png", "rb");
FILE * des = fopen("b.png", "wb");

char buf[20];
int readCnt;

if (src == NULL || des == NULL) {
    puts("File open failed");
    return -1;
}

while (1) {
    readCnt = fread((void*)buf, 1, sizeof(buf), src);

    if (readCnt < sizeof(buf)) {
        if (feof(src) != 0) {
            fwrite((void*)buf, 1, readCnt, des);
            puts("File copy complete");
            break;
        }
        else
            puts("File copy Failed");

        break;
    }
    fwrite((void*)buf, 1, sizeof(buf), des);
}
fclose(src);
fclose(des);
return 0;

}

Body:
This should probably be a comment but i don't have the reputation for that. In your code:

if (src == NULL || des == NULL) {
      puts("File open failed");
      return -1;
  }

There is a chance that either src or des may have been opened correctly and therefore should have fclose(); called for it.

Something like:

if (src == NULL || des == NULL)
{
      if(src)
      {
        fclose(src);
      }
      if(des)
      {
        fclose(des);
      }
      puts("File open failed");
      return -1;
  }

would be better.


问:
laravel eloquent resources api send status code
In Laravel 5.5 We can set API through resources (https://laracasts.com/series/whats-new-in-laravel-5-5/episodes/20), but how can we send STATUS CODE?

Also how should I set status dynamically which is defined in with()

```<code>//namespace App\Http\Resources;

//use Illuminate\Http\Resources\Json\Resource;

//class User extends Resource

public function with($request)
{
    return [
        'status' => 'success',
    ];
}
</code>```

答:
By default, HTTP responses include a status code.. So you don't have to get it in data sent/received but in the HTTP response headers.

For example, if you are using axios to send AJAX requests, you will just  have to do something like..

```<code>axios.get('/path/to/get/your/data/').
  then(function(response) {
    // response.status will represent your status code
});
</code>```

So when you use abort(404); in your controller, the status code will be 404. And when you have an internal error (code 500) you will get 500 as response code.

Body:
In Laravel 5.5 We can set API through resources (https://laracasts.com/series/whats-new-in-laravel-5-5/episodes/20), but how can we send STATUS CODE?

Also how should I set status dynamically which is defined in with()

//namespace App\Http\Resources;

//use Illuminate\Http\Resources\Json\Resource;

//class User extends Resource

public function with($request)
{
    return [
        'status' => 'success',
    ];
}

Body:
By default, HTTP responses include a status code.. So you don't have to get it in data sent/received but in the HTTP response headers.

For example, if you are using axios to send AJAX requests, you will just  have to do something like..

axios.get('/path/to/get/your/data/').
  then(function(response) {
    // response.status will represent your status code
});

So when you use abort(404); in your controller, the status code will be 404. And when you have an internal error (code 500) you will get 500 as response code.


问:
How to sum a matrice of matrices
I have a matrix that each spot in it is another matrix, and I need to print a new matrix which is a form from the sum of each matrix in the same index .

```<code> >>sum_matrices([[[1,2,3],[4,5,6]],[[11,12,13],[14,15,16]],[[21,22,23],[24,25,26]],[[31,3 2,13],[34,35,36]]])

    [[64, 68, 52], [76, 80, 84]]
</code>```

I have this code which adds 2 matrices together.

```<code>def sum_matrices(mat_lst):
    result = []
    for i in range(len(mat_lst)):
        rows=[]
        for j in range(len(mat_lst)):
            rows.append(add_matrices(mat_lst[i][j]))
        result.append(rows)
    return result
</code>```

答:
Try like this,</p>

```<code>def sum(matrix):
    result = matrix[0][:]
    for i in range(1, len(matrix)):
        for j in range(len(result)):
            for k in range(len(result[j])):
                result[j][k] += matrix[i][j][k]

    print result
</code>```

Title: How to sum a matrice of matrices

Body:
I have a matrix that each spot in it is another matrix, and I need to print a new matrix which is a form from the sum of each matrix in the same index .

 >>sum_matrices([[[1,2,3],[4,5,6]],[[11,12,13],[14,15,16]],[[21,22,23],[24,25,26]],[[31,3 2,13],[34,35,36]]])

    [[64, 68, 52], [76, 80, 84]]

I have this code which adds 2 matrices together.

def sum_matrices(mat_lst):
    result = []
    for i in range(len(mat_lst)):
        rows=[]
        for j in range(len(mat_lst)):
            rows.append(add_matrices(mat_lst[i][j]))
        result.append(rows)
    return result

Body:
Try like this,

def sum(matrix):
    result = matrix[0][:]
    for i in range(1, len(matrix)):
        for j in range(len(result)):
            for k in range(len(result[j])):
                result[j][k] += matrix[i][j][k]

    print result


问:
How to return values from dynamically generated "insert" command?
I have a stored procedure that performs inserts and updates in the tables. The need to create it was to try to centralize all the scan functions before inserting or updating records. Today the need arose to return the value of the field ID of the table so that my application can locate the registry and perform other stored procedures.

Stored procedure

```<code>SET TERM ^ ;

CREATE OR ALTER procedure sp_insupd (
    iaction varchar(3),
    iusuario varchar(20),
    iip varchar(15),
    imodulo varchar(30),
    ifieldsvalues varchar(2000),
    iwhere varchar(1000),
    idesclogs varchar(200))
returns (
    oid integer)
as
declare variable vdesc varchar(10000);
begin
  if (iaction = 'ins') then
  begin
    vdesc = idesclogs;

    /*** the error is on the line below ***/
    execute statement 'insert into '||:imodulo||' '||:ifieldsvalues||' returning ID into '||:oid||';';
  end else
  if (iaction = 'upd') then
  begin
    execute statement 'select '||:idesclogs||' from '||:imodulo||' where '||:iwhere into :vdesc;

    execute statement 'execute procedure SP_CREATE_AUDIT('''||:imodulo||''');';

    execute statement 'update '||:imodulo||' set '||:ifieldsvalues||' where '||:iwhere||';';
  end

  insert into LOGS(USUARIO, IP, MODULO, TIPO, DESCRICAO) values (
  :iusuario, :iip, :imodulo, (case :iaction when 'ins' then 1 when 'upd' then 2 end), :vdesc);
end^

SET TERM ; ^
</code>```

The error in the above line is occurring due to syntax error. The procedure is compiled normally, that is, the error does not happen in the compilation, since the line in question is executed through the "execute statement". When there was no need to return the value of the ID field, the procedure worked normally with the line like this:

```<code>...
execute statement 'insert into '||:imodulo||' '||:ifieldsvalues||';';
...
</code>```

What would be the correct way for the value of the ID field to be stored in the OID variable?

答:
What is REAL VALUE in ifieldsvalues ?

you can not have BOTH

'insert into '||:imodulo||' '||:ifieldsvalues

'update '||:imodulo||' set '||:ifieldsvalues

because methods to specify column names and column values in INSERT and UPDATE statements is fundamentally different!!! You either would have broken update-stmt or broken insert-stmt!

The error in the above line is occurring due to syntax error

This is not enough. Show the real error text, all of it.
It includes the actual command you generate and it seems you had generated it really wrong way.

all the scan functions before inserting or updating records

Move those functions out of the SQL server and into your application server.
Then you would not have to make insert/update in that "strings splicing" way, which is VERY fragile and "SQL injection" friendly. You stepped into the road to hell here.

the error does not happen in the compilation

Exactly. And that is only for starters. You are removing all the safety checks that should had helped you in applications development.

http://searchsoftwarequality.techtarget.com/definition/3-tier-application

https://en.wikipedia.org/wiki/Multitier_architecture#Three-tier_architecture

http://bobby-tables.com

On modern Firebird versions EXECUTE STATEMENT command can have the same INTO clause as PSQL SELECT command.

https://www.firebirdsql.org/file/documentation/reference_manuals/fblangref25-en/html/fblangref25-psql-coding.html#fblangref25-psql-execstmt

Use http://translate.ru to read http://www.firebirdsql.su/doku.php?id=execute_statement

Or just see SQL examples there. Notice, however, those examples all use SELECT dynamic command, not INSERT. So I am not sure it would work that way.

This works in Firebird 2.5 (but not in Firebird 2.1) PSQL blocks.

```<code>execute statement 'insert into Z(payload) values(2) returning id' into :i;
</code>```

To run it from IBExpert/FlameRobin/iSQL interactive shell add that obvious boilerplate:

```<code>execute block returns (i integer) as
begin
  execute statement 'insert into Z(payload) values(2) returning id' into :i;
  suspend;
end
</code>```

Body:
I have a stored procedure that performs inserts and updates in the tables. The need to create it was to try to centralize all the scan functions before inserting or updating records. Today the need arose to return the value of the field ID of the table so that my application can locate the registry and perform other stored procedures.

Stored procedure

SET TERM ^ ;

CREATE OR ALTER procedure sp_insupd (
    iaction varchar(3),
    iusuario varchar(20),
    iip varchar(15),
    imodulo varchar(30),
    ifieldsvalues varchar(2000),
    iwhere varchar(1000),
    idesclogs varchar(200))
returns (
    oid integer)
as
declare variable vdesc varchar(10000);
begin
  if (iaction = 'ins') then
  begin
    vdesc = idesclogs;

    /*** the error is on the line below ***/
    execute statement 'insert into '||:imodulo||' '||:ifieldsvalues||' returning ID into '||:oid||';';
  end else
  if (iaction = 'upd') then
  begin
    execute statement 'select '||:idesclogs||' from '||:imodulo||' where '||:iwhere into :vdesc;

    execute statement 'execute procedure SP_CREATE_AUDIT('''||:imodulo||''');';

    execute statement 'update '||:imodulo||' set '||:ifieldsvalues||' where '||:iwhere||';';
  end

  insert into LOGS(USUARIO, IP, MODULO, TIPO, DESCRICAO) values (
  :iusuario, :iip, :imodulo, (case :iaction when 'ins' then 1 when 'upd' then 2 end), :vdesc);
end^

SET TERM ; ^

The error in the above line is occurring due to syntax error. The procedure is compiled normally, that is, the error does not happen in the compilation, since the line in question is executed through the "execute statement". When there was no need to return the value of the ID field, the procedure worked normally with the line like this:

...
execute statement 'insert into '||:imodulo||' '||:ifieldsvalues||';';
...

What would be the correct way for the value of the ID field to be stored in the OID variable?

Body:
What is REAL VALUE in ifieldsvalues ?

you can not have BOTH

'insert into '||:imodulo||' '||:ifieldsvalues

'update '||:imodulo||' set '||:ifieldsvalues

because methods to specify column names and column values in INSERT and UPDATE statements is fundamentally different!!! You either would have broken update-stmt or broken insert-stmt!

The error in the above line is occurring due to syntax error

This is not enough. Show the real error text, all of it.
It includes the actual command you generate and it seems you had generated it really wrong way.

all the scan functions before inserting or updating records

Move those functions out of the SQL server and into your application server.
Then you would not have to make insert/update in that "strings splicing" way, which is VERY fragile and "SQL injection" friendly. You stepped into the road to hell here.

the error does not happen in the compilation

Exactly. And that is only for starters. You are removing all the safety checks that should had helped you in applications development.

http://searchsoftwarequality.techtarget.com/definition/3-tier-application

https://en.wikipedia.org/wiki/Multitier_architecture#Three-tier_architecture

http://bobby-tables.com

On modern Firebird versions EXECUTE STATEMENT command can have the same INTO clause as PSQL SELECT command.

https://www.firebirdsql.org/file/documentation/reference_manuals/fblangref25-en/html/fblangref25-psql-coding.html#fblangref25-psql-execstmt

Use http://translate.ru to read http://www.firebirdsql.su/doku.php?id=execute_statement

Or just see SQL examples there. Notice, however, those examples all use SELECT dynamic command, not INSERT. So I am not sure it would work that way.

This works in Firebird 2.5 (but not in Firebird 2.1) PSQL blocks.

execute statement 'insert into Z(payload) values(2) returning id' into :i;

To run it from IBExpert/FlameRobin/iSQL interactive shell add that obvious boilerplate:

execute block returns (i integer) as
begin
  execute statement 'insert into Z(payload) values(2) returning id' into :i;
  suspend;
end


问:
How to change an element of an array into object?
I am fetching data from a table having different columns then I saved it in a array. Here is my code:

```<code>$sql="SELECT image,image1,image2,image3,image4,image5 FROM `app_places` where place_id='".$place_id."'  ";
    $check= mysqli_query($conn, $sql);
    $rowcount=mysqli_num_rows($check);
    //var_dump($rowcount);
    if($rowcount<=0)
    {
        $minfo = array("success"=>'false',"msg"=>'invalid place_id');
        $jsondata = json_encode($minfo);
        print_r($jsondata);
        exit();

        }
        else
        {
            $data = array();
            while ($row = mysqli_fetch_array($check,MYSQLI_NUM))
            {
                $data[] = $row;
            }
</code>```

I encode this in json format and my out is like this:

```<code>{"allplaces":
[
{
"image":"http://www.freepngimg.com/download/lion/3-2-lion-png.png","image1":"http://mobileappdatabase.in/city/uploads/default-image/defaultimage.png","image2":"http://mobileappdatabase.in/city/uploads/default-image/defaultimage.png","image3":"http://mobileappdatabase.in/city/uploads/default-image/defaultimage.png","image4":"http://mobileappdatabase.in/city/uploads/default-image/defaultimage.png","image5":"http://mobileappdatabase.in/city/uploads/default-image/defaultimage.png"
}
]
}
</code>```

But I need like this :

```<code>     {"allplaces":[
    {"image":"http://www.freepngimg.com/download/lion/3-2-lion-png.png"},
{"image1":"http://mobileappdatabase.in/city/uploads/default-image/defaultimage.png"},

{"image2":"http://mobileappdatabase.in/city/uploads/default-image/defaultimage.png"},

{"image3":"http://mobileappdatabase.in/city/uploads/default-image/defaultimage.png"},

{"image4":"http://mobileappdatabase.in/city/uploads/default-image/defaultimage.png"},

{"image5":"http://mobileappdatabase.in/city/uploads/default-image/defaultimage.png"}]}
</code>```

答:
This is only going to work if you have 1 row. Your table structure is pretty bad, but here you go. </p>

```<code>while ($row = mysqli_fetch_array($check,MYSQLI_ASSOC)) {
    foreach($row as $key => $value){
     $data[] = array(
       $key => $value
     );
    }
}
</code>```

Body:
I am fetching data from a table having different columns then I saved it in a array. Here is my code:

$sql="SELECT image,image1,image2,image3,image4,image5 FROM `app_places` where place_id='".$place_id."'  ";
    $check= mysqli_query($conn, $sql);
    $rowcount=mysqli_num_rows($check);
    //var_dump($rowcount);
    if($rowcount<=0)
    {
        $minfo = array("success"=>'false',"msg"=>'invalid place_id');
        $jsondata = json_encode($minfo);
        print_r($jsondata);
        exit();

        }
        else
        {
            $data = array();
            while ($row = mysqli_fetch_array($check,MYSQLI_NUM))
            {
                $data[] = $row;
            }

I encode this in json format and my out is like this:

{"allplaces":
[
{
"image":"http://www.freepngimg.com/download/lion/3-2-lion-png.png","image1":"http://mobileappdatabase.in/city/uploads/default-image/defaultimage.png","image2":"http://mobileappdatabase.in/city/uploads/default-image/defaultimage.png","image3":"http://mobileappdatabase.in/city/uploads/default-image/defaultimage.png","image4":"http://mobileappdatabase.in/city/uploads/default-image/defaultimage.png","image5":"http://mobileappdatabase.in/city/uploads/default-image/defaultimage.png"
}
]
}

But I need like this :

     {"allplaces":[
    {"image":"http://www.freepngimg.com/download/lion/3-2-lion-png.png"},
{"image1":"http://mobileappdatabase.in/city/uploads/default-image/defaultimage.png"},

{"image2":"http://mobileappdatabase.in/city/uploads/default-image/defaultimage.png"},

{"image3":"http://mobileappdatabase.in/city/uploads/default-image/defaultimage.png"},

{"image4":"http://mobileappdatabase.in/city/uploads/default-image/defaultimage.png"},

{"image5":"http://mobileappdatabase.in/city/uploads/default-image/defaultimage.png"}]}

Body:
This is only going to work if you have 1 row. Your table structure is pretty bad, but here you go.

while ($row = mysqli_fetch_array($check,MYSQLI_ASSOC)) {
    foreach($row as $key => $value){
     $data[] = array(
       $key => $value
     );
    }
}


问:
JIRA SOAP API : get the list of users
I'm working on a tool in C# that interfaces the JIRA SOAP API. I have read the doc one can find here: http://docs.atlassian.com/software/jira/docs/api/rpc-jira-plugin/latest/index.html

Does anyone know how I could get the list of all the assignable users for a specific project? I haven't been able to find how to do that yet...

答:
It's a bit counter-intuitive as there's no general "Get Users" type command, and you need to load a project and role object before you can ask the question.

Here's the same basic implementation in PHP (since I just wrote it), but keying off the "Users" role rather than "Developers":

```<code>$base_url = 'https://yourjira.domain.com';
$wsdl = $base_url . '/rpc/soap/jirasoapservice-v2?wsdl';

$username = 'username';
$password = 'password';

$client = new SoapClient($wsdl);

try {
    $token = $client->login($username, $password);
}
catch (SoapFault $fault) {
    echo "Error logging in to JIRA";
    print_r($fault);
}

$code = 'MYPROJECT'

$project = $client->getProjectByKey($token, $code);

$role = $client->getProjectRole($token, 10000); // 10000 is typically the "users" role

$users = $client->getProjectRoleActors($token, $role, $project);

print_r($users);
</code>```

Title: JIRA SOAP API : get the list of users

Body:
It's a bit counter-intuitive as there's no general "Get Users" type command, and you need to load a project and role object before you can ask the question.

Here's the same basic implementation in PHP (since I just wrote it), but keying off the "Users" role rather than "Developers":

$base_url = 'https://yourjira.domain.com';
$wsdl = $base_url . '/rpc/soap/jirasoapservice-v2?wsdl';

$username = 'username';
$password = 'password';

$client = new SoapClient($wsdl);

try {
    $token = $client->login($username, $password);
}
catch (SoapFault $fault) {
    echo "Error logging in to JIRA";
    print_r($fault);
}

$code = 'MYPROJECT'

$project = $client->getProjectByKey($token, $code);

$role = $client->getProjectRole($token, 10000); // 10000 is typically the "users" role

$users = $client->getProjectRoleActors($token, $role, $project);

print_r($users);


问:
Count How Many Letters In A List With 'n' Input
Basically i wanted to know how to count the number of letters in a list, for example lets say i add the word 'EXAMPLE' to a list and then lets say i wanna find out how many times the letter 'e' is used given e as the user input how would i write it so it says there are 2 e's in the word 'EXAMPLE'.

So far i got

```<code>WordList = []
print("1. Enter A Word")
print("2. Check Letter Or Vowel Times")

userInput = input("Please Choose An Option: ")
if userInput == "1":
    wordInput = input("Please Enter A Word: ")
    WordList.append(wordInput.lower())
</code>```

答:
I isolated your problem. Use collections' Counter for this:</p>

```<code>from collections import Counter

wordInput = input("Please Enter A Word: ").lower()
wordDict = Counter(wordInput) # converts to dictionary with counts

letterInput = input("Please Enter A Letter: ").lower()

print(wordDict.get(letterInput,0)) # return counts of letter (0 if not found)
</code>```

Body:
Basically i wanted to know how to count the number of letters in a list, for example lets say i add the word 'EXAMPLE' to a list and then lets say i wanna find out how many times the letter 'e' is used given e as the user input how would i write it so it says there are 2 e's in the word 'EXAMPLE'.

So far i got

WordList = []
print("1. Enter A Word")
print("2. Check Letter Or Vowel Times")

userInput = input("Please Choose An Option: ")
if userInput == "1":
    wordInput = input("Please Enter A Word: ")
    WordList.append(wordInput.lower())

Body:
I isolated your problem. Use collections' Counter for this:

from collections import Counter

wordInput = input("Please Enter A Word: ").lower()
wordDict = Counter(wordInput) # converts to dictionary with counts

letterInput = input("Please Enter A Letter: ").lower()

print(wordDict.get(letterInput,0)) # return counts of letter (0 if not found)


问:
Pycharm with Django throws ImportError: cannot import name 'unittest'
I am working through the Django tutorial, and am trying to get the test cases to run with PyCharm. I have encountered a problem however. When I run the command: app test

I am faced with this exception: test framework quit unexpectedly:

```<code>F:\programming\Python\python.exe "F:\programming\JetBrains\PyCharm 2017.2.4\helpers\pycharm\django_test_manage.py" test a F:\programming\Projects\pycharm\untitled
Testing started at 4:54 PM ...
Traceback (most recent call last):
  File "F:\programming\JetBrains\PyCharm 2017.2.4\helpers\pycharm\django_test_manage.py", line 157, in <module>
    utility.execute()
  File "F:\programming\JetBrains\PyCharm 2017.2.4\helpers\pycharm\django_test_manage.py", line 110, in execute
    from django_test_runner import is_nosetest
  File "F:\programming\JetBrains\PyCharm 2017.2.4\helpers\pycharm\django_test_runner.py", line 42, in <module>
    from django.utils import unittest
ImportError: cannot import name 'unittest'

Process finished with exit code 1
</code>```

Apparently, the django_test_manage.py file does not work. How can I fix this?
this happens even when the test.py class is empty. So it must be a problem with PyCharm then(?)
I am using PyCharm Pro 2017.2.4, Django 2.0 and Python 3.6
My run/debug configurations are just the basic, preset Django Settings that PyCharm does.

答:
django.utils.unittest was removed in Django 1.9 So I suspect you may be using an old version of the tutorial.

In pycharm are you using the django.tests.testcases run config? Better to use the Python unittest.TestCase as detailed here

edit: So in django_test_runner.py you have the following:

```<code>from django.test.testcases import TestCase
from django import VERSION

# See: https://docs.djangoproject.com/en/1.8/releases/1.7/#django-utils-unittest
# django.utils.unittest provided uniform access to the unittest2 library on all Python versions.
# Since unittest2 became the standard library's unittest module in Python 2.7,
# and Django 1.7 drops support for older Python versions, this module isn't useful anymore.
# It has been deprecated. Use unittest instead.
if VERSION >= (1,7):
  import unittest
else:
  from django.utils import unittest
</code>```

So it appears that the version of django that you are using in the intepreter for your test runconfig is < 1.7 (when django.utils.unittest was deprecated.) What is returned if you do from django import VERSION and print it in your interpreter?

Body:
I am working through the Django tutorial, and am trying to get the test cases to run with PyCharm. I have encountered a problem however. When I run the command: app test

I am faced with this exception: test framework quit unexpectedly:

F:\programming\Python\python.exe "F:\programming\JetBrains\PyCharm 2017.2.4\helpers\pycharm\django_test_manage.py" test a F:\programming\Projects\pycharm\untitled
Testing started at 4:54 PM ...
Traceback (most recent call last):
  File "F:\programming\JetBrains\PyCharm 2017.2.4\helpers\pycharm\django_test_manage.py", line 157, in <module>
    utility.execute()
  File "F:\programming\JetBrains\PyCharm 2017.2.4\helpers\pycharm\django_test_manage.py", line 110, in execute
    from django_test_runner import is_nosetest
  File "F:\programming\JetBrains\PyCharm 2017.2.4\helpers\pycharm\django_test_runner.py", line 42, in <module>
    from django.utils import unittest
ImportError: cannot import name 'unittest'

Process finished with exit code 1

Apparently, the django_test_manage.py file does not work. How can I fix this?
this happens even when the test.py class is empty. So it must be a problem with PyCharm then(?)
I am using PyCharm Pro 2017.2.4, Django 2.0 and Python 3.6
My run/debug configurations are just the basic, preset Django Settings that PyCharm does.

Body:
django.utils.unittest was removed in Django 1.9 So I suspect you may be using an old version of the tutorial.

In pycharm are you using the django.tests.testcases run config? Better to use the Python unittest.TestCase as detailed here

edit: So in django_test_runner.py you have the following:

from django.test.testcases import TestCase
from django import VERSION

# See: https://docs.djangoproject.com/en/1.8/releases/1.7/#django-utils-unittest
# django.utils.unittest provided uniform access to the unittest2 library on all Python versions.
# Since unittest2 became the standard library's unittest module in Python 2.7,
# and Django 1.7 drops support for older Python versions, this module isn't useful anymore.
# It has been deprecated. Use unittest instead.
if VERSION >= (1,7):
  import unittest
else:
  from django.utils import unittest

So it appears that the version of django that you are using in the intepreter for your test runconfig is < 1.7 (when django.utils.unittest was deprecated.) What is returned if you do from django import VERSION and print it in your interpreter?


问:
DataGridView Selected Cell border showing wrong cell
I currently am using a code to make a border for a selected cell.  Though I suspect with how I am implementing it I getting some visual problems.  For my application I have a dynamic number of tabs, each with its own DataGridView, so the following event is used by all grids:

```<code>    private void gridSelection_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
    {
        TabPage currentPage = tabs.SelectedTab;
        DataGridView currentGrid = currentPage.Controls[0] as DataGridView;
        if (currentGrid.Equals(sender))
        {
            if (e.ColumnIndex != -1 && e.RowIndex != -1 && currentGrid[e.ColumnIndex, e.RowIndex].Selected)
            {
                using (Pen borderPen = new Pen(Color.Black, 2))
                {
                    Rectangle rectDimensions = e.CellBounds;
                    rectDimensions.Width -= 2;
                    rectDimensions.Height -= 2;
                    rectDimensions.X = rectDimensions.Left + 1;
                    rectDimensions.Y = rectDimensions.Top + 1;

                    e.Graphics.DrawRectangle(borderPen, rectDimensions);

                    e.Handled = true;
                }

            }
        }
    }
</code>```

My issue came from changing tabs.  The selected cell on the tab that is selected still shows the cell from the previous tab.  The work around is that the user just needs to select a new cell and then everything returns to normal operation. (I would to show a visual but every cell is filled with very secret Intellectual Property for my company).

As can be seen in the code above I tried to make sure that the only grid firing off the event is the grid currently being displayed to the user. I even tried preventing the previous grid from firing the event with the tab_change event:

```<code>    private void tabChange(object sender, EventArgs e)
    {
        TabPage currentPage = tabs.SelectedTab;
        DataGridView currentGrid = currentPage.Controls[0] as DataGridView;
        currentGrid.CellPainting += new System.Windows.Forms.DataGridViewCellPaintingEventHandler(gridSelection_CellPainting);
        foreach (TabPage tab1 in tabs.TabPages)
        {
            if (!tab1.Equals(currentPage))
            {
                DataGridView otherGrid = operation.Controls[0] as DataGridView;
                otherGrid.CellPainting -= new System.Windows.Forms.DataGridViewCellPaintingEventHandler(gridSelection_CellPainting);
            }
        }
    }
</code>```

Sadly, I'm still having it where I switch tabs and the selected cell in the selected tab visually shows the previous tabs selected cell.

I also found I may be able to recreate the problem with just one grid.  When I click a column header and the rows are then ordered by that column (default functionality), I noticed that the selected cell remains constant.

For a visual.  If I had the following as a column

1

2

3

4

And I have the cell with the value 3 selected when I clicked to order the column I would get

4

3

3

1

And when I change which cell is selected, I would then have the correct order of

4

3

2

1

I suspect the issue is something to do with a nuance the DrawRectangle function that I don't know about.  Anyone else seen this or resolved yet?

Thanks

EDIT:

For the updated, cleaner code.  Tabchange is pretty much empty now, it has some code I haven't shown, because if I comment it out it has no affect on my issue.

For cell painting:

```<code>    private void gridSelection_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
    {
        TabPage currentPage = tabs.SelectedTab;
        DataGridView currentGrid = currentPage.Controls[0] as DataGridView;
        if (e.ColumnIndex != -1 && e.RowIndex != -1 && currentGrid[e.ColumnIndex, e.RowIndex].Selected)
        {
            using (Pen borderPen = new Pen(Color.Black, 2))
            {
                Rectangle rectDimensions = e.CellBounds;
                rectDimensions.Width -= 2;
                rectDimensions.Height -= 2;
                rectDimensions.X = rectDimensions.Left + 1;
                rectDimensions.Y = rectDimensions.Top + 1;

                e.Graphics.DrawRectangle(borderPen, rectDimensions);

                e.Handled = true;
            }

        }
    }
</code>```

I needed to keep the currentGrid code as I need to verify the cell is selected.  The code I took this from expected the event to be tied to one grid only which could be called easily and not an event that would be tied to a dynamic number of grids.

EDIT EDIT:

Image of cell showing visual error

I added an image that is cropped to hide IP content.  This is taken from a grid where the first column is blank, this after selecting a cell in a different tab that has different sizing.  As can be seen the selected cell on top has a border as intended but inside it is not blank but instead the image of another grid.

For issues inside the same grid here are some extra pictures:

Correct descending order

After column header clicked to be ascending order

After changing which cell is selected

答:
After some digging and experimenting, it appeared to me that whenever I used the graphics to paint a rectangle, the rectangle was cleanly painted each time, but the inside of the cell was just whatever was leftover from the last paint event for that cell.  It wasn't like it was doing the default paint of a cell and then painting a rectangle on top of it. i.e. I felt like I was overriding the normal paint event that would show a cell and it's values.

This would make sense, as I was overriding the default behavior to show the cell highlighted.  Which looking at my code, all it is doing is drawing a rectangle and should have noticed that it was not changing the color of the selected cell (default is blue). So my solution was simply to try and recreate the cell in it's entirety.

```<code>    private void gridSelection_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
    {
        TabPage currentPage = tabs.SelectedTab;
        DataGridView currentGrid = currentPage.Controls[0] as DataGridView;
        if (e.ColumnIndex != -1 && e.RowIndex != -1 && currentGrid[e.ColumnIndex, e.RowIndex].Selected)
        {
            using (Pen borderPen = new Pen(Color.Black, 2))
            {
                Brush backColorBrush = new SolidBrush(e.CellStyle.BackColor);
                // Erase the cell.
                e.Graphics.FillRectangle(backColorBrush, e.CellBounds);

                Rectangle rectDimensions = e.CellBounds;
                rectDimensions.Width -= 2;
                rectDimensions.Height -= 2;
                rectDimensions.X = rectDimensions.Left + 1;
                rectDimensions.Y = rectDimensions.Top + 1;

                e.Graphics.DrawRectangle(borderPen, rectDimensions);

                // Draw the text content of the cell, ignoring alignment.
                if (e.Value != null)
                {
                    Brush textColor = new SolidBrush(e.CellStyle.ForeColor);

                    e.Graphics.DrawString(e.Value.ToString(), e.CellStyle.Font,
                        textColor, e.CellBounds.X +1,
                        e.CellBounds.Y + 3, StringFormat.GenericDefault);
                }

                e.Handled = true;
            }

        }
    }
</code>```

A good eye will still see it is not a perfect recreation, I would have to work with the format and alignment more for that, but it's pretty darn good that it is not worth my time getting it perfect.

And of course credit where it is due, got most of that code from MSDN.

Surprised I haven't seen this linked as much when there are discussions about making borders or simply anything about modifying selected cells.

Body:
I currently am using a code to make a border for a selected cell.  Though I suspect with how I am implementing it I getting some visual problems.  For my application I have a dynamic number of tabs, each with its own DataGridView, so the following event is used by all grids:

    private void gridSelection_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
    {
        TabPage currentPage = tabs.SelectedTab;
        DataGridView currentGrid = currentPage.Controls[0] as DataGridView;
        if (currentGrid.Equals(sender))
        {
            if (e.ColumnIndex != -1 && e.RowIndex != -1 && currentGrid[e.ColumnIndex, e.RowIndex].Selected)
            {
                using (Pen borderPen = new Pen(Color.Black, 2))
                {
                    Rectangle rectDimensions = e.CellBounds;
                    rectDimensions.Width -= 2;
                    rectDimensions.Height -= 2;
                    rectDimensions.X = rectDimensions.Left + 1;
                    rectDimensions.Y = rectDimensions.Top + 1;

                    e.Graphics.DrawRectangle(borderPen, rectDimensions);

                    e.Handled = true;
                }

            }
        }
    }

My issue came from changing tabs.  The selected cell on the tab that is selected still shows the cell from the previous tab.  The work around is that the user just needs to select a new cell and then everything returns to normal operation. (I would to show a visual but every cell is filled with very secret Intellectual Property for my company).

As can be seen in the code above I tried to make sure that the only grid firing off the event is the grid currently being displayed to the user. I even tried preventing the previous grid from firing the event with the tab_change event:

    private void tabChange(object sender, EventArgs e)
    {
        TabPage currentPage = tabs.SelectedTab;
        DataGridView currentGrid = currentPage.Controls[0] as DataGridView;
        currentGrid.CellPainting += new System.Windows.Forms.DataGridViewCellPaintingEventHandler(gridSelection_CellPainting);
        foreach (TabPage tab1 in tabs.TabPages)
        {
            if (!tab1.Equals(currentPage))
            {
                DataGridView otherGrid = operation.Controls[0] as DataGridView;
                otherGrid.CellPainting -= new System.Windows.Forms.DataGridViewCellPaintingEventHandler(gridSelection_CellPainting);
            }
        }
    }

Sadly, I'm still having it where I switch tabs and the selected cell in the selected tab visually shows the previous tabs selected cell.

I also found I may be able to recreate the problem with just one grid.  When I click a column header and the rows are then ordered by that column (default functionality), I noticed that the selected cell remains constant.

For a visual.  If I had the following as a column

1

2

3

4

And I have the cell with the value 3 selected when I clicked to order the column I would get

4

3

3

1

And when I change which cell is selected, I would then have the correct order of

4

3

2

1

I suspect the issue is something to do with a nuance the DrawRectangle function that I don't know about.  Anyone else seen this or resolved yet?

Thanks

EDIT:

For the updated, cleaner code.  Tabchange is pretty much empty now, it has some code I haven't shown, because if I comment it out it has no affect on my issue.

For cell painting:

    private void gridSelection_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
    {
        TabPage currentPage = tabs.SelectedTab;
        DataGridView currentGrid = currentPage.Controls[0] as DataGridView;
        if (e.ColumnIndex != -1 && e.RowIndex != -1 && currentGrid[e.ColumnIndex, e.RowIndex].Selected)
        {
            using (Pen borderPen = new Pen(Color.Black, 2))
            {
                Rectangle rectDimensions = e.CellBounds;
                rectDimensions.Width -= 2;
                rectDimensions.Height -= 2;
                rectDimensions.X = rectDimensions.Left + 1;
                rectDimensions.Y = rectDimensions.Top + 1;

                e.Graphics.DrawRectangle(borderPen, rectDimensions);

                e.Handled = true;
            }

        }
    }

I needed to keep the currentGrid code as I need to verify the cell is selected.  The code I took this from expected the event to be tied to one grid only which could be called easily and not an event that would be tied to a dynamic number of grids.

EDIT EDIT:

Image of cell showing visual error

I added an image that is cropped to hide IP content.  This is taken from a grid where the first column is blank, this after selecting a cell in a different tab that has different sizing.  As can be seen the selected cell on top has a border as intended but inside it is not blank but instead the image of another grid.

For issues inside the same grid here are some extra pictures:

Correct descending order

After column header clicked to be ascending order

After changing which cell is selected

Body:
After some digging and experimenting, it appeared to me that whenever I used the graphics to paint a rectangle, the rectangle was cleanly painted each time, but the inside of the cell was just whatever was leftover from the last paint event for that cell.  It wasn't like it was doing the default paint of a cell and then painting a rectangle on top of it. i.e. I felt like I was overriding the normal paint event that would show a cell and it's values.

This would make sense, as I was overriding the default behavior to show the cell highlighted.  Which looking at my code, all it is doing is drawing a rectangle and should have noticed that it was not changing the color of the selected cell (default is blue). So my solution was simply to try and recreate the cell in it's entirety.

    private void gridSelection_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
    {
        TabPage currentPage = tabs.SelectedTab;
        DataGridView currentGrid = currentPage.Controls[0] as DataGridView;
        if (e.ColumnIndex != -1 && e.RowIndex != -1 && currentGrid[e.ColumnIndex, e.RowIndex].Selected)
        {
            using (Pen borderPen = new Pen(Color.Black, 2))
            {
                Brush backColorBrush = new SolidBrush(e.CellStyle.BackColor);
                // Erase the cell.
                e.Graphics.FillRectangle(backColorBrush, e.CellBounds);

                Rectangle rectDimensions = e.CellBounds;
                rectDimensions.Width -= 2;
                rectDimensions.Height -= 2;
                rectDimensions.X = rectDimensions.Left + 1;
                rectDimensions.Y = rectDimensions.Top + 1;

                e.Graphics.DrawRectangle(borderPen, rectDimensions);

                // Draw the text content of the cell, ignoring alignment.
                if (e.Value != null)
                {
                    Brush textColor = new SolidBrush(e.CellStyle.ForeColor);

                    e.Graphics.DrawString(e.Value.ToString(), e.CellStyle.Font,
                        textColor, e.CellBounds.X +1,
                        e.CellBounds.Y + 3, StringFormat.GenericDefault);
                }

                e.Handled = true;
            }

        }
    }

A good eye will still see it is not a perfect recreation, I would have to work with the format and alignment more for that, but it's pretty darn good that it is not worth my time getting it perfect.

And of course credit where it is due, got most of that code from MSDN.

Surprised I haven't seen this linked as much when there are discussions about making borders or simply anything about modifying selected cells.


问:
Android Studio 3.0: Unable to delete file
Android Studio 3.0

```<code>classpath 'com.android.tools.build:gradle:3.0.0'
</code>```

Sometimes when I try to start app I get the next error:

```<code>Error:java.io.IOException: Unable to delete file: myproject\common\build\intermediates\intermediate-jars\debug\classes.jar
> Unable to delete file: myproejct\common\build\intermediates\intermediate-jars\debug\classes.jar
</code>```

The proccess java.exe lock this. Why?

答:
Try to disable the Instant Run

Preferences > Build, Execution, Deployment > Instant Run

Body:
Android Studio 3.0

classpath 'com.android.tools.build:gradle:3.0.0'

Sometimes when I try to start app I get the next error:

Error:java.io.IOException: Unable to delete file: myproject\common\build\intermediates\intermediate-jars\debug\classes.jar
> Unable to delete file: myproejct\common\build\intermediates\intermediate-jars\debug\classes.jar

The proccess java.exe lock this. Why?


问:
npm doesn't work after 'npm install'

I installed node.js + npm from https://nodejs.org/en/
 and created a folder for project and cd into it (OS: Windows 10). When i try

```<code>C:\nodejs\demo>npm install express@3.5.0
</code>```

npm starts to delete the all standart packages and after the process of installation I see that it deleted 460 packages and installed 1-express (express is just an example, the same thing happens with any package I tried to install).

```<code>npm WARN saveError ENOENT: no such file or directory, open 'C:\nodejs\package.json'
npm WARN enoent ENOENT: no such file or directory, open 'C:\nodejs\package.json'
npm WARN nodejs No description
npm WARN nodejs No repository field.
npm WARN nodejs No README data
npm WARN nodejs No license field.

+ express@3.5.0
removed 460 packages and updated 1 package in 8.63s
</code>```

And there npm stops working, if I try npm -v I see the following:

```<code>module.js:538
    throw err;
    ^

Error: Cannot find module 'C:\nodejs\node_modules\npm\bin\npm-cli.js'
    at Function.Module._resolveFilename (module.js:536:15)
    at Function.Module._load (module.js:466:25)
    at Function.Module.runMain (module.js:676:10)
    at startup (bootstrap_node.js:187:16)
    at bootstrap_node.js:608:3
module.js:538
    throw err;
    ^

Error: Cannot find module 'C:\nodejs\node_modules\npm\bin\npm-cli.js'
    at Function.Module._resolveFilename (module.js:536:15)
    at Function.Module._load (module.js:466:25)
    at Function.Module.runMain (module.js:676:10)
    at startup (bootstrap_node.js:187:16)
    at bootstrap_node.js:608:3
</code>```

I don't know if it's important, but after the installation of node.js I had to add it into PATH variable by myself.

Could someone explain me what I did wrong or how I can fix this, please?

答:
hey i got the solution..

In Environmental variable there are two variable so in user variable "Path" should  consist C:\Users\username\AppData\Roaming\npm

And in System variable "Path" should consist  C:\Program Files\nodejs\

Title: npm doesn't work after 'npm install'

Body:
I installed node.js + npm from https://nodejs.org/en/
 and created a folder for project and cd into it (OS: Windows 10). When i try

C:\nodejs\demo>npm install express@3.5.0

npm starts to delete the all standart packages and after the process of installation I see that it deleted 460 packages and installed 1-express (express is just an example, the same thing happens with any package I tried to install).

npm WARN saveError ENOENT: no such file or directory, open 'C:\nodejs\package.json'
npm WARN enoent ENOENT: no such file or directory, open 'C:\nodejs\package.json'
npm WARN nodejs No description
npm WARN nodejs No repository field.
npm WARN nodejs No README data
npm WARN nodejs No license field.

+ express@3.5.0
removed 460 packages and updated 1 package in 8.63s

And there npm stops working, if I try npm -v I see the following:

module.js:538
    throw err;
    ^

Error: Cannot find module 'C:\nodejs\node_modules\npm\bin\npm-cli.js'
    at Function.Module._resolveFilename (module.js:536:15)
    at Function.Module._load (module.js:466:25)
    at Function.Module.runMain (module.js:676:10)
    at startup (bootstrap_node.js:187:16)
    at bootstrap_node.js:608:3
module.js:538
    throw err;
    ^

Error: Cannot find module 'C:\nodejs\node_modules\npm\bin\npm-cli.js'
    at Function.Module._resolveFilename (module.js:536:15)
    at Function.Module._load (module.js:466:25)
    at Function.Module.runMain (module.js:676:10)
    at startup (bootstrap_node.js:187:16)
    at bootstrap_node.js:608:3

I don't know if it's important, but after the installation of node.js I had to add it into PATH variable by myself.

Could someone explain me what I did wrong or how I can fix this, please?


问:
MaxActive database connection parameter doesn't work
I have a problem with datasource configuration.

I have a Tomcat 7 with Java 7 and a Quartz web application.
This application has a datasource configured:

```<code><Resource
   auth="Container"
   driverClassName="com.mysql.jdbc.Driver"
   factory="org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory"
   logAbandoned="true"
   maxActive="3"
   maxIdle="1"
   maxWait="10000"
   name="jdbc/name"
   password="XXXXXX"
   removeAbandoned="true"
   removeAbandonedTimeout="120"
   type="javax.sql.DataSource"
   url="jdbc:mysql://xxxxxx:3306/xxxxx?autoReconnect=true&zeroDateTimeBehavior=convertToNull&rewriteBatchedStatements=true"
   username="usr"
   validationQuery="SELECT 1" />
</code>```

With maxActive = 3 I expected to see no more than 3 connection opened. Instead of this, I see a new connection opened every time a Quartz Job starts, untill 8 connection (don't know if this is the default limit).

So it seems this parameter is not considered, but other yes, because the connection to database is correct so username, password etc... are ok.

Can you help me please?

thanks

答:
The problem is, that you use wrong attribute to set max connections, you should use maxTotal instead of maxActive.

For more information see BasicDataSource Configuration Parameters

Body:
I have a problem with datasource configuration.

I have a Tomcat 7 with Java 7 and a Quartz web application.
This application has a datasource configured:

<Resource
   auth="Container"
   driverClassName="com.mysql.jdbc.Driver"
   factory="org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory"
   logAbandoned="true"
   maxActive="3"
   maxIdle="1"
   maxWait="10000"
   name="jdbc/name"
   password="XXXXXX"
   removeAbandoned="true"
   removeAbandonedTimeout="120"
   type="javax.sql.DataSource"
   url="jdbc:mysql://xxxxxx:3306/xxxxx?autoReconnect=true&zeroDateTimeBehavior=convertToNull&rewriteBatchedStatements=true"
   username="usr"
   validationQuery="SELECT 1" />

With maxActive = 3 I expected to see no more than 3 connection opened. Instead of this, I see a new connection opened every time a Quartz Job starts, untill 8 connection (don't know if this is the default limit).

So it seems this parameter is not considered, but other yes, because the connection to database is correct so username, password etc... are ok.

Can you help me please?

thanks