问:
A case insensitive string class in python
I need to perform case insensitive string comparisons in python in sets and dictionary keys. Now, to create sets and dict subclasses that are case insensitive proves surprisingly tricky (see: Case insensitive dictionary for ideas, note they all use lower - hey there's even a rejected PEP, albeit its scope is a bit broader). So I went with creating a case insensitive string class (leveraging this answer by @AlexMartelli):

```<code>class CIstr(unicode):
    """Case insensitive with respect to hashes and comparisons string class"""

    #--Hash/Compare
    def __hash__(self):
        return hash(self.lower())
    def __eq__(self, other):
        if isinstance(other, basestring):
            return self.lower() == other.lower()
        return NotImplemented
    def __ne__(self, other): return not (self == other)
    def __lt__(self, other):
        if isinstance(other, basestring):
            return self.lower() < other.lower()
        return NotImplemented
    def __ge__(self, other): return not (self < other)
    def __gt__(self, other):
        if isinstance(other, basestring):
            return self.lower() > other.lower()
        return NotImplemented
    def __le__(self, other): return not (self > other)
</code>```

I am fully aware that lower is not really enough to cover all cases of string comparisons in unicode but I am refactoring existing code that used a much clunkier class for string comparisons (memory and speed wise) which anyway used lower() - so I can amend this on a later stage - plus I am on python 2 (as seen by unicode). My questions are:

did I get the operators right ?

is this class enough for my purposes, given that I take care to construct keys in dicts and set elements as CIstr instances - my purposes being checking equality, containment, set differences and similar operations in a case insensitive way. Or am I missing something ?

is it worth it to cache the lower case version of the string (as seen for instance in this ancient python recipe: Case Insensitive Strings). This comment suggests that not - plus I want to have construction as fast as possible and size as small as possible but people seem to include this.

Python 3 compatibility tips are appreciated !

Tiny demo:

```<code>d = {CIstr('A'): 1, CIstr('B'): 2}
print 'a' in d # True
s = set(d)
print {'a'} - s # set([])
</code>```

答:
The code mostly looks fine.  I would eliminate the short-cut's in __ge__, __le__, and __ne__ and expand them to call lower() directly.

The short-cut looks like what is done in `functools.total_ordering() but it just slows down the code and makes it harder to test cross-type comparisons which are tricky to get right when the methods are interdependent.

Body:
I need to perform case insensitive string comparisons in python in sets and dictionary keys. Now, to create sets and dict subclasses that are case insensitive proves surprisingly tricky (see: Case insensitive dictionary for ideas, note they all use lower - hey there's even a rejected PEP, albeit its scope is a bit broader). So I went with creating a case insensitive string class (leveraging this answer by @AlexMartelli):

class CIstr(unicode):
    """Case insensitive with respect to hashes and comparisons string class"""

    #--Hash/Compare
    def __hash__(self):
        return hash(self.lower())
    def __eq__(self, other):
        if isinstance(other, basestring):
            return self.lower() == other.lower()
        return NotImplemented
    def __ne__(self, other): return not (self == other)
    def __lt__(self, other):
        if isinstance(other, basestring):
            return self.lower() < other.lower()
        return NotImplemented
    def __ge__(self, other): return not (self < other)
    def __gt__(self, other):
        if isinstance(other, basestring):
            return self.lower() > other.lower()
        return NotImplemented
    def __le__(self, other): return not (self > other)

I am fully aware that lower is not really enough to cover all cases of string comparisons in unicode but I am refactoring existing code that used a much clunkier class for string comparisons (memory and speed wise) which anyway used lower() - so I can amend this on a later stage - plus I am on python 2 (as seen by unicode). My questions are:

did I get the operators right ?

is this class enough for my purposes, given that I take care to construct keys in dicts and set elements as CIstr instances - my purposes being checking equality, containment, set differences and similar operations in a case insensitive way. Or am I missing something ?

is it worth it to cache the lower case version of the string (as seen for instance in this ancient python recipe: Case Insensitive Strings). This comment suggests that not - plus I want to have construction as fast as possible and size as small as possible but people seem to include this.

Python 3 compatibility tips are appreciated !

Tiny demo:

d = {CIstr('A'): 1, CIstr('B'): 2}
print 'a' in d # True
s = set(d)
print {'a'} - s # set([])


来源: stackexchange

问:
how to append option into select combo box in d3
I want to add the option into select combo box for example I have data like

```<code>[{ "NAME": "JONE", "ID": {"id1":123,"id2":124}}, { "NAME": "ANGEL", "ID": {"id1":125,"id2":127}}]`
</code>```

I want to append into options the "Name", I have done this so far:

```<code>dataset=d3.json("namees.json", function(data) {
    select = d3.select('body')
    .append('select')
    .attr('class','style');
    options = select
    .selectAll('option')

    .append('option')
            .text(data.forEach(function (d) {return d.Name}))

});
</code>```

But it doesn't show the values in select option

答:
You can do it like the following:

Append the select element

```<code> var dropDown = d3.select("body").append("select")
    .attr("name", "name-list");
</code>```

Append options to your select element based on data

```<code>var options = dropDown.selectAll("option")
 .data(data)
 .enter()
 .append("option");
</code>```

Set the text and value for your options

```<code>options.text(function(d) {
return d.NAME;
 })
   .attr("value", function(d) {
return d.NAME;
});
</code>```

JSFiddle - https://jsfiddle.net/x4a8ejk6/

ContentLicense: CC BY-SA 3.0

Body:
I want to add the option into select combo box for example I have data like

[{ "NAME": "JONE", "ID": {"id1":123,"id2":124}}, { "NAME": "ANGEL", "ID": {"id1":125,"id2":127}}]`

I want to append into options the "Name", I have done this so far:

dataset=d3.json("namees.json", function(data) {
    select = d3.select('body')
    .append('select')
    .attr('class','style');
    options = select
    .selectAll('option')

    .append('option')
            .text(data.forEach(function (d) {return d.Name}))

});

But it doesn't show the values in select option

Body:
You can do it like the following:

Append the select element

 var dropDown = d3.select("body").append("select")
    .attr("name", "name-list");

Append options to your select element based on data

var options = dropDown.selectAll("option")
 .data(data)
 .enter()
 .append("option");

Set the text and value for your options

options.text(function(d) {
return d.NAME;
 })
   .attr("value", function(d) {
return d.NAME;
});

JSFiddle - https://jsfiddle.net/x4a8ejk6/


问:
" Use of unassigned local variable" error for three local variables but not for the fourth local variable. Why?
For the following code in C#, why are the errors obtained: -

Error 1: Use of unassigned local variable circleArea

  Error 2: Use of unassigned local variable circleRadius

  Error 3: Use of unassigned local variable circleDiameter

but not for paramaterChoice; even though it also is an uninitialized local variable?

```<code>static void Main(string[] args)
{
    char paramaterChoice;
    double circleRadius, circleDiameter, circleArea;
    const double PI=3.14;

    Console.WriteLine("If you know the radius press r or R, If you know the diameter press d or D");
    paramaterChoice = Convert.ToChar(Console.ReadLine());

    switch (paramaterChoice)
    {
        case 'r':
        case 'R':
            Console.WriteLine("Enter the Radius of the Circle");
            circleRadius = Convert.ToDouble(Console.ReadLine());
            circleArea = PI * circleRadius * circleRadius;
            //Console.WriteLine("Area of Cirle is: {0:f2}", circleArea);
            break;
        case 'd':
        case 'D':
            Console.WriteLine("Enter the Diameter of the Circle");
            circleDiameter = Convert.ToDouble(Console.ReadLine());
            circleArea = PI * circleDiameter * circleDiameter / 4;
            //Console.WriteLine("Area of Cirle is: {0:f2}", circleArea);
            break;
    }

    // The error occurs on the next line:
    Console.WriteLine("Parameter: {0}, Radius: {1:f2}, Diameter: {2:f2}, Area: {3:f2}",
        paramaterChoice, circleRadius, circleDiameter, circleArea);

    Console.WriteLine("\nProgram Info: Calculates the Area of a circle");
}
</code>```

答:
Your problem is here:

```<code>Console.WriteLine("Radius: {0:f2}, Diameter: {1:f2}, Area: {2:f2}", circleRadius, circleDiameter, circleArea);
</code>```

Those values are only assigned in your switch statement, and only if they enter one of your optional values. (either r, R, d or D).

Which means if neither one of those was entered, well...

So to fix this, either set the values to 0 to start with:

```<code>double circleRadius = 0, circleDiameter = 0, circleArea = 0;
</code>```

Or handle the values in your switch statement using

```<code>default:
//Set values here.
break;
</code>```

default basically means if neither of these was entered.

Body:
For the following code in C#, why are the errors obtained: -

Error 1: Use of unassigned local variable circleArea

  Error 2: Use of unassigned local variable circleRadius

  Error 3: Use of unassigned local variable circleDiameter

but not for paramaterChoice; even though it also is an uninitialized local variable?

static void Main(string[] args)
{
    char paramaterChoice;
    double circleRadius, circleDiameter, circleArea;
    const double PI=3.14;

    Console.WriteLine("If you know the radius press r or R, If you know the diameter press d or D");
    paramaterChoice = Convert.ToChar(Console.ReadLine());

    switch (paramaterChoice)
    {
        case 'r':
        case 'R':
            Console.WriteLine("Enter the Radius of the Circle");
            circleRadius = Convert.ToDouble(Console.ReadLine());
            circleArea = PI * circleRadius * circleRadius;
            //Console.WriteLine("Area of Cirle is: {0:f2}", circleArea);
            break;
        case 'd':
        case 'D':
            Console.WriteLine("Enter the Diameter of the Circle");
            circleDiameter = Convert.ToDouble(Console.ReadLine());
            circleArea = PI * circleDiameter * circleDiameter / 4;
            //Console.WriteLine("Area of Cirle is: {0:f2}", circleArea);
            break;
    }

    // The error occurs on the next line:
    Console.WriteLine("Parameter: {0}, Radius: {1:f2}, Diameter: {2:f2}, Area: {3:f2}",
        paramaterChoice, circleRadius, circleDiameter, circleArea);

    Console.WriteLine("\nProgram Info: Calculates the Area of a circle");
}

Body:
Your problem is here:

Console.WriteLine("Radius: {0:f2}, Diameter: {1:f2}, Area: {2:f2}", circleRadius, circleDiameter, circleArea);

Those values are only assigned in your switch statement, and only if they enter one of your optional values. (either r, R, d or D).

Which means if neither one of those was entered, well...

So to fix this, either set the values to 0 to start with:

double circleRadius = 0, circleDiameter = 0, circleArea = 0;

Or handle the values in your switch statement using

default:
//Set values here.
break;

default basically means if neither of these was entered.


问:
Understanding ReactJS Controlled form components
I am implementing the following code based on the following page: https://facebook.github.io/react/docs/forms.html

```<code>class Reservation extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isGoing: true,
      numberOfGuests: 2
    };

    this.handleInputChange = this.handleInputChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleInputChange(event) {
    const target = event.target;
    const value = target.type === 'checkbox' ? target.checked : target.value;
    const name = target.name;

    this.setState({
      [name]: value
    });
  }

  handleSubmit(event) {
    event.preventDefault();

    let data = {
      isGoing: this.state.isGoing,
      numberOfGuests: this.state.numberofGuests
    }

    /* Send data in ajax request here */

  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Is going:
          <input
            name="isGoing"
            type="checkbox"
            checked={this.state.isGoing}
            onChange={this.handleInputChange} />
        </label>
        <br />
        <label>
          Number of guests:
          <input
            name="numberOfGuests"
            type="number"
            value={this.state.numberOfGuests}
            onChange={this.handleInputChange} />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}
</code>```

Some questions I have about it:

Why do we need to store the component values in state? Why not
just grab the values we need when the form is submitted as normally
would be done with standard JavaScript? The recommended way would seem to reload the render function for every single character typed in or deleted. To me this makes little sense.

Since the execution of setState is asynchronous and there may be a delay between this.setState() and actually accessing the state with this.state.numberOfGuests does this mean that this code may end up grabbing the state before it has been set? If so, why is this code being suggested in the official React docs? If not, why not?

答:
Regarding point number two, then yes it is logically possible that handleSubmit could run before the state update in handleInputChanged has completed.  The reason this isn't mentioned in the React docs, or is generally a concern for anyone is because the setState function runs really quickly.  As an experiment I made a codepen to determine the average time taken for setState to run.  It seems to take in the order of around 0.02 milliseconds.  There is no way someone can change their input, then submit the form in less than that time.  In fact, the e.preventDefault() call in handleSubmit takes nearly a quarter of that time anyway.

If you have a situation where it is absolutely crucial that setState has completed before continuing, then you can use a callback function to setState, e.g.

```<code>this.setState({
    colour: 'red'
}, () => {
    console.log(this.state.color)
});
</code>```

Then red will always be logged, as opposed to the following where the previous value may be logged.

```<code>this.setState({
    colour: 'red'
});
console.log(this.state.color);
</code>```

Body:
I am implementing the following code based on the following page: https://facebook.github.io/react/docs/forms.html

class Reservation extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isGoing: true,
      numberOfGuests: 2
    };

    this.handleInputChange = this.handleInputChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleInputChange(event) {
    const target = event.target;
    const value = target.type === 'checkbox' ? target.checked : target.value;
    const name = target.name;

    this.setState({
      [name]: value
    });
  }

  handleSubmit(event) {
    event.preventDefault();

    let data = {
      isGoing: this.state.isGoing,
      numberOfGuests: this.state.numberofGuests
    }

    /* Send data in ajax request here */

  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>

          Is going:
          <input
            name="isGoing"
            type="checkbox"
            checked={this.state.isGoing}
            onChange={this.handleInputChange} />

          Number of guests:
          <input
            name="numberOfGuests"
            type="number"
            value={this.state.numberOfGuests}
            onChange={this.handleInputChange} />

        <input type="submit" value="Submit" />
      </form>
    );
  }
}

Some questions I have about it:

Why do we need to store the component values in state? Why not
just grab the values we need when the form is submitted as normally
would be done with standard JavaScript? The recommended way would seem to reload the render function for every single character typed in or deleted. To me this makes little sense.

Since the execution of setState is asynchronous and there may be a delay between this.setState() and actually accessing the state with this.state.numberOfGuests does this mean that this code may end up grabbing the state before it has been set? If so, why is this code being suggested in the official React docs? If not, why not?

Body:
Regarding point number two, then yes it is logically possible that handleSubmit could run before the state update in handleInputChanged has completed.  The reason this isn't mentioned in the React docs, or is generally a concern for anyone is because the setState function runs really quickly.  As an experiment I made a codepen to determine the average time taken for setState to run.  It seems to take in the order of around 0.02 milliseconds.  There is no way someone can change their input, then submit the form in less than that time.  In fact, the e.preventDefault() call in handleSubmit takes nearly a quarter of that time anyway.

If you have a situation where it is absolutely crucial that setState has completed before continuing, then you can use a callback function to setState, e.g.

this.setState({
    colour: 'red'
}, () => {
    console.log(this.state.color)
});

Then red will always be logged, as opposed to the following where the previous value may be logged.

this.setState({
    colour: 'red'
});
console.log(this.state.color);


问:
Python Tkinter: How to modify the font of the Menu widget?
I am trying to make a tkinter Menu widget with the font of Courier New. Unfortunately the font attribute doesn't seem to be working. I am using Python 3.4.1. Below is the code:

```<code>from tkinter import *

class Arshi(Frame):

    def __init__(self, master):
        Frame.__init__(self, master)
        self.pack(fill=BOTH)
        self.topbar()

    def topbar(self):
        self.menufont = ("Courier New", 9)
        self.menu = Menu(self, font=self.menufont)
        self.master.config(menu=self.menu)

root = Tk()
root.title("Arshi")
window = Arshi(root)
window.mainloop()
</code>```

答:
Tkinter is a Python binding to Tk widgets.  Tk's menu widget is designed to have a non-programmable font.  That is the approach other popular widget toolkits have taken under GUI development, namely:

-- A system's applications should have standardized menus no matter which toolkit was used to create it.

-- All applications menu-fonts are configurable by the individual user under a single system-wide configuration option (look for your system's user setting for the font settings for menus).

-- All menus will look the same, regardless of whether you use Tk or a competitors widget.

-- If another menu does look different, then it's not really a menu widget.

For example, within Ubuntu, an applications menu will be thrown to the top-left of the screen, separate from the main application window.  OS-X has a similar approach.  Windows, Mac and Linux Desktops all allow their individual users to adjust their menu fonts to their personal preference, but not to the programmer's personal preference.

It is possible to use another widget class to mimic the appearance of a menu, and the programmer can customize the font to their own personal liking that way.  For example, you can use the menubutton widget and adjust it's font option, and place those within a frame.  It would then serve the purpose of a  non-standard menu.

Body:
I am trying to make a tkinter Menu widget with the font of Courier New. Unfortunately the font attribute doesn't seem to be working. I am using Python 3.4.1. Below is the code:

from tkinter import *

class Arshi(Frame):

    def __init__(self, master):
        Frame.__init__(self, master)
        self.pack(fill=BOTH)
        self.topbar()

    def topbar(self):
        self.menufont = ("Courier New", 9)
        self.menu = Menu(self, font=self.menufont)
        self.master.config(menu=self.menu)

root = Tk()
root.title("Arshi")
window = Arshi(root)
window.mainloop()


问:
Business Objects JAVA SDK ISessionMgr.logon hangs
We recently upgraded our Business Object XI environment for a new Business Objects 4.1 but we are now experiencing some issues with it

We have an Java web application hosted on a Weblogic server  that use the BO SDK to schedule Crystal Report on another server (Windows VM + tomcat server & BO 4.1)

Here’s the code used for the schedule :

```<code>  /**
   * Schedule a report inside CrystalReport
   */
  public void executeReport(ReportContext reportContext) throws Exception {
  logger.info("Class CrystalReportHelper, Executing report request for report '" + reportContext.getReportName() + "'");

  IEnterpriseSession enterpriseSession = null;
  try {
     String password = getPassword(reportContext);
     logger.info("Class CrystalReportHelper, Retrievieving password ");
     if (password != null) {
        if (logger.isDebugEnabled()) {
           logger.debug("Class CrystalReportHelper, Password obtained '" + password + "'");
        }
        else {
           logger.info("Class CrystalReportHelper, Password obtained ");
        }
     }
     else {
        logger.error("Class CrystalReportHelper, Invalid password for BO Logon");
        throw new Exception("Invalid password for BO Logon - password is null");
     }

     String username = getUserName(reportContext);
     logger.info("Class CrystalReportHelper, Retrievieving username ");
     if (username != null) {
        logger.info("Class CrystalReportHelper, User name obtained '" + username + "'");
     }
     else {
        logger.error("Class CrystalReportHelper, Invalid username for BO Logon");
        throw new Exception("Invalid username for BO Logon - username is null");
     }

     String cmsName = getCentralManagementServerName();
     logger.info("Class CrystalReportHelper, Retrievieving Central Management Server Name ");
     if (cmsName != null) {
        logger.info("Class CrystalReportHelper,Central Management Server Name obtained = " + cmsName);
     }
     else {
        logger.error("Class CrystalReportHelper, Invalid Central Management Server Name for BO Logon.");
        throw new Exception("Invalid Central Management Server Name for BO Logon - Central Management Server Name is null");
     }

     enterpriseSession = getSession(username, password, cmsName);
     if (logger.isDebugEnabled()) {
        logger.debug("Class CrystalReportHelper, Retrieving BusinessObjectEnterprise Session with username'" + username + "' password '" + password + "' cmsName '" + cmsName + "' ");
     }
     else {
        logger.info("Class CrystalReportHelper, Retrieving BusinessObjectEnterprise Session with username'" + username + "' password '" + "XXXX" + "' cmsName '" + cmsName + "' ");
     }
     if (enterpriseSession == null) {
        logger.error("Class CrystalReportHelper, Coud not retrieve BusinessObjectEnterprise Session with username'" + username + "' password '" + password + "' cmsName '" + cmsName + "' ");
        throw new Exception("Could not retreive BO Session with username : " + username + " and CMS : " + cmsName);
     }
     if (logger.isDebugEnabled()) {
        logger.debug("Class CrystalReportHelper, BusinessObjectEnterprise Session retrieve with username'" + username + "' password '" + password + "' cmsName '" + cmsName + "' ");
     }
     else {
        logger.info("Class CrystalReportHelper, BusinessObjectEnterprise Session retrieve with username'" + username + "' password '" + "XXXX" + "' cmsName '" + cmsName + "' ");
     }

     IInfoStore infoStore = (IInfoStore) enterpriseSession.getService(cmsName, BO_INFO_STORE);
     logger.info("Class CrystalReportHelper, Retrieving BO service with cmsName'" + cmsName + "' BO_INFO_STORE '" + BO_INFO_STORE + "'");
     if (infoStore == null) {
        logger.error("Class CrystalReportHelper, Coud not obtain BO service with cmsName'" + cmsName + "' BO_INFO_STORE '" + BO_INFO_STORE + "'");
        throw new Exception("Could not obtain BO service : " + BO_INFO_STORE);
     }

     // Queries the CMS for the report.
     logger.info("Class CrystalReportHelper, BO service retrieved with cmsName'" + cmsName + "' BO_INFO_STORE '" + BO_INFO_STORE + "'");

     String queryReport = REPORT_QUERY.replaceFirst(REPLACE_REPORT_NAME, getReportName(reportContext));

     logger.info("Class CrystalReportHelper, Executing query report '" + queryReport + "'.");
     IInfoObjects reports = infoStore.query(queryReport);
     if (reports.size() == 0) {
        logger.error("Class CrystalReportHelper, Report '" + queryReport + "' not found..");
        throw new Exception("Report " + getReportName(reportContext) + " not found in BusinessObject");
     }
     IReport report = (IReport) reports.get(0);

     // Set report format.
     IReportFormatOptions reportFormat = report.getReportFormatOptions();

     int formatType = IReportFormatOptions.CeReportFormat.CRYSTAL_REPORT;
     reportFormat.setFormat(formatType);

     String destinationInbox = getDestinationInbox(reportContext);
     IDestinationPlugin destinationPlugin = getDestinationPlugin(infoStore, destinationInbox);

     // Create an interface to the scheduling options for the report.
     ISchedulingInfo scheduleInfo = report.getSchedulingInfo();
     scheduleInfo.setType(CeScheduleType.ONCE);
     scheduleInfo.setRightNow(true);

     IDestination destination = scheduleInfo.getDestination();
     destination.setFromPlugin(destinationPlugin);

     // copy the report parameters
     this.setParameters(reportContext, report);

     logger.info("Class CrystalReportHelper, Scheduling report '" + getReportName(reportContext) + "'. ");
     infoStore.schedule(reports);
     logger.info("Class CrystalReportHelper, Report '" + getReportName(reportContext) + "' has been scheduled. ");

     if (reportContext.isEmailRequired() & isEmailEnabled()) {
        sendEmail(reportContext);
     }
  }
  catch (SDKRuntimeException SDKre) {
     logger.error("Class CrystalReportHelper, Could not execute report request for report '" + reportContext.getReportName() + "' caught SDKRuntimeException:  " + SDKre.getMessage(), SDKre);
     throw new Exception(SDKre);
  }
  catch (SDKException SDKe) {
     logger.error("Class CrystalReportHelper, Could not execute report request for report '" + reportContext.getReportName() + "' caught SDKException:  " + SDKe.getMessage(), SDKe);
     throw new Exception(SDKe);
  }
  finally {
     if (null != enterpriseSession) {
        enterpriseSession.logoff();
     }
  }
</code>```

Here’s some data info :

Reportcontext contains things like user/password for BO, report name and report prompt parameter to use

BO_INFO_STORE = “InfoStore”;

REPORT_QUERY = "Select * From CI_INFOOBJECTS WHERE SI_NAME='" + REPLACE_REPORT_NAME + "' AND SI_INSTANCE = 'false'";

Here's the method getSession used to connect to BO :

```<code>    /**
     * return BusinessObjectEnterprise session
     *
     * @param username
     * @param password
     * @return IEnterpriseSession
     * @throws SDKException
     */
     public IEnterpriseSession getSession(String username, String password,      String cmsName) throws SDKException {
     logger.debug("Class CrystalReportHelper, Retrieving    BusinessObjectEnterprise Session  username'" + username + "' password '" +   password + "' cmsName '" + cmsName + "' ");

  IEnterpriseSession enterpriseSession = null;
  ISessionMgr sessionMgr = CrystalEnterprise.getSessionMgr();

  boolean isAuthenticateEnterprise = getReportProperties().getAuthenticationTypeEnterprise();
  logger.debug("Class CrystalReportHelper, isAuthenticateEnterprise  '" + isAuthenticateEnterprise + "' ");
  if (isAuthenticateEnterprise) {
     enterpriseSession = sessionMgr.logon(username, password, cmsName, CeProgID.SEC_ENTERPRISE);
  }
  else {
     enterpriseSession = sessionMgr.logon(username, password, cmsName, CeProgID.SEC_LDAP);
  }

  logger.debug("Class CrystalReportHelper, BusinessObjectEnterprise Session  obtained for username'" + username + "' password '" + password + "' cmsName '" + cmsName + "' ");
  return enterpriseSession;
}
</code>```

The problem we’re experiencing is sometimes the process will hang on this line for about 45min :

```<code>enterpriseSession = sessionMgr.logon(username, password, cmsName, CeProgID.SEC_ENTERPRISE);
</code>```

Here’s a stacktrace from Weblogic when this occurs :

```<code>"[ACTIVE] ExecuteThread: '7' for queue: 'weblogic.kernel.Default (self-tuning)'" waiting for lock java.lang.Object@3d24ae2c WAITING
   java.lang.Object.wait(Native Method)
   java.lang.Object.wait(Object.java:485)
       com.crystaldecisions.thirdparty.com.ooc.OB.Downcall.waitUntilCompleted(Downcall.java:831)
       com.crystaldecisions.thirdparty.com.ooc.OB.GIOPClientWorkerThreaded.receive(GIOPClientWorkerThreaded.java:327)
       com.crystaldecisions.thirdparty.com.ooc.OB.GIOPClientWorkerThreaded.sendReceive(GIOPClientWorkerThreaded.java:353)
   com.crystaldecisions.thirdparty.com.ooc.OB.Downcall.request(Downcall.java:336)
   com.crystaldecisions.thirdparty.com.ooc.OB.DowncallStub.invoke(DowncallStub.java:583)
   com.crystaldecisions.thirdparty.com.ooc.CORBA.Delegate.invoke(Delegate.java:579)
       com.crystaldecisions.thirdparty.org.omg.CORBA.portable.ObjectImpl._invoke(ObjectImpl.java:125)
       com.crystaldecisions.enterprise.ocaframework.idl.ImplServ._OSCAFactoryStub.newService(_OSCAFactoryStub.java:78)
   com.crystaldecisions.enterprise.ocaframework.i.a(Unknown Source)
   com.crystaldecisions.enterprise.ocaframework.i.a(Unknown Source)
   com.crystaldecisions.enterprise.ocaframework.i.buildClusterInfo(Unknown Source)
   com.crystaldecisions.enterprise.ocaframework.aa.int(Unknown Source)
   com.crystaldecisions.enterprise.ocaframework.ServiceMgr.int(Unknown Source)
   com.crystaldecisions.enterprise.ocaframework.p.a(Unknown Source)
   com.crystaldecisions.enterprise.ocaframework.ServiceMgr.getManagedService(Unknown Source)
   com.crystaldecisions.sdk.occa.security.internal.f.if(Unknown Source)
   com.crystaldecisions.sdk.occa.security.internal.f.<init>(Unknown Source)
       com.crystaldecisions.sdk.occa.security.internal.SecurityFactory.makeSecuritySession(Unknown Source)
   com.crystaldecisions.sdk.occa.security.internal.t.a(Unknown Source)
   com.crystaldecisions.sdk.occa.security.internal.t.userLogon(Unknown Source)
   com.crystaldecisions.sdk.occa.security.internal.l.userLogon(Unknown Source)
   com.crystaldecisions.sdk.framework.internal.b.logon(Unknown Source)
       com.tranme.guide.commonservices.report.CrystalReportHelper.getSession(CrystalReportHelper.java:156)
       com.tranme.guide.commonservices.report.CrystalReportHelper.getReportInfoObjectsByReportName(CrystalReportHelper.java:503)
       com.tranme.guide.notificationmgt.manager.reports.util.ReportManagementTools.getReportInstanceStatuses(ReportManagementTools.java:81)
       com.tranme.guide.notificationmgt.manager.reports.util.ReportManagementTools.getGenerationStatusResults(ReportManagementTools.java:51)
       com.tranme.guide.notificationmgt.manager.BaseNotificationManager.updateReportGenerationStatus(BaseNotificationManager.java:244)
       com.tranme.guide.notificationmgt.business.ejb.impl.NotificationManagementFacadeBeanImpl.updateReportGenerationStatus(NotificationManagementFacadeBeanImpl.java:123)
        com.tranme.guide.notificationmgt.business.ejb.impl.NotificationManagementFacadeBeanImpl_z3lp9c_EOImpl.updateReportGenerationStatus(NotificationManagementFacadeBeanImpl_z3lp9c_EOImpl.java:140)
       com.tranme.guide.notificationmgt.business.ejb.impl.NotificationManagementFacadeBeanImpl_z3lp9c_EOImpl_WLSkel.invoke(Unknown Source)
   weblogic.rmi.internal.BasicServerRef.invoke(BasicServerRef.java:589)
   weblogic.rmi.cluster.ClusterableServerRef.invoke(ClusterableServerRef.java:230)
   weblogic.rmi.internal.BasicServerRef$1.run(BasicServerRef.java:477)
   weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:363)
   weblogic.security.service.SecurityManager.runAs(SecurityManager.java:147)
   weblogic.rmi.internal.BasicServerRef.handleRequest(BasicServerRef.java:473)
   weblogic.rmi.internal.wls.WLSExecuteRequest.run(WLSExecuteRequest.java:118)
   weblogic.work.ExecuteThread.execute(ExecuteThread.java:201)
   weblogic.work.ExecuteThread.run(ExecuteThread.java:173)
"Business Objects - Sessions Clean up" TIMED_WAITING
   java.lang.Thread.sleep(Native Method)
   com.crystaldecisions.enterprise.ocaframework.n.run(Unknown Source)
   java.lang.Thread.run(Thread.java:619)
"OracleTimeoutPollingThread" TIMED_WAITING
   java.lang.Thread.sleep(Native Method)
   oracle.jdbc.driver.OracleTimeoutPollingThread.run(OracleTimeoutPollingThread.java:150)
</code>```

This never happened before on our BO XI environment.

答:
Hi Found my own answer.

For people facing the same issue : we have a firewall between the two machines.

When we open a connection between our app and BO, the port is dynamically chosen on the app side.

For now, we disabled the firewall and are looking into a way to set a static port to use on the app side.

ContentLicense: CC BY-SA 4.0

Body:
We recently upgraded our Business Object XI environment for a new Business Objects 4.1 but we are now experiencing some issues with it

We have an Java web application hosted on a Weblogic server  that use the BO SDK to schedule Crystal Report on another server (Windows VM + tomcat server & BO 4.1)

Here’s the code used for the schedule :

  /**
   * Schedule a report inside CrystalReport
   */
  public void executeReport(ReportContext reportContext) throws Exception {
  logger.info("Class CrystalReportHelper, Executing report request for report '" + reportContext.getReportName() + "'");

  IEnterpriseSession enterpriseSession = null;
  try {
     String password = getPassword(reportContext);
     logger.info("Class CrystalReportHelper, Retrievieving password ");
     if (password != null) {
        if (logger.isDebugEnabled()) {
           logger.debug("Class CrystalReportHelper, Password obtained '" + password + "'");
        }
        else {
           logger.info("Class CrystalReportHelper, Password obtained ");
        }
     }
     else {
        logger.error("Class CrystalReportHelper, Invalid password for BO Logon");
        throw new Exception("Invalid password for BO Logon - password is null");
     }

     String username = getUserName(reportContext);
     logger.info("Class CrystalReportHelper, Retrievieving username ");
     if (username != null) {
        logger.info("Class CrystalReportHelper, User name obtained '" + username + "'");
     }
     else {
        logger.error("Class CrystalReportHelper, Invalid username for BO Logon");
        throw new Exception("Invalid username for BO Logon - username is null");
     }

     String cmsName = getCentralManagementServerName();
     logger.info("Class CrystalReportHelper, Retrievieving Central Management Server Name ");
     if (cmsName != null) {
        logger.info("Class CrystalReportHelper,Central Management Server Name obtained = " + cmsName);
     }
     else {
        logger.error("Class CrystalReportHelper, Invalid Central Management Server Name for BO Logon.");
        throw new Exception("Invalid Central Management Server Name for BO Logon - Central Management Server Name is null");
     }

     enterpriseSession = getSession(username, password, cmsName);
     if (logger.isDebugEnabled()) {
        logger.debug("Class CrystalReportHelper, Retrieving BusinessObjectEnterprise Session with username'" + username + "' password '" + password + "' cmsName '" + cmsName + "' ");
     }
     else {
        logger.info("Class CrystalReportHelper, Retrieving BusinessObjectEnterprise Session with username'" + username + "' password '" + "XXXX" + "' cmsName '" + cmsName + "' ");
     }
     if (enterpriseSession == null) {
        logger.error("Class CrystalReportHelper, Coud not retrieve BusinessObjectEnterprise Session with username'" + username + "' password '" + password + "' cmsName '" + cmsName + "' ");
        throw new Exception("Could not retreive BO Session with username : " + username + " and CMS : " + cmsName);
     }
     if (logger.isDebugEnabled()) {
        logger.debug("Class CrystalReportHelper, BusinessObjectEnterprise Session retrieve with username'" + username + "' password '" + password + "' cmsName '" + cmsName + "' ");
     }
     else {
        logger.info("Class CrystalReportHelper, BusinessObjectEnterprise Session retrieve with username'" + username + "' password '" + "XXXX" + "' cmsName '" + cmsName + "' ");
     }

     IInfoStore infoStore = (IInfoStore) enterpriseSession.getService(cmsName, BO_INFO_STORE);
     logger.info("Class CrystalReportHelper, Retrieving BO service with cmsName'" + cmsName + "' BO_INFO_STORE '" + BO_INFO_STORE + "'");
     if (infoStore == null) {
        logger.error("Class CrystalReportHelper, Coud not obtain BO service with cmsName'" + cmsName + "' BO_INFO_STORE '" + BO_INFO_STORE + "'");
        throw new Exception("Could not obtain BO service : " + BO_INFO_STORE);
     }

     // Queries the CMS for the report.
     logger.info("Class CrystalReportHelper, BO service retrieved with cmsName'" + cmsName + "' BO_INFO_STORE '" + BO_INFO_STORE + "'");

     String queryReport = REPORT_QUERY.replaceFirst(REPLACE_REPORT_NAME, getReportName(reportContext));

     logger.info("Class CrystalReportHelper, Executing query report '" + queryReport + "'.");
     IInfoObjects reports = infoStore.query(queryReport);
     if (reports.size() == 0) {
        logger.error("Class CrystalReportHelper, Report '" + queryReport + "' not found..");
        throw new Exception("Report " + getReportName(reportContext) + " not found in BusinessObject");
     }
     IReport report = (IReport) reports.get(0);

     // Set report format.
     IReportFormatOptions reportFormat = report.getReportFormatOptions();

     int formatType = IReportFormatOptions.CeReportFormat.CRYSTAL_REPORT;
     reportFormat.setFormat(formatType);

     String destinationInbox = getDestinationInbox(reportContext);
     IDestinationPlugin destinationPlugin = getDestinationPlugin(infoStore, destinationInbox);

     // Create an interface to the scheduling options for the report.
     ISchedulingInfo scheduleInfo = report.getSchedulingInfo();
     scheduleInfo.setType(CeScheduleType.ONCE);
     scheduleInfo.setRightNow(true);

     IDestination destination = scheduleInfo.getDestination();
     destination.setFromPlugin(destinationPlugin);

     // copy the report parameters
     this.setParameters(reportContext, report);

     logger.info("Class CrystalReportHelper, Scheduling report '" + getReportName(reportContext) + "'. ");
     infoStore.schedule(reports);
     logger.info("Class CrystalReportHelper, Report '" + getReportName(reportContext) + "' has been scheduled. ");

     if (reportContext.isEmailRequired() & isEmailEnabled()) {
        sendEmail(reportContext);
     }
  }
  catch (SDKRuntimeException SDKre) {
     logger.error("Class CrystalReportHelper, Could not execute report request for report '" + reportContext.getReportName() + "' caught SDKRuntimeException:  " + SDKre.getMessage(), SDKre);
     throw new Exception(SDKre);
  }
  catch (SDKException SDKe) {
     logger.error("Class CrystalReportHelper, Could not execute report request for report '" + reportContext.getReportName() + "' caught SDKException:  " + SDKe.getMessage(), SDKe);
     throw new Exception(SDKe);
  }
  finally {
     if (null != enterpriseSession) {
        enterpriseSession.logoff();
     }
  }

Here’s some data info :

Reportcontext contains things like user/password for BO, report name and report prompt parameter to use

BO_INFO_STORE = “InfoStore”;

REPORT_QUERY = "Select * From CI_INFOOBJECTS WHERE SI_NAME='" + REPLACE_REPORT_NAME + "' AND SI_INSTANCE = 'false'";

Here's the method getSession used to connect to BO :

    /**
     * return BusinessObjectEnterprise session
     *
     * @param username
     * @param password
     * @return IEnterpriseSession
     * @throws SDKException
     */
     public IEnterpriseSession getSession(String username, String password,      String cmsName) throws SDKException {
     logger.debug("Class CrystalReportHelper, Retrieving    BusinessObjectEnterprise Session  username'" + username + "' password '" +   password + "' cmsName '" + cmsName + "' ");

  IEnterpriseSession enterpriseSession = null;
  ISessionMgr sessionMgr = CrystalEnterprise.getSessionMgr();

  boolean isAuthenticateEnterprise = getReportProperties().getAuthenticationTypeEnterprise();
  logger.debug("Class CrystalReportHelper, isAuthenticateEnterprise  '" + isAuthenticateEnterprise + "' ");
  if (isAuthenticateEnterprise) {
     enterpriseSession = sessionMgr.logon(username, password, cmsName, CeProgID.SEC_ENTERPRISE);
  }
  else {
     enterpriseSession = sessionMgr.logon(username, password, cmsName, CeProgID.SEC_LDAP);
  }

  logger.debug("Class CrystalReportHelper, BusinessObjectEnterprise Session  obtained for username'" + username + "' password '" + password + "' cmsName '" + cmsName + "' ");
  return enterpriseSession;
}

The problem we’re experiencing is sometimes the process will hang on this line for about 45min :

enterpriseSession = sessionMgr.logon(username, password, cmsName, CeProgID.SEC_ENTERPRISE);

Here’s a stacktrace from Weblogic when this occurs :

"[ACTIVE] ExecuteThread: '7' for queue: 'weblogic.kernel.Default (self-tuning)'" waiting for lock java.lang.Object@3d24ae2c WAITING
   java.lang.Object.wait(Native Method)
   java.lang.Object.wait(Object.java:485)
       com.crystaldecisions.thirdparty.com.ooc.OB.Downcall.waitUntilCompleted(Downcall.java:831)
       com.crystaldecisions.thirdparty.com.ooc.OB.GIOPClientWorkerThreaded.receive(GIOPClientWorkerThreaded.java:327)
       com.crystaldecisions.thirdparty.com.ooc.OB.GIOPClientWorkerThreaded.sendReceive(GIOPClientWorkerThreaded.java:353)
   com.crystaldecisions.thirdparty.com.ooc.OB.Downcall.request(Downcall.java:336)
   com.crystaldecisions.thirdparty.com.ooc.OB.DowncallStub.invoke(DowncallStub.java:583)
   com.crystaldecisions.thirdparty.com.ooc.CORBA.Delegate.invoke(Delegate.java:579)
       com.crystaldecisions.thirdparty.org.omg.CORBA.portable.ObjectImpl._invoke(ObjectImpl.java:125)
       com.crystaldecisions.enterprise.ocaframework.idl.ImplServ._OSCAFactoryStub.newService(_OSCAFactoryStub.java:78)
   com.crystaldecisions.enterprise.ocaframework.i.a(Unknown Source)
   com.crystaldecisions.enterprise.ocaframework.i.a(Unknown Source)
   com.crystaldecisions.enterprise.ocaframework.i.buildClusterInfo(Unknown Source)
   com.crystaldecisions.enterprise.ocaframework.aa.int(Unknown Source)
   com.crystaldecisions.enterprise.ocaframework.ServiceMgr.int(Unknown Source)
   com.crystaldecisions.enterprise.ocaframework.p.a(Unknown Source)
   com.crystaldecisions.enterprise.ocaframework.ServiceMgr.getManagedService(Unknown Source)
   com.crystaldecisions.sdk.occa.security.internal.f.if(Unknown Source)
   com.crystaldecisions.sdk.occa.security.internal.f.<init>(Unknown Source)
       com.crystaldecisions.sdk.occa.security.internal.SecurityFactory.makeSecuritySession(Unknown Source)
   com.crystaldecisions.sdk.occa.security.internal.t.a(Unknown Source)
   com.crystaldecisions.sdk.occa.security.internal.t.userLogon(Unknown Source)
   com.crystaldecisions.sdk.occa.security.internal.l.userLogon(Unknown Source)
   com.crystaldecisions.sdk.framework.internal.b.logon(Unknown Source)
       com.tranme.guide.commonservices.report.CrystalReportHelper.getSession(CrystalReportHelper.java:156)
       com.tranme.guide.commonservices.report.CrystalReportHelper.getReportInfoObjectsByReportName(CrystalReportHelper.java:503)
       com.tranme.guide.notificationmgt.manager.reports.util.ReportManagementTools.getReportInstanceStatuses(ReportManagementTools.java:81)
       com.tranme.guide.notificationmgt.manager.reports.util.ReportManagementTools.getGenerationStatusResults(ReportManagementTools.java:51)
       com.tranme.guide.notificationmgt.manager.BaseNotificationManager.updateReportGenerationStatus(BaseNotificationManager.java:244)
       com.tranme.guide.notificationmgt.business.ejb.impl.NotificationManagementFacadeBeanImpl.updateReportGenerationStatus(NotificationManagementFacadeBeanImpl.java:123)
        com.tranme.guide.notificationmgt.business.ejb.impl.NotificationManagementFacadeBeanImpl_z3lp9c_EOImpl.updateReportGenerationStatus(NotificationManagementFacadeBeanImpl_z3lp9c_EOImpl.java:140)
       com.tranme.guide.notificationmgt.business.ejb.impl.NotificationManagementFacadeBeanImpl_z3lp9c_EOImpl_WLSkel.invoke(Unknown Source)
   weblogic.rmi.internal.BasicServerRef.invoke(BasicServerRef.java:589)
   weblogic.rmi.cluster.ClusterableServerRef.invoke(ClusterableServerRef.java:230)
   weblogic.rmi.internal.BasicServerRef$1.run(BasicServerRef.java:477)
   weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:363)
   weblogic.security.service.SecurityManager.runAs(SecurityManager.java:147)
   weblogic.rmi.internal.BasicServerRef.handleRequest(BasicServerRef.java:473)
   weblogic.rmi.internal.wls.WLSExecuteRequest.run(WLSExecuteRequest.java:118)
   weblogic.work.ExecuteThread.execute(ExecuteThread.java:201)
   weblogic.work.ExecuteThread.run(ExecuteThread.java:173)
"Business Objects - Sessions Clean up" TIMED_WAITING
   java.lang.Thread.sleep(Native Method)
   com.crystaldecisions.enterprise.ocaframework.n.run(Unknown Source)
   java.lang.Thread.run(Thread.java:619)
"OracleTimeoutPollingThread" TIMED_WAITING
   java.lang.Thread.sleep(Native Method)
   oracle.jdbc.driver.OracleTimeoutPollingThread.run(OracleTimeoutPollingThread.java:150)

This never happened before on our BO XI environment.


问:
What is the most mature MongoDB driver for C#?
So, there are

mongodb-csharp

simple-mongodb

NoRM

as C# drivers for MongoDB available.

Which one of them is the most mature and stable one?
Why would you choose one over the other two?

Are they production ready?

答:
Since this question was answered 10gen have released an official MongoDB C# driver, and although it isn't the most mature C# driver in terms of age, with 10gen behind it it may end up as the most up to date.

It is more low level than the mongodb-csharp driver (no Linq support at the moment) but we haven't found that to be a problem. We moved to the official driver from mongodb-csharp recently on a project (that isn't in production yet) for the following reasons:

Replica Set support in an official release

SafeMode allows you to specify how many servers a write must be replicated to

The driver handles connecting/disconnecting to the database

We're hoping that as an official driver, it will have more developer support

ContentLicense: CC BY-SA 2.5


问:
Angular 2 inject service into service
In my app, I have extended the Angular Http class with our own implementation that adds some headers.

```<code>export class Secure_Http extends Http {
    private getJwtUrl = environment.employerApiUrl + '/getJwt';
    private refreshJwtUrl = environment.employerApiUrl + '/refreshJwt';

    constructor(backend: ConnectionBackend, defaultOptions: RequestOptions, private storage: SessionStorageService) {
        super(backend, defaultOptions);
    }
</code>```

Then, in the app.mobule.ts file, I've done this so our secure version is used everytime instead of the base version:

```<code>@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    ....
  ],
  providers: [
    ....
    SessionStorageService,
    {
      provide: Http,
      useFactory: secureHttpFactory,
      deps: [XHRBackend, RequestOptions, SessionStorageService]
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

export function secureHttpFactory(backend: XHRBackend, options: RequestOptions, sessionStorage: SessionStorageService) {
    return new Secure_Http(backend, options, sessionStorage);
}
</code>```

Now, in our services, we use the standard constructor/DI approach:

```<code>@Injectable()

export class MySecurityService {
    employerApiBaseUrl: string = environment.employerApiUrl;

    constructor(private _http: Http) { } //, private _secureHttp: Secure_Http

    getUser() : Observable<User> {
        this.log('getUser', 'getting the current user');

        var thisUrl = this.employerApiBaseUrl + '/jwt/userinfo';

        var searchParam = {
            jwt: this.getToken()
        };

        return this._http.post(thisUrl, searchParam)
            .map((response: Response) => this.extractGetUserResponse(response))
            .catch(this.handleError);
    }
}
</code>```

Now my problem is, the SecurityService needs to also inject the Secure_Http class/service because there's one function on there that is needed to get the JWT.

But, as soon as I add the Secure_Http class/service as a constructor parameter, I get the error No provider for Secure_Http.

So, my next thought is to add the Secure_Http to the providers section in the app.module.ts file, right next to where I specify Http needs to use Secure_Http. But as soon as I do that, I then get the error No provider for ConnectionBackend. If I turn around and add ConnectionBackend into the providers, then there's an error on the @NgModule saying Type 'typeof ConnectionBackend' is not assignable to type provider.

Where am I going wrong here? I just have 1 method that I need to access on the Secure_Http class directly. That's needed because it needs to be a parameter for one of my post calls. I can't just call it from the Secure_Http service/class because the parameters have already been passed...

答:
If you explicitly want to inject Secure_Http, you need to provide it

```<code>{
  provide: Secure_Http,
  useFactory: secureHttpFactory,
  deps: [XHRBackend, RequestOptions, SessionStorageService]
},
{ provide: Http, useExisting: Secure_Http }
</code>```

this way both lead to Secure_Http being injected

```<code>constructor(private _http: Http) { }
constructor(private _secureHttp: Secure_Http) {}
</code>```

but if you know that Http injects Secure_http (as your configuration would do) you can just cast

```<code>private _http: SecureHttp;
constructor(http: Http) {
  this._http = http as Secure_Http;
}
</code>```

Title: Angular 2 inject service into service

Body:
In my app, I have extended the Angular Http class with our own implementation that adds some headers.

export class Secure_Http extends Http {
    private getJwtUrl = environment.employerApiUrl + '/getJwt';
    private refreshJwtUrl = environment.employerApiUrl + '/refreshJwt';

    constructor(backend: ConnectionBackend, defaultOptions: RequestOptions, private storage: SessionStorageService) {
        super(backend, defaultOptions);
    }

Then, in the app.mobule.ts file, I've done this so our secure version is used everytime instead of the base version:

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    ....
  ],
  providers: [
    ....
    SessionStorageService,
    {
      provide: Http,
      useFactory: secureHttpFactory,
      deps: [XHRBackend, RequestOptions, SessionStorageService]
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

export function secureHttpFactory(backend: XHRBackend, options: RequestOptions, sessionStorage: SessionStorageService) {
    return new Secure_Http(backend, options, sessionStorage);
}

Now, in our services, we use the standard constructor/DI approach:

@Injectable()

export class MySecurityService {
    employerApiBaseUrl: string = environment.employerApiUrl;

    constructor(private _http: Http) { } //, private _secureHttp: Secure_Http

    getUser() : Observable<User> {
        this.log('getUser', 'getting the current user');

        var thisUrl = this.employerApiBaseUrl + '/jwt/userinfo';

        var searchParam = {
            jwt: this.getToken()
        };

        return this._http.post(thisUrl, searchParam)
            .map((response: Response) => this.extractGetUserResponse(response))
            .catch(this.handleError);
    }
}

Now my problem is, the SecurityService needs to also inject the Secure_Http class/service because there's one function on there that is needed to get the JWT.

But, as soon as I add the Secure_Http class/service as a constructor parameter, I get the error No provider for Secure_Http.

So, my next thought is to add the Secure_Http to the providers section in the app.module.ts file, right next to where I specify Http needs to use Secure_Http. But as soon as I do that, I then get the error No provider for ConnectionBackend. If I turn around and add ConnectionBackend into the providers, then there's an error on the @NgModule saying Type 'typeof ConnectionBackend' is not assignable to type provider.

Where am I going wrong here? I just have 1 method that I need to access on the Secure_Http class directly. That's needed because it needs to be a parameter for one of my post calls. I can't just call it from the Secure_Http service/class because the parameters have already been passed...

Body:
If you explicitly want to inject Secure_Http, you need to provide it

{
  provide: Secure_Http,
  useFactory: secureHttpFactory,
  deps: [XHRBackend, RequestOptions, SessionStorageService]
},
{ provide: Http, useExisting: Secure_Http }

this way both lead to Secure_Http being injected

constructor(private _http: Http) { }
constructor(private _secureHttp: Secure_Http) {}

but if you know that Http injects Secure_http (as your configuration would do) you can just cast

private _http: SecureHttp;
constructor(http: Http) {
  this._http = http as Secure_Http;
}


问:
How to escape single quote (') in Thymeleaf

I want this to output

What's up?

But I get an TemplateInputException. I have tried with HTML entity but it fails the same.

答:
Double single quote.  Like this:</p>

```<code><h1 th:text="${'What''s up?'}" />
</code>```

Body:
Double single quote.  Like this:

<h1 th:text="${'What''s up?'}" />


问:
How to replace Glyphicons with FontAwesome in Bootstrap 3 without changing HTML?
I'm using Bootstrap 3 in my project and I'm using FontAwesome icons library instead of bundled Glyphicons.

The problem is that I have some third-party components that rely on Glyphicons and I don't want to change their HTML.

I'm including font-awesome via Bower and SASS + Compass (SCSS).

Is it possible to replace Glyphicons with FontAwesome without changing the HTML and applying another CSS classes?

答:
In pure CSS just define glyphicon class with same properties as font-awesome class (.fa) and make correspondance with desired icons :</p>

```<code>.glyphicon{
    display: inline-block;
    font: normal normal normal 14px/1 FontAwesome;
    font-size: inherit;
    text-rendering: auto;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}
.glyphicon-chevron-left:before{
    content:"\f053"
}
.glyphicon-chevron-right:before{
    content:"\f054"
}
</code>```

Body:
In pure CSS just define glyphicon class with same properties as font-awesome class (.fa) and make correspondance with desired icons :

.glyphicon{
    display: inline-block;
    font: normal normal normal 14px/1 FontAwesome;
    font-size: inherit;
    text-rendering: auto;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}
.glyphicon-chevron-left:before{
    content:"\f053"
}
.glyphicon-chevron-right:before{
    content:"\f054"
}


问:
Efficiently count the number of bits in an integer in JavaScript
Let's say I have an integer I and want to get the count of 1s in its binary form.

I am currently using the following code.

```<code>Number(i.toString(2).split("").sort().join("")).toString().length;
</code>```

Is there a faster way to do this? I am thinking about using bitwise operators.  Any thoughts?

NOTE: i is within the 32-bit limitation.

答:
Below works fine with any number:

var i=8823475632,count=0;while (i=Math.floor(i)) i&1?count++:0,i/=2
console.log(count); //17```
</div>
</div>
</p>

<p>change the i to the value you want or wrap it as a function</p>

<p>if integer is within 32-bit , below works</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var i=10,count=0;while (i) i&1?count++:0,i>>=1</code>```

Body:
Let's say I have an integer I and want to get the count of 1s in its binary form.

I am currently using the following code.

Number(i.toString(2).split("").sort().join("")).toString().length;

Is there a faster way to do this? I am thinking about using bitwise operators.  Any thoughts?

NOTE: i is within the 32-bit limitation.

Body:
Below works fine with any number:

var i=8823475632,count=0;while (i=Math.floor(i)) i&1?count++:0,i/=2
console.log(count); //17

change the i to the value you want or wrap it as a function

if integer is within 32-bit , below works

var i=10,count=0;while (i) i&1?count++:0,i>>=1


问:
What is wrong with my solr account?
I am trying to get familiar solr to eventually complete a school project that involves indexing a .csv file. I am following the instructions on the following website: https://lucene.apache.org/solr/5_4_1/quickstart.html
and in particular, under the section Indexing CSV (Comma/Column Separated Values). I entered the commands just as specified (except im using solr version 6.3.0) and getting constant errors.

Below is what I entered into terminal:

```<code>Tylers-MacBook-Pro:6.3.0 tyler$ solr start
Archiving 1 old GC log files to /usr/local/Cellar/solr/6.3.0/server/logs/archived
Archiving 1 console log files to /usr/local/Cellar/solr/6.3.0/server/logs/archived
Rotating solr logs, keeping a max of 9 generations
Waiting up to 180 seconds to see Solr running on port 8983 [-]
Started Solr server on port 8983 (pid=20594). Happy searching!

Tylers-MacBook-Pro:6.3.0 tyler$ bin/post -c gettingstarted example/exampledocs/books.csv
java -classpath /usr/local/Cellar/solr/6.3.0/libexec/dist/solr-core-6.3.0.jar -Dauto=yes -Dc=gettingstarted -Ddata=files org.apache.solr.util.SimplePostTool example/exampledocs/books.csv
SimplePostTool version 5.0.0
Posting files to [base] url http://localhost:8983/solr/gettingstarted/update...
Entering auto mode. File endings considered are xml,json,jsonl,csv,pdf,doc,docx,ppt,pptx,xls,xlsx,odt,odp,ods,ott,otp,ots,rtf,htm,html,txt,log
POSTing file books.csv (text/csv) to [base]
SimplePostTool: WARNING: Solr returned an error #404 (Not Found) for url: http://localhost:8983/solr/gettingstarted/update
SimplePostTool: WARNING: Response: <html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<title>Error 404 Not Found</title>
</head>
<body><h2>HTTP ERROR 404</h2>
<p>Problem accessing /solr/gettingstarted/update. Reason:
```    Not Found```</p>
</body>
</html>
SimplePostTool: WARNING: IOException while reading response: java.io.FileNotFoundException: http://localhost:8983/solr/gettingstarted/update
1 files indexed.
COMMITting Solr index changes to http://localhost:8983/solr/gettingstarted/update...
SimplePostTool: WARNING: Solr returned an error #404 (Not Found) for url: http://localhost:8983/solr/gettingstarted/update?commit=true
SimplePostTool: WARNING: Response: <html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<title>Error 404 Not Found</title>
</head>
<body><h2>HTTP ERROR 404</h2>
<p>Problem accessing /solr/gettingstarted/update. Reason:
```    Not Found```</p>
</body>
</html>
Time spent: 0:00:00.199
Tylers-MacBook-Pro:6.3.0 tyler$
</code>```

What exactly is going on? All I have done is followed exactly what I was supposed to do. Thanks for any help.

答:
Try bin/solr start -e techproducts. And then use techproducts instead of gettingstarted. There is no gettingstarted collection anymore and the techproducts is the nearest one.

What you've done is started a server with no collections in it at all. So you could also create a collection there, but you would need the right configuration to bootstrap it. So, the first method might be a bit easier at this point.

Title: What is wrong with my solr account?

Body:
I am trying to get familiar solr to eventually complete a school project that involves indexing a .csv file. I am following the instructions on the following website: https://lucene.apache.org/solr/5_4_1/quickstart.html
and in particular, under the section Indexing CSV (Comma/Column Separated Values). I entered the commands just as specified (except im using solr version 6.3.0) and getting constant errors.

Below is what I entered into terminal:

Tylers-MacBook-Pro:6.3.0 tyler$ solr start
Archiving 1 old GC log files to /usr/local/Cellar/solr/6.3.0/server/logs/archived
Archiving 1 console log files to /usr/local/Cellar/solr/6.3.0/server/logs/archived
Rotating solr logs, keeping a max of 9 generations
Waiting up to 180 seconds to see Solr running on port 8983 [-]
Started Solr server on port 8983 (pid=20594). Happy searching!

Tylers-MacBook-Pro:6.3.0 tyler$ bin/post -c gettingstarted example/exampledocs/books.csv
java -classpath /usr/local/Cellar/solr/6.3.0/libexec/dist/solr-core-6.3.0.jar -Dauto=yes -Dc=gettingstarted -Ddata=files org.apache.solr.util.SimplePostTool example/exampledocs/books.csv
SimplePostTool version 5.0.0
Posting files to [base] url http://localhost:8983/solr/gettingstarted/update...
Entering auto mode. File endings considered are xml,json,jsonl,csv,pdf,doc,docx,ppt,pptx,xls,xlsx,odt,odp,ods,ott,otp,ots,rtf,htm,html,txt,log
POSTing file books.csv (text/csv) to [base]
SimplePostTool: WARNING: Solr returned an error #404 (Not Found) for url: http://localhost:8983/solr/gettingstarted/update
SimplePostTool: WARNING: Response:

<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<title>Error 404 Not Found</title>

HTTP ERROR 404

Problem accessing /solr/gettingstarted/update. Reason:

    Not Found

SimplePostTool: WARNING: IOException while reading response: java.io.FileNotFoundException: http://localhost:8983/solr/gettingstarted/update
1 files indexed.
COMMITting Solr index changes to http://localhost:8983/solr/gettingstarted/update...
SimplePostTool: WARNING: Solr returned an error #404 (Not Found) for url: http://localhost:8983/solr/gettingstarted/update?commit=true
SimplePostTool: WARNING: Response:

<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<title>Error 404 Not Found</title>

HTTP ERROR 404

Problem accessing /solr/gettingstarted/update. Reason:

    Not Found

Time spent: 0:00:00.199
Tylers-MacBook-Pro:6.3.0 tyler$

What exactly is going on? All I have done is followed exactly what I was supposed to do. Thanks for any help.


问:
Passing data between PHP and Wordpress and vice versa
I need help or advise. I have a wordpress website and on it "CSS3 Responsive Wordpress 3 column pricing table" plugin.
Problem is I have a login/Sign up dual purpose form done in PHP, I want that when user clicks on Login or Sign up at
the top of the menu, the PHP form is loaded and the user can login if he is alrady a user or fill up his name, email
and password and when he cllicks on the Register button he will be taken to the membership pricing table where he
compares the plans and when he clicks the "Sign up" button of the plan of his choice, the selected plan, user name,
email etc will be passed to the registration process which proceeds with a mail sent to the user who validates the
registration by clicking on the link in the mail, clicking the link will load a form to login and if the login is
successful the user gains access to a PHP dashboard with the details user filled or selected like name, email,
membership are reflected on the dashboard.
The problem is that the programmer I have hired for the job says it is not possible to transfer data from PHP to WP
and vice versa but something tells me it is possible.
I would like to know whether it is possible and if it is, any hints on how to achieve what I have explained.</p>

答:
It depends on whether you want to import the functionality inside Wordpress or if you want to use an external PHP script using an iFrame.

The developer is correct and if you want to use native WP signup functionality, you will have to convert the PHP code into a plugin.

The alternative to this would be adding the PHP code as an iFrame on your WP website but this may not give your visitors the best customer experience.

I would recommend converting your PHP Script into WP Plugin or switching to a basic PHP/MySQL website.


答:
You can skip Number, sort and the second toString. Use filter to only consider the 1s (a truthy value) in the array then retrieve how many got through with length.

```<code>i.toString(2).split('').filter(v => +v).length
</code>```

Title: Efficiently count the number of bits in an integer in JavaScript

Body:
You can skip Number, sort and the second toString. Use filter to only consider the 1s (a truthy value) in the array then retrieve how many got through with length.

i.toString(2).split('').filter(v => +v).length


问:
A generic list of anonymous class
In C# 3.0 you can create anonymous class with the following syntax

```<code>var o = new { Id = 1, Name = "Foo" };
</code>```

Is there a way to add these anonymous class to a generic list?

Example:

```<code>var o = new { Id = 1, Name = "Foo" };
var o1 = new { Id = 2, Name = "Bar" };

List<var> list = new List<var>();
list.Add(o);
list.Add(o1);
</code>```

Another Example:

```<code>List<var> list = new List<var>();

while (....)
{
    ....
    list.Add(new {Id = x, Name = y});
    ....
}
</code>```

答:
Instead of this:

```<code>var o = new { Id = 1, Name = "Foo" };
var o1 = new { Id = 2, Name = "Bar" };

List <var> list = new List<var>();
list.Add(o);
list.Add(o1);
</code>```

You could do this:

```<code>var o = new { Id = 1, Name = "Foo" };
var o1 = new { Id = 2, Name = "Bar" };

List<object> list = new List<object>();
list.Add(o);
list.Add(o1);
</code>```

However, you will get a compiletime error if you try to do something like this in another scope, although it works at runtime:

```<code>private List<object> GetList()
{
    List<object> list = new List<object>();
    var o = new { Id = 1, Name = "Foo" };
    var o1 = new { Id = 2, Name = "Bar" };
    list.Add(o);
    list.Add(o1);
    return list;
}

private void WriteList()
{
    foreach (var item in GetList())
    {
        Console.WriteLine("Name={0}{1}", item.Name, Environment.NewLine);
    }
}
</code>```

The problem is that only the members of Object are available at runtime, although intellisense will show the properties id and name.

In .net 4.0 a solution is to use the keyword dynamic istead of object in the code above.

Another solution is to use reflection to get the properties

```<code>using System;
using System.Collections.Generic;
using System.Reflection;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Program p = new Program();
            var anonymous = p.GetList(new[]{
                new { Id = 1, Name = "Foo" },
                new { Id = 2, Name = "Bar" }
            });

            p.WriteList(anonymous);
        }

        private List<T> GetList<T>(params T[] elements)
        {
            var a = TypeGenerator(elements);
            return a;
        }

        public static List<T> TypeGenerator<T>(T[] at)
        {
            return new List<T>(at);
        }

        private void WriteList<T>(List<T> elements)
        {
            PropertyInfo[] pi = typeof(T).GetProperties();
            foreach (var el in elements)
            {
                foreach (var p in pi)
                {
                    Console.WriteLine("{0}", p.GetValue(el, null));
                }
            }
            Console.ReadLine();
        }
    }
}
</code>```

OwnerDisplayName: DHornpout

Title: A generic list of anonymous class

Body:
In C# 3.0 you can create anonymous class with the following syntax

var o = new { Id = 1, Name = "Foo" };

Is there a way to add these anonymous class to a generic list?

Example:

var o = new { Id = 1, Name = "Foo" };
var o1 = new { Id = 2, Name = "Bar" };

List<var> list = new List<var>();
list.Add(o);
list.Add(o1);

Another Example:

List<var> list = new List<var>();

while (....)
{
    ....
    list.Add(new {Id = x, Name = y});
    ....
}

LastEditorDisplayName: DHornpout

Body:
Instead of this:

var o = new { Id = 1, Name = "Foo" };
var o1 = new { Id = 2, Name = "Bar" };

List <var> list = new List<var>();
list.Add(o);
list.Add(o1);

You could do this:

var o = new { Id = 1, Name = "Foo" };
var o1 = new { Id = 2, Name = "Bar" };

List<object> list = new List<object>();
list.Add(o);
list.Add(o1);

However, you will get a compiletime error if you try to do something like this in another scope, although it works at runtime:

private List<object> GetList()
{
    List<object> list = new List<object>();
    var o = new { Id = 1, Name = "Foo" };
    var o1 = new { Id = 2, Name = "Bar" };
    list.Add(o);
    list.Add(o1);
    return list;
}

private void WriteList()
{
    foreach (var item in GetList())
    {
        Console.WriteLine("Name={0}{1}", item.Name, Environment.NewLine);
    }
}

The problem is that only the members of Object are available at runtime, although intellisense will show the properties id and name.

In .net 4.0 a solution is to use the keyword dynamic istead of object in the code above.

Another solution is to use reflection to get the properties

using System;
using System.Collections.Generic;
using System.Reflection;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Program p = new Program();
            var anonymous = p.GetList(new[]{
                new { Id = 1, Name = "Foo" },
                new { Id = 2, Name = "Bar" }
            });

            p.WriteList(anonymous);
        }

        private List<T> GetList<T>(params T[] elements)
        {
            var a = TypeGenerator(elements);
            return a;
        }

        public static List<T> TypeGenerator<T>(T[] at)
        {
            return new List<T>(at);
        }

        private void WriteList<T>(List<T> elements)
        {
            PropertyInfo[] pi = typeof(T).GetProperties();
            foreach (var el in elements)
            {
                foreach (var p in pi)
                {
                    Console.WriteLine("{0}", p.GetValue(el, null));
                }
            }
            Console.ReadLine();
        }
    }
}


答:
Doing n = n & (n - 1) you removing last 1 bit in the number.
According to this, you can use the following algorithm:

function getBitCount(n) {
  var tmp = n;
  var count = 0;
  while (tmp > 0) {
    tmp = tmp & (tmp - 1);
    count++;
  }
  return count;
}

console.log(getBitCount(Math.pow(2, 10) -1));```


问:
Show/Hide div element with rails view html.erb file
I am trying to show/hide certain divs depending on the click of a button/link. I have done some reading on how to do this with JQuery, but it doesn't seem to be working.

edit.html.erb

```<code><script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<div class="pad-bottom">
  <a id="edit-profile-button" class="button default ok" href="#">
    Edit Profile
  </a>
  <div id="profile-information" class="hidden">
    <div class="row pad-top">
      <div class="col-xs-6 col-sm-6 field-row">
        <div class="roboto bold black field-label">
          First
        </div>
        <%= f.text_field :first_name, class: 'field', placeholder: 'First Name'%>
      </div>
  </div>
</div>

<script type="text/javascript">
  $(document).ready(function(event){
    $('#edit-profile-button').click(function(){
      event.preventDefault();
      $('#profile-information').toggle();
    });
  });
</script>
</code>```

application.css

```<code>.hidden {
  display: none;
}
</code>```

I can click on the link and fall into a debugger and access the two elements that I try to select in the jQuery code, but it doesn't seem do be doing anything at all, the div is never made visible.

答:
Your css has an issue, hidden is not a valid value for display. It should be:

  $(document).ready(function(){
    $('#edit-profile-button').click(function(){
      $('#profile-information').toggle();
    });
  });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hidden {
  display: none;
}</code>```

    Edit Profile

          First

        <%= f.text_field :first_name, class: 'field', placeholder: 'First Name'%>

```

Body:
I am trying to show/hide certain divs depending on the click of a button/link. I have done some reading on how to do this with JQuery, but it doesn't seem to be working.

edit.html.erb

    Edit Profile

          First

        <%= f.text_field :first_name, class: 'field', placeholder: 'First Name'%>

application.css

.hidden {
  display: none;
}

I can click on the link and fall into a debugger and access the two elements that I try to select in the jQuery code, but it doesn't seem do be doing anything at all, the div is never made visible.

Body:
Your css has an issue, hidden is not a valid value for display. It should be:

  $(document).ready(function(){
    $('#edit-profile-button').click(function(){
      $('#profile-information').toggle();
    });
  });

.hidden {
  display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="pad-bottom">
  <a id="edit-profile-button" class="button default ok">
    Edit Profile
  </a>
  <div id="profile-information" class="hidden">
    <div class="row pad-top">
      <div class="col-xs-6 col-sm-6 field-row">
        <div class="roboto bold black field-label">
          First
        </div>
        <%= f.text_field :first_name, class: 'field', placeholder: 'First Name'%>
      </div>
  </div>
</div>


问:
Need help in extracting unique lines from a file using python
I have a file with the below details:

```<code>**169.254.230.157 : 169.254.42.146**
169.254.230.157 : 169.254.138.97
169.254.230.157 : 169.254.162.67
169.254.223.76 : 169.254.42.146
**169.254.223.76 : 169.254.138.97**
169.254.223.76 : 169.254.162.67
</code>```

I need to get the unique lines like the below

```<code>169.254.230.157 : 169.254.42.146
169.254.223.76 : 169.254.138.97
</code>```

Below is what i was trying:

```<code>    ping_ip = open("ping.txt","r")
    ping_lines = ping_ip.readlines()

    list1 = []
    list2 = []
    for line in ping_lines:
        ip_s, ip_d = line.split(":")
        #print ip_s, " : ", ip_d
        m = re.search(ip_s.rstrip(),line)
        n = re.search(ip_d.rstrip(),line)
        if m and n not in list1 and list2 :
            list1.append(m.group(0))
            list2.append(n.group(0))
            print line
    print set(list1)
</code>```

答:
Looks like you are looking for unique combinations (i.e. neither item has been added already). You should be clearer on your definition of unique:

```<code>r = []
with open(...) as f:
    seen = set()
    for line in f:
        x = line.strip().split(' : ')
        if all(i not in seen for i in x):
            r.append(line.strip())
            seen |= set(x)
r
</code>```

Output:

```<code>['169.254.230.157 : 169.254.42.146', '169.254.223.76 : 169.254.138.97']
</code>```

Body:
I have a file with the below details:

**169.254.230.157 : 169.254.42.146**
169.254.230.157 : 169.254.138.97
169.254.230.157 : 169.254.162.67
169.254.223.76 : 169.254.42.146
**169.254.223.76 : 169.254.138.97**
169.254.223.76 : 169.254.162.67

I need to get the unique lines like the below

169.254.230.157 : 169.254.42.146
169.254.223.76 : 169.254.138.97

Below is what i was trying:

    ping_ip = open("ping.txt","r")
    ping_lines = ping_ip.readlines()

    list1 = []
    list2 = []
    for line in ping_lines:
        ip_s, ip_d = line.split(":")
        #print ip_s, " : ", ip_d
        m = re.search(ip_s.rstrip(),line)
        n = re.search(ip_d.rstrip(),line)
        if m and n not in list1 and list2 :
            list1.append(m.group(0))
            list2.append(n.group(0))
            print line
    print set(list1)

Body:
Looks like you are looking for unique combinations (i.e. neither item has been added already). You should be clearer on your definition of unique:

r = []
with open(...) as f:
    seen = set()
    for line in f:
        x = line.strip().split(' : ')
        if all(i not in seen for i in x):
            r.append(line.strip())
            seen |= set(x)
r

Output:

['169.254.230.157 : 169.254.42.146', '169.254.223.76 : 169.254.138.97']


问:
How to stop my app from crashing using AsyncTask in Android Studio?
I have built a user interface in Android Studio to test the PSO algorithm in Java. I took this project on from someone else who did it last year, the person before me used AsyncTask with Boolean[] parameters to execute his application. Below is his version of this class, this is because he used a checkbox in his MainActivity that the user can check, so it can either be one or the other.

```<code>  public class runTests extends AsyncTask<Boolean, Void, Void> {
    @Override
    protected Void doInBackground(Boolean... params) {
        boolean one    = params[0];
        boolean custom = params[1];

        if (one)
            results = runTest("TestOne");
        else if (custom) {
            double[] re = runTest("customTest");
            if (re != null) results = re;
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void v) {
        // execution of result of Long time consuming operation
        pd.dismiss();
        if (results[0] != -1 || results != null) {
            loadIntent(results);
        }
    }

    @Override
    protected void onPreExecute() {
        pd = ProgressDialog.show(MainActivity.this, "Busy", "Algorithm is currently executing");
    }
}
</code>```

Whereas my code doesn't have a checkbox it only needs to implement one test rather than having the option of two. I just want to run "CustomUseCase" and nothing else. I don't want to use a boolean parameter however I still want to have AsyncTask. Please help me!

```<code>public class runTests extends AsyncTask<Boolean, Void, Void> {
    @Override
    protected Void doInBackground(Boolean... params) { //sort this out
        boolean one    = params[0];
        boolean custom = params[1];

        if (one)
            results = runTest("CustomUseCase"); //i only want to run this one!!!
        else if (custom) {
            double[] re = runTest("testOne"); //I don't need this, I dont want to run this test
            if (re != null) results = re;
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void v) {
        // execution of result of Long time consuming operation
        if(pd!=null){
            pd.dismiss();
            pd = null;
        }
        if (results[0] != -1 || results != null) {
            loadIntent(results);
        }
    }
  @Override
    protected void onPreExecute() {
        pd = ProgressDialog.show(ParticleActivity.this, "Busy", "Algorithm is currently executing");
    }
}
</code>```

答:
First, you need to change

```<code>if (results[0] != -1 || results != null) {
    loadIntent(results);
}
</code>```

to

```<code>if (results != null && results.length > 0 && results[0] != -1) {
    loadIntent(results);
}
</code>```

That is an example of a "short circuiting" if statement. The logical AND (&&) operator will cause the entire statement to fail if results is null, otherwise it will evaluate the next logic statement results[0] != -1 with no chance of a NullPointerException.

Try this as well

```<code>public class runTests extends AsyncTask<Void, Void, Void> {
    @Override
    protected Void doInBackground(Void... params) { //sort this out

        results = runTest("CustomUseCase"); //i only want to run this one!!!
    }
    ...
}
</code>```

UPDATE

do I return null when executing the doInBackground?

To clarify how the Template Type List (ie, <Void,Void,Void>) works, here is an example. Here, we have <URL, Integer, Long>. Notice how doInBackground takes an array of URL (urls) and returns a Long, onProgressUpdate takes an Integer array, and onPostExecute takes a Long.

```<code>private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {
         long totalSize = urls.length;
         ...
         return totalSize;
     }

     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }

     protected void onPostExecute(Long result) {
         showDialog("Downloaded " + result + " bytes");
     }
 }
</code>```

For <Void, Void, Void> we would have (empty function argument list "()" corresponds to Void):

```<code>private class DownloadFilesTask extends AsyncTask<Void, Void, Void> {
     protected Void doInBackground() {
         ...
         return;
     }

     protected void onProgressUpdate() {
         setProgressPercent("hi");
     }

     protected void onPostExecute() {
         showDialog("bye");
     }
 }
</code>```

Body:
I have built a user interface in Android Studio to test the PSO algorithm in Java. I took this project on from someone else who did it last year, the person before me used AsyncTask with Boolean[] parameters to execute his application. Below is his version of this class, this is because he used a checkbox in his MainActivity that the user can check, so it can either be one or the other.

  public class runTests extends AsyncTask<Boolean, Void, Void> {
    @Override
    protected Void doInBackground(Boolean... params) {
        boolean one    = params[0];
        boolean custom = params[1];

        if (one)
            results = runTest("TestOne");
        else if (custom) {
            double[] re = runTest("customTest");
            if (re != null) results = re;
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void v) {
        // execution of result of Long time consuming operation
        pd.dismiss();
        if (results[0] != -1 || results != null) {
            loadIntent(results);
        }
    }

    @Override
    protected void onPreExecute() {
        pd = ProgressDialog.show(MainActivity.this, "Busy", "Algorithm is currently executing");
    }
}

Whereas my code doesn't have a checkbox it only needs to implement one test rather than having the option of two. I just want to run "CustomUseCase" and nothing else. I don't want to use a boolean parameter however I still want to have AsyncTask. Please help me!

public class runTests extends AsyncTask<Boolean, Void, Void> {
    @Override
    protected Void doInBackground(Boolean... params) { //sort this out
        boolean one    = params[0];
        boolean custom = params[1];

        if (one)
            results = runTest("CustomUseCase"); //i only want to run this one!!!
        else if (custom) {
            double[] re = runTest("testOne"); //I don't need this, I dont want to run this test
            if (re != null) results = re;
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void v) {
        // execution of result of Long time consuming operation
        if(pd!=null){
            pd.dismiss();
            pd = null;
        }
        if (results[0] != -1 || results != null) {
            loadIntent(results);
        }
    }
  @Override
    protected void onPreExecute() {
        pd = ProgressDialog.show(ParticleActivity.this, "Busy", "Algorithm is currently executing");
    }
}

Body:
First, you need to change

if (results[0] != -1 || results != null) {
    loadIntent(results);
}

to

if (results != null && results.length > 0 && results[0] != -1) {
    loadIntent(results);
}

That is an example of a "short circuiting" if statement. The logical AND (&&) operator will cause the entire statement to fail if results is null, otherwise it will evaluate the next logic statement results[0] != -1 with no chance of a NullPointerException.

Try this as well

public class runTests extends AsyncTask<Void, Void, Void> {
    @Override
    protected Void doInBackground(Void... params) { //sort this out

        results = runTest("CustomUseCase"); //i only want to run this one!!!
    }
    ...
}

UPDATE

do I return null when executing the doInBackground?

To clarify how the Template Type List (ie, <Void,Void,Void>) works, here is an example. Here, we have <URL, Integer, Long>. Notice how doInBackground takes an array of URL (urls) and returns a Long, onProgressUpdate takes an Integer array, and onPostExecute takes a Long.

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {
         long totalSize = urls.length;
         ...
         return totalSize;
     }

     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }

     protected void onPostExecute(Long result) {
         showDialog("Downloaded " + result + " bytes");
     }
 }

For <Void, Void, Void> we would have (empty function argument list "()" corresponds to Void):

private class DownloadFilesTask extends AsyncTask<Void, Void, Void> {
     protected Void doInBackground() {
         ...
         return;
     }

     protected void onProgressUpdate() {
         setProgressPercent("hi");
     }

     protected void onPostExecute() {
         showDialog("bye");
     }
 }


问:
What is __pycache__?
From what I understand, a cache is an encrypted file of similar files.

What do we do with the __pycache__ folder? Is it what we give to people instead of our source code? Is it just my input data? This folder keeps getting created, what it is for?

答: In 3.2 and later, Python saves .pyc compiled byte code files in a sub-directory named __pycache__ located in the directory where your source files reside with filenames that identify the Python version that created them (e.g. script.cpython-33.pyc)

Title: What is __pycache__?


问:
Cygwin bash concatenate variables results in $'VALUE1/VALUE2\r'
I am creating a script in bash using CYGWIN.

This is essentially what I have:

```<code>#!/bin/bash

username=someuser
passwd=someuserpasswd
hostname=thehost
port=1521
sid=dbname
</code>```

When I concatenate the variables, as in

```<code>LOGIN_STR=${username}/${passwd}@${hostname}:${port}/${sid}
echo "Login String = $LOGIN_STR"
</code>```

The result is:

```<code>Login String = $'someuser/someuserpasswd\r@thehost:1521/dbname\r'
</code>```

To login into sqlplus, obviously this will not work.

I've also tried LOGIN_STR=$username/$passwd@$hostname:$port/$sid..  Same result.

I understand this probably is related to how Windows handles carriage returns vs Unix.  What I'm not clear is what I need to do to cause this to not happen any  longer.

Thank you in advance!

答:
Be sure to do this in your .bash_profile or equivalent:

```<code>export SHELLOPTS
set -o igncr
</code>```

This will take care of these types of carriage-return problems inside of Cygwin.

Body:
I am creating a script in bash using CYGWIN.

This is essentially what I have:

#!/bin/bash

username=someuser
passwd=someuserpasswd
hostname=thehost
port=1521
sid=dbname

When I concatenate the variables, as in

LOGIN_STR=${username}/${passwd}@${hostname}:${port}/${sid}
echo "Login String = $LOGIN_STR"

The result is:

Login String = $'someuser/someuserpasswd\r@thehost:1521/dbname\r'

To login into sqlplus, obviously this will not work.

I've also tried LOGIN_STR=$username/$passwd@$hostname:$port/$sid..  Same result.

I understand this probably is related to how Windows handles carriage returns vs Unix.  What I'm not clear is what I need to do to cause this to not happen any  longer.

Thank you in advance!

Body:
Be sure to do this in your .bash_profile or equivalent:

export SHELLOPTS
set -o igncr

This will take care of these types of carriage-return problems inside of Cygwin.


问:
Why doesnt this xPath (c#) work?
Got this xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<video xmlns="UploadXSD">
  <title>
    A vid with Pete
  </title>
  <description>
  Petes vid
  </description>
  <contributor>
    Pete
  </contributor>
  <subject>
    Cat 2
  </subject>
</video>
</code>```

And this xpath:

```<code>videoToAdd.Title = doc.SelectSingleNode(@"/video/title").InnerXml;
</code>```

And im getting an 'object reference not set to an instance of an object'.  Any ideas why this is a valid xpath from what I can see and it used to work...

答: It's the xmlns="UploadXSD" attribute causing you grief here.  I think you'll need to use a XmlNamespaceManager to help the parser resolve the names, or remove the xmlns attribute if you don't need it.

Title: Why doesnt this xPath (c#) work?

Body:
Got this xml:

<?xml version="1.0" encoding="UTF-8"?>
<video xmlns="UploadXSD">
  <title>
    A vid with Pete
  </title>
  <description>
  Petes vid
  </description>
  <contributor>
    Pete
  </contributor>
  <subject>
    Cat 2
  </subject>
</video>

And this xpath:

videoToAdd.Title = doc.SelectSingleNode(@"/video/title").InnerXml;

And im getting an 'object reference not set to an instance of an object'.  Any ideas why this is a valid xpath from what I can see and it used to work...


问:
Can a Go App dynamically compile Go code?
Say I have a Lua program that accepts user input which happens to be valid Lua source code. This is sanitized, compiled and executed while the program is still running. Is (or will) such a thing (be) possible with Go?</p>

答:
I have an idea on how you could accomplish that, but you would pretty much have to do the same in C.

Go is a compiled language, so in order to achieve what you would like to accomplish you would need to write a wrapper over CSP that would support versioning of the binary and export functionality over some kind of a RPC. The steps would be as following:

locally try to build the Go code

start the result

the new program connects to the RPC of the currently running program

the first program is instructed to point all the CSP data (channel, goroutine scheduling) into the new runtime

the external interface switches to the new program, after all goroutines from the old program end, kills the old process

Obviously this is ridiculously complicated and you'll end up saving a lot of time using a scripting language through something like Otto or go-lua.