问:
DocuSign Rest API - TAB_REFERS_TO_MISSING_DOCUMENT
I'm getting the error below while try to create envelope based on template via DocuSign Rest API (Java). Getting the error message as specific document ID which is not present. I used to upload the document with Document ID as "1", but for one template I am getting below error.

```<code>Exception: com.docusign.esign.client.ApiException: {
  "errorCode": "TAB_REFERS_TO_MISSING_DOCUMENT",
  "message": "The DocumentId specified in the tab element does not refer to a document in this envelope. Tab refers to DocumentId 69681238 which is not present."
}
</code>```

Can anyone explain for the above scenario? do I need to do make any changes in my template or in my code? any additional parameter i have to pass?

Envelope Creation Code:

```<code>try {
    Path path = Paths.get(file);
    fileBytes = Files.readAllBytes(path);
} catch (IOException ioExcp) {
    System.out.println("Exception: " + ioExcp);
    return null;
}
// add a document to the envelope
Document doc = new Document();
String base64Doc = Base64.encodeBase64String(fileBytes);

doc.setDocumentBase64(base64Doc);
doc.setName(fileName);

doc.setDocumentId("1");

List<Document> docs = new ArrayList<Document>();
docs.add(doc);
envDef.setTemplateId(templateId());
envDef.setDocuments(docs);

List<TemplateRole> templateRolesList = new LinkedList<TemplateRole>();
TemplateRole templateRole = new TemplateRole();

templateRole.setEmail(signerEmail);
templateRole.setName(signerName);
templateRole.setRoleName("Signer1");
templateRole.setRoutingOrder("1");
templateRolesList.add(templateRole);

TemplateRole templateRole2 = new TemplateRole();
templateRole2.setName(signerName1);
templateRole2.setRoleName("Signer2");
templateRole2.setRoutingOrder("2");
templateRole2.setEmail(signerEmail1);
templateRolesList.add(templateRole2);

envDef.setTemplateRoles(templateRolesList);

envDef.setAllowRecipientRecursion("true");
envDef.setStatus("created");

try {
    EnvelopesApi envelopesApi = new EnvelopesApi();

    EnvelopeSummary envelopeSummary = envelopesApi.createEnvelope(accountId(), envDef);

    DocumentTemplateList documentTemplateList = new DocumentTemplateList();
    DocumentTemplate documentTemplate = new DocumentTemplate();
    documentTemplate.setTemplateId(templateId());
    documentTemplate.setDocumentId(doc.getDocumentId());
    documentTemplateList.getDocumentTemplates().add(documentTemplate);

    envelopesApi.applyTemplateToDocument(accountId,
            envelopId(), doc.getDocumentId(),
            documentTemplateList);

} catch (com.docusign.esign.client.ApiException ex) {
    System.out.println("Exception: " + ex);
    ex.printStackTrace();
}
</code>```

As you mentioned to get document ID from template list. I'm getting documents array as empty. Here is the response.

```<code>class EnvelopeTemplateResult {
    templateId: <templateId>
    name: Template 1
    shared: true
    password:
    description:
    lastModified: 2017-06-06T19:45:35.7670000Z
    pageCount: 15
    uri: /templates/<uri>
    folderName: Templates
    folderId: <folderId>
    folderUri: /folders/<folderUri>
    parentFolderUri: null
    owner: class UserInfo {
        userName: User Name
        email: email@email.com
        userId: userID
        userType: null
        userStatus: null
        uri: null
        errorDetails: null
    }
    documents: []
    recipients: null
    transactionId: null
    status: null
    documentsUri: null
    recipientsUri: null
    asynchronous: null
    envelopeUri: null
    emailSubject: Sign Document
    emailBlurb: Please sign this document
    envelopeId: null
    signingLocation: Online
    customFieldsUri: null
    envelopeIdStamping: null
    authoritativeCopy: false
    notification: null
    notificationUri: null
    enforceSignerVisibility: false
    enableWetSign: true
    allowMarkup: false
    allowReassign: false
    createdDateTime: null
    lastModifiedDateTime: null
    deliveredDateTime: null
    sentDateTime: null
    completedDateTime: null
    voidedDateTime: null
    voidedReason: null
    deletedDateTime: null
    declinedDateTime: null
    statusChangedDateTime: null
    documentsCombinedUri: null
    certificateUri: null
    templatesUri: null
    messageLock: null
    recipientsLock: null
    brandLock: null
    brandId: null
    useDisclosure: null
    emailSettings: null
    purgeState: null
    lockInformation: null
    is21CFRPart11: null
    isUniversalSignatureEnvelope: null
}
</code>```

答:
Its hard to tell your exact problem without seeing your envelope creation code.

Most likely you are using the wrong DocumentId during envelope creation.

Use the listTemplateDocuments api to retrieve the document id's on your template. Use the exact DocumentId's from the template during envelope creation.

Also see this answer and this answer

Body:
I'm getting the error below while try to create envelope based on template via DocuSign Rest API (Java). Getting the error message as specific document ID which is not present. I used to upload the document with Document ID as "1", but for one template I am getting below error.

Exception: com.docusign.esign.client.ApiException: {
  "errorCode": "TAB_REFERS_TO_MISSING_DOCUMENT",
  "message": "The DocumentId specified in the tab element does not refer to a document in this envelope. Tab refers to DocumentId 69681238 which is not present."
}

Can anyone explain for the above scenario? do I need to do make any changes in my template or in my code? any additional parameter i have to pass?

Envelope Creation Code:

try {
    Path path = Paths.get(file);
    fileBytes = Files.readAllBytes(path);
} catch (IOException ioExcp) {
    System.out.println("Exception: " + ioExcp);
    return null;
}
// add a document to the envelope
Document doc = new Document();
String base64Doc = Base64.encodeBase64String(fileBytes);

doc.setDocumentBase64(base64Doc);
doc.setName(fileName);

doc.setDocumentId("1");

List<Document> docs = new ArrayList<Document>();
docs.add(doc);
envDef.setTemplateId(templateId());
envDef.setDocuments(docs);

List<TemplateRole> templateRolesList = new LinkedList<TemplateRole>();
TemplateRole templateRole = new TemplateRole();

templateRole.setEmail(signerEmail);
templateRole.setName(signerName);
templateRole.setRoleName("Signer1");
templateRole.setRoutingOrder("1");
templateRolesList.add(templateRole);

TemplateRole templateRole2 = new TemplateRole();
templateRole2.setName(signerName1);
templateRole2.setRoleName("Signer2");
templateRole2.setRoutingOrder("2");
templateRole2.setEmail(signerEmail1);
templateRolesList.add(templateRole2);

envDef.setTemplateRoles(templateRolesList);

envDef.setAllowRecipientRecursion("true");
envDef.setStatus("created");

try {
    EnvelopesApi envelopesApi = new EnvelopesApi();

    EnvelopeSummary envelopeSummary = envelopesApi.createEnvelope(accountId(), envDef);

    DocumentTemplateList documentTemplateList = new DocumentTemplateList();
    DocumentTemplate documentTemplate = new DocumentTemplate();
    documentTemplate.setTemplateId(templateId());
    documentTemplate.setDocumentId(doc.getDocumentId());
    documentTemplateList.getDocumentTemplates().add(documentTemplate);

    envelopesApi.applyTemplateToDocument(accountId,
            envelopId(), doc.getDocumentId(),
            documentTemplateList);

} catch (com.docusign.esign.client.ApiException ex) {
    System.out.println("Exception: " + ex);
    ex.printStackTrace();
}

As you mentioned to get document ID from template list. I'm getting documents array as empty. Here is the response.

class EnvelopeTemplateResult {
    templateId: <templateId>
    name: Template 1
    shared: true
    password:
    description:
    lastModified: 2017-06-06T19:45:35.7670000Z
    pageCount: 15
    uri: /templates/<uri>
    folderName: Templates
    folderId: <folderId>
    folderUri: /folders/<folderUri>
    parentFolderUri: null
    owner: class UserInfo {
        userName: User Name
        email: email@email.com
        userId: userID
        userType: null
        userStatus: null
        uri: null
        errorDetails: null
    }
    documents: []
    recipients: null
    transactionId: null
    status: null
    documentsUri: null
    recipientsUri: null
    asynchronous: null
    envelopeUri: null
    emailSubject: Sign Document
    emailBlurb: Please sign this document
    envelopeId: null
    signingLocation: Online
    customFieldsUri: null
    envelopeIdStamping: null
    authoritativeCopy: false
    notification: null
    notificationUri: null
    enforceSignerVisibility: false
    enableWetSign: true
    allowMarkup: false
    allowReassign: false
    createdDateTime: null
    lastModifiedDateTime: null
    deliveredDateTime: null
    sentDateTime: null
    completedDateTime: null
    voidedDateTime: null
    voidedReason: null
    deletedDateTime: null
    declinedDateTime: null
    statusChangedDateTime: null
    documentsCombinedUri: null
    certificateUri: null
    templatesUri: null
    messageLock: null
    recipientsLock: null
    brandLock: null
    brandId: null
    useDisclosure: null
    emailSettings: null
    purgeState: null
    lockInformation: null
    is21CFRPart11: null
    isUniversalSignatureEnvelope: null
}


来源: stackexchange

问:
how applying transformation to matrix from random rotations
i have object that are receiving 4 transformations step by step at different location in the software. We use a CAD engine library so i have custom objects to do transformation.

The Situation

i need to recuperate from the matrix of one of the object translation and rotation so that i can create a new matrix later one from those rotation.

The Code (sample)

```<code>// create a transformation object, very simple 1 translation and 3 rotations
var  t = new Translation(10, 15, 20)
         * new Rotation(10d.ToRadian(), Vector3D.AxisX)
         * new Rotation(10d.ToRadian(), Vector3D.AxisY)
         * new Rotation(10d.ToRadian(), Vector3D.AxisZ);

// convert to the windows Matrix3D
var m1 = ToWindowsMatrix(t);

// decompose the matrix to get one random possibility of combinaison of rotation x, y and Z to obtain the same result
var rx = Math.Atan2(m1.M32, m1.M33).ToDegree();
var ry = Math.Atan2(-m1.M31, Math.Sqrt(Math.Pow(m1.M32, 2) + Math.Pow(m1.M33, 2))).ToDegree();
var rz = Math.Atan2(m1.M21, m1.M11).ToDegree();
</code>```

Source for formula to get rotation x,y and z:

```<code>// create a transformation object, in the same order, hardcoded translate but use the computed equivalent rotation x,y and z
var  t2 = new Translation(10, 15, 20)
         * new Rotation(rx.ToRadian(), Vector3D.AxisX)
         * new Rotation(ry.ToRadian(), Vector3D.AxisY)
         * new Rotation(rz.ToRadian(), Vector3D.AxisZ);

// convert to the windows Matrix3D
var m2 = ToWindowsMatrix(t2);
</code>```

The Problem

if i take a 3d object and apply the transformation of t2 the rotation of the object is completely off compared to what t1 gives.

I absolutely need to get decomposed value as the whole system display the objects using 6 parameters (origin x,y,z and rotation x,y,z) which then create an identity matrix and apply a translate and 3 rotate.

I have been working of this for around 7 hours and i figured out that if i ONLY apply a single rotation on t1 ie "rotation X 90" and on t2 i still apply ALL rotations with the computed value the rotation DO match. So i have the feeling that the order of transformation need to be in a specific order but i cannot change it. So it mean i need to get the rotation x,y and z so that by applying Translate * RotX * RotY * RotZ it matches.

Anything i might have missed ? i have found some mathlab samples too but formula are all the same so far.

答:
Figured out after a while how to get the XYZ rotation of a matrix. The problem is that the Euler angles return in a ZYX rotation. More operation need to be performed in order to extract the XYZ from it.

```<code>public static double[] GetXYZRotation(this Matrix3D matrix)
    {
        // get the euler angles
        var eulerX = Math.Atan2(matrix.M32, matrix.M33).ToDegree();
        var eulerY = Math.Atan2(-matrix.M31, Math.Sqrt(Math.Pow(matrix.M32, 2) + Math.Pow(matrix.M33, 2))).ToDegree();
        var eulerZ = Math.Atan2(matrix.M21, matrix.M11).ToDegree();

        // create transformation of the euler angle to get a matrix. euler rotation is ZYX
        var eulerMatrix = (new Translation(matrix.OffsetX,matrix.OffsetY,matrix.OffsetZ)
              * new Rotation(eulerZ.ToRadian(), Vector3D.AxisZ)
              * new Rotation(eulerY.ToRadian(), Vector3D.AxisY)
              * new Rotation(eulerX.ToRadian(), Vector3D.AxisX)).ToWindowsMatrix();

        // get the Alpha Beta and Gamma of the euler matrix
        var beta = Math.Atan2(eulerMatrix.M13, Math.Sqrt(Math.Pow(eulerMatrix.M11, 2d) + Math.Pow(-eulerMatrix.M12, 2d)));
        var alpha = Math.Atan2(-(eulerMatrix.M23 / Math.Cos(beta)), eulerMatrix.M33 / Math.Cos(beta));
        var gamma = Math.Atan2(-(eulerMatrix.M12 / Math.Cos(beta)), eulerMatrix.M11 / Math.Cos(beta));

        // get the XYZ rotation per euler computed alpha beta gamma
        var rotationX = alpha.ToDegree();
        var rotationY = beta.ToDegree();
        var rotationZ = gamma.ToDegree();

        return new[] { rotationX, rotationY, rotationZ };
    }
</code>```

So i needed to compute the matrix applying the euler angle in the reverse order : Z then Y then X and from there calculate the Alpha, Beta and Gamma which retreive a XYZ rotation values

ContentLicense: CC BY-SA 3.0

Body:
i have object that are receiving 4 transformations step by step at different location in the software. We use a CAD engine library so i have custom objects to do transformation.

The Situation

i need to recuperate from the matrix of one of the object translation and rotation so that i can create a new matrix later one from those rotation.

The Code (sample)

// create a transformation object, very simple 1 translation and 3 rotations
var  t = new Translation(10, 15, 20)
         * new Rotation(10d.ToRadian(), Vector3D.AxisX)
         * new Rotation(10d.ToRadian(), Vector3D.AxisY)
         * new Rotation(10d.ToRadian(), Vector3D.AxisZ);

// convert to the windows Matrix3D
var m1 = ToWindowsMatrix(t);

// decompose the matrix to get one random possibility of combinaison of rotation x, y and Z to obtain the same result
var rx = Math.Atan2(m1.M32, m1.M33).ToDegree();
var ry = Math.Atan2(-m1.M31, Math.Sqrt(Math.Pow(m1.M32, 2) + Math.Pow(m1.M33, 2))).ToDegree();
var rz = Math.Atan2(m1.M21, m1.M11).ToDegree();

Source for formula to get rotation x,y and z:

// create a transformation object, in the same order, hardcoded translate but use the computed equivalent rotation x,y and z
var  t2 = new Translation(10, 15, 20)
         * new Rotation(rx.ToRadian(), Vector3D.AxisX)
         * new Rotation(ry.ToRadian(), Vector3D.AxisY)
         * new Rotation(rz.ToRadian(), Vector3D.AxisZ);

// convert to the windows Matrix3D
var m2 = ToWindowsMatrix(t2);

The Problem

if i take a 3d object and apply the transformation of t2 the rotation of the object is completely off compared to what t1 gives.

I absolutely need to get decomposed value as the whole system display the objects using 6 parameters (origin x,y,z and rotation x,y,z) which then create an identity matrix and apply a translate and 3 rotate.

I have been working of this for around 7 hours and i figured out that if i ONLY apply a single rotation on t1 ie "rotation X 90" and on t2 i still apply ALL rotations with the computed value the rotation DO match. So i have the feeling that the order of transformation need to be in a specific order but i cannot change it. So it mean i need to get the rotation x,y and z so that by applying Translate * RotX * RotY * RotZ it matches.

Anything i might have missed ? i have found some mathlab samples too but formula are all the same so far.

Body:
Figured out after a while how to get the XYZ rotation of a matrix. The problem is that the Euler angles return in a ZYX rotation. More operation need to be performed in order to extract the XYZ from it.

public static double[] GetXYZRotation(this Matrix3D matrix)
    {
        // get the euler angles
        var eulerX = Math.Atan2(matrix.M32, matrix.M33).ToDegree();
        var eulerY = Math.Atan2(-matrix.M31, Math.Sqrt(Math.Pow(matrix.M32, 2) + Math.Pow(matrix.M33, 2))).ToDegree();
        var eulerZ = Math.Atan2(matrix.M21, matrix.M11).ToDegree();

        // create transformation of the euler angle to get a matrix. euler rotation is ZYX
        var eulerMatrix = (new Translation(matrix.OffsetX,matrix.OffsetY,matrix.OffsetZ)
              * new Rotation(eulerZ.ToRadian(), Vector3D.AxisZ)
              * new Rotation(eulerY.ToRadian(), Vector3D.AxisY)
              * new Rotation(eulerX.ToRadian(), Vector3D.AxisX)).ToWindowsMatrix();

        // get the Alpha Beta and Gamma of the euler matrix
        var beta = Math.Atan2(eulerMatrix.M13, Math.Sqrt(Math.Pow(eulerMatrix.M11, 2d) + Math.Pow(-eulerMatrix.M12, 2d)));
        var alpha = Math.Atan2(-(eulerMatrix.M23 / Math.Cos(beta)), eulerMatrix.M33 / Math.Cos(beta));
        var gamma = Math.Atan2(-(eulerMatrix.M12 / Math.Cos(beta)), eulerMatrix.M11 / Math.Cos(beta));

        // get the XYZ rotation per euler computed alpha beta gamma
        var rotationX = alpha.ToDegree();
        var rotationY = beta.ToDegree();
        var rotationZ = gamma.ToDegree();

        return new[] { rotationX, rotationY, rotationZ };
    }

So i needed to compute the matrix applying the euler angle in the reverse order : Z then Y then X and from there calculate the Alpha, Beta and Gamma which retreive a XYZ rotation values


问:
Black corners on UITableView Group Style
I have a problem where my UITableView (group style) has a black "tip" above it's rounded corner.

I'm setting up the background of the tableview like so:

```<code>[meetingTableView setBackgroundColor:[[UIColor alloc] initWithPatternImage:[[UIImage alloc] initWithContentsOfFile:@"background.png"]]];
</code>```

And my table view ends up looking like this:

black pointy edge on rounded corner http://papernapkin.org/pastebin/resource/images/imageEntryId/6487

Any ideas how I can get rid of those black points?

答:
I have got the same problem.
When I set clear color by xib, I have the back corner
The solution is to set it by code !

(The same problem with interface builder exist for webviews)

ContentLicense: CC BY-SA 2.5

Body:
I have a problem where my UITableView (group style) has a black "tip" above it's rounded corner.

I'm setting up the background of the tableview like so:

[meetingTableView setBackgroundColor:[[UIColor alloc] initWithPatternImage:[[UIImage alloc] initWithContentsOfFile:@"background.png"]]];

And my table view ends up looking like this:

black pointy edge on rounded corner http://papernapkin.org/pastebin/resource/images/imageEntryId/6487

Any ideas how I can get rid of those black points?


问:
Python Selenium unable to find table element by xpath
Here is what the table looks like on the web page (it's just one column):

Here is the HTML of the table I am trying to scrape:

If it matters, that table is nested within another table.

Here is my code:

```<code>    def filter_changed_records():
        # Scrape webpage for addresses from table of changed properties
        row_number = 0
        results_frame = locate_element(
            '//*[@id="oGridFrame"]'
        )
        driver.switch_to.frame(results_frame)
        while True:
            try:
                address = locate_element("id('row" + str(row_number) +
                                         "FC')/x:td")
                print(address)
                changed_addresses.append(address)
                row_number += 1
            except:
                print("No more addresses to add.")
                break
</code>```

As you can see, there is a
 tag with an id of row0FC. This table is dynamically generated, and each new
 gets an id with a increasing number: row0FC, row1FC, row2FC etc. That is how I planned on iterating through all the entries and adding them to a list.

My locate_element function is the following:

```<code>    def locate_element(path):
        element = WebDriverWait(driver, 50).until(
            EC.presence_of_element_located((By.XPATH, path)))
        return element
</code>```

It always times out after 50 seconds from not finding the element. Unsure of how to proceed. Is there a better way of locating the element?

SOLUTION BY ANDERSSON

```<code>address = locate_element("//tr[@id='row%sFC']/td" % row_number).text
</code>```

答:
Your XPath seem to be incorrect.

Try below:

```<code>address = locate_element("//tr[@id='row%sFC']/td" % row_number)
</code>```

Also note that address is a WebElement. If you want to get its text content, you should use

```<code>address = locate_element("//tr[@id='row%sFC']/td" % row_number).text
</code>```

Body:
Here is what the table looks like on the web page (it's just one column):

Here is the HTML of the table I am trying to scrape:

If it matters, that table is nested within another table.

Here is my code:

    def filter_changed_records():
        # Scrape webpage for addresses from table of changed properties
        row_number = 0
        results_frame = locate_element(
            '//*[@id="oGridFrame"]'
        )
        driver.switch_to.frame(results_frame)
        while True:
            try:
                address = locate_element("id('row" + str(row_number) +
                                         "FC')/x:td")
                print(address)
                changed_addresses.append(address)
                row_number += 1
            except:
                print("No more addresses to add.")
                break

As you can see, there is a
 tag with an id of row0FC. This table is dynamically generated, and each new
 gets an id with a increasing number: row0FC, row1FC, row2FC etc. That is how I planned on iterating through all the entries and adding them to a list.

My locate_element function is the following:

    def locate_element(path):
        element = WebDriverWait(driver, 50).until(
            EC.presence_of_element_located((By.XPATH, path)))
        return element

It always times out after 50 seconds from not finding the element. Unsure of how to proceed. Is there a better way of locating the element?

SOLUTION BY ANDERSSON

address = locate_element("//tr[@id='row%sFC']/td" % row_number).text

Body:
Your XPath seem to be incorrect.

Try below:

address = locate_element("//tr[@id='row%sFC']/td" % row_number)

Also note that address is a WebElement. If you want to get its text content, you should use

address = locate_element("//tr[@id='row%sFC']/td" % row_number).text


问:
Add a text near my checkbox slider
I'm using some slider to replace my checkboxes.

```<code><div class="col-sm-4">
    <label class="switch small">
        <input type="checkbox">
        <div class="slider small"></div>
    </label>
</div>
</code>```

https://jsfiddle.net/dky16b53/

How can I add some text near each sliders please ?

Thanks.

答:
I just found a quick hack for it. Add a  for each side text and put position: absolute and margin on it.

EDIT: Now with check/uncheck functionality:

https://jsfiddle.net/dky16b53/2/

HTML:

```<code><label class="switch small">
    <input type="checkbox">
    <div class="slider small"></div>
</label>
<span>More Text</span>
</code>```

CSS:

```<code>..existing code

div span {
  position: absolute;
  margin-left: 5px;
}
</code>```

Title: Add a text near my checkbox slider

Body:
I'm using some slider to replace my checkboxes.

        <input type="checkbox">

https://jsfiddle.net/dky16b53/

How can I add some text near each sliders please ?

Thanks.

Body:
I just found a quick hack for it. Add a <span> for each side text and put position: absolute and margin on it.

EDIT: Now with check/uncheck functionality:

https://jsfiddle.net/dky16b53/2/

HTML:

<label class="switch small">
    <input type="checkbox">
    <div class="slider small"></div>
</label>
<span>More Text</span>

CSS:

..existing code

div span {
  position: absolute;
  margin-left: 5px;
}


问:
How to stop ASP .NET from JSONifying JSON
I am currently trying to wrap an internal API and make it external. To do so, I am trying to relay the JSON responses from the internal API and send that exact response when someone makes a get request. Instead, ASP .NET is JSONifying that son and adding extra back slashes as escape characters (when in fact those slashes are really escape slashes put in by the internal api).

How can i get it so asp does not jsonify the string

答:
You can write your json data directly to response and set right content headers.</p>

```<code>public HttpResponseMessage GetData()
{
    var json = "\"value\": \"da\\ta\"";
    var resp = Request.CreateResponse(HttpStatusCode.OK);
    resp.Content = new StringContent(json);
    resp.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
    resp.Content.Headers.ContentEncoding = //your json encoding, you can get it from response inner API

    return resp;
}
</code>```

Body:
You can write your json data directly to response and set right content headers.

public HttpResponseMessage GetData()
{
    var json = "\"value\": \"da\\ta\"";
    var resp = Request.CreateResponse(HttpStatusCode.OK);
    resp.Content = new StringContent(json);
    resp.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
    resp.Content.Headers.ContentEncoding = //your json encoding, you can get it from response inner API

    return resp;
}


问:
ActiveRecord: sort of complicated query with nested associations and sorting
Alrigth, so I'm not sure if this isn't too specific... But I really don't have a clue how to construct such a query, neither in AR, nor in SQL. So here's the situation:

I have a User model. User has_many Projects. A Project, in turn, have a following associations:

Project has_one BasicEvent

Project had_many AdditionalEvents

BasicEvent and AdditionalEvent classes are built on inheritance from a AR model class, Event

Now, the goal is this: on my view, I need:

access to all Projects count per User

access to all Events count, where happened_at attribute in nil

have all the Users sorted, by the count of Events, where happened_at attribute in nil

I made a couple of attempts at it so far, but didn't really get too far... I will appreciate any help with this complicated (at least from my perspective) query.

答:
Projects count per User: Project.group(:user_id).count

Events count, where happened_at attribute in nil: Event.where(happened_at: nil).count

Users sorted, by the count of Events, where happened_at attribute in nil: This is the trickiest but it's also not particularly difficult:

```<code>User.
  select("users.*, (SELECT COUNT(*) FROM events WHERE user_id = users.id AND happened_at IS NULL) AS unhappened_events_count").
  order("unhappened_events_count DESC")
</code>```

This is not a particularly efficient query but it should do its job well for several thousand records (easily) – especially if you set an index on user_id and happened_at in the events table.

Body:
Projects count per User: Project.group(:user_id).count

Events count, where happened_at attribute in nil: Event.where(happened_at: nil).count

Users sorted, by the count of Events, where happened_at attribute in nil: This is the trickiest but it's also not particularly difficult:

User.
  select("users.*, (SELECT COUNT(*) FROM events WHERE user_id = users.id AND happened_at IS NULL) AS unhappened_events_count").
  order("unhappened_events_count DESC")

This is not a particularly efficient query but it should do its job well for several thousand records (easily) – especially if you set an index on user_id and happened_at in the events table.


问:
making a jar file for console
I have a program without a GUI and I use console! So first I read a line from a user from console

BufferedReader userReader = new BufferedReader(new InputStreamReader(System.in));

and then I will write an answer for the user in the console!

System.out.println("Server:"+output);

I want to create a jar file for it ! but how can i show my console in jar file with out using GUI?
please help me thanks.

答:
Making an executable jar is the same no matter GUI or not. You need to specify your Main-Class in your META-INF/MANIFEST.MF. See here and and here

Of course, if you want to start something on the console, just open the console and use the following: java -jar archive.jar (with the above requirements met)

Then I'd recommend using java.io.Console for reading and writing to the console.

Title: making a jar file for console


问:
export array content to csv row with php
I am trying to export an array to csv, but my csv contains only one row with many fields (columns). I want to achieve to export into rows my data.
My data looks like when I dump:

```<code>array(2) { [0]=> string(10) "something1" [1]=> string(18) "something2" }
</code>```

here is the php code: ($names is my array)

```<code>$list = array ($names);
$fp = fopen('download.csv', 'w');
    foreach ($list as $fields) {
    fputcsv($fp, $fields);
}
fclose($fp);
</code>```

Thank you in advance!

EDIT: now looks like:

how to achieve this:

答:
There's no need to put the $names into an array to accomplish what you want.

```<code>$fp = fopen('download.csv', 'w');
foreach ($names as $name) {
    fputcsv($fp, [$name]);
}
fclose($fp);
</code>```

Body:
I am trying to export an array to csv, but my csv contains only one row with many fields (columns). I want to achieve to export into rows my data.
My data looks like when I dump:

array(2) { [0]=> string(10) "something1" [1]=> string(18) "something2" }

here is the php code: ($names is my array)

$list = array ($names);
$fp = fopen('download.csv', 'w');
    foreach ($list as $fields) {
    fputcsv($fp, $fields);
}
fclose($fp);

Thank you in advance!

EDIT: now looks like:

how to achieve this:

Body:
There's no need to put the $names into an array to accomplish what you want.

$fp = fopen('download.csv', 'w');
foreach ($names as $name) {
    fputcsv($fp, [$name]);
}
fclose($fp);


问:
Received incoming SIP connection from unknown peer
I have created 2 users in sip_additional.config. which is like:

```<code>[james]
secret=12345
context=tenancy1
host=dynamic
type=friend
allow=ulaw,alaw

[caleb]
secret=12345
context=tenancy1
host=dynamic
type=friend
allow=ulaw,alaw
</code>```

And created dialplan for above context. Here I am assigning duplicate extensions but with different context ie. 2222,2225 is already assigned to another users but with different context (from-internal).

```<code>[tenancy1]
exten => 2222,1,NoOp(james calling)
same => n,Dial(SIP/james)
same => n,Hangup

exten => 2225,1,NoOp(caleb calling)
same => n,Dial(SIP/caleb)
same => n,Hangup
</code>```

The issue here is, when i make call from 2222 to 2225 then 2224 is ringing but 2225 is unable to make a call. I traced from CLI, it is saying

```<code> -- Executing [2222@from-sip-external:1] NoOp("SIP/caleb-00000004", "Received incoming SIP connection from unknown peer to 2222") in new stack
-- Executing [2222@from-sip-external:2] Set("SIP/caleb-00000004", "DID=2222") in new stack
-- Executing [2222@from-sip-external:3] Goto("SIP/caleb-00000004", "s,1") in new stack
-- Goto (from-sip-external,s,1)
-- Executing [s@from-sip-external:1] GotoIf("SIP/caleb-00000004", "0?checklang:noanonymous") in new stack
-- Goto (from-sip-external,s,5)
-- Executing [s@from-sip-external:5] Set("SIP/caleb-00000004", "TIMEOUT(absolute)=15") in new stack
-- Channel will hangup at 2017-07-07 07:59:00.448 EDT.
-- Executing [s@from-sip-external:6] Log("SIP/caleb-00000004", "WARNING,"Rejecting unknown SIP connection from 172.16.9.112"") in new stack
[2017-07-07 07:58:45] WARNING[5606][C-00000003]: Ext. s:6 @ from-sip-external: "Rejecting unknown SIP connection from 172.16.9.112"
-- Executing [s@from-sip-external:7] Answer("SIP/caleb-00000004", "") in new stack
[2017-07-07 07:58:45] NOTICE[5606][C-00000003]: res_rtp_asterisk.c:4365 ast_rtp_read: Unknown RTP codec 95 received from '172.16.9.112:8000'
-- Executing [s@from-sip-external:8] Wait("SIP/caleb-00000004", "2") in new stack
-- Executing [s@from-sip-external:9] Playback("SIP/caleb-00000004", "ss-noservice") in new stack
-- <SIP/caleb-00000004> Playing 'ss-noservice.ulaw' (language 'en')
-- Executing [s@from-sip-external:10] PlayTones("SIP/caleb-00000004", "congestion") in new stack
-- Executing [s@from-sip-external:11] Congestion("SIP/caleb-00000004", "5") in new stack
</code>```

Do anyone have any idea about this issue.

答:
Acordinly to your trace you are using freepxb web.

So if you are using it, it is nice idea add number at your web in incoming section.

"Unknown peer" mean asterisk not matched incoming request with your sip sections. For more info enable debug and check what exactly asterisk see.

Body:
I have created 2 users in sip_additional.config. which is like:

[james]
secret=12345
context=tenancy1
host=dynamic
type=friend
allow=ulaw,alaw

[caleb]
secret=12345
context=tenancy1
host=dynamic
type=friend
allow=ulaw,alaw

And created dialplan for above context. Here I am assigning duplicate extensions but with different context ie. 2222,2225 is already assigned to another users but with different context (from-internal).

[tenancy1]
exten => 2222,1,NoOp(james calling)
same => n,Dial(SIP/james)
same => n,Hangup

exten => 2225,1,NoOp(caleb calling)
same => n,Dial(SIP/caleb)
same => n,Hangup

The issue here is, when i make call from 2222 to 2225 then 2224 is ringing but 2225 is unable to make a call. I traced from CLI, it is saying

 -- Executing [2222@from-sip-external:1] NoOp("SIP/caleb-00000004", "Received incoming SIP connection from unknown peer to 2222") in new stack
-- Executing [2222@from-sip-external:2] Set("SIP/caleb-00000004", "DID=2222") in new stack
-- Executing [2222@from-sip-external:3] Goto("SIP/caleb-00000004", "s,1") in new stack
-- Goto (from-sip-external,s,1)
-- Executing [s@from-sip-external:1] GotoIf("SIP/caleb-00000004", "0?checklang:noanonymous") in new stack
-- Goto (from-sip-external,s,5)
-- Executing [s@from-sip-external:5] Set("SIP/caleb-00000004", "TIMEOUT(absolute)=15") in new stack
-- Channel will hangup at 2017-07-07 07:59:00.448 EDT.
-- Executing [s@from-sip-external:6] Log("SIP/caleb-00000004", "WARNING,"Rejecting unknown SIP connection from 172.16.9.112"") in new stack
[2017-07-07 07:58:45] WARNING[5606][C-00000003]: Ext. s:6 @ from-sip-external: "Rejecting unknown SIP connection from 172.16.9.112"
-- Executing [s@from-sip-external:7] Answer("SIP/caleb-00000004", "") in new stack
[2017-07-07 07:58:45] NOTICE[5606][C-00000003]: res_rtp_asterisk.c:4365 ast_rtp_read: Unknown RTP codec 95 received from '172.16.9.112:8000'
-- Executing [s@from-sip-external:8] Wait("SIP/caleb-00000004", "2") in new stack
-- Executing [s@from-sip-external:9] Playback("SIP/caleb-00000004", "ss-noservice") in new stack
-- <SIP/caleb-00000004> Playing 'ss-noservice.ulaw' (language 'en')
-- Executing [s@from-sip-external:10] PlayTones("SIP/caleb-00000004", "congestion") in new stack
-- Executing [s@from-sip-external:11] Congestion("SIP/caleb-00000004", "5") in new stack

Do anyone have any idea about this issue.


问:
Display number in rectangle
Note that I am using Python3 and Phoenix.

I would like to display a number (double, but that does not matter now) formatted in some way (again, no matter what that way is) within a rectangle: almost a wx.StaticText but not editable by the user. This is to display some data coming from some hardware, such as a temperature.

Is there such a widget?

I tried with using the default wx.StaticText with a style but I must have done something wrong:

```<code>    hbox = wx.BoxSizer(wx.HORIZONTAL)

    title = wx.StaticText(parent, label=label)
    title.SetLabelMarkup("<b>{}</b>".format(label))
    hbox.Add(title, border=5)

    value = wx.StaticText(parent, label="3.141592", style=wx.BORDER_RAISED)
    value.SetWindowStyle(wx.BORDER_SIMPLE)
    hbox.Add(value, border=5)

    title = wx.StaticText(parent, label="\u2103")
    hbox.Add(title, border=5)
</code>```

Shows this on Linux (Fedora 24, GTK):

答:
Wouldn't using a wx.TextCtrl set to read only do the job?

```<code>Temp = wx.TextCtrl(panel1, value="3.141592", style=wx.TE_READONLY)
Temp.SetBackgroundColour('green')
</code>```

Title: Display number in rectangle

Body:
Note that I am using Python3 and Phoenix.

I would like to display a number (double, but that does not matter now) formatted in some way (again, no matter what that way is) within a rectangle: almost a wx.StaticText but not editable by the user. This is to display some data coming from some hardware, such as a temperature.

Is there such a widget?

I tried with using the default wx.StaticText with a style but I must have done something wrong:

    hbox = wx.BoxSizer(wx.HORIZONTAL)

    title = wx.StaticText(parent, label=label)
    title.SetLabelMarkup("{}".format(label))
    hbox.Add(title, border=5)

    value = wx.StaticText(parent, label="3.141592", style=wx.BORDER_RAISED)
    value.SetWindowStyle(wx.BORDER_SIMPLE)
    hbox.Add(value, border=5)

    title = wx.StaticText(parent, label="\u2103")
    hbox.Add(title, border=5)

Shows this on Linux (Fedora 24, GTK):

Body:
Wouldn't using a wx.TextCtrl set to read only do the job?

Temp = wx.TextCtrl(panel1, value="3.141592", style=wx.TE_READONLY)
Temp.SetBackgroundColour('green')


问:
python plotting data from excel csv file
my excel file is saved as a csv. It has three columns and I am trying to plot column 1 vs column 2 and column 1 vs column 3 on the same plot. I am able to separate the three columns into separate variables, but for some reason cannot plot it. Only the X and Y axis shows up, but no actual graph. Do you know how to plot it?

```<code>import matplotlib.pyplot as plt
import pandas as pd
data = pd.read_csv('file:///C:/Users/Avalanche/Documents/data/FL20data/FL20BU%2317.H-Transfer.1 cycle_data.csv', skiprows = 1)
Htran = data.head(1201)
colm1 = Htran.loc[: , "H-Transfer.1 cycle.Field (Oe)"]
colm2 = Htran.loc[: , "H-Transfer.1 cycle.F1"]
colm3 = Htran.loc[: , "H-Transfer.1 cycle.R1"]
plt.plot([colm1], [colm2])
plt.plot([colm1], [colm3])
plt.xlim(-3500,3500)
plt.ylim(2400,2600)
plt.title('R vs. H')
plt.xlabel('H (Oe)')
plt.ylabel('Resistance')
plt.show()
</code>```

DATA: (I made sure to skip the first row in my code)

```<code>(1-5)R6C10  FL20BU-17   Failed: NONE Passed: skipgrade;

H-Transfer.1 cycle.Field (Oe)   H-Transfer.1 cycle.F1   H-Transfer.1 cycle.R1

-3000.3 2487.508    2487.508
-2994.7 2492.037    2487.508
-2989.9 2510.315    2496.582
-2985.1 2478.497    2505.721
-2980.3 2478.497    2496.582
-2974.7 2496.582    2514.925
-2969.9 2474.016    2524.195
-2965.2 2496.582    2482.995
-2960.4 2501.143    2487.508
-2954.8 2501.143    2478.497
-2950   2501.143    2505.721
</code>```

答:
First, plt.plot([colm1], [colm2]) is a bad idea: you are wrapping a pandas series in a list and then trying to plot it, which is generally not going to work. Second, you likely just want an array of values rather than a pandas series, so tack on the .values attribute to just get the values.

Assuming you have your dataframe is made up of numerical data, this should work for you.

```<code>colm1 = Htran.loc[: , "H-Transfer.1 cycle.Field (Oe)"].values
colm2 = Htran.loc[: , "H-Transfer.1 cycle.F1"].values
colm3 = Htran.loc[: , "H-Transfer.1 cycle.R1"].values
plt.plot(colm1, colm2)
plt.plot(colm1, colm3)
</code>```

As an aside, I recommend looking through the pandas documentation on plotting. Lots of useful information: https://pandas.pydata.org/pandas-docs/stable/visualization.html

Body:
my excel file is saved as a csv. It has three columns and I am trying to plot column 1 vs column 2 and column 1 vs column 3 on the same plot. I am able to separate the three columns into separate variables, but for some reason cannot plot it. Only the X and Y axis shows up, but no actual graph. Do you know how to plot it?

import matplotlib.pyplot as plt
import pandas as pd
data = pd.read_csv('file:///C:/Users/Avalanche/Documents/data/FL20data/FL20BU%2317.H-Transfer.1 cycle_data.csv', skiprows = 1)
Htran = data.head(1201)
colm1 = Htran.loc[: , "H-Transfer.1 cycle.Field (Oe)"]
colm2 = Htran.loc[: , "H-Transfer.1 cycle.F1"]
colm3 = Htran.loc[: , "H-Transfer.1 cycle.R1"]
plt.plot([colm1], [colm2])
plt.plot([colm1], [colm3])
plt.xlim(-3500,3500)
plt.ylim(2400,2600)
plt.title('R vs. H')
plt.xlabel('H (Oe)')
plt.ylabel('Resistance')
plt.show()

DATA: (I made sure to skip the first row in my code)

(1-5)R6C10  FL20BU-17   Failed: NONE Passed: skipgrade;

H-Transfer.1 cycle.Field (Oe)   H-Transfer.1 cycle.F1   H-Transfer.1 cycle.R1

-3000.3 2487.508    2487.508
-2994.7 2492.037    2487.508
-2989.9 2510.315    2496.582
-2985.1 2478.497    2505.721
-2980.3 2478.497    2496.582
-2974.7 2496.582    2514.925
-2969.9 2474.016    2524.195
-2965.2 2496.582    2482.995
-2960.4 2501.143    2487.508
-2954.8 2501.143    2478.497
-2950   2501.143    2505.721

Body:
First, plt.plot([colm1], [colm2]) is a bad idea: you are wrapping a pandas series in a list and then trying to plot it, which is generally not going to work. Second, you likely just want an array of values rather than a pandas series, so tack on the .values attribute to just get the values.

Assuming you have your dataframe is made up of numerical data, this should work for you.

colm1 = Htran.loc[: , "H-Transfer.1 cycle.Field (Oe)"].values
colm2 = Htran.loc[: , "H-Transfer.1 cycle.F1"].values
colm3 = Htran.loc[: , "H-Transfer.1 cycle.R1"].values
plt.plot(colm1, colm2)
plt.plot(colm1, colm3)

As an aside, I recommend looking through the pandas documentation on plotting. Lots of useful information: https://pandas.pydata.org/pandas-docs/stable/visualization.html


问:
Calculating the total hours
How can i add the hours, minutes, and seconds that exceeds in 24 hours given a string format time in php?
ex.

```<code>$time1 = '10:50:00';
$time1 = '24:00:15';
</code>```

where the result would be:
'34:00:15'

答:
You won't be able to use typical date classes (like DateTime) or functions (like date()) to output hours beyond 24. So you'll have to do this manually.

First you will need to get the times into seconds, so that you can easily add them together. You can use the explode function to get the hours, minutes, and seconds, and multiply those values by the number of seconds required. (60 seconds is 1 minute. 60*60 seconds is 1 hour).

Then you'll need to output the total number of hours, minutes, and seconds. This can be achieved fairly easily through division (again 1 hour is 60*60 seconds, so divide the number of seconds by 60*60 to get the hours), and the modulus operator (%) to get the "remainder" of minutes and seconds.

```<code><?php
// Starting values
$time1 = "10:50:00";
$time2 = "24:00:15";

// First, get the times into seconds
$time1 = explode(":", $time1);
$time1 = $time1[0] * (60*60)    // Hours to seconds
            + $time1[1] * (60)  // Minutes to seconds
            + $time1[2];        // Seconds

$time2 = explode(":", $time2);
$time2 = $time2[0] * (60*60)    // Hours to seconds
            + $time2[1] * (60)  // Minutes to seconds
            + $time2[2];        // Seconds

// Add the seconds together to get the total number of seconds
$total_time = $time1 + $time2;

// Now the "tricky" part: Output it in the hh:mm:ss format.
// Use modulo to determine the hours, minutes, and seconds.
// Don't forget to round when dividing.
print
    //Hours
    floor($total_time / (60 * 60)) .
    // Minutes
    ":" . floor(($total_time % (60 * 60)) / 60) .
    // Seconds
    ":" . $total_time % 60;

    // The output is "34:50:15"
?>
</code>```

Because you're new to PHP, I've done this using functions rather than DateTime, since OOP in PHP may make it harder for you to understand what is happening here. However, if you're learning OOP in PHP, it may be a fun exercise to rewrite my answer using DateTime.

Edit: I've realized that you can use date() to get the number of minutes and seconds, rather than a modulo. You can replace that last print statement with something like this, if you would like:

```<code>print
    //Hours
    floor($total_time / (60 * 60)) .
    // Minutes
    ":" . date('i', $total_time) .
    // Seconds
    ":" . date('s', $total_time);
</code>```

Title: Calculating the total hours

Body:
How can i add the hours, minutes, and seconds that exceeds in 24 hours given a string format time in php?
ex.

$time1 = '10:50:00';
$time1 = '24:00:15';

where the result would be:
'34:00:15'

Body:
You won't be able to use typical date classes (like DateTime) or functions (like date()) to output hours beyond 24. So you'll have to do this manually.

First you will need to get the times into seconds, so that you can easily add them together. You can use the explode function to get the hours, minutes, and seconds, and multiply those values by the number of seconds required. (60 seconds is 1 minute. 60*60 seconds is 1 hour).

Then you'll need to output the total number of hours, minutes, and seconds. This can be achieved fairly easily through division (again 1 hour is 60*60 seconds, so divide the number of seconds by 60*60 to get the hours), and the modulus operator (%) to get the "remainder" of minutes and seconds.

<?php
// Starting values
$time1 = "10:50:00";
$time2 = "24:00:15";

// First, get the times into seconds
$time1 = explode(":", $time1);
$time1 = $time1[0] * (60*60)    // Hours to seconds
            + $time1[1] * (60)  // Minutes to seconds
            + $time1[2];        // Seconds

$time2 = explode(":", $time2);
$time2 = $time2[0] * (60*60)    // Hours to seconds
            + $time2[1] * (60)  // Minutes to seconds
            + $time2[2];        // Seconds

// Add the seconds together to get the total number of seconds
$total_time = $time1 + $time2;

// Now the "tricky" part: Output it in the hh:mm:ss format.
// Use modulo to determine the hours, minutes, and seconds.
// Don't forget to round when dividing.
print
    //Hours
    floor($total_time / (60 * 60)) .
    // Minutes
    ":" . floor(($total_time % (60 * 60)) / 60) .
    // Seconds
    ":" . $total_time % 60;

    // The output is "34:50:15"
?>

Because you're new to PHP, I've done this using functions rather than DateTime, since OOP in PHP may make it harder for you to understand what is happening here. However, if you're learning OOP in PHP, it may be a fun exercise to rewrite my answer using DateTime.

Edit: I've realized that you can use date() to get the number of minutes and seconds, rather than a modulo. You can replace that last print statement with something like this, if you would like:

print
    //Hours
    floor($total_time / (60 * 60)) .
    // Minutes
    ":" . date('i', $total_time) .
    // Seconds
    ":" . date('s', $total_time);


问:
How to change subtitles in VideoView
I have multiple languages for subtitles in separate files. I would like to change subtitles when watching a movie. What is the right way to change the subtitles using addSubtitleSource() method in android VideoView?

```<code>if (subtitle.equals("Language_1")){ //button "Language_1"
mVideoView.addSubtitleSource(source_1, MediaFormat.createSubtitleFormat("text/vtt", "en"));
}
if (subtitle.equals("Language2")){ //button "Language_2"
mVideoView.addSubtitleSource(source_2, MediaFormat.createSubtitleFormat("text/vtt", "en"));
}
</code>```

If I stop and start video, then I can switch between subtitles with this code (probably because after restarting the video it has "forgotten" about added sub source). Is there a way to unload one subtitle source and add different subtitle source without reloading the video? I am thinking of a method like removeSubtitleSource() which doesn't exist.

EDIT: Maybe I can use CaptioningManger for this?

答:
I know is late for your question but maybe the answer can help other people...
I was just working on this recently and needed the same feature of changing displayed subtitles of VideView.

First, add the two subtitles (source_1 and source_2) when you initialize the VideoView.

Then, what you can do is, inside the onPrepared() listener of your VideoView object, you can iterate through the tracks available for the current playing video and, what I did, was save them into a map declared on your class:

The needed reference to the MediaPlayer attached to your videoView, the map for the available subtitle tracks and the current selected subtitle track are private class members declared on my fragment, the one that contains the VideoView:

```<code>private MediaPlayer mediaPlayer;
private HashMap<String, IndexedTrackInfo> availableSubtitleTracks = new HashMap();
private IndexedTrackInfo currentSubtitleTrack;
</code>```

Contents of onPrepared listener

```<code>@Override
public void onPrepared(MediaPlayer mp) {
    Log.d(JGA,"onPrepared");
    loadingIndicator.setVisibility(View.GONE);
    videoView.start();
    controllerFragmentListener.notifyPlaying();
    isPlaying=true;

    if(mediaPlayer == null) {
        mediaPlayer = mp;
    }

    MediaPlayer.TrackInfo[] tracks = mp.getTrackInfo();
    Log.d(TAG, "onInfo: MediaPlayer.getTrackInfo()[" + tracks.length + "]");
    MediaPlayer.TrackInfo track;
    IndexedTrackInfo indexedTrackInfo = null;
    for (int i = 0; i < tracks.length; i++) {
        track = tracks[i];
        Log.d(TAG, "onInfo: track received@" + i + ": " + track.getTrackType() + " = " + track.toString());
        if (track.getTrackType() == MediaPlayer.TrackInfo.MEDIA_TRACK_TYPE_SUBTITLE) {
            indexedTrackInfo = new IndexedTrackInfo(track, i);
            if(track.getFormat().containsKey(TRACK_SUBTITLE_IS_DEFAULT_KEY)) {
                Log.d(TAG, "onInfo: Subtitle track has '" + TRACK_SUBTITLE_IS_DEFAULT_KEY + "' with value = " + track.getFormat().getInteger(TRACK_SUBTITLE_IS_DEFAULT_KEY));
                if(track.getFormat().getInteger(TRACK_SUBTITLE_IS_DEFAULT_KEY) == 1) {
                    Log.d(TAG, "onInfo: This track set as default");
                    currentSubtitleTrack = indexedTrackInfo;
                }
            }
            availableSubtitleTracks.put(track.getLanguage(), indexedTrackInfo);
        }
    }
    if(currentSubtitleTrack == null && indexedTrackInfo != null) {
        currentSubtitleTrack = indexedTrackInfo;
        mediaPlayer.selectTrack(currentSubtitleTrack.getIndex());
        Log.d(TAG, "onInfo: There was no default sub track but there are tracks available... picking the last one as default [" + currentSubtitleTrack.getIndex() + "]");
    }
    controllerFragmentListener.updateSpinnerSubtitleTracks(availableSubtitleTracks);
    controllerFragmentListener.updateSpinnerCurrentSelection(currentSubtitleTrack.getTrackInfo().getLanguage());
}
</code>```

And the custom POJO to asociate each track with its corresponding index in the TrackInfo of the mediaPlayer (IndexedTrackInfo.java):

```<code>public class IndexedTrackInfo {

    private MediaPlayer.TrackInfo trackInfo;
    private int index;

    public IndexedTrackInfo(MediaPlayer.TrackInfo trackInfo, int index) {
        this.trackInfo = trackInfo;
        this.index = index;
    }

    public MediaPlayer.TrackInfo getTrackInfo() {
        return trackInfo;
    }

    public int getIndex() {
        return index;
    }
}
</code>```

At the end, what I did was having a Spinner to display the available subtitles to the user and change them according to it's "index".

That depends on your needs, but for showing/hidding/changing the current subtitle track, what you need to do is something like:

```<code>//To show the subtitles:
mediaPlayer.selectTrack(currentSubtitleTrack.getIndex());
//To hide the subtitles:
mediaPlayer.deselectTrack(currentSubtitleTrack.getIndex());
//To change the track (secondSourceSubtitleTrack is the object in the map corresponding to your other subtitle source):
currentSubtitleTrack = secondSourceSubtitleTrack;
mediaPlayer.selectTrack(currentSubtitleTrack.getIndex());
</code>```

I hope this can help someone else... I was strugging with this for a long time... there seems to be not much documentation or examples about this yet...

Title: How to change subtitles in VideoView

Body:
I have multiple languages for subtitles in separate files. I would like to change subtitles when watching a movie. What is the right way to change the subtitles using addSubtitleSource() method in android VideoView?

if (subtitle.equals("Language_1")){ //button "Language_1"
mVideoView.addSubtitleSource(source_1, MediaFormat.createSubtitleFormat("text/vtt", "en"));
}
if (subtitle.equals("Language2")){ //button "Language_2"
mVideoView.addSubtitleSource(source_2, MediaFormat.createSubtitleFormat("text/vtt", "en"));
}

If I stop and start video, then I can switch between subtitles with this code (probably because after restarting the video it has "forgotten" about added sub source). Is there a way to unload one subtitle source and add different subtitle source without reloading the video? I am thinking of a method like removeSubtitleSource() which doesn't exist.

EDIT: Maybe I can use CaptioningManger for this?

Body:
I know is late for your question but maybe the answer can help other people...
I was just working on this recently and needed the same feature of changing displayed subtitles of VideView.

First, add the two subtitles (source_1 and source_2) when you initialize the VideoView.

Then, what you can do is, inside the onPrepared() listener of your VideoView object, you can iterate through the tracks available for the current playing video and, what I did, was save them into a map declared on your class:

The needed reference to the MediaPlayer attached to your videoView, the map for the available subtitle tracks and the current selected subtitle track are private class members declared on my fragment, the one that contains the VideoView:

private MediaPlayer mediaPlayer;
private HashMap<String, IndexedTrackInfo> availableSubtitleTracks = new HashMap();
private IndexedTrackInfo currentSubtitleTrack;

Contents of onPrepared listener

@Override
public void onPrepared(MediaPlayer mp) {
    Log.d(JGA,"onPrepared");
    loadingIndicator.setVisibility(View.GONE);
    videoView.start();
    controllerFragmentListener.notifyPlaying();
    isPlaying=true;

    if(mediaPlayer == null) {
        mediaPlayer = mp;
    }

    MediaPlayer.TrackInfo[] tracks = mp.getTrackInfo();
    Log.d(TAG, "onInfo: MediaPlayer.getTrackInfo()[" + tracks.length + "]");
    MediaPlayer.TrackInfo track;
    IndexedTrackInfo indexedTrackInfo = null;
    for (int i = 0; i < tracks.length; i++) {
        track = tracks[i];
        Log.d(TAG, "onInfo: track received@" + i + ": " + track.getTrackType() + " = " + track.toString());
        if (track.getTrackType() == MediaPlayer.TrackInfo.MEDIA_TRACK_TYPE_SUBTITLE) {
            indexedTrackInfo = new IndexedTrackInfo(track, i);
            if(track.getFormat().containsKey(TRACK_SUBTITLE_IS_DEFAULT_KEY)) {
                Log.d(TAG, "onInfo: Subtitle track has '" + TRACK_SUBTITLE_IS_DEFAULT_KEY + "' with value = " + track.getFormat().getInteger(TRACK_SUBTITLE_IS_DEFAULT_KEY));
                if(track.getFormat().getInteger(TRACK_SUBTITLE_IS_DEFAULT_KEY) == 1) {
                    Log.d(TAG, "onInfo: This track set as default");
                    currentSubtitleTrack = indexedTrackInfo;
                }
            }
            availableSubtitleTracks.put(track.getLanguage(), indexedTrackInfo);
        }
    }
    if(currentSubtitleTrack == null && indexedTrackInfo != null) {
        currentSubtitleTrack = indexedTrackInfo;
        mediaPlayer.selectTrack(currentSubtitleTrack.getIndex());
        Log.d(TAG, "onInfo: There was no default sub track but there are tracks available... picking the last one as default [" + currentSubtitleTrack.getIndex() + "]");
    }
    controllerFragmentListener.updateSpinnerSubtitleTracks(availableSubtitleTracks);
    controllerFragmentListener.updateSpinnerCurrentSelection(currentSubtitleTrack.getTrackInfo().getLanguage());
}

And the custom POJO to asociate each track with its corresponding index in the TrackInfo of the mediaPlayer (IndexedTrackInfo.java):

public class IndexedTrackInfo {

    private MediaPlayer.TrackInfo trackInfo;
    private int index;

    public IndexedTrackInfo(MediaPlayer.TrackInfo trackInfo, int index) {
        this.trackInfo = trackInfo;
        this.index = index;
    }

    public MediaPlayer.TrackInfo getTrackInfo() {
        return trackInfo;
    }

    public int getIndex() {
        return index;
    }
}

At the end, what I did was having a Spinner to display the available subtitles to the user and change them according to it's "index".

That depends on your needs, but for showing/hidding/changing the current subtitle track, what you need to do is something like:

//To show the subtitles:
mediaPlayer.selectTrack(currentSubtitleTrack.getIndex());
//To hide the subtitles:
mediaPlayer.deselectTrack(currentSubtitleTrack.getIndex());
//To change the track (secondSourceSubtitleTrack is the object in the map corresponding to your other subtitle source):
currentSubtitleTrack = secondSourceSubtitleTrack;
mediaPlayer.selectTrack(currentSubtitleTrack.getIndex());

I hope this can help someone else... I was strugging with this for a long time... there seems to be not much documentation or examples about this yet...


问:
Earth movers distance in torch/lua (or how to use a criterion to just obtain a comparison)
I'm trying to calculate the distance between two histograms in torch7, in order to do this I was thinking about using the earth mover's distance. Now I know it's not that hard to do this in python using something like https://github.com/garydoranjr/pyemd however I have my data in torch and need to execute this computation many times. As such moving the entire data between torch7 and python is not an option.

So my question is what is the fastest earth mover distance calculator in torch7? I have searched but could not find anything like a library and was hoping there is some better way to implement this then line by line translation of python code especially seeing as how torch is often better at handling things on the gpu.

Edit I have found this but am not sure how to use it.

I currently have the following code:

```<code>    function ColourCompareHistEMD (imagers)
        sumdistance=0
        k={}
        for i=1,$images do
            k[i]=torch.bhistc(images[i],20,-100,100)
        end

        for i=1,$images do
           for j=1,$images do
                #what to do here?
           end
        end
    end

My current best guess is something like this:

function ColourCompareHistEMD (images)
    sumdistance=0
    r={}
    for i=1,#images do
        print(images[i])

        r[i]=torch.histc(images[i][1]:view(images[i][1]:nElement()),20,-100,100)
    end

    for i=1,#images do
       for j=1,#images do
            criterion = nn.EMDCriterion()
            criterion:forward(r[i],r[j])
            sumdistance=sumdistance+criterion.loss

       end
   end

return sumdistance
end
</code>```

but that doesn't seem to work as criterion.loss isn't working and it gives me an error

```<code>/home/thijser/torch/install/bin/luajit: bad argument #2 to '?' (out of range at /home/thijser/torch/pkg/torch/generic/Tensor.c:704)
stack traceback:
    [C]: at 0x7f2048fdc530
    [C]: in function '__newindex'
    /home/thijser/torch/install/share/lua/5.1/EMDCriterion.lua:52: in function 'preprocess'
    /home/thijser/torch/install/share/lua/5.1/EMDCriterion.lua:255: in function 'forward'
    imageSelector.lua:343: in function 'evalHueImages'
    imageSelector.lua:66: in function 'evaluate'
    imageSelector.lua:81: in function 'SelectTop'
    imageSelector.lua:151: in function 'evolve'
    imageSelector.lua:158: in function <imageSelector.lua:156>
    [C]: in function 'dofile'
    ...jser/torch/install/lib/luarocks/rocks/trepl/scm-1/bin/th:150: in main chunk
    [C]: at 0x5641c3f40470
</code>```

But am not sure how to use it such that in the comment the earth mover distance between image i and j is calculated.

答:
It appears that EMDCriterion expects the input and target to be at least 2-dimensional. It also expects the points in your comparison to be laid out horizontally. Since the result of torch.histc is 1-dimensional, you can reshape it into 2-dimensional row tensor like so:

```<code>for i=1,#images do
    print(images[i])
    local hist = torch.histc(images[i][1]:view(images[i][1]:nElement()),20,-100,100)
    r[i] = hist:reshape(1,hist:nElement())
end
</code>```

Additionally, I tried running the code

```<code>criterion:forward(r[i],r[j])
print(criterion.loss)
</code>```

and the result was nil. Try this instead for accumulating the losses:

```<code>local loss = criterion:forward(r[i],r[j])
sumdistance = sumdistance + loss
</code>```

Also, it'll be a bit more efficient if you define the criterion criterion = nn.EMDCriterion() outside of the nested for-loop.

Body:
I'm trying to calculate the distance between two histograms in torch7, in order to do this I was thinking about using the earth mover's distance. Now I know it's not that hard to do this in python using something like https://github.com/garydoranjr/pyemd however I have my data in torch and need to execute this computation many times. As such moving the entire data between torch7 and python is not an option.

So my question is what is the fastest earth mover distance calculator in torch7? I have searched but could not find anything like a library and was hoping there is some better way to implement this then line by line translation of python code especially seeing as how torch is often better at handling things on the gpu.

Edit I have found this but am not sure how to use it.

I currently have the following code:

    function ColourCompareHistEMD (imagers)
        sumdistance=0
        k={}
        for i=1,$images do
            k[i]=torch.bhistc(images[i],20,-100,100)
        end

        for i=1,$images do
           for j=1,$images do
                #what to do here?
           end
        end
    end

My current best guess is something like this:

function ColourCompareHistEMD (images)
    sumdistance=0
    r={}
    for i=1,#images do
        print(images[i])

        r[i]=torch.histc(images[i][1]:view(images[i][1]:nElement()),20,-100,100)
    end

    for i=1,#images do
       for j=1,#images do
            criterion = nn.EMDCriterion()
            criterion:forward(r[i],r[j])
            sumdistance=sumdistance+criterion.loss

       end
   end

return sumdistance
end

but that doesn't seem to work as criterion.loss isn't working and it gives me an error

/home/thijser/torch/install/bin/luajit: bad argument #2 to '?' (out of range at /home/thijser/torch/pkg/torch/generic/Tensor.c:704)
stack traceback:
    [C]: at 0x7f2048fdc530
    [C]: in function '__newindex'
    /home/thijser/torch/install/share/lua/5.1/EMDCriterion.lua:52: in function 'preprocess'
    /home/thijser/torch/install/share/lua/5.1/EMDCriterion.lua:255: in function 'forward'
    imageSelector.lua:343: in function 'evalHueImages'
    imageSelector.lua:66: in function 'evaluate'
    imageSelector.lua:81: in function 'SelectTop'
    imageSelector.lua:151: in function 'evolve'
    imageSelector.lua:158: in function <imageSelector.lua:156>
    [C]: in function 'dofile'
    ...jser/torch/install/lib/luarocks/rocks/trepl/scm-1/bin/th:150: in main chunk
    [C]: at 0x5641c3f40470

But am not sure how to use it such that in the comment the earth mover distance between image i and j is calculated.

Body:
It appears that EMDCriterion expects the input and target to be at least 2-dimensional. It also expects the points in your comparison to be laid out horizontally. Since the result of torch.histc is 1-dimensional, you can reshape it into 2-dimensional row tensor like so:

for i=1,#images do
    print(images[i])
    local hist = torch.histc(images[i][1]:view(images[i][1]:nElement()),20,-100,100)
    r[i] = hist:reshape(1,hist:nElement())
end

Additionally, I tried running the code

criterion:forward(r[i],r[j])
print(criterion.loss)

and the result was nil. Try this instead for accumulating the losses:

local loss = criterion:forward(r[i],r[j])
sumdistance = sumdistance + loss

Also, it'll be a bit more efficient if you define the criterion criterion = nn.EMDCriterion() outside of the nested for-loop.


问:
duplicated useres detection and deletion from UAAdb
I have experienced an issue that User exists twice with the same user name in the uaa db. Is there any script that does detection of ducplicated users and deletetion?

What is the best way you would suggest for the detection and deletion?

答:
UAA does not allow you add the same user twice.

You can try the following..

$ uaac target

$ uaac token client get admin -s

$ uaac users | grep -i username

$ uaac clients | grep -i username

This will give you the list of UAA users and clients.
Give it a try.


问:
Can I host two separate web servers on a LAN to the outside world through 1 IP address?
I am a web programmer with a home web dev operation. I have multiple web servers in my house on a FIOS connection. I have my own domain pointed to my router through dyndns.org's custom domain service.

My ISP gives me ONE static IP address, which at the moment allows me to configure my router to direct outbound web traffic from one server through port 80 and another server through port 8080. This sucks because many companies block port 8080 these days causing some of my corporate clients to not be able to hit my second web server.

Is there any way for me to direct regular old port 80 web traffic to TWO SEPARATE web servers internally on my network using two separate host names?

For instance. I want http://webserver1.mydomain.com to hit one web server on my network, and http://webserver2.mydomain.com to hit another web server and have both sets of traffic served on port 80.

Is this even possible? If not, can I do a hack by programmatically routing traffic from one web server transparently to another?

For the record I run MS Windows Server 2008 IIS 7.0 stack, a D-link DIR-655 router, and use DynDNS for my domain needs.

答: Why not keep it simple and just order or request a second IP address on your account?  This seems to be a much easier solution than a convoluted hardware and/or software setup.  Just don't tell them you're hosting websites because ISPs generally don't like people to do that on residential accounts (I'm actually surprised they don't block port 80).</p>

OwnerDisplayName: Matias Nino

OwnerDisplayName: Marc Novakowski


问:
Converting Declaractive PrincipalPermission to Programmatic .Demand
I currently have two roles like this:

[PrincipalPermission(SecurityAction.Demand,
  Role="Domain\Admin")]
  [PrincipalPermission(SecurityAction.Demand,
  Role="Domain\AnotherRole")]

The problem is that this inherited code is specific to the domain, and I want to eventually get the roles from the web.config file, so I can work on a VM not in the domain.

I have seen an example like this:

```<code>PrincipalPermission permCheck = new PrincipalPermission(
                                     null,
                                     @"Domain\Admin");
permCheck.Demand();
</code>```

Since this throws an exception if user is not in role, how do I change this example to allow either of the two roles?  I could use multiple IPrincipal.IsInRole() and then throw my own exception, but seems like there is probably a way to use the .Demand method with multiple roles.

Update 12/21: Sample Code based on Union link from Ladislav's answer below:

```<code>PrincipalPermission ppAdmin = new PrincipalPermission(null, @"Domain\Admin");
PrincipalPermission ppAnother = new PrincipalPermission(null, @"Domain\AnotherRole");
(ppAdmin.Union(ppAnother)).Demand();
</code>```

But AzMan (suggested by Ladislav looks like a better but more involved solution).

答: PrincipalPermission has Union method. This method allows you combining several PrincipalPermissions before you call Demand. But instead of using imperative permissions you can check Authorization manager (AzMan) and related role provider (AuthorizationStoreRoleProvider). Authorization manager allows you defining abstract roles in your application and assign real user groups and roles through MMC. </p>

Body:
I currently have two roles like this:

[PrincipalPermission(SecurityAction.Demand,
  Role="Domain\Admin")]
  [PrincipalPermission(SecurityAction.Demand,
  Role="Domain\AnotherRole")]

The problem is that this inherited code is specific to the domain, and I want to eventually get the roles from the web.config file, so I can work on a VM not in the domain.

I have seen an example like this:

PrincipalPermission permCheck = new PrincipalPermission(
                                     null,
                                     @"Domain\Admin");
permCheck.Demand();

Since this throws an exception if user is not in role, how do I change this example to allow either of the two roles?  I could use multiple IPrincipal.IsInRole() and then throw my own exception, but seems like there is probably a way to use the .Demand method with multiple roles.

Update 12/21: Sample Code based on Union link from Ladislav's answer below:

PrincipalPermission ppAdmin = new PrincipalPermission(null, @"Domain\Admin");
PrincipalPermission ppAnother = new PrincipalPermission(null, @"Domain\AnotherRole");
(ppAdmin.Union(ppAnother)).Demand();

But AzMan (suggested by Ladislav looks like a better but more involved solution).


问:
How to organize images within a folder by mtime using python
I'm a beginner at python who has been trying to write a script that moves images, renames them and then organizes them by mtime. At the moment I've achieved the first two steps, but I have no clue how to organize images by time within a folder. So far, I've been able to organize the names of the images by mtime and then print them using this code:

```<code>    import os

    path = os.path.join('C:\\', 'Users', 'Francisco', 'Desktop', 'Archive2')

    def sorted_ls(path):
        mtime = lambda f: os.stat(os.path.join(path, f)).st_mtime
        return list(sorted(os.listdir(path), key=mtime))

    print(sorted_ls(path))
</code>```

However, I want to make it so that the script actually reorganizes the images in 'Archive2' by mtime, not just print out a list of the images already organized. Any help would be very much appreciated, thanks!

答:
If I got it correctly, you want to change the names of files so that when you organize them by name they are organized by mtime as well.

You already achieved in getting them sorted by mtime, only thing that is left to do is to iterate through the list and rename the files.

To do that you can use this code:

```<code>l = sorted_ls(path)
location = 'C:/Users/Francisco/Desktop/Archive2/'
for i in range(len(l)):
    os.rename(location+l[i], location+'file'+str(i).zfill(4))
</code>```

str.fill fills up higher digits with zeros if the number is too small.

Body:
I'm a beginner at python who has been trying to write a script that moves images, renames them and then organizes them by mtime. At the moment I've achieved the first two steps, but I have no clue how to organize images by time within a folder. So far, I've been able to organize the names of the images by mtime and then print them using this code:

    import os

    path = os.path.join('C:\\', 'Users', 'Francisco', 'Desktop', 'Archive2')

    def sorted_ls(path):
        mtime = lambda f: os.stat(os.path.join(path, f)).st_mtime
        return list(sorted(os.listdir(path), key=mtime))

    print(sorted_ls(path))

However, I want to make it so that the script actually reorganizes the images in 'Archive2' by mtime, not just print out a list of the images already organized. Any help would be very much appreciated, thanks!

Body:
If I got it correctly, you want to change the names of files so that when you organize them by name they are organized by mtime as well.

You already achieved in getting them sorted by mtime, only thing that is left to do is to iterate through the list and rename the files.

To do that you can use this code:

l = sorted_ls(path)
location = 'C:/Users/Francisco/Desktop/Archive2/'
for i in range(len(l)):
    os.rename(location+l[i], location+'file'+str(i).zfill(4))

str.fill fills up higher digits with zeros if the number is too small.


问:
How to implement a blocking queue in C++ to process data between threads?
I need to make an app that will have two threads.
One will produce data (file paths and an action to be performed for that path - create/update/delete) and the other thread will need to consume this data and actually perform the tasks.

For this I thought to have a queue and from one thread to put data in it and from the other to take the items and performa the actions sequentially.

My problem is how do I make this data to be shareable between these threads and then how can I make the second thread to block while waiting for data to be put in the queue? Just having a while to check if queue is not empty would eat CPU like crazy for nothing. Adding a "sleep" to check every few milliseconds or seconds would not be efficient.

How can this be done? Any libraries that implement such data?

答:
A couple of examples for you:

Intel TBB concurrent_bounded_queue.

EventQueue with usage example.

Detailed design explanation of building a concurrent queue.

Another concurrent queue, along with benchmark comparisons against TBB and Boost.


问:
Assigning an image to a numpy array makes colors of the image change
I load an image and add it to an empty numpy array:

```<code>plt.imshow(im)
plt.show()
im = imread('/path_to_image',mode = 'RGB')
array = np.zeros((1, 299, 299,3), dtype = np.int8)
array[0][:,:,:3] = im
print(array[0].shape)
print(im.shape)
plt.imshow(array[0])
plt.show()
</code>```

I expect the two images to look the same when displayed. The image seems to change when I assign it to an array with:

```<code>array = np.zeros((1, 299, 299,3), dtype = np.int8)
array[0][:,:,:3] = im
</code>```

答:
im and array should have the same dtype. You can explicitly define the appropriate dtype for the array of zeros (as suggested by @Divakar) or alternatively you can use NumPy's zeros_like  and newaxis as follows:

```<code>import numpy as np
import matplotlib.pyplot as plt
from skimage import io

im = io.imread('https://i.stack.imgur.com/crpfS.png')

array = np.zeros_like(im[np.newaxis, :])
array[0] = im

fig, (ax0, ax1) = plt.subplots(1, 2)
ax0.imshow(im)
ax0.set_title('im')
ax1.imshow(array[0])
ax1.set_title('array[0]')
plt.show()
</code>```

Body:
I load an image and add it to an empty numpy array:

plt.imshow(im)
plt.show()
im = imread('/path_to_image',mode = 'RGB')
array = np.zeros((1, 299, 299,3), dtype = np.int8)
array[0][:,:,:3] = im
print(array[0].shape)
print(im.shape)
plt.imshow(array[0])
plt.show()

I expect the two images to look the same when displayed. The image seems to change when I assign it to an array with:

array = np.zeros((1, 299, 299,3), dtype = np.int8)
array[0][:,:,:3] = im

Body:
im and array should have the same dtype. You can explicitly define the appropriate dtype for the array of zeros (as suggested by @Divakar) or alternatively you can use NumPy's zeros_like  and newaxis as follows:

import numpy as np
import matplotlib.pyplot as plt
from skimage import io

im = io.imread('https://i.stack.imgur.com/crpfS.png')

array = np.zeros_like(im[np.newaxis, :])
array[0] = im

fig, (ax0, ax1) = plt.subplots(1, 2)
ax0.imshow(im)
ax0.set_title('im')
ax1.imshow(array[0])
ax1.set_title('array[0]')
plt.show()


问:
How to get input through a dropdownlist Combobox?
I want to take user input from a ComboBox but don't let the user write anything into the ComboBox, rather he would select from the options given in that ComboBox.
I have tried these 2 lines, but these are not working.

```<code>string var = ComboBox1.SelectedItem.Text;
string var = Convert.ToString(ComboBox1.Text);
</code>```

Any help will be appreciated.

答:
Sounds like you have items in your combobox, and want to get what the user selects. It also looks like you're trying to get the text of the selected value.

To get selected item text:

```<code>string val = ((ComboboxItem)Combobox1.SelectedItem).Text;
</code>```

To get selected index:

```<code>int selectedIndex = Combobox1.SelectedIndex;
</code>```

Notable Problems with your code

SelectedItem does not have a text property. It must be cast to a ComboboxItem.

"var" is a protected keyword. You can't use it as a variable name.

Converting a string to a string is redundant.

Body:
I want to take user input from a ComboBox but don't let the user write anything into the ComboBox, rather he would select from the options given in that ComboBox.
I have tried these 2 lines, but these are not working.

string var = ComboBox1.SelectedItem.Text;
string var = Convert.ToString(ComboBox1.Text);

Any help will be appreciated.

Body:
Sounds like you have items in your combobox, and want to get what the user selects. It also looks like you're trying to get the text of the selected value.

To get selected item text:

string val = ((ComboboxItem)Combobox1.SelectedItem).Text;

To get selected index:

int selectedIndex = Combobox1.SelectedIndex;

Notable Problems with your code

SelectedItem does not have a text property. It must be cast to a ComboboxItem.

"var" is a protected keyword. You can't use it as a variable name.

Converting a string to a string is redundant.


问:
Leak in MiniZip
I'm using MiniZip to unzip a file in an iPhone project. Everything works fine but i get a leak in instruments in the MiniZip code on this line :

unzip.c
line 493

```<code>s=(unz_s*)ALLOC(sizeof(unz_s));
*s=us;
unzGoToFirstFile((unzFile)s);
return (unzFile)s;
</code>```

I understand that the var allocated with ALLOC is returned and not deallocated. In objective-C i would simply do an autorelease, but how can i achieve that in plain C ?

Thanks,
Vincent.

答:
unzOpen() is intended to allocate and return a handle s to the caller. After you got that handle you may operate on this zip-archive (i.e. search for a file, inflate files from archive, ...). After all operations are finished, you have to explicitiely close zip-archive by calling unzClose(s) which de-allocates s for you.

Here is an example to extract a specific file from an archive:

```<code>unzFile hArchive;
unsigned char buffer[1024];
hArchive = unzOpen("abc.zip");
if (hArchive != NULL) {
  if (unzLocateFile(hArchiveFile, "example.txt", 0) == UNZ_OK) {
    if (unzOpenCurrentFile(hArchiveFile) == UNZ_OK) {
      while (unzReadCurrentFile(hArchiveFile,buffer,sizeof(buffer)) > 0) {
        /* write buffer to another file / to stdout / ... */
      }
      unzCloseCurrentFile((unzFile) *hArchiveFile);
    }
  }
}
unzClose(hArchive);
</code>```

see http://www.winimage.com/zLibDll/minizip.html for further information.

Title: Leak in MiniZip

Body:
I'm using MiniZip to unzip a file in an iPhone project. Everything works fine but i get a leak in instruments in the MiniZip code on this line :

unzip.c
line 493

s=(unz_s*)ALLOC(sizeof(unz_s));
*s=us;
unzGoToFirstFile((unzFile)s);
return (unzFile)s;

I understand that the var allocated with ALLOC is returned and not deallocated. In objective-C i would simply do an autorelease, but how can i achieve that in plain C ?

Thanks,
Vincent.

Body:
unzOpen() is intended to allocate and return a handle s to the caller. After you got that handle you may operate on this zip-archive (i.e. search for a file, inflate files from archive, ...). After all operations are finished, you have to explicitiely close zip-archive by calling unzClose(s) which de-allocates s for you.

Here is an example to extract a specific file from an archive:

unzFile hArchive;
unsigned char buffer[1024];
hArchive = unzOpen("abc.zip");
if (hArchive != NULL) {
  if (unzLocateFile(hArchiveFile, "example.txt", 0) == UNZ_OK) {
    if (unzOpenCurrentFile(hArchiveFile) == UNZ_OK) {
      while (unzReadCurrentFile(hArchiveFile,buffer,sizeof(buffer)) > 0) {
        /* write buffer to another file / to stdout / ... */
      }
      unzCloseCurrentFile((unzFile) *hArchiveFile);
    }
  }
}
unzClose(hArchive);

see http://www.winimage.com/zLibDll/minizip.html for further information.


问:
ReactJS - Can I open open a Modal from different component
I am trying to call a model in "model.js" by onClick a button from another component (list.js) , just wonder if I have missed any step please see below:

model.js

```<code>import React from 'react';

class Model extends React.Component{

 render(){
  return(
   <div>
    //code inside the Model etc...
    <Button onClick={this.submit.bind(this)}>Submit</Button>
   </div>
  )
 }
}

export default Model;
</code>```

list.js

```<code>import Model from './model';
class List extends React.Component{
 render(){

  constructor() {
  super();

   this.toggleModal = this.toggleModal.bind(this);
   this.state = {
     open: false
   }
  }

  toggleModal() {
   this.setState({
   open: this.state.open
   });
  }

return(
 <div>
  <Button onClick={this.toggleModal}>Add</Button>
 </div>
 <div>
  <Model open={this.state.open} toggleModal={this.toggleModal}/>
 </div>
  )
 }
}

export default List;
</code>```

I have tried many ways to change the event handler code in List , but it still doesnt work.

That would be much appreciate if you guys could give me a hand and point out where the problems are, so that i can move forward.

答:
Why aren't you changing the state open value to either true or false

```<code>this.setState({
   open: this.state.open
});
</code>```

The above code will always set the value as false. Maybe what you could do is !this.state.open

Body:
I am trying to call a model in "model.js" by onClick a button from another component (list.js) , just wonder if I have missed any step please see below:

model.js

import React from 'react';

class Model extends React.Component{

 render(){
  return(

    //code inside the Model etc...
    <Button onClick={this.submit.bind(this)}>Submit</Button>

  )
 }
}

export default Model;

list.js

import Model from './model';
class List extends React.Component{
 render(){

  constructor() {
  super();

   this.toggleModal = this.toggleModal.bind(this);
   this.state = {
     open: false
   }
  }

  toggleModal() {
   this.setState({
   open: this.state.open
   });
  }

return(

  <Button onClick={this.toggleModal}>Add</Button>

  <Model open={this.state.open} toggleModal={this.toggleModal}/>

  )
 }
}

export default List;

I have tried many ways to change the event handler code in List , but it still doesnt work.

That would be much appreciate if you guys could give me a hand and point out where the problems are, so that i can move forward.

Body:
Why aren't you changing the state open value to either true or false

this.setState({
   open: this.state.open
});

The above code will always set the value as false. Maybe what you could do is !this.state.open


问:
When is it possible to change the subnet group within AWS RDS?
I have one Oracle SE instance that is not multi-az and does not have encryption enabled, and I have an Oracle EE instance that is multi-az and has encryption enabled. The former has the option to change the subnet group through the console (modify instance > network and security), whereas the latter does not. Both instances are in a subnet group within the default vpc, and I have a custom vpc within the same account with another subnet group in it. </p>

<p>What conditions determine whether or not it is possible to change the subnet group of an RDS instance? I have not been able to find any documentation on this so far. </p>

答:
It is the Multi AZ Deployment that is the determining factor. To test this, modify your DB instance and turn off the Multi AZ Deployment. Once it is done, go modify it again and you'll notice you now have the option to change the subnet group.

I haven't found any indication as to the reason for this behavior in the AWS documentation.

Body:
I have one Oracle SE instance that is not multi-az and does not have encryption enabled, and I have an Oracle EE instance that is multi-az and has encryption enabled. The former has the option to change the subnet group through the console (modify instance > network and security), whereas the latter does not. Both instances are in a subnet group within the default vpc, and I have a custom vpc within the same account with another subnet group in it.

What conditions determine whether or not it is possible to change the subnet group of an RDS instance? I have not been able to find any documentation on this so far.


问:
Do not prompt to change password when expired OleDbConnection
```<code>        string connectionString = String.Format("Provider=OraOLEDB.Oracle;OLEDB.NET=true;User ID={0};password={1};Data Source={2}", username, password, database);
        OleDbConnection connection = new OleDbConnection(connectionString);

        connection.Open();
</code>```

<p>When opening the connection if the oracle password is expired it prompts the user to change the password. I just want it to fail and not prompt them for a password. </p>

答:
According to Oracle, you need to add the PwdChgDlg option to your connectionString.

BTW, I searched for "oracle oledb password expire" in my browser.

Body:
        string connectionString = String.Format("Provider=OraOLEDB.Oracle;OLEDB.NET=true;User ID={0};password={1};Data Source={2}", username, password, database);
        OleDbConnection connection = new OleDbConnection(connectionString);

        connection.Open();

When opening the connection if the oracle password is expired it prompts the user to change the password. I just want it to fail and not prompt them for a password.