问:
Reference to range using embeded variable
I'm having an issue with referring to multiple ranges using for loop.
I created a set of ranges using standardized names like range_[number].
Unfortunately when i try to refer to them I constantly get errors or empty ranges.

```<code>Sub add_new_country()

'count initial number of countries
n = WorksheetFunction.CountA(Range("countries_list"))
'name of last country
last_country = Range("countries_list").Cells(n).Value

range_1 = ActiveWorkbook.Sheets("Countries").Columns(5).Cells
range_2 = ActiveWorkbook.Sheets("Operations").Columns(2).Cells

On Error Resume Next

For i = 1 To 2
    Set active_range = Range("range_" & i)
    For Each c In active_range
        If c.Value = last_country Then
            c.Offset(1).EntireRow.Insert
            c.EntireRow.Cells.Copy
            c.Offset(1).EntireRow.Cells.PasteSpecial Paste:=xlPasteFormats
            c.Offset(1).EntireRow.Cells.PasteSpecial Paste:=xlPasteFormulas
            c.Offset(1).EntireRow.SpecialCells(xlCellTypeConstants).ClearContents
        End If
    Next c
Next i

End Sub
</code>```

Any ideas how to solve this?

答:
you can't refer like you're trying to do

better use an array of ranges

```<code>Dim ranges(1 To 2) As Range
Set ranges(1) = ActiveWorkbook.Sheets("Countries").Columns(5).Cells
Set ranges(2) = ActiveWorkbook.Sheets("Operations").Columns(2).Cells

On Error Resume Next

For i = 1 To 2
    Set active_range = ranges(i)
</code>```

Body:
I'm having an issue with referring to multiple ranges using for loop.
I created a set of ranges using standardized names like range_[number].
Unfortunately when i try to refer to them I constantly get errors or empty ranges.

Sub add_new_country()

'count initial number of countries
n = WorksheetFunction.CountA(Range("countries_list"))
'name of last country
last_country = Range("countries_list").Cells(n).Value

range_1 = ActiveWorkbook.Sheets("Countries").Columns(5).Cells
range_2 = ActiveWorkbook.Sheets("Operations").Columns(2).Cells

On Error Resume Next

For i = 1 To 2
    Set active_range = Range("range_" & i)
    For Each c In active_range
        If c.Value = last_country Then
            c.Offset(1).EntireRow.Insert
            c.EntireRow.Cells.Copy
            c.Offset(1).EntireRow.Cells.PasteSpecial Paste:=xlPasteFormats
            c.Offset(1).EntireRow.Cells.PasteSpecial Paste:=xlPasteFormulas
            c.Offset(1).EntireRow.SpecialCells(xlCellTypeConstants).ClearContents
        End If
    Next c
Next i

End Sub

Any ideas how to solve this?

Body:
you can't refer like you're trying to do

better use an array of ranges

Dim ranges(1 To 2) As Range
Set ranges(1) = ActiveWorkbook.Sheets("Countries").Columns(5).Cells
Set ranges(2) = ActiveWorkbook.Sheets("Operations").Columns(2).Cells

On Error Resume Next

For i = 1 To 2
    Set active_range = ranges(i)


来源: stackexchange

问:
Rails: Controller code out of control
First off, I must apologize for the punny title.

With that out of the way, I'm new to RoR and I am working on a small project that is slowly growing in size. One of the controllers is now a mess of logic that I would like to refactor it.

What I'm seeing from a multitude of questions/answers out there on this topic is mostly fragmented information on what I think is best practice. I'm having a hard time seeing the big picture. The sites for "where to put code?" have a high level information and miss the nitty-gritty.

Here's the question:

What's the best practice for refactoring code out of Controllers? (Locations, type of code)

Background: My app does not use a database, the code in the controller is mostly HTTP calls to external APIs based on params from a form, and a few lines of logic for creating arrays with fetched data for the view to consume. Some of these API calls depend on previously fetched info.

Thank you very much in advance!

MP

答: I couldn't find the link before posting this answer, but something that will take you quite a ways is utilizing the helper files. This will get a lot of code out of your controllers and views.</p>

ContentLicense: CC BY-SA 3.0

Title: Rails: Controller code out of control


问:
Concentric Box colliders in Unity
I have two concentric Box Colliders on same GameObject. Outer Box Collider rotates the object (on swiping the screen) and inner Box Collider plays animation when we touch the screen.

But when ray goes from my mobile screen to outer Collider it destroys and does not pass through that collider.

Is there any way to do it?

答:
Take a look at Physics.RayCastAll. With RayCastAll your Ray won't return just the first collision but an array of all collisions.

```<code>RayCastHit[] hits;
Ray ray = camera.ScreenPointToRay(Input.mousePosition);
hits = Physics.RaycastAll(ray);

// If you have objects behind your object then sort the hit array by distance:
// hits = hits.OrderBy(l => l.distance).ToArray();

for(int i = 0; i < hits.Length; i++)
{
    RaycastHit hit = hits[i];
    // From here you can use a tag approach similar to what Flaming Zombie posted to check whether the collision object supports swipes or touches.
    // Once you find the first valid object then you can perform your action and break out of this loop.
}
</code>```

However, there are a couple of things to note with this approach:

You will need to loop through each collision.

You will need to determine whether or not the user swiped or touched (you probably already have this down)

Colliders behind the GameObject will also return collisions.

If there is not a specific reason you are using two colliders then I would do what Flaming Zombie suggested and use a single collider. Here is a simple implementation:

Component on collider:

```<code>public class ExampleComponent : MonoBehaviour
{
    public void OnInteract(bool isSwipe)
    {
        if (isSwipe)
        {
            //Rotate
        }
        else
        {
            //Animate
        }
    }
}
</code>```

Raycast logic:

```<code>RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{
    ExampleComponent c = hit.transform.GetComponent<ExampleComponent>()
    if(c != null)
    {
        c.OnInteract(isSwipe); // You'll need to implement isSwipe
    }
}
</code>```

Title: Concentric Box colliders in Unity

Body:
Take a look at Physics.RayCastAll. With RayCastAll your Ray won't return just the first collision but an array of all collisions.

RayCastHit[] hits;
Ray ray = camera.ScreenPointToRay(Input.mousePosition);
hits = Physics.RaycastAll(ray);

// If you have objects behind your object then sort the hit array by distance:
// hits = hits.OrderBy(l => l.distance).ToArray();

for(int i = 0; i < hits.Length; i++)
{
    RaycastHit hit = hits[i];
    // From here you can use a tag approach similar to what Flaming Zombie posted to check whether the collision object supports swipes or touches.
    // Once you find the first valid object then you can perform your action and break out of this loop.
}

However, there are a couple of things to note with this approach:

You will need to loop through each collision.

You will need to determine whether or not the user swiped or touched (you probably already have this down)

Colliders behind the GameObject will also return collisions.

If there is not a specific reason you are using two colliders then I would do what Flaming Zombie suggested and use a single collider. Here is a simple implementation:

Component on collider:

public class ExampleComponent : MonoBehaviour
{
    public void OnInteract(bool isSwipe)
    {
        if (isSwipe)
        {
            //Rotate
        }
        else
        {
            //Animate
        }
    }
}

Raycast logic:

RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{
    ExampleComponent c = hit.transform.GetComponent<ExampleComponent>()
    if(c != null)
    {
        c.OnInteract(isSwipe); // You'll need to implement isSwipe
    }
}


问:
Check for changes to a SQL Server database?
is there a way to get database checksum using system SQL Server functions?

Or other way to quickly figure out if there are any changes in database?

I do not want to use any specific database analysis software for this.

I look for any changes in database (schema/object changes, data changes).

I use SQL Server 2008.

答:
You might find the information in the transaction log...

Use

```<code>DBCC LOG(<database name>[,{0|1|2|3|4}])
</code>```

0 - Basic Log Information (default)

1 - Lengthy Info

2 - Very Length Info

3 - Detailed

4 - Full

Example:

```<code>DBCC log (MY_DB, 4)
</code>```

The result is somewhat cryptic and is better used with a third-party tool thought...

Credits: http://www.mssqlcity.com/Articles/KnowHow/ViewLog.htm

EDIT:

You might try

```<code>Select * from ::fn_dblog(null, null)
</code>```

This page contains some usefull information about the results returned by the functions...
http://www.novicksoftware.com/udfofweek/Vol1/T-SQL-UDF-Volume-1-Number-27-fn_dblog.htm

Keep in mind, that those procedures are not for the public and therefore not easy to understand. The other possibility is to add triggers on all tables. But that is on the otherhand a lot of work.

Body:
You might find the information in the transaction log...

Use

DBCC LOG(<database name>[,{0|1|2|3|4}])

0 - Basic Log Information (default)

1 - Lengthy Info

2 - Very Length Info

3 - Detailed

4 - Full

Example:

DBCC log (MY_DB, 4)

The result is somewhat cryptic and is better used with a third-party tool thought...

Credits: http://www.mssqlcity.com/Articles/KnowHow/ViewLog.htm

EDIT:

You might try

Select * from ::fn_dblog(null, null)

This page contains some usefull information about the results returned by the functions...
http://www.novicksoftware.com/udfofweek/Vol1/T-SQL-UDF-Volume-1-Number-27-fn_dblog.htm

Keep in mind, that those procedures are not for the public and therefore not easy to understand. The other possibility is to add triggers on all tables. But that is on the otherhand a lot of work.

ContentLicense: CC BY-SA 2.5


问:
How does 'parseInt(String, radix)' work?
I understand that the parseInt method is used to convert strings to int, but I do not know how. I understand that if you say:

```<code>System.out.println(Integer.parseInt("52", 10));
</code>```

will give you 52 in base 10. What I am unaware of is if you say replace base 10 with 15, how does it exactly compute. From some research, I found people saying that you must use ASCII values. If it helps, I am trying to be able to solve this on paper solely, without the work of any more code.

答:
You're right that the number denotes the base. You are not right that

Integer.parseInt("52", 10) will give you 52 in base 10.

This will in fact parse the number 52 as if it were in base 10. 52 could be base 6 for all we know.

For example:

```<code>Integer.parseInt("101", 2);
</code>```

Is saying parse the binary (base 2) number one-zero-one. It is not saying parse one hundred and one into binary. This will return the base 10 number 5.

Any number which is returned is a standard integer which if you try to print it will be in base 10.

Worth noting that if you try and parse a number which can not possibly exist in that base, for example:

```<code>Integer.parseInt("599", 2);
</code>```

then you will get an exception.

Body:
I understand that the parseInt method is used to convert strings to int, but I do not know how. I understand that if you say:

System.out.println(Integer.parseInt("52", 10));

will give you 52 in base 10. What I am unaware of is if you say replace base 10 with 15, how does it exactly compute. From some research, I found people saying that you must use ASCII values. If it helps, I am trying to be able to solve this on paper solely, without the work of any more code.

Body:
You're right that the number denotes the base. You are not right that

Integer.parseInt("52", 10) will give you 52 in base 10.

This will in fact parse the number 52 as if it were in base 10. 52 could be base 6 for all we know.

For example:

Integer.parseInt("101", 2);

Is saying parse the binary (base 2) number one-zero-one. It is not saying parse one hundred and one into binary. This will return the base 10 number 5.

Any number which is returned is a standard integer which if you try to print it will be in base 10.

Worth noting that if you try and parse a number which can not possibly exist in that base, for example:

Integer.parseInt("599", 2);

then you will get an exception.


问:
Control-Alt-Delete from python or command line
I've done some research but I would like to be able to call control-alt-delete from python. If that is not possible is it possible to call it from command line because then I could just use that command in python because I can call command lines in python. If someone could point me in the right direction that would be great. this is for a task manager written with wxPython.
edit:
im trying to launch the windows security and from a user answer i tried </p>

```<code>import win32com.client

shell = win32com.client.Dispatch("WScript.Shell")
shell.SendKeys("{CONTROL}{ALT}{DELETE}")
</code>```

<p>and i get this error </p>

```<code>Traceback (most recent call last):
    File "C:/Python27/tescontrol.py", line 4, in <module>
      shell.SendKeys("{CONTROL}{ALT}{DELETE}")
    File "<COMObject WScript.Shell>", line 2, in SendKeys
com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147024809), None)
</code>```

答:
You can use vncdotool library
At:

lib

And use vncdotool by:

```<code>os.system("vncdotool key ctrl-alt-del")
</code>```

Body:
I've done some research but I would like to be able to call control-alt-delete from python. If that is not possible is it possible to call it from command line because then I could just use that command in python because I can call command lines in python. If someone could point me in the right direction that would be great. this is for a task manager written with wxPython.
edit:
im trying to launch the windows security and from a user answer i tried

import win32com.client

shell = win32com.client.Dispatch("WScript.Shell")
shell.SendKeys("{CONTROL}{ALT}{DELETE}")

and i get this error

Traceback (most recent call last):
    File "C:/Python27/tescontrol.py", line 4, in <module>
      shell.SendKeys("{CONTROL}{ALT}{DELETE}")
    File "<COMObject WScript.Shell>", line 2, in SendKeys
com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147024809), None)

Body:
You can use vncdotool library
At:

lib

And use vncdotool by:

os.system("vncdotool key ctrl-alt-del")


问:
localization using resx files generates MissingManifestResourceException
It is my first effort with localization and the more I read about it the more confused I become. To be honest, I am just looking for an answer at this point. So here is the error I am getting:

Unhandled Exception:System.Resources.MissingManifestResourceException: Could not find any resources appropriate for the specified culture or the neutral culture.  Make sure "MeetnGreetSf.Resources.AppResources.resources" was correctly embedded or linked into assembly "MeetnGreetSf" at compile time, or that all the satellite assemblies required are loadable and fully signed. occurred

And here is the class:

```<code>public class TranslateHelper
{
    readonly CultureInfo ci;
    private string ResourceId = "MeetnGreetSf.Resources.AppResources";
    private ResourceManager resmgr;
    private CultureInfo cui = new CultureInfo("es-ES");
    public TranslateHelper()
    {
        //ResourceId += "." + cui.Name;
        resmgr = new ResourceManager(ResourceId, typeof(AppResource).GetTypeInfo().Assembly);

    }

    public string Translate(string Name)
    {
        var translation = resmgr.GetString(Name, ci);
        return translation;
    }

}
</code>```

I think I am close for some reason it is appending .resources to the file instead of .resx?

Thanks in advance for any help.

Forgot to include how the translate class is being used.

```<code>public Colors()
    {
        colorInfo = new ObservableCollection<ColorType>();
        t = new TranslateHelper();
        this.GenerateColors();

    }

    private void GenerateColors()
    {
        colorInfo.Add(new ColorType(t.Translate("Aqua"), Color.Aqua));
        colorInfo.Add(new ColorType(t.Translate("Black"), Color.Black));
        colorInfo.Add(new ColorType(t.Translate("Blue"), Color.Blue));
        colorInfo.Add(new ColorType(t.Translate("Gray"), Color.Gray));
        colorInfo.Add(new ColorType(t.Translate("Green"), Color.Green));
        colorInfo.Add(new ColorType(t.Translate("Lime"), Color.Lime));
        colorInfo.Add(new ColorType(t.Translate("Maroon"), Color.Maroon));
        colorInfo.Add(new ColorType(t.Translate("Navy"), Color.Navy));
        colorInfo.Add(new ColorType(t.Translate("Olive"), Color.Olive));
        colorInfo.Add(new ColorType(t.Translate("Purple"), Color.Purple));
        colorInfo.Add(new ColorType(t.Translate("Red"), Color.Red));
        colorInfo.Add(new ColorType(t.Translate("Silver"), Color.Silver));
        colorInfo.Add(new ColorType(t.Translate("Teal"), Color.Teal));
        colorInfo.Add(new ColorType(t.Translate("White"), Color.White));
        colorInfo.Add(new ColorType(t.Translate("Yellow"), Color.Yellow));
    }
}
</code>```

答:
Note that I'm the author of a commercial localization tool for Visual Studio (in the interest of full disclosure). You should investigate "System.Threading.Thread.CurrentThread.CurrentUICulture" which is normally what all translation in .NET revolves around (for handling localized resources). The mechanics of how you deal with it however can vary depending on the type of project. The way you're doing it now isn't normally required. It's normally much easier than that (no dedicated classes are necessary). Here's the basic process for a simple console app for instance (again, things can vary depending on your project type).

Create a new console app called "TestApp"

Open the project's properties (right-click it in Solution Explorer for instance and choose "Properties"), and click the "Resources" tab in the properties window. Now click the button seen in the middle of the screen that says "This project does not contain a default resource file. Click here to create one". This will add "Resources.resx" to your solution (under the "Properties" folder in Solution Explorer) and it will be automatically opened in the ".resx" editor.

Add a single string called "MyString" in the ".resx" editor. Assign it "This is my default string" (or whatever).

In your code, where you want to use the string, add a "using TestApp.Properties" statement (read on). You can now access the string via the static property "Resources.MyString". This is declared in "Resources.Designer.cs" which is a "code-behind" file automatically created by VS in step 2 above (i.e., it's a child of "Resources.resx" in Solution Explorer). VS looks after this file for you (adding a new static property to the "TestApp.Properties" namespace for each string you add in 3 above). Note that these strings are referred to as "strongly typed resources".

Add a new ".resx" file to your project and call it "Resources.es.resx". This will contain strings in Spanish. Once created, drag it in Solution Explorer to the "Properties" folder (so it's now in the same folder as "Resources.resx" - all localized ".resx" files must be in the same folder as "Resources.resx").

Double click "Resources.es.resx" and add "MyString" to it. Set its text to "This is my Spanish string".

When you want to change the language in your code to pick up the Spanish version of your string, simply set the "System.Threading.Thread.CurrentThread.CurrentUICulture" property in your code to "es". Now whenever you reference "Resources.MyString", the Spanish version of that string will be returned instead (automatically). IOW, it follows whatever "System.Threading.Thread.CurrentThread.CurrentUICulture" is currently set to. You'ld therefore normally change the latter property based on your app's requirements (say, when a user clicks their desired language from your GUI), and all your strongly-typed resources (usually strings only) will automatically adopt the new language.

How does this work? The passage below is an excerpt from something I once sent to a customer of mine. It should be enough to get you started (note that references to "YourApp" below will change to "TestApp" for the above example):

"You should investigate "Strongly Typed" resources instead of the
  way you're handling things. Also investigate satellite assemblies and
  the "System.Threading.Thread.CurrentThread.CurrentUICulture" property
  (there's also the "CurrentCulture" property you should look at but
  that doesn't impact your resources, which are always controlled by the
  "CurrentUICulture" property). Note that the "CurrentUICulture"
  property is set to the system's current language normally (when your
  app starts). When you access any resource in your program, such as
  "Resources.MyString" (this is an example of a strongly-typed
  resource which you'll need to review), the system will look for
  "MyString" based on the "CurrentUICulture" property. If that property
  is currently set to the system default (it normally will be unless
  you change it in code), then you'll get the version of "MyString" back
  from your app's main assembly (the default language resources are
  stored there). If you change "CurrentUICulture" in code to "es"
  however (for Spanish), then the system will look for "MyString" in the
  file "es\YourApp.resources.dll" (off your program's root folder).
  If it doesn't find it there (the folder may not exist if you don't
  support Spanish), or more realistically, "MyString" simply has no
  translation in that (Spanish) DLL, then it will fallback to your app's
  main assembly, so you'll get the default language string again.
  Again, this is the short-story, but it covers the basic details. It's
  traditionally known as the "hub and spoke" model in MSFT's
  documentation (though other terms are sometimes used), and it relies
  on the "fallback" process mentioned earlier. For instance, if you set
  "System.Threading.Thread.CurrentThread.CurrentUICulture" to "es-AR"
  which is Spanish as spoken in Argentina, then the program will look
  for "MyString" in "es-AR\YourApp.resources.dll". If not found there
  (you don't support "es-AR" for instance, so there is no such folder,
  or the string simply isn't there), then it will "fallback" to the
  "es" folder instead (known as the neutral culture, in this case just
  plain Spanish which the system assumes is the next best thing). If not
  found there (in "es\YourApp.resources.dll"), then again, the system
  will fallback to the default language strings embedded in your main
  assembly. Research all of this and you'll find that handling your
  strings is a breeze compared to how you're now doing it. Everything
  is handled for you automatically including the fallback situation
  (just by adjusting the
  "System.Threading.Thread.CurrentThread.CurrentUICulture" property -
  all references to any strongly typed resources such as
  "Resources.MyString" will then appear in whatever language that
  property is currently set to). I hope that helps.

Body:
It is my first effort with localization and the more I read about it the more confused I become. To be honest, I am just looking for an answer at this point. So here is the error I am getting:

Unhandled Exception:System.Resources.MissingManifestResourceException: Could not find any resources appropriate for the specified culture or the neutral culture.  Make sure "MeetnGreetSf.Resources.AppResources.resources" was correctly embedded or linked into assembly "MeetnGreetSf" at compile time, or that all the satellite assemblies required are loadable and fully signed. occurred

And here is the class:

public class TranslateHelper
{
    readonly CultureInfo ci;
    private string ResourceId = "MeetnGreetSf.Resources.AppResources";
    private ResourceManager resmgr;
    private CultureInfo cui = new CultureInfo("es-ES");
    public TranslateHelper()
    {
        //ResourceId += "." + cui.Name;
        resmgr = new ResourceManager(ResourceId, typeof(AppResource).GetTypeInfo().Assembly);

    }

    public string Translate(string Name)
    {
        var translation = resmgr.GetString(Name, ci);
        return translation;
    }

}

I think I am close for some reason it is appending .resources to the file instead of .resx?

Thanks in advance for any help.

Forgot to include how the translate class is being used.

public Colors()
    {
        colorInfo = new ObservableCollection<ColorType>();
        t = new TranslateHelper();
        this.GenerateColors();

    }

    private void GenerateColors()
    {
        colorInfo.Add(new ColorType(t.Translate("Aqua"), Color.Aqua));
        colorInfo.Add(new ColorType(t.Translate("Black"), Color.Black));
        colorInfo.Add(new ColorType(t.Translate("Blue"), Color.Blue));
        colorInfo.Add(new ColorType(t.Translate("Gray"), Color.Gray));
        colorInfo.Add(new ColorType(t.Translate("Green"), Color.Green));
        colorInfo.Add(new ColorType(t.Translate("Lime"), Color.Lime));
        colorInfo.Add(new ColorType(t.Translate("Maroon"), Color.Maroon));
        colorInfo.Add(new ColorType(t.Translate("Navy"), Color.Navy));
        colorInfo.Add(new ColorType(t.Translate("Olive"), Color.Olive));
        colorInfo.Add(new ColorType(t.Translate("Purple"), Color.Purple));
        colorInfo.Add(new ColorType(t.Translate("Red"), Color.Red));
        colorInfo.Add(new ColorType(t.Translate("Silver"), Color.Silver));
        colorInfo.Add(new ColorType(t.Translate("Teal"), Color.Teal));
        colorInfo.Add(new ColorType(t.Translate("White"), Color.White));
        colorInfo.Add(new ColorType(t.Translate("Yellow"), Color.Yellow));
    }
}


问:
How to create word docs programmatically from a template
I am trying to create about 600 reports in Microsoft office Word. The documents are populated with data from a database, and images found on a local drive.
I have figured out, that I might create a Word Template project in visual studio 2010, and program the template, so that when you enter a single value (id-number), it automatically fills out the entire document.

I am quite confident that this is possible. the only problem is. How do I loop through all entries in the database, open a new document based on the template and set the id-value?

```<code>for(int i = 0; i < idnumbers.Count(); i++)
{
     Word.Application app = new Word.Application();
     Word.Document doc = app.Documents.Add(@"C:\..\WordGenerator\bin\Debug\WordTemplate.dotx");
     //input the id-number below: HOW??

     doc.SaveAs(FileName: @"c:\temp\test.docx");
}
</code>```

The application is supposed to run only once, generating the reports, and it doesn´t have to be fast. It just has to be easy to develop.

The problem here is, that it seems that the DocumentBase object is not accessible outside the Word project. The substitute Microsoft.Office.Interop.Word.Document does not have functionality like SelectContentControlsByTitle that allows me to find and set my ContentControls. And that is exactly what I need to do..

EDIT: This is what my code looks like now to insert the text into my field:

```<code>Word.Application app = new Word.Application();

Word.Document doc = app.Documents.Add(@"C:\..\test.dotx");

foreach (Word.ContentControl cc in doc.SelectContentControlsByTitle("MyCCTitle"))
{
    cc.Range.Text += "1234";
}

doc.SaveAs(FileName: @"c:\temp\test.docx");
</code>```

Then an eventhandler on my template on BeforeSave fills out the document based on the text in MyCCTitle-titled object.

答:
Maybe you should be looking at Microsoft.Office.Tools.Word.Document?

Document.SelectContentControlsByTitle

ContentLicense: CC BY-SA 4.0

Body:
I am trying to create about 600 reports in Microsoft office Word. The documents are populated with data from a database, and images found on a local drive.
I have figured out, that I might create a Word Template project in visual studio 2010, and program the template, so that when you enter a single value (id-number), it automatically fills out the entire document.

I am quite confident that this is possible. the only problem is. How do I loop through all entries in the database, open a new document based on the template and set the id-value?

for(int i = 0; i < idnumbers.Count(); i++)
{
     Word.Application app = new Word.Application();
     Word.Document doc = app.Documents.Add(@"C:\..\WordGenerator\bin\Debug\WordTemplate.dotx");
     //input the id-number below: HOW??

     doc.SaveAs(FileName: @"c:\temp\test.docx");
}

The application is supposed to run only once, generating the reports, and it doesn´t have to be fast. It just has to be easy to develop.

The problem here is, that it seems that the DocumentBase object is not accessible outside the Word project. The substitute Microsoft.Office.Interop.Word.Document does not have functionality like SelectContentControlsByTitle that allows me to find and set my ContentControls. And that is exactly what I need to do..

EDIT: This is what my code looks like now to insert the text into my field:

Word.Application app = new Word.Application();

Word.Document doc = app.Documents.Add(@"C:\..\test.dotx");

foreach (Word.ContentControl cc in doc.SelectContentControlsByTitle("MyCCTitle"))
{
    cc.Range.Text += "1234";
}

doc.SaveAs(FileName: @"c:\temp\test.docx");

Then an eventhandler on my template on BeforeSave fills out the document based on the text in MyCCTitle-titled object.


问:
jQuery getJSON function not returning anything
I have this code:

```<code>$.getJSON('data.json', function (data) {
    console.log(data);
});
</code>```

And this is the data.json file:

```<code>{
  "Sameer": {
    "Phone": "0123456789",
  },
  "Mona": {
    "Phone": "0123456789",
  },
}
</code>```

But the console.log(data) not returning anything, Not even an error I don't know what is wrong with my code.

I tried to use $.ajax() function instead but no luck. And when I change my data.json file to something random like: data.asd I get an error that saying the file data.asd not found!

答:
There are syntax errors on your JSON (commas), this is the right version:

```<code>{
  "Sameer": {
    "Phone": "0123456789"
  },
  "Mona": {
    "Phone": "0123456789"
  }
}
</code>```

If you have silent failures, check your JSON with a tool like http://jsonlint.com/.

From jQuery $.getJson() documentation:

Important: As of jQuery 1.4, if the JSON file contains a syntax error,
  the request will usually fail silently.

Body:
I have this code:

$.getJSON('data.json', function (data) {
    console.log(data);
});

And this is the data.json file:

{
  "Sameer": {
    "Phone": "0123456789",
  },
  "Mona": {
    "Phone": "0123456789",
  },
}

But the console.log(data) not returning anything, Not even an error I don't know what is wrong with my code.

I tried to use $.ajax() function instead but no luck. And when I change my data.json file to something random like: data.asd I get an error that saying the file data.asd not found!

Body:
There are syntax errors on your JSON (commas), this is the right version:

{
  "Sameer": {
    "Phone": "0123456789"
  },
  "Mona": {
    "Phone": "0123456789"
  }
}

If you have silent failures, check your JSON with a tool like http://jsonlint.com/.

From jQuery $.getJson() documentation:

Important: As of jQuery 1.4, if the JSON file contains a syntax error,
  the request will usually fail silently.


问:
Javascript - How do I find out which condition(s) triggered?
Let's say I have the following statement:

```<code>if (height > 4.25 || length > 6 || weight > 1) {
  //Do Something
}
</code>```

Is there a way to tell which of the conditions was met in order for that statement to be true?

Something more elegant than below, which is obviously redundant:

```<code>if (height > 4.25 || length > 6 || weight > 1) {
  if (height > 4.25){...};
  if (length > 6){...};
  if (weight > 1){...};
}
</code>```

答:
I think i would do something like this:</p>

```<code>let height = 2;
let length = 2;
let weight = 2;

var conditions = [
{name: "con1",con: (height > 4.25)},
{name: "con2",con: (length > 6)},
{name: "con3",con: (weight > 1)}
]

conditions.forEach(function(value, key){
if(value.con)
{
console.log(value.name+" was triggered")
}
})
</code>```

Body:
Let's say I have the following statement:

if (height > 4.25 || length > 6 || weight > 1) {
  //Do Something
}

Is there a way to tell which of the conditions was met in order for that statement to be true?

Something more elegant than below, which is obviously redundant:

if (height > 4.25 || length > 6 || weight > 1) {
  if (height > 4.25){...};
  if (length > 6){...};
  if (weight > 1){...};
}

Body:
I think i would do something like this:

let height = 2;
let length = 2;
let weight = 2;

var conditions = [
{name: "con1",con: (height > 4.25)},
{name: "con2",con: (length > 6)},
{name: "con3",con: (weight > 1)}
]

conditions.forEach(function(value, key){
if(value.con)
{
console.log(value.name+" was triggered")
}
})


问:
how do you access a jenkins api which uses Github OAuth using CURL
I have a jenkins server using the Github OAuth plugin and authorized in the "Authorized applications" section of github, it works fine from my browser, i can access to the jenkins server as long as i'm authenticated with github.

Is there a way to access to the jenkins server api using oauth credentials/token from CURL or a ruby client?

I've generated a token in https://github.com/settings/applications -> Personal access tokens -> Generate new token (there is no option to scope it to a third party application)

that token works fine to access github :

    curl -H "Authorization: token cfbcff42e6a8a52a1076dd9fcxxxxxxxxxxxxxxx" https://api.github.com/user

however, that token is not valid for jenkins-server:

    curl -H "Authorization: token cfbcff42e6a8a52a1076dd9fcxxxxxxxxxxxxxxx"        https://jenkins-server/user/restebanez/api/json/\?pretty\=true

It generates this error:

```<code><html><head><meta http-equiv='refresh' content='1;url=/securityRealm/commenceLogin?from=%2Fuser%2Frestebanez%2Fapi%2Fjson%2F%3Fpretty%3Dtrue'/><script>window.location.replace('/securityRealm/commenceLogin?from=%2Fuser%2Frestebanez%2Fapi%2Fjson%2F%3Fpretty%3Dtrue');</script></head><body style='background-color:white; color:white;'>

    Authentication required
<!--
You are authenticated as: anonymous
Groups that you are in:

                        Permission you need to have (but didn't): hudson.model.Hudson.Read
 ... which is implied by: hudson.security.Permission.GenericRead
 ... which is implied by: hudson.model.Hudson.Administer
-->

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

```

the jenkins server has installed GitHub API Plugin 1.58 and Github Authentication plugin 0.19

I'm probably missing some fundamentals of oauth b/c i have googled this for a while and i haven't found anything

答:
You should use "Basic" rather than "token"

For example:

```<code>curl -H "Authorization: Basic cfbcff42e6a8a52a1076dd9fcxx"
https://jenkins-server/user/restebanez/api/json
</code>```

Body:
I have a jenkins server using the Github OAuth plugin and authorized in the "Authorized applications" section of github, it works fine from my browser, i can access to the jenkins server as long as i'm authenticated with github.

Is there a way to access to the jenkins server api using oauth credentials/token from CURL or a ruby client?

I've generated a token in https://github.com/settings/applications -> Personal access tokens -> Generate new token (there is no option to scope it to a third party application)

that token works fine to access github :

    curl -H "Authorization: token cfbcff42e6a8a52a1076dd9fcxxxxxxxxxxxxxxx" https://api.github.com/user

however, that token is not valid for jenkins-server:

    curl -H "Authorization: token cfbcff42e6a8a52a1076dd9fcxxxxxxxxxxxxxxx"        https://jenkins-server/user/restebanez/api/json/\?pretty\=true

It generates this error:

<meta http-equiv='refresh' content='1;url=/securityRealm/commenceLogin?from=%2Fuser%2Frestebanez%2Fapi%2Fjson%2F%3Fpretty%3Dtrue'/>

    Authentication required

```

the jenkins server has installed GitHub API Plugin 1.58 and Github Authentication plugin 0.19

I'm probably missing some fundamentals of oauth b/c i have googled this for a while and i haven't found anything

Body:
You should use "Basic" rather than "token"

For example:

curl -H "Authorization: Basic cfbcff42e6a8a52a1076dd9fcxx"
https://jenkins-server/user/restebanez/api/json


问:
Sql left join with 2 columns
I have a problem with left join i have 2 tables. Table A:

```<code>Itemid InventlocationID
10001    200
10001    301
10001    302
</code>```

And table B

```<code>ItemId InventLocationID ItemOption
10001    200               A
10001    301               B
</code>```

I want to get the following result

```<code>Itemid InventlocationID ItemOption
10001    200                A
10001    301                B
10001    302               null
</code>```

I use left join:

```<code>SELECT a.itemid,a.inventlocationid,b.ItemOption
FROM  a
left  join b
on (a.ItemID = b.ITEMID and a.InventLocationid = b.INVENTLOCATIONID)
</code>```

and the result i get is:

```<code>Itemid InventlocationID Itemoption
10001    200                A
10001    301                B
</code>```

Any ideas how can i achieve the result i want?
Edit : tables a and b have more records

答:
Your query works fine. (Check your data)

```<code>create table tablea (Itemid int,  InventlocationID int);
insert into tablea values
(10001,    200),
(10001,    301),
(10001,    302);

create table tableb (ItemId int, InventLocationID int, ItemOption char(1));
insert into tableb values
(10001,    200,               'A'),
(10001,    301,               'B');
GO
</code>```

```
5 rows affected
```

```<code>select    a.ItemId, a.InventlocationID, b.ItemOPtion
from      tableA a
left join tableB b
on        a.itemId = b.ItemId
and       a.InventlocationID = b.InventlocationID
GO
</code>```

```
ItemId | InventlocationID | ItemOPtion
-----: | ---------------: | :---------
 10001 |              200 | A
 10001 |              301 | B
 10001 |              302 | <em>null</em>
```

dbfiddle here

Title: Sql left join with 2 columns

Body:
I have a problem with left join i have 2 tables. Table A:

Itemid InventlocationID
10001    200
10001    301
10001    302

And table B

ItemId InventLocationID ItemOption
10001    200               A
10001    301               B

I want to get the following result

Itemid InventlocationID ItemOption
10001    200                A
10001    301                B
10001    302               null

I use left join:

SELECT a.itemid,a.inventlocationid,b.ItemOption
FROM  a
left  join b
on (a.ItemID = b.ITEMID and a.InventLocationid = b.INVENTLOCATIONID)

and the result i get is:

Itemid InventlocationID Itemoption
10001    200                A
10001    301                B

Any ideas how can i achieve the result i want?
Edit : tables a and b have more records

Body:
Your query works fine. (Check your data)

create table tablea (Itemid int,  InventlocationID int);
insert into tablea values
(10001,    200),
(10001,    301),
(10001,    302);

create table tableb (ItemId int, InventLocationID int, ItemOption char(1));
insert into tableb values
(10001,    200,               'A'),
(10001,    301,               'B');
GO

5 rows affected

select    a.ItemId, a.InventlocationID, b.ItemOPtion
from      tableA a
left join tableB b
on        a.itemId = b.ItemId
and       a.InventlocationID = b.InventlocationID
GO

ItemId | InventlocationID | ItemOPtion
-----: | ---------------: | :---------
 10001 |              200 | A
 10001 |              301 | B
 10001 |              302 | null

dbfiddle here


问:
Select within a Select returning 0 returns. How to debug?
```<code>var items = pSelectedItem.Nodes
                .Expand(e => e.Nodes)
                .Where(e => e.Nodes == null)
                .Select(e => e.Tag as List<ActionObject>)
                .Select(e=> e.Select (i=>i as ActionObject)
                    .Where(i => i != null)
                    .Select(i => new ListViewItem()
                    {
                        Tag = new ListViewValue[]
                        {
                            new ListViewValue() { Value = i.Command },
                            new ListViewValue() { Value = i.Target },
                            new ListViewValue() { Value = i.Value },
                            new ListViewValue() { Value = i.Comment }
                        }
}) as ListViewItem);

return new ObservableCollection<ListViewItem>(items);
</code>```

The code above, I am trying to capture all listviewitems.  Each list view item has a tag property. This tag property is of type object.

The code above makes complete sense to me however its always returning null. I have tried debugging the code above unfortunately the code above doesn't let me debug the inner select code.  the e.Select (i=>.... is where it won't debug.

Thoughts?  Maybe my code is more complicated than it needs to be.

答: one way to debug is start commenting out Where statements one by one and see if you get results. this will help you in understanding which where clause is causing your results to come back as null. you can go from there.</p>

Body:
var items = pSelectedItem.Nodes
                .Expand(e => e.Nodes)
                .Where(e => e.Nodes == null)
                .Select(e => e.Tag as List<ActionObject>)
                .Select(e=> e.Select (i=>i as ActionObject)
                    .Where(i => i != null)
                    .Select(i => new ListViewItem()
                    {
                        Tag = new ListViewValue[]
                        {
                            new ListViewValue() { Value = i.Command },
                            new ListViewValue() { Value = i.Target },
                            new ListViewValue() { Value = i.Value },
                            new ListViewValue() { Value = i.Comment }
                        }
}) as ListViewItem);

return new ObservableCollection<ListViewItem>(items);

The code above, I am trying to capture all listviewitems.  Each list view item has a tag property. This tag property is of type object.

The code above makes complete sense to me however its always returning null. I have tried debugging the code above unfortunately the code above doesn't let me debug the inner select code.  the e.Select (i=>.... is where it won't debug.

Thoughts?  Maybe my code is more complicated than it needs to be.


问:
Symfony passing request to function to an other controller
I try to give '$_REQUEST['vider']' to an other controller like this :

```<code>return $this->forward('TestBundle:Rapport:bo', array('vider' => 'vider'));
//, array ($_REQUEST['vider'] => 'vider) doesn't work too
</code>```

But in my function Rapport:bo, $_REQUEST['vider'] is null, i give it in the array, where i failed ?

edit :
my Rapport:bo function :

```<code>public function boAction(Request $request) {
var_dump($_REQUEST['vider']); // is null
if ( isset($_REQUEST['vider']) ) ) {
        var_dump('test');
    }

}
</code>```

答:
Try with:</p>

```<code>public function boAction($vider) {
    your logic...
</code>```

Body:
I try to give '$_REQUEST['vider']' to an other controller like this :

return $this->forward('TestBundle:Rapport:bo', array('vider' => 'vider'));
//, array ($_REQUEST['vider'] => 'vider) doesn't work too

But in my function Rapport:bo, $_REQUEST['vider'] is null, i give it in the array, where i failed ?

edit :
my Rapport:bo function :

public function boAction(Request $request) {
var_dump($_REQUEST['vider']); // is null
if ( isset($_REQUEST['vider']) ) ) {
        var_dump('test');
    }

}

Body:
Try with:

public function boAction($vider) {
    your logic...


问:
Batch command to open files of the same name in Notepad++
I would like to open all files called "asdf.txt" in Notepad++, found in all subfolders from the directory that the batch file is located in.

The solution found here applies to file types but does not translate to exact file names:
Batch command to open all files of a certain type in Notepad++

Here is my attempt:

```<code>FOR /R %%a IN (asdf.txt) DO "C:\Program Files (x86)\Notepad++\notepad++.exe" "%%a"
</code>```

This results in Notepad++ stating that asdf.txt doesn't exist and would I like to create it. It continues to ask me for every subfolder that exists (which can be hundreds of times). If I say yes, then it creates the file asdf.txt in every subfolder. If I keep pressing yes/no, then it eventually does open the existing files. What I want, however, is to open all existing files with exactly the same name and not create new files.

答:
You could also use the Where command:

@For /F "Delims=" %%A In ('Where/R <srcDir> asdf.txt') Do @Start "" "%ProgramFiles(x86)%\Notepad++\notepad++.exe" "%%A"
```

Change <srcDir> to your specific source directory, (use a dot for the current directory). You can of course remove the Start "" command if it doesn't suit your specific requirements

Body:
I would like to open all files called "asdf.txt" in Notepad++, found in all subfolders from the directory that the batch file is located in.

The solution found here applies to file types but does not translate to exact file names:
Batch command to open all files of a certain type in Notepad++

Here is my attempt:

FOR /R %%a IN (asdf.txt) DO "C:\Program Files (x86)\Notepad++\notepad++.exe" "%%a"

This results in Notepad++ stating that asdf.txt doesn't exist and would I like to create it. It continues to ask me for every subfolder that exists (which can be hundreds of times). If I say yes, then it creates the file asdf.txt in every subfolder. If I keep pressing yes/no, then it eventually does open the existing files. What I want, however, is to open all existing files with exactly the same name and not create new files.

Body:
You could also use the Where command:

@For /F "Delims=" %%A In ('Where/R <srcDir> asdf.txt') Do @Start "" "%ProgramFiles(x86)%\Notepad++\notepad++.exe" "%%A"

Change <srcDir> to your specific source directory, (use a dot for the current directory). You can of course remove the Start "" command if it doesn't suit your specific requirements


问:
What are the chances for collision in sum of 2 hash codes?
What is the probability of collision if a new hash code is generated by added 2 other hash codes in Java

Eg:

```<code>Integer reportHashCode = reportFields.hashCode() + reportId.hashCode();
</code>```

Let's assume Java's hash code is 32bits and we can ignore normal collision in the hash code itself.

答:
How about we find out? The below program will simulate this for you. Note that the two addends for the sum are generated at random, so both have approximately the full integer range of probability. In reality the two hash codes that you sum might not have a flat distribution over the entire integer space. The program could be adjusted to simulate that.

```<code>package hashcode;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Random;
import java.util.Set;

public class HashCode {
    // Number of test cases
    private static final int TEST_CASES = 10_000_000;
    public static void main(String[] args) {
        // Random number generator
        Random rand = new Random();
        // Map from integers (result hash codes) to a list of addend pairs that formed those hash codes
        Map<Integer, Set<Pair>> hashCodesToComposites = new HashMap<>();
        // Number of collissions
        int collisions = 0;
        // Running simulations
        for (int i = 0; i < TEST_CASES; ++i) {
            if (TEST_CASES / 4 == i) {
                System.out.println("25 %");
            }
            if (TEST_CASES / 2 == i) {
                System.out.println("50 %");
            }
            if ((TEST_CASES * 3) / 4 == i) {
                System.out.println("75 %");
            }
            // Generating addends as random integers
            int first = rand.nextInt();
            int second = rand.nextInt();
            // The pair; its hash code is the sum of the above
            Pair pair = new Pair(first, second);
            // Did it occur before?
            if (hashCodesToComposites.containsKey(pair.hashCode())) {
                // Getting the set of addend pairs that created this hash code
                Set<Pair> composites = hashCodesToComposites.get(pair.hashCode());
                // Checking if by any chance the two random numbers happened to be the same (almost negligible)
                if (!composites.contains(pair)) {
                    // Actual collision from different numbers
                    collisions++;
                    // Adding to the set of composites
                    composites.add(pair);
                } // Same numbers; doesn't count as collision
            } else {
                // First occurrence of this hash code
                Set<Pair> composites = new HashSet<>();
                composites.add(pair);
                hashCodesToComposites.put(pair.hashCode(), composites);
            }
        }
        // Results
        System.out.println("Test cases: " + TEST_CASES);
        System.out.println("Collisions: " + collisions);
        System.out.println("Probability: " + ((double) collisions / (double) TEST_CASES));
    }
    private static class Pair {
        final int first;
        final int second;
        final int hashCode;
        Pair(int first, int second) {
            this.first = first;
            this.second = second;
            hashCode = first + second;
        }
        @Override
        public int hashCode() {
            return hashCode;
        }
        @Override
        public boolean equals(Object obj) {
            if (this == obj) {
                return true;
            }
            final Pair other = (Pair) obj;
            return (this.first == other.first && this.second == other.second) || (this.first == other.second && this.second == other.first);
        }
    }
}
</code>```

The outcome is usually around 0.00115. This means there's roughly a 0.115 % chance of collisions. I've run the below to find out what the odds are for collisions between just random integers.

```<code>package hashcode;

import java.util.HashSet;
import java.util.Random;
import java.util.Set;

public class HashCode2 {
    // Number of test cases
    private static final int TEST_CASES = 10_000_000;
    public static void main(String[] args) {
        // Random number generator
        Random rand = new Random();
        Set<Integer> hashCodes = new HashSet<>();
        // Number of collissions
        int collisions = 0;
        // Running simulations
        for (int i = 0; i < TEST_CASES; ++i) {
            if (TEST_CASES / 4 == i) {
                System.out.println("25 %");
            }
            if (TEST_CASES / 2 == i) {
                System.out.println("50 %");
            }
            if ((TEST_CASES * 3) / 4 == i) {
                System.out.println("75 %");
            }
            int next = rand.nextInt();
            if (hashCodes.contains(next)) {
                collisions++;
            } else {
                hashCodes.add(next);
            }
        }
        // Results
        System.out.println("Test cases: " + TEST_CASES);
        System.out.println("Collisions: " + collisions);
        System.out.println("Probability: " + ((double) collisions / (double) TEST_CASES));
    }
}
</code>```

The probability is actually about the same. It is only slightly lower, but still rounds to 0.115 %. Finally, I tried the first program again, but with an xor in the hashCode method of Pair instead of a sum. The result? Pretty much the same thing again.

So in the end, you can expect very close to the same collision rate as random integers for a sum of two hash codes and an xor, provided both hash codes being summed/xor'ed have a good distribution.

Body:
What is the probability of collision if a new hash code is generated by added 2 other hash codes in Java

Eg:

Integer reportHashCode = reportFields.hashCode() + reportId.hashCode();

Let's assume Java's hash code is 32bits and we can ignore normal collision in the hash code itself.

Body:
How about we find out? The below program will simulate this for you. Note that the two addends for the sum are generated at random, so both have approximately the full integer range of probability. In reality the two hash codes that you sum might not have a flat distribution over the entire integer space. The program could be adjusted to simulate that.

package hashcode;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Random;
import java.util.Set;

public class HashCode {
    // Number of test cases
    private static final int TEST_CASES = 10_000_000;
    public static void main(String[] args) {
        // Random number generator
        Random rand = new Random();
        // Map from integers (result hash codes) to a list of addend pairs that formed those hash codes
        Map<Integer, Set<Pair>> hashCodesToComposites = new HashMap<>();
        // Number of collissions
        int collisions = 0;
        // Running simulations
        for (int i = 0; i < TEST_CASES; ++i) {
            if (TEST_CASES / 4 == i) {
                System.out.println("25 %");
            }
            if (TEST_CASES / 2 == i) {
                System.out.println("50 %");
            }
            if ((TEST_CASES * 3) / 4 == i) {
                System.out.println("75 %");
            }
            // Generating addends as random integers
            int first = rand.nextInt();
            int second = rand.nextInt();
            // The pair; its hash code is the sum of the above
            Pair pair = new Pair(first, second);
            // Did it occur before?
            if (hashCodesToComposites.containsKey(pair.hashCode())) {
                // Getting the set of addend pairs that created this hash code
                Set<Pair> composites = hashCodesToComposites.get(pair.hashCode());
                // Checking if by any chance the two random numbers happened to be the same (almost negligible)
                if (!composites.contains(pair)) {
                    // Actual collision from different numbers
                    collisions++;
                    // Adding to the set of composites
                    composites.add(pair);
                } // Same numbers; doesn't count as collision
            } else {
                // First occurrence of this hash code
                Set<Pair> composites = new HashSet<>();
                composites.add(pair);
                hashCodesToComposites.put(pair.hashCode(), composites);
            }
        }
        // Results
        System.out.println("Test cases: " + TEST_CASES);
        System.out.println("Collisions: " + collisions);
        System.out.println("Probability: " + ((double) collisions / (double) TEST_CASES));
    }
    private static class Pair {
        final int first;
        final int second;
        final int hashCode;
        Pair(int first, int second) {
            this.first = first;
            this.second = second;
            hashCode = first + second;
        }
        @Override
        public int hashCode() {
            return hashCode;
        }
        @Override
        public boolean equals(Object obj) {
            if (this == obj) {
                return true;
            }
            final Pair other = (Pair) obj;
            return (this.first == other.first && this.second == other.second) || (this.first == other.second && this.second == other.first);
        }
    }
}

The outcome is usually around 0.00115. This means there's roughly a 0.115 % chance of collisions. I've run the below to find out what the odds are for collisions between just random integers.

package hashcode;

import java.util.HashSet;
import java.util.Random;
import java.util.Set;

public class HashCode2 {
    // Number of test cases
    private static final int TEST_CASES = 10_000_000;
    public static void main(String[] args) {
        // Random number generator
        Random rand = new Random();
        Set<Integer> hashCodes = new HashSet<>();
        // Number of collissions
        int collisions = 0;
        // Running simulations
        for (int i = 0; i < TEST_CASES; ++i) {
            if (TEST_CASES / 4 == i) {
                System.out.println("25 %");
            }
            if (TEST_CASES / 2 == i) {
                System.out.println("50 %");
            }
            if ((TEST_CASES * 3) / 4 == i) {
                System.out.println("75 %");
            }
            int next = rand.nextInt();
            if (hashCodes.contains(next)) {
                collisions++;
            } else {
                hashCodes.add(next);
            }
        }
        // Results
        System.out.println("Test cases: " + TEST_CASES);
        System.out.println("Collisions: " + collisions);
        System.out.println("Probability: " + ((double) collisions / (double) TEST_CASES));
    }
}

The probability is actually about the same. It is only slightly lower, but still rounds to 0.115 %. Finally, I tried the first program again, but with an xor in the hashCode method of Pair instead of a sum. The result? Pretty much the same thing again.

So in the end, you can expect very close to the same collision rate as random integers for a sum of two hash codes and an xor, provided both hash codes being summed/xor'ed have a good distribution.


问:
stripping html tags in php with allowing an exception
For the past hour I've been trying to add an exception to strip tags, allowing only

 to remain, but unfortunately I haven't been successful in making this work, I don't get any errors either, the trim is present because it's removing whitespace from the data, any feedback would be much appreciated, thank you very much

```<code>trim(strip_tags($html->find('div[id=data]',"<p></p>")));
</code>```

答:
The second parameter is for strip_tags, not for $html->find(), and the value must be single tags without closing '
```'</code>:</p>

```trim(strip_tags( $html->find('div[id=data]') ,"
"));
```

Body:
For the past hour I've been trying to add an exception to strip tags, allowing only

 to remain, but unfortunately I haven't been successful in making this work, I don't get any errors either, the trim is present because it's removing whitespace from the data, any feedback would be much appreciated, thank you very much

trim(strip_tags($html->find('div[id=data]',"

")));

Body:
The second parameter is for strip_tags, not for $html->find(), and the value must be single tags without closing '<p><span><pre>':

trim(strip_tags( $html->find('div[id=data]') ,"<p>"));


答:
You can abuse the switch construct:</p>

```<code>var height = 4;
var length = 7;
var weight= 1;
switch(true) {
case (height > 4.25):
  alert(1);
  break;
 case (length > 6):
   alert(2);
  break;
case (weight > 1):
  alert(3);
  break;
default:
  alert(4);
}
</code>```

Title: Javascript - How do I find out which condition(s) triggered?

Body:
You can abuse the switch construct:

var height = 4;
var length = 7;
var weight= 1;
switch(true) {
case (height > 4.25):
  alert(1);
  break;
 case (length > 6):
   alert(2);
  break;
case (weight > 1):
  alert(3);
  break;
default:
  alert(4);
}


问:
Pin Button to Bottom Right Corner of TextField IOS
I would like to pin a button to the bottom right corner of a textfield. I completed this in Android using a relativelayout. I don't know how to do this in IOS. I attempted to set top and bottom constraints, but it didn't work.
Help?

Example

答:
```<code>    UITextField * rightField;
    rightField.rightViewMode = UITextFieldViewModeAlways;
    UIImageView *rightImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image.png"]];
    rightField.rightView = rightImageView; // Set right view as image view
</code>```

<p>set UITextField rightView as your button. Here in my example I added UIImageView to UITextField rightView. </p>

Body:
    UITextField * rightField;
    rightField.rightViewMode = UITextFieldViewModeAlways;
    UIImageView *rightImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image.png"]];
    rightField.rightView = rightImageView; // Set right view as image view

set UITextField rightView as your button. Here in my example I added UIImageView to UITextField rightView.


问:
Firebird connection with java
I have installed Firebird 2.1 on windows Xp and using firebirdsql.jdbc-2.1.6 driver to connect with java. Code:

```<code>Class.forName("org.firebirdsql.jdbc.FBDriver");

connection = DriverManager.getConnection(
    "jdbc:firebirdsql://localhost/3050//C:/firebird/database/EMPLOYEE.FDB",
    "test","test");
</code>```

I am getting following error:

```
Caused by: org.firebirdsql.jdbc.FBSQLException: GDS Exception. 335544375.
unavailable database
Reason: unavailable database at
org.firebirdsql.jdbc.FBDataSource.getConnection(FBDataSource.java:122) at
org.firebirdsql.jdbc.FBDriver.connect(FBDriver.java:140) at
java.sql.DriverManager.getConnection(DriverManager.java:525) at
java.sql.DriverManager.getConnection(DriverManager.java:171)
```

Please help.

Problem solved:
Actually I had problem with jar file that I got from

http://mirrors.ibiblio.org/pub/mirrors/maven2

I downloaded jaybird-full-2.1.6.jar from firebird offical website and problem got solved.

Correct URL is

```<code>"jdbc:firebirdsql://localhost:3050/C:\\firebird\\database\\EMPLOYEE.FDB"
</code>```

I tried this URL earlier also but it was not working beacuse of jar issue.

答:
From https://www.firebirdsql.org/file/documentation/drivers_documentation/java/faq.html#pure-java-default

Default URL format:

```<code>"jdbc:firebirdsql://host[:port]/<database>"
</code>```

Deprecated, but still supported legacy URL format:

```<code>"jdbc:firebirdsql:host[/port]:<database>"
</code>```

Then, the correct URL should be:

```<code>"jdbc:firebirdsql://localhost:3050/C:/firebird/database/EMPLOYEE.FDB"
</code>```

Title: Firebird connection with java

Body:
I have installed Firebird 2.1 on windows Xp and using firebirdsql.jdbc-2.1.6 driver to connect with java. Code:

Class.forName("org.firebirdsql.jdbc.FBDriver");

connection = DriverManager.getConnection(
    "jdbc:firebirdsql://localhost/3050//C:/firebird/database/EMPLOYEE.FDB",
    "test","test");

I am getting following error:

Caused by: org.firebirdsql.jdbc.FBSQLException: GDS Exception. 335544375.
unavailable database
Reason: unavailable database at
org.firebirdsql.jdbc.FBDataSource.getConnection(FBDataSource.java:122) at
org.firebirdsql.jdbc.FBDriver.connect(FBDriver.java:140) at
java.sql.DriverManager.getConnection(DriverManager.java:525) at
java.sql.DriverManager.getConnection(DriverManager.java:171)

Please help.

Problem solved:
Actually I had problem with jar file that I got from

http://mirrors.ibiblio.org/pub/mirrors/maven2

I downloaded jaybird-full-2.1.6.jar from firebird offical website and problem got solved.

Correct URL is

"jdbc:firebirdsql://localhost:3050/C:\\firebird\\database\\EMPLOYEE.FDB"

I tried this URL earlier also but it was not working beacuse of jar issue.

Body:
From https://www.firebirdsql.org/file/documentation/drivers_documentation/java/faq.html#pure-java-default

Default URL format:

"jdbc:firebirdsql://host[:port]/<database>"

Deprecated, but still supported legacy URL format:

"jdbc:firebirdsql:host[/port]:<database>"

Then, the correct URL should be:

"jdbc:firebirdsql://localhost:3050/C:/firebird/database/EMPLOYEE.FDB"


问:
What is the reason for a Kerberos keytab file when setting up SSH authentication on a server?
I haven't really have had much experience with Kerberos but I am trying to set up SSH authentication with AD on one of my servers using sssd. I have followed the instructions on the sssd documentation here and got it working but I am struggling to understand why I need a keytab file to set this up?

I've been doing a bit of reading about Kerberos lately and it appears you only need to create a keytab file on the server when the server needs to authenticate to AD without user interaction or when you need to implement SSO (when a user requests a ticket for that service).

I simply want my users to enter their username / password when logging in via SSH and have sssd authenticate this user against AD and create a TGT ticket for them. The funny thing is - even when I don't setup sssd and only set up the kerberos side I can run kinit and I get a ticket!

So my question is this: Can I set up SSH authentication using sssd without generating a keytab file on the server? if not then why not?

答:
Your question in the Subject line "What is the reason for a Kerberos keytab file when setting up SSH authentication on a server?" boils down to a one-line answer:  it allows for Kerberos single sign-on authentication to the Directory server by de-crypting the inbound Kerberos service ticket to "tell" who the user is.  As far as your other question, "Can I set up SSH authentication using sssd without generating a keytab file on the server?", the answer is yes, you can.  But you will be prompted for a username or password whenever you connect to the SSH service, unless you choose to cache the password in whatever SSH utility you might be using to connect.  Caching the password though, in such a method, is not considered to be "single sign-on".

For additional reference, you can read more about my article on Kerberos keytabs on Microsoft Technet:  Kerberos Keytabs – Explained.  I frequently go back and edit it based on questions I see here in this forum.


问:
migrating ContainerOS (CoreOS) alpha from etcd2 to etcd3
I have Container Linux by CoreOS 1353.1.0 installed and it uses etcd2 by default. I can't even find an etcd3 service file (systemctl | grep etcd only shows etcd2.service).

I wanna play with etcd3. especially because it's the default storage backend for kubernetes 1.6.

is there any way (easy or hard) to migrate from etcd2 to etcd3? when I say migrate.. I don't mind recofiguring my ignition file and reinstalling the all OS.

any information regarding the issue would be greatly appreciated.

how come ContainerOS Alpha doesn't come with etcd3?!?!

thanks!

答:
I can use etcd-member.service to start a container image with any version that I want. it's cool !:)

more info at https://coreos.com/etcd/docs/latest/getting-started-with-etcd.html#setting-up-etcd


问:
Is it possible to have function extensions on lambdas?
I'd like to check if some code throws a determined exception.

In particular, for my case, I'd like to write like:

{shaderCodeOf(gl, this::class.java, data + "$FRAGMENT_FAIL.frag")} shallThrow GLException::java.class

I tried to write

infix fun (() -> Unit).shallThrow(java: Class<*>)

but I didn't have much success..

any idea, guys?

答:
There are no problems with declaring extension functions on lambdas.

```<code>infix fun (()->Unit).shallThrow(java: Class<out Throwable>) {
    // do whatever you need                 ^ you mean this, didn't you?
}
</code>```

Then:

```<code>{} shallThrow RuntimeException::class.java
</code>```

Body:
There are no problems with declaring extension functions on lambdas.

infix fun (()->Unit).shallThrow(java: Class<out Throwable>) {
    // do whatever you need                 ^ you mean this, didn't you?
}

Then:

{} shallThrow RuntimeException::class.java


问:
How can an AWS Lambda function update all records in a DynamoDB table?
I'm working on an AWS Lambda function (Node 4.3) that needs to run through all the items in a DynamoDB table and update certain attributes.

The problem I'm having is how to get Lambda to wait until all of the DynamoDB operations are finished.

```<code>var async = require('async');
var aws = require('aws-sdk');
var doc = new aws.DynamoDB.DocumentClient();

exports.handler = (event, context, callback) => {
    doc.scan({
        TableName: 'Occupations_dev'
    }, function (err, data) {
        console.log(data.Items.length);

        var funcs = [];

        data.Items.forEach(function (item) {
            funcs.push(function (cb) {
                item.Popularity = 0;

                doc.put({
                    TableName: 'Occupations_dev',
                    Item: item
                }, function (err, data) {
                    if (err) {
                        console.log("ERROR: " + item.Name);
                        cb(err);
                    } else {
                        console.log('Finished put for ' + item.Id)
                        cb(null, item);
                    }
                });
            });
        });

        async.parallel(funcs, function (err, results) {
            console.log('Finished');

            if (err) {
                context.fail(err);
            } else {
                callback(null, 'Finished');
            }
        });
    });
};
</code>```

I tried using async.parallel to wait for all of the db.put requests to finish but it ends with a Process exited before completing request error whenever the Lambda function runs.

It does update some of the DynamoDB items but definitely not all of them.

I added some console.log calls when there are errors but the only output I see in the log is this:

```<code>START RequestId: b72fd7c6-14ed-11e7-a95a-c1185af4e870 Version: $LATEST
2017-03-30T02:08:11.691Z    b72fd7c6-14ed-11e7-a95a-c1185af4e870    1362
END RequestId: b72fd7c6-14ed-11e7-a95a-c1185af4e870
REPORT RequestId: b72fd7c6-14ed-11e7-a95a-c1185af4e870  Duration: 37165.80 ms   Billed Duration: 37200 ms   Memory Size: 128 MB Max Memory Used: 128 MB
RequestId: b72fd7c6-14ed-11e7-a95a-c1185af4e870 Process exited before completing request
</code>```

What's the proper way to make the Lambda function wait until everything is done? (It's not a huge amount of data so I'm not worried about running longer than 5 minutes and timing out.)

答:
The async.parallel function invocations are occurring asynchronously, which is likely flooding DynamoDB with many simultaneous updates and raising "too many connections" errors at the DB level

I'd recommend using a synchronous operation, like async.series to perform the DB updates. DynamoDB should have not trouble processing these updates one after the other.

Body:
I'm working on an AWS Lambda function (Node 4.3) that needs to run through all the items in a DynamoDB table and update certain attributes.

The problem I'm having is how to get Lambda to wait until all of the DynamoDB operations are finished.

var async = require('async');
var aws = require('aws-sdk');
var doc = new aws.DynamoDB.DocumentClient();

exports.handler = (event, context, callback) => {
    doc.scan({
        TableName: 'Occupations_dev'
    }, function (err, data) {
        console.log(data.Items.length);

        var funcs = [];

        data.Items.forEach(function (item) {
            funcs.push(function (cb) {
                item.Popularity = 0;

                doc.put({
                    TableName: 'Occupations_dev',
                    Item: item
                }, function (err, data) {
                    if (err) {
                        console.log("ERROR: " + item.Name);
                        cb(err);
                    } else {
                        console.log('Finished put for ' + item.Id)
                        cb(null, item);
                    }
                });
            });
        });

        async.parallel(funcs, function (err, results) {
            console.log('Finished');

            if (err) {
                context.fail(err);
            } else {
                callback(null, 'Finished');
            }
        });
    });
};

I tried using async.parallel to wait for all of the db.put requests to finish but it ends with a Process exited before completing request error whenever the Lambda function runs.

It does update some of the DynamoDB items but definitely not all of them.

I added some console.log calls when there are errors but the only output I see in the log is this:

START RequestId: b72fd7c6-14ed-11e7-a95a-c1185af4e870 Version: $LATEST
2017-03-30T02:08:11.691Z    b72fd7c6-14ed-11e7-a95a-c1185af4e870    1362
END RequestId: b72fd7c6-14ed-11e7-a95a-c1185af4e870
REPORT RequestId: b72fd7c6-14ed-11e7-a95a-c1185af4e870  Duration: 37165.80 ms   Billed Duration: 37200 ms   Memory Size: 128 MB Max Memory Used: 128 MB
RequestId: b72fd7c6-14ed-11e7-a95a-c1185af4e870 Process exited before completing request

What's the proper way to make the Lambda function wait until everything is done? (It's not a huge amount of data so I'm not worried about running longer than 5 minutes and timing out.)


问:
android - dynamically changing the position of an imageview
i'm currently using the matrix method to implement drag and pinch zoom for an image (image A)

Now i want a part of image A to be clickable so i put another imageview (image B) over image A and set the layout_margins for it in the xml file.

My question is...is there a way to dynamically change my layout_margins as i'm scaling my image for drag and pinch zoom?

I guess the simpler question is...how do i dynamically set the layout_margins for an imageview?

```<code><RelativeLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent" >

   <ImageView android:id="@+id/imageView"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"
     android:src="@drawable/map"
     android:scaleType="matrix" />

    <ImageView
       android:id="@+id/dundas_station"
       android:layout_width="75px"
       android:layout_height="75px"
       android:layout_marginTop="337px"
   android:layout_marginLeft="373px"
       android:clickable="true"
       android:src="@drawable/google_maps_icon"
       android:scaleType="matrix"
       />
</RelativeLayout>
</code>```

thanks!

答:
Use following code snippet. Don forget to import
"android.widget.FrameLayout.LayoutParams" or marginal layout params.</p>

```<code>ImageView image;
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.setMargins(100,0, 0,0);

// OR
params.topMargin= 100;
image.setLayoutParams(params);
</code>```

Body:
i'm currently using the matrix method to implement drag and pinch zoom for an image (image A)

Now i want a part of image A to be clickable so i put another imageview (image B) over image A and set the layout_margins for it in the xml file.

My question is...is there a way to dynamically change my layout_margins as i'm scaling my image for drag and pinch zoom?

I guess the simpler question is...how do i dynamically set the layout_margins for an imageview?

<RelativeLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent" >

   <ImageView android:id="@+id/imageView"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"
     android:src="@drawable/map"
     android:scaleType="matrix" />

    <ImageView
       android:id="@+id/dundas_station"
       android:layout_width="75px"
       android:layout_height="75px"
       android:layout_marginTop="337px"
   android:layout_marginLeft="373px"
       android:clickable="true"
       android:src="@drawable/google_maps_icon"
       android:scaleType="matrix"
       />
</RelativeLayout>

thanks!

Body:
Use following code snippet. Don forget to import
"android.widget.FrameLayout.LayoutParams" or marginal layout params.

ImageView image;
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.setMargins(100,0, 0,0);

// OR
params.topMargin= 100;
image.setLayoutParams(params);


问:
Python curve fit with change point
As I'm really struggleing to get from R-code, to Python code, I would like to ask some help. The code I want to use has been provided to my from withing the mathematics forum of stackexchange.

https://math.stackexchange.com/questions/2205573/curve-fitting-on-dataset

I do understand what is going on. But I'm really having a hard time trying to solve the R-code, as I have never seen anything of it. I have written the function to return the sum of squares. But I'm stuck at how I could use a function similar to the optim function. And also I don't really like the guesswork at the initial values. I would like it better to run and re-run a type of optim function untill I get the wanted result, because my needs for a nearly perfect curve fit are really high.

```<code>def model (par,x):
    n = len(x)
    res = []
    for i in range(1,n):
        A0 = par[3] + (par[4]-par[1])*par[6] + (par[5]-par[2])*par[6]**2
        if(x[i] == par[6]):
            res[i] = A0 + par[1]*x[i] + par[2]*x[i]**2
        else:
            res[i] = par[3] + par[4]*x[i] + par[5]*x[i]**2
    return res
</code>```

This is my model function...

```<code>def sum_squares (par, x, y):
    ss = sum((y-model(par,x))^2)
    return ss
</code>```

And this is the sum of squares

But I have no idea on how to convert this:

```<code> #I found these initial values with a few minutes of guess and check.
 par0 <- c(7,-1,-395,70,-2.3,10)
 sol <- optim(par= par0, fn=sqerror, x=x, y=y)$par
</code>```

To Python code...

答:
Seems like I have been able to fix the problem.

```<code>def model (par,x):
    n = len(x)
    res = np.array([])
    for i in range(0,n):
        A0 = par[2] + (par[3]-par[0])*par[5] + (par[4]-par[1])*par[5]**2
        if(x[i] <= par[5]):
            res = np.append(res, A0 + par[0]*x[i] + par[1]*x[i]**2)
        else:
            res = np.append(res,par[2] + par[3]*x[i] + par[4]*x[i]**2)
    return res

def sum_squares (par, x, y):
    ss = sum((y-model(par,x))**2)
    print('Sum of squares = {0}'.format(ss))
    return ss
</code>```

And then I used the functions as follow:

```<code>parameter = sy.array([0.0,-8.0,0.0018,0.0018,0,200])
res = least_squares(sum_squares, parameter, bounds=(-360,360), args=(x1,y1),verbose = 1)
</code>```

The only problem is that it doesn't produce the results I'm looking for... And that is mainly because my x values are [0,360] and the Y values only vary by about 0.2, so it's a hard nut to crack for this function, and it produces this (poor) result:

Result

Title: Python curve fit with change point

Body:
As I'm really struggleing to get from R-code, to Python code, I would like to ask some help. The code I want to use has been provided to my from withing the mathematics forum of stackexchange.

https://math.stackexchange.com/questions/2205573/curve-fitting-on-dataset

I do understand what is going on. But I'm really having a hard time trying to solve the R-code, as I have never seen anything of it. I have written the function to return the sum of squares. But I'm stuck at how I could use a function similar to the optim function. And also I don't really like the guesswork at the initial values. I would like it better to run and re-run a type of optim function untill I get the wanted result, because my needs for a nearly perfect curve fit are really high.

def model (par,x):
    n = len(x)
    res = []
    for i in range(1,n):
        A0 = par[3] + (par[4]-par[1])*par[6] + (par[5]-par[2])*par[6]**2
        if(x[i] == par[6]):
            res[i] = A0 + par[1]*x[i] + par[2]*x[i]**2
        else:
            res[i] = par[3] + par[4]*x[i] + par[5]*x[i]**2
    return res

This is my model function...

def sum_squares (par, x, y):
    ss = sum((y-model(par,x))^2)
    return ss

And this is the sum of squares

But I have no idea on how to convert this:

 #I found these initial values with a few minutes of guess and check.
 par0 <- c(7,-1,-395,70,-2.3,10)
 sol <- optim(par= par0, fn=sqerror, x=x, y=y)$par

To Python code...

Body:
Seems like I have been able to fix the problem.

def model (par,x):
    n = len(x)
    res = np.array([])
    for i in range(0,n):
        A0 = par[2] + (par[3]-par[0])*par[5] + (par[4]-par[1])*par[5]**2
        if(x[i] <= par[5]):
            res = np.append(res, A0 + par[0]*x[i] + par[1]*x[i]**2)
        else:
            res = np.append(res,par[2] + par[3]*x[i] + par[4]*x[i]**2)
    return res

def sum_squares (par, x, y):
    ss = sum((y-model(par,x))**2)
    print('Sum of squares = {0}'.format(ss))
    return ss

And then I used the functions as follow:

parameter = sy.array([0.0,-8.0,0.0018,0.0018,0,200])
res = least_squares(sum_squares, parameter, bounds=(-360,360), args=(x1,y1),verbose = 1)

The only problem is that it doesn't produce the results I'm looking for... And that is mainly because my x values are [0,360] and the Y values only vary by about 0.2, so it's a hard nut to crack for this function, and it produces this (poor) result:

Result


答:
Try SelectMany instead, you're currently selecting a IEnumerable<IEnumerable<ListViewItem>>:

```<code>var items = pSelectedItem.Nodes
            .Expand(e => e.Nodes)
            .Where(e => e.Nodes == null && e.Tag is List<ActionObject>)
            .Select(e => (List<ActionObject>)e.Tag)
            .SelectMany(aclist => aclist.Where(ac => ac != null))
            .Select(i => new ListViewItem()
            {
                Tag = new ListViewValue[]
                {
                    new ListViewValue() { Value = i.Command },
                    new ListViewValue() { Value = i.Target },
                    new ListViewValue() { Value = i.Value },
                    new ListViewValue() { Value = i.Comment }
                }
            };
</code>```

Title: Select within a Select returning 0 returns. How to debug?

Body:
var items = pSelectedItem.Nodes
                .Expand(e => e.Nodes)
                .Where(e => e.Nodes == null)
                .Select(e => e.Tag as List<ActionObject>)
                .Select(e=> e.Select (i=>i as ActionObject)
                    .Where(i => i != null)
                    .Select(i => new ListViewItem()
                    {
                        Tag = new ListViewValue[]
                        {
                            new ListViewValue() { Value = i.Command },
                            new ListViewValue() { Value = i.Target },
                            new ListViewValue() { Value = i.Value },
                            new ListViewValue() { Value = i.Comment }
                        }
}) as ListViewItem);

return new ObservableCollection<ListViewItem>(items);

The code above, I am trying to capture all listviewitems.  Each list view item has a tag property. This tag property is of type object.

The code above makes complete sense to me however its always returning null. I have tried debugging the code above unfortunately the code above doesn't let me debug the inner select code.  the e.Select (i=>.... is where it won't debug.

Thoughts?  Maybe my code is more complicated than it needs to be.

Body:
Try SelectMany instead, you're currently selecting a IEnumerable<IEnumerable<ListViewItem>>:

var items = pSelectedItem.Nodes
            .Expand(e => e.Nodes)
            .Where(e => e.Nodes == null && e.Tag is List<ActionObject>)
            .Select(e => (List<ActionObject>)e.Tag)
            .SelectMany(aclist => aclist.Where(ac => ac != null))
            .Select(i => new ListViewItem()
            {
                Tag = new ListViewValue[]
                {
                    new ListViewValue() { Value = i.Command },
                    new ListViewValue() { Value = i.Target },
                    new ListViewValue() { Value = i.Value },
                    new ListViewValue() { Value = i.Comment }
                }
            };


问:
remove strong tag for empty spaces in ckeditor
How can I remove the strong tag for the empty spaces created after clicking on bold and giving spaces for my text
for example :
if i  give 10 spaces then it is taking as nbsp space with in strong tag

```<code>`like_so_                          ` .
</code>```

I want to eliminate that strong tag for my spaces

```<code><html>((<strong>  `like_so_                          `  </strong>)) </html>
</code>```

答:
Use a regexp

```<code>$output = preg_replace('~<strong>(( |\s)*)</strong>~', '$1', $input);
</code>```

It'll remove strong tags containing any number of only   or white characters

Body:
How can I remove the strong tag for the empty spaces created after clicking on bold and giving spaces for my text
for example :
if i  give 10 spaces then it is taking as nbsp space with in strong tag

`like_so_                          ` .

I want to eliminate that strong tag for my spaces

((  `like_so_                          `  ))

Body:
Use a regexp

$output = preg_replace('~<strong>((&nbsp;|\s)*)</strong>~', '$1', $input);

It'll remove strong tags containing any number of only &nbsp; or white characters


问:
getCanonicalFile and getAbsoluteFile returns the current (project) directory instead of the expected one
I try to make a simple program that contains the function of browsing local file system.

However, I met a problem when the address is directly input.

```<code>public void setWorkingDirectory(File newDir)
{
    try
    {
        //try to eliminate redundancy
        this.workingDir = newDir.getCanonicalFile();
    }
    catch (IOException e)
    {
        this.workingDir = newDir;
    }
}
</code>```

I need the absolute path to display on the screen. So I use getCanonicalFile(). Everything works fine except that when I input "D:" the workingDir will be set to the current project directory in Eclipse (I think it should be the current directory when executed independently, the example is "D:\EclipseWorkspace\workspace\FTPClient") but the File newDir contains exactly the same path ("D:") (I traced it).

If I input "C:" or "D:\", then everything is fine. I couldn't find any information about this on the Internet. Could anyone tell me what's going on here and how to solve the problem?

Thanks in advance.

EDIT: I work on Windows XP SP3 with Java 6 if that matters.

答:
The path command

```<code>D:
</code>```

indicates a change to the currently selected directory on disk D.

Whereas

```<code>D:\
</code>```

indicates a change to the root directory of disk D.

This is basic Windows, you'd get the same results in a (CMD) console window.

If it really is an issue, you'd need to look at the filename and see if it terminates with a File.separator and if not, append one.

Body:
I try to make a simple program that contains the function of browsing local file system.

However, I met a problem when the address is directly input.

public void setWorkingDirectory(File newDir)
{
    try
    {
        //try to eliminate redundancy
        this.workingDir = newDir.getCanonicalFile();
    }
    catch (IOException e)
    {
        this.workingDir = newDir;
    }
}

I need the absolute path to display on the screen. So I use getCanonicalFile(). Everything works fine except that when I input "D:" the workingDir will be set to the current project directory in Eclipse (I think it should be the current directory when executed independently, the example is "D:\EclipseWorkspace\workspace\FTPClient") but the File newDir contains exactly the same path ("D:") (I traced it).

If I input "C:" or "D:\", then everything is fine. I couldn't find any information about this on the Internet. Could anyone tell me what's going on here and how to solve the problem?

Thanks in advance.

EDIT: I work on Windows XP SP3 with Java 6 if that matters.

Body:
The path command

D:

indicates a change to the currently selected directory on disk D.

Whereas

D:\

indicates a change to the root directory of disk D.

This is basic Windows, you'd get the same results in a (CMD) console window.

If it really is an issue, you'd need to look at the filename and see if it terminates with a File.separator and if not, append one.


问:
Applying lock on HashMap
I have a HashMap which is static and three threads which try to access HashMap simultaneously from their corresponding class`s.

each thread task is get list value of a specified key, process some operations on the list(modify the list). and put the processed list in HashMap.

I want to make other threads trying to access the HashMap wait until current thread finishes the processing and modifying the HashMap.

in some situation, the flow is like this,

thread A is retrieved HashMap, while Thread A is processing on the list of HashMap, other Thread B retrieves the HashMap and starts its processing.

Actual behaviour has to be like:

    Thread A -> retrieves HashMap -> process -> put value in HashMap.
    Thread B -> retrieves HashMap -> process -> put value in HashMap.
    Thread C -> retrieves HashMap -> process -> put value in HashMap.

logic :

apply lock on HashMap

retrieve.

process.

put into HashMap.

release lock.

help me in converting the logic to code, or any suggestions are accepted with smile.

答:
You can use ConcurrentHashMap instead of HashMap. The ConcurrentHashMap gives better performance and reduces overhead of locking the whole HashMap while other thread is accessing it.
You can find more details on this page as well - http://crunchify.com/hashmap-vs-concurrenthashmap-vs-synchronizedmap-how-a-hashmap-can-be-synchronized-in-java/

Title: Applying lock on HashMap


问:
jQuery - slideUp / slideDown not working on ul?
I have the following code in my masterpage:

jQuery:

```<code>$(window).load(function () {
    $("li.submenu").hover(
        function () { $(this).find("ul").slideDown("slow"); },
        function () { $(this).find("ul").slideUp("slow"); }
    );
});
</code>```

HTML:

```<code><ul class="menu" runat="server" id="Menu">
    <li class="first" runat="server"><asp:HyperLink runat="server" NavigateUrl="/index.aspx">Home</asp:HyperLink></li>
    <li class="submenu" runat="server">
        <asp:HyperLink runat="server" NavigateUrl="/categories/index.aspx">Products</asp:HyperLink>
        <ul runat="server">
            <li runat="server"><asp:HyperLink runat="server" NavigateUrl="/categories/category1.aspx">Dogs</asp:HyperLink></li>
            <li runat="server"><asp:HyperLink runat="server" NavigateUrl="/categories/category2.aspx">Category 2</asp:HyperLink></li>
            <li runat="server"><asp:HyperLink runat="server" NavigateUrl="/categories/category3.aspx">Category 3</asp:HyperLink></li>
            <li runat="server"><asp:HyperLink runat="server" NavigateUrl="/categories/category4.aspx">Category 4</asp:HyperLink></li>
            <li runat="server"><asp:HyperLink runat="server" NavigateUrl="/categories/category5.aspx">Category 5</asp:HyperLink></li>
            <li class="last" runat="server"><asp:HyperLink runat="server" NavigateUrl="/categories/category6.aspx">Category 6</asp:HyperLink></li>
         </ul>
    </li>
    <li class="last" runat="server"><asp:HyperLink runat="server" NavigateUrl="/contact.aspx">Contact Us</asp:HyperLink></li>
</ul>
</code>```

If I changed this to toggle("slide") it slides in from one side and then exits on the same side when the mouse enters and leaves the li.submenu. This means that the elements exist for definite, and there are no typos. However the slideDown and slideUp functions do not seem to be functioning (unless slow means ultra fast...).

The files I am including for jQuery and jQuery UI are jquery-1.4.2.js and jquery-ui-1.7.2.custom.min.js. This is enough, isn't it?

I have CSS to specify that the submenu is displayed or hidden instantly (display: block; / display: none;) in case the user does not have JS. Is there any chance that this is causing the problem? Should I alter the class of the submenu using JS so that the CSS cannot act on it if JS is enabled? Or is there some other problem which is not caused by the CSS?

答:
EDIT

This solution does not actually work, now that I have tested it. I need the submenu to stay visible when the mouse moves out of the link. In this case it doesn't. Back to the drawing board..

It actually turns out that my original solution does work, but only if I put

```<code>$("ul li.submenu ul").toggle(0);
</code>```

before it (this sets the menus to the opposite and back to their original state without the user even realising). Strange, but I can live with that.

ORIGINAL ANSWER

Well after a while, and quite a long time gazing at the code wondering what the hell was wrong with it, it occurred to me that the link directly within the li.submenu was set to display: block, with width and height set to 100%. It was actually this which needed changing, resulting in the jQuery looking like the following:

```<code>$(document).ready(function () {
    $("li.submenu > a").hover(
        function () { $(this).closest("li.submenu").find("ul").slideDown("slow"); },
        function () { $(this).closest("li.submenu").find("ul").slideUp("slow"); }
    );
});
</code>```

This is it... problem solved. However it seems to take a second or two to pick up the slide instructions. This simply means that if anyone hovers over the li.submenu within a second or two of the page loading then it will display the menu instantly rather than sliding - I think that is a non-issue though.

Hope this helps someone out in the future.

Body:
I have the following code in my masterpage:

jQuery:

$(window).load(function () {
    $("li.submenu").hover(
        function () { $(this).find("ul").slideDown("slow"); },
        function () { $(this).find("ul").slideUp("slow"); }
    );
});

HTML:

<asp:HyperLink runat="server" NavigateUrl="/index.aspx">Home</asp:HyperLink>

        <asp:HyperLink runat="server" NavigateUrl="/categories/index.aspx">Products</asp:HyperLink>

<asp:HyperLink runat="server" NavigateUrl="/categories/category1.aspx">Dogs</asp:HyperLink>

<asp:HyperLink runat="server" NavigateUrl="/categories/category2.aspx">Category 2</asp:HyperLink>

<asp:HyperLink runat="server" NavigateUrl="/categories/category3.aspx">Category 3</asp:HyperLink>

<asp:HyperLink runat="server" NavigateUrl="/categories/category4.aspx">Category 4</asp:HyperLink>

<asp:HyperLink runat="server" NavigateUrl="/categories/category5.aspx">Category 5</asp:HyperLink>

<asp:HyperLink runat="server" NavigateUrl="/categories/category6.aspx">Category 6</asp:HyperLink>

<asp:HyperLink runat="server" NavigateUrl="/contact.aspx">Contact Us</asp:HyperLink>

If I changed this to toggle("slide") it slides in from one side and then exits on the same side when the mouse enters and leaves the li.submenu. This means that the elements exist for definite, and there are no typos. However the slideDown and slideUp functions do not seem to be functioning (unless slow means ultra fast...).

The files I am including for jQuery and jQuery UI are jquery-1.4.2.js and jquery-ui-1.7.2.custom.min.js. This is enough, isn't it?

I have CSS to specify that the submenu is displayed or hidden instantly (display: block; / display: none;) in case the user does not have JS. Is there any chance that this is causing the problem? Should I alter the class of the submenu using JS so that the CSS cannot act on it if JS is enabled? Or is there some other problem which is not caused by the CSS?

Body:
EDIT

This solution does not actually work, now that I have tested it. I need the submenu to stay visible when the mouse moves out of the link. In this case it doesn't. Back to the drawing board..

It actually turns out that my original solution does work, but only if I put

$("ul li.submenu ul").toggle(0);

before it (this sets the menus to the opposite and back to their original state without the user even realising). Strange, but I can live with that.

ORIGINAL ANSWER

Well after a while, and quite a long time gazing at the code wondering what the hell was wrong with it, it occurred to me that the link directly within the li.submenu was set to display: block, with width and height set to 100%. It was actually this which needed changing, resulting in the jQuery looking like the following:

$(document).ready(function () {
    $("li.submenu > a").hover(
        function () { $(this).closest("li.submenu").find("ul").slideDown("slow"); },
        function () { $(this).closest("li.submenu").find("ul").slideUp("slow"); }
    );
});

This is it... problem solved. However it seems to take a second or two to pick up the slide instructions. This simply means that if anyone hovers over the li.submenu within a second or two of the page loading then it will display the menu instantly rather than sliding - I think that is a non-issue though.

Hope this helps someone out in the future.