问:
How to write reusable javascript function with cypress commands
I am new to cypress and testing. I need to get the visible text from an element in cypress also store it inside a variable. with selenium we can easily get element value using getText() method. But in cypress we need to use a code like below.

HTML element:

```<code><div class='myClass'>this is text</div>
</code>```

javascript reusable function

```<code>function getText(byclassName)
    {
     let campaign;
        cy.get(byclassName)
        .invoke('text').then((text) => {
          campaign = text
          cy.log('campaign',  text)
          return text
        })
    }
</code>```

then my cypress test goes like this

```<code> it('finds the role', () => {
   const elementText= getText('.myClass')//fails
    cy.log('campaign',  getText('.myClass'))
 }) // it fails
</code>```

Please tell me what am I missing here? I want to write a generic function which returns me the visible text from div element and also store it or log it in console.

答:
You can also write this as a custom command, which I find to be a bit easier to read and being able to control what's logged to the command log is a bonus.

Here is a custom command I'm using in a bunch of our tests to get text from an element.  It gets text differently than what you are doing - I have found using invoke() pretty finicky, maybe it's the way our app is designed.  If you want to get text using invoke() you can do that as well inside of a custom command.

```<code>Cypress.Commands.add("text", { prevSubject: "element" }, subject => {
  return cy.wrap(subject, { log: false }).then($el => {
    var text = $el.get(0).text();

    Cypress.log({
      name: "text",
      message: "",
      consoleProps() {
        return {
          yielded: text,
        };
      },
    });

    return text;
  });
});

it('finds the role', function () {
    cy.visit(...);

    return cy.get('.myClass').text().then(elementText => {
        cy.log('campaign', elementText);

        expect(elementText).to.equal(...);
    });
})
</code>```

Body:
I am new to cypress and testing. I need to get the visible text from an element in cypress also store it inside a variable. with selenium we can easily get element value using getText() method. But in cypress we need to use a code like below.

HTML element:

this is text

javascript reusable function

function getText(byclassName)
    {
     let campaign;
        cy.get(byclassName)
        .invoke('text').then((text) => {
          campaign = text
          cy.log('campaign',  text)
          return text
        })
    }

then my cypress test goes like this

 it('finds the role', () => {
   const elementText= getText('.myClass')//fails
    cy.log('campaign',  getText('.myClass'))
 }) // it fails

Please tell me what am I missing here? I want to write a generic function which returns me the visible text from div element and also store it or log it in console.

Body:
You can also write this as a custom command, which I find to be a bit easier to read and being able to control what's logged to the command log is a bonus.

Here is a custom command I'm using in a bunch of our tests to get text from an element.  It gets text differently than what you are doing - I have found using invoke() pretty finicky, maybe it's the way our app is designed.  If you want to get text using invoke() you can do that as well inside of a custom command.

Cypress.Commands.add("text", { prevSubject: "element" }, subject => {
  return cy.wrap(subject, { log: false }).then($el => {
    var text = $el.get(0).text();

    Cypress.log({
      name: "text",
      message: "",
      consoleProps() {
        return {
          yielded: text,
        };
      },
    });

    return text;
  });
});

it('finds the role', function () {
    cy.visit(...);

    return cy.get('.myClass').text().then(elementText => {
        cy.log('campaign', elementText);

        expect(elementText).to.equal(...);
    });
})


来源: stackexchange

问:
how to edit xml file in C#
```<code><Family_Inventory>
  <FamilyCategory>Curtain Panels
    <FamilyName>System Panel
        <FamilySymbol>Glazed</FamilySymbol>
        <FamilySymbol>Wall</FamilySymbol>
    </FamilyName>
  </FamilyCategory>

  <FamilyCategory>Curtain Panels
    <FamilyName>Rectangular Mullion
      <FamilySymbol>2.5" x 5" rectangular</FamilySymbol>
    </FamilyName>
  </FamilyCategory>
  ...........
  ...........// many other family categories
  ...........

</Family_Inventory>
</code>```

i want create only one FamilyCategory tag based on its value as above is 'Curtain Panels'
so output will be

```<code><Family_Inventory>
  <FamilyCategory>Curtain Panels
    <FamilyName>System Panel
        <FamilySymbol>Glazed</FamilySymbol>
        <FamilySymbol>Wall</FamilySymbol>
    </FamilyName>

    <FamilyName>Rectangular Mullion
      <FamilySymbol>2.5" x 5" rectangular</FamilySymbol>
    </FamilyName>

  </FamilyCategory>

  ...........
  ...........// many other family categories
  ...........

</Family_Inventory>
</code>```

Please tell me how Can i do this?.

Thanks in Advance
Regards,
Nitin

答:
The first thing that comes to my mind is to use linq to get the whole document... then just create two classes

```<code>class FamilyCategory
{
    string name;
    List<FamilyName> familyNames;
}

class FamilyName
{
    string name;
    List<string> familySymbol;
}
</code>```

after you parse the whole document just sort them by familyCategory.. then you just go through the list. You create a new instance of FamilyCategory and add all the FamilyNames to its list... For each new Cateogry you create a new class... after that you just need to add them all back which is described Here

ContentLicense: CC BY-SA 3.0

Title: how to edit xml file in C#

Body:
<Family_Inventory>
  <FamilyCategory>Curtain Panels
    <FamilyName>System Panel
        <FamilySymbol>Glazed</FamilySymbol>
        <FamilySymbol>Wall</FamilySymbol>
    </FamilyName>
  </FamilyCategory>

  <FamilyCategory>Curtain Panels
    <FamilyName>Rectangular Mullion
      <FamilySymbol>2.5" x 5" rectangular</FamilySymbol>
    </FamilyName>
  </FamilyCategory>
  ...........
  ...........// many other family categories
  ...........

</Family_Inventory>

i want create only one FamilyCategory tag based on its value as above is 'Curtain Panels'
so output will be

<Family_Inventory>
  <FamilyCategory>Curtain Panels
    <FamilyName>System Panel
        <FamilySymbol>Glazed</FamilySymbol>
        <FamilySymbol>Wall</FamilySymbol>
    </FamilyName>

    <FamilyName>Rectangular Mullion
      <FamilySymbol>2.5" x 5" rectangular</FamilySymbol>
    </FamilyName>

  </FamilyCategory>

  ...........
  ...........// many other family categories
  ...........

</Family_Inventory>

Please tell me how Can i do this?.

Thanks in Advance
Regards,
Nitin

Body:
The first thing that comes to my mind is to use linq to get the whole document... then just create two classes

class FamilyCategory
{
    string name;
    List<FamilyName> familyNames;
}

class FamilyName
{
    string name;
    List<string> familySymbol;
}

after you parse the whole document just sort them by familyCategory.. then you just go through the list. You create a new instance of FamilyCategory and add all the FamilyNames to its list... For each new Cateogry you create a new class... after that you just need to add them all back which is described Here


问:
How to subscribe to an Observable that emits in some other part of the code?
I'm sort of a beginner on RxJava. I have the following issue.
I have a Presenter and a Fragment. I'm creating the Presenter inside onCreate of the Fragment.
I want to subscribe to an Observable in the Presenter's constructor. And this Observable should emit when the Fragment's onViewCreated fires (which calls some method in the Presenter - i.e. onViewReady).
The issue I'm running into is that when I create the Observable (in the Presenter's constructor), I also have to pass the emitter then. How can I subscribe to the observable in the constructor and emit later inside onViewReady?

I tried searching bunch of StackOverflow and Medium links. All of them seem to always pass the emitter during Observable creation.

Fragment

```<code>@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    // create presenter
}

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    // call presenter.onViewReady
}
</code>```

Presenter

```<code>Presenter() {
    // create and subscribe to observable
}

public void onViewReady() {
    // emit observable
}
</code>```

答:
Have you considered using a Subject?

Fragment Code:

```<code>public Subject<Integer> subject = PublishSubject.create()

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    presenter = new Presenter(subject);
}

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    subject.onNext(1);
}
</code>```

Presenter Code:

```<code>Presenter(Subject<Integer> subject) {
    subject.doOnNext(i -> onViewReay()).subscribe();
}

public void onViewReady() {
    // code here...
}
</code>```

I hope the syntax is good, as I did this without android studio. also. I would suggest using a disposable to make sure you dispose the subscription on fragment destroy.

and I only tried this in RxJava2. so if you are using RxJava1 some additional adjustments may be needed.

ContentLicense: CC BY-SA 4.0

Body:
I'm sort of a beginner on RxJava. I have the following issue.
I have a Presenter and a Fragment. I'm creating the Presenter inside onCreate of the Fragment.
I want to subscribe to an Observable in the Presenter's constructor. And this Observable should emit when the Fragment's onViewCreated fires (which calls some method in the Presenter - i.e. onViewReady).
The issue I'm running into is that when I create the Observable (in the Presenter's constructor), I also have to pass the emitter then. How can I subscribe to the observable in the constructor and emit later inside onViewReady?

I tried searching bunch of StackOverflow and Medium links. All of them seem to always pass the emitter during Observable creation.

Fragment

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    // create presenter
}

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    // call presenter.onViewReady
}

Presenter

Presenter() {
    // create and subscribe to observable
}

public void onViewReady() {
    // emit observable
}

Body:
Have you considered using a Subject?

Fragment Code:

public Subject<Integer> subject = PublishSubject.create()

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    presenter = new Presenter(subject);
}

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    subject.onNext(1);
}

Presenter Code:

Presenter(Subject<Integer> subject) {
    subject.doOnNext(i -> onViewReay()).subscribe();
}

public void onViewReady() {
    // code here...
}

I hope the syntax is good, as I did this without android studio. also. I would suggest using a disposable to make sure you dispose the subscription on fragment destroy.

and I only tried this in RxJava2. so if you are using RxJava1 some additional adjustments may be needed.


问:
Optimal way of creating object from two objects
I built this, which is working fine, it takes about 7-9 seconds to run and display.
I'm wondering, is there a faster/optimal way of building this custom object?

As you can see, I want all the drivers information from Win32_PNPsigneddriver but to that, I add two other properties from Win32_PNPentity (configmanagererrorcode and status) based on the DeviceID.

This way, the final object contains all drivers and shows if there is an error for the device using that driver.

```<code>$poste = "COMPUTER1234"

$DriversUp = Get-WmiObject -computername $poste Win32_PNPsigneddriver |
             Where-Object {$_.DeviceName -ne $null}
$Devices = Get-WmiObject -computername $poste Win32_PNPentity

$DriversDevices = foreach ($driver in $DriversUp) {
    $driver |
        Select-Object DeviceClass, Manufacturer, DeviceName,
            FriendlyName, DriverName, InfName,
            @{name='Status';expression={$Devices | Where-Object {$_.DeviceID -eq "$($driver.DeviceID)"} | Select-Object -ExpandProperty status}},
            @{name='ConfigManagerErrorCode';expression={$Devices | Where-Object {$_.DeviceID -eq "$($driver.DeviceID)"} | Select-Object -ExpandProperty ConfigManagerErrorCode}},
            @{name='DriverDate';expression={[DateTime]::ParseExact(($_.DriverDate).Split('.')[0], "yyyyMMddHHmmss", [System.Globalization.CultureInfo]::InvariantCulture)}},
            DriverVersion
}

$DriversDevices |
    Sort-Object DeviceClass |
    Out-GridView -Title "$poste - Drivers utilisés"
</code>```

Like I said everything works fine already. However, I'm curious to know if there's a faster way!

答:
Starting in PowerShell 3.0, the Get-WmiObject cmdlet has been superseded by Get-CimInstance.

```<code>$poste = "COMPUTER1234"
$cimses = New-CimSession -ComputerName $poste
$p = & {$args} DeviceClass Manufacturer DeviceName FriendlyName DriverName `
               InfName DriverVersion DeviceID DriverDate
Get-CimInstance -CimSession $cimses -ClassName Win32_PnPSignedDriver `
                -Property $p -Filter 'DeviceName != NULL' |
  ForEach-Object {
    $dev = Get-CimInstance -CimSession $cimses -ClassName Win32_PnPEntity `
                           -Property Status, ConfigManagerErrorCode `
                           -Filter "PNPDeviceID='$($_.DeviceID.Replace('\', '\\'))'"
    [pscustomobject]@{
      DeviceClass = $_.DeviceClass
      Manufacturer = $_.Manufacturer
      DeviceName = $_.DeviceName
      FriendlyName = $_.FriendlyName
      DriverName = $_.DriverName
      InfName = $_.InfName
      Status = $dev.Status
      ConfigManagerErrorCode = $dev.ConfigManagerErrorCode
      DriverDate = '{0:yyyyMMddHHmmss}' -f $_.DriverDate
      DriverVersion = $_.DriverVersion
    }
  } | Sort-Object DeviceClass | Out-GridView -Title "$poste - Drivers utilisés"
Remove-CimSession -CimSession $cimses
</code>```

On my machine, the type of the Win32_PnPSignedDriver.DriverDate member is DateTime.

```<code>Get-CimClass -ClassName Win32_PnPSignedDriver |
  Select-Object -ExpandProperty CimClassProperties |
  Where-Object Name -eq 'DriverDate' |
  Select-Object CimType | Format-Table -AutoSize

 CimType
 -------
DateTime
</code>```

Body:
I built this, which is working fine, it takes about 7-9 seconds to run and display.
I'm wondering, is there a faster/optimal way of building this custom object?

As you can see, I want all the drivers information from Win32_PNPsigneddriver but to that, I add two other properties from Win32_PNPentity (configmanagererrorcode and status) based on the DeviceID.

This way, the final object contains all drivers and shows if there is an error for the device using that driver.

$poste = "COMPUTER1234"

$DriversUp = Get-WmiObject -computername $poste Win32_PNPsigneddriver |
             Where-Object {$_.DeviceName -ne $null}
$Devices = Get-WmiObject -computername $poste Win32_PNPentity

$DriversDevices = foreach ($driver in $DriversUp) {
    $driver |
        Select-Object DeviceClass, Manufacturer, DeviceName,
            FriendlyName, DriverName, InfName,
            @{name='Status';expression={$Devices | Where-Object {$_.DeviceID -eq "$($driver.DeviceID)"} | Select-Object -ExpandProperty status}},
            @{name='ConfigManagerErrorCode';expression={$Devices | Where-Object {$_.DeviceID -eq "$($driver.DeviceID)"} | Select-Object -ExpandProperty ConfigManagerErrorCode}},
            @{name='DriverDate';expression={[DateTime]::ParseExact(($_.DriverDate).Split('.')[0], "yyyyMMddHHmmss", [System.Globalization.CultureInfo]::InvariantCulture)}},
            DriverVersion
}

$DriversDevices |
    Sort-Object DeviceClass |
    Out-GridView -Title "$poste - Drivers utilisés"

Like I said everything works fine already. However, I'm curious to know if there's a faster way!

Body:
Starting in PowerShell 3.0, the Get-WmiObject cmdlet has been superseded by Get-CimInstance.

$poste = "COMPUTER1234"
$cimses = New-CimSession -ComputerName $poste
$p = & {$args} DeviceClass Manufacturer DeviceName FriendlyName DriverName `
               InfName DriverVersion DeviceID DriverDate
Get-CimInstance -CimSession $cimses -ClassName Win32_PnPSignedDriver `
                -Property $p -Filter 'DeviceName != NULL' |
  ForEach-Object {
    $dev = Get-CimInstance -CimSession $cimses -ClassName Win32_PnPEntity `
                           -Property Status, ConfigManagerErrorCode `
                           -Filter "PNPDeviceID='$($_.DeviceID.Replace('\', '\\'))'"
    [pscustomobject]@{
      DeviceClass = $_.DeviceClass
      Manufacturer = $_.Manufacturer
      DeviceName = $_.DeviceName
      FriendlyName = $_.FriendlyName
      DriverName = $_.DriverName
      InfName = $_.InfName
      Status = $dev.Status
      ConfigManagerErrorCode = $dev.ConfigManagerErrorCode
      DriverDate = '{0:yyyyMMddHHmmss}' -f $_.DriverDate
      DriverVersion = $_.DriverVersion
    }
  } | Sort-Object DeviceClass | Out-GridView -Title "$poste - Drivers utilisés"
Remove-CimSession -CimSession $cimses

On my machine, the type of the Win32_PnPSignedDriver.DriverDate member is DateTime.

Get-CimClass -ClassName Win32_PnPSignedDriver |
  Select-Object -ExpandProperty CimClassProperties |
  Where-Object Name -eq 'DriverDate' |
  Select-Object CimType | Format-Table -AutoSize

 CimType
 -------
DateTime


问:
Is there a way of hiding sections of a form with JavaScript?
I am trying to build a Form that is dynamic. I have the form sections built.
In the Header of the form, there is a dropdown option, with five option's that are relevant to five sections of the form. I want to hide all sections until a dropdown option is selected, revealing the relevant section.

I'm trying to do this without Jquery, as I'm trying to grow my javascript skills

```<code>    <label for="issueDescInput">Date of Requests</label>
        <br>
     <input type="date" class="form-control" id="issueSeverityInput">
        <br>

        <label for="TOR">Tasks</label>
         <select class="form-control" id="issueSeverityInput">
          <option value="CO">Task 1</option>
          <option value="ASM">task 2</option>
          <option value="SM">task 3</option>
          <option value="AM">Task 4</option>
          <option value="RC">Task 5</option>
        </select>

       <div class="Tasks-section">
        <div class="Task 1">

      <p>test</p>

       </div>
       </div>

     var select = document.getElementById('TOR'),
     onChange = function(event) {
    var shown = this.options[this.selectedIndex].value == "SM";

    document.getElementById('hidden_div').style.display = shown ? 'block'
  : 'none';
};
</code>```

答:
JavaScript

There a couple of issues with the present JS:

Issue #1

 An on-event property needs to be suffixed to an object by dot notation and must be lowercase. A comma operator just includes the declaration of select and then fails.

```<code>var select = document.getElementById('TOR'),
onChange = function(event) {...
</code>```

 First declare a variable to reference a DOM Object, then use dot notation to bind the on-event property to the variable.

```<code>var select = document.getElementById('TOR');
select.onchange = function(event) {...
</code>```

Issue #2

 I'm assuming that the next line was to assign the value of currently selected option because the next line uses it...sort of...I think. Anyways a == is for comparing two loosely typed values (which means that a string "3" can be duck-typed to a number 3). Assigning only one value out of five possibilities defeats the purpose of using a select.

```<code>var shown = this.options[this.selectedIndex].value == "SM";
</code>```

 A select can be accessed directly to get the value of the currently selected option. The use and reuse of variables is an important and fundamental paradigm in programming. So reuse what you already have. Note a specific value is not assigned ("SM") -- instead the value of whatever will be selected is assigned to shown.

```<code>var shown = select.value;
</code>```

Issue #3

The last line is syntactically correct yet it is wrong in that it belies what the rest of the code will end as. Referencing #id is fine in of itself but having multiple tags that are similar in purpose and design should be grouped. Class and in forms name attributes should be used for groups. document.querySelectorAll() can be used for collecting multiple tags into groups called NodeLists or HTML Collections (slight difference between them). Being that you have a form, the following demo employs a few special Web APIs that specialize in form tags and form controls. Here's a list of references of what was used for the demo, details on what's happening line by line is commented in the demo:

HTMLFormElement API - Accessing <form> tags.

HTMLFormControlsCollection and .elements property - Accessing that <form> tags form controls.

classList property - Manipulate the class attribute.

There are a substantial amount of changes to the OP code (just about everything but basic function.) Of note is that the option values are changed to index numbers in order to facilitate efficiency and flexibility by use of generic values.

Demo

// Reference the form
const main = document.forms.main;
/*
Collect all form controls into a NodeList (input, output,
textarea, select, button, fieldset) nested within form#main.
*/
const x = main.elements;
/*
A - Pass Event Object
B - Get the value of select#TOR (e.target always points to the
    clicked, changed, hovered, etc tag) and convert it into a real
    number.
C - Collect all form controls [name=tasks] into a NodeList
    (x.tasks).
D - Loop through the NodeList and remove .show class from each
    tag of NodeList (fieldset[name=tasks])
E - if the value from line #B is NOT -1...
F - Assign class .show to the fieldset within the NodeList at the
    indexed position of the value from line #B
*/
function menu(e) { //A
  const selected = Number(e.target.value); //B
  const tasks = x.tasks; //C

  for (let t = 0; t < tasks.length; t++) { //D
    tasks[t].classList.remove('show'); //D
  }
  if (selected != -1) { //E
    tasks[selected].classList.add('show'); //F
  }
}

// Register select#TOR to the change event, menu() is the callback
x.TOR.onchange = menu;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>:root {
  font: 700 2.5vw/1.2 Verdana;
}

html,
body {
  width: 100%;
  height: 100%;
}

body {
  overflow-x: hidden;
  overflow-y: scroll;
}

#main {
  width: 100vw;
  height: 100vh;
}

section.task {
  position: relative;
  min-width: 300px;
  height: 100vh;
  margin: 0 auto;
  padding: 5vh 2vw;
}

fieldset.task {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  width: 85%;
  margin: 2vh auto 5vh 1vw;
  visibility: collapse;
  transform: scaleY(0);
  transform-origin: top;
}

fieldset.task.show {
  z-index: 1;
  visibility: visible;
  transform: scaleY(1);
  transition: 0.4s transform ease-out
}

input,
output,
select,
button {
  display: inline-block;
  font: inherit;
  height: 6vh;
  line-height: 6vh;
  vertical-align: middle;
  padding: 0 3px
}

#date0 {
  height: 7vh;
  line-height: 7vh;
  width: 30vw;
}

#TOR {
  height: 8vh;
  line-height: 8vh;
}</code>```

<form id='main'>

    Date of Requests
    <input id="date0" name='date' class="date" type="date">
    Tasks
    <select id="TOR" class="menu">
      <option value='-1' selected>Choose a Task</option>
      <option value="0">Task 1</option>
      <option value="1">Task 2</option>
      <option value="2">Task 3</option>
      <option value="3">Task 4</option>
      <option value="4">Task 5</option>
    </select>

    <fieldset id='CO' name='tasks' class="task show">
      <legend>Task 1</legend>

CO

CO

CO

CO

    </fieldset>
    <fieldset id='ASM' name='tasks' class="task">
      <legend>Task 2</legend>

ASM

ASM

ASM

ASM

ASM

ASM

    </fieldset>
    <fieldset id='SM' name='tasks' class="task">
      <legend>Task 3</legend>

SM

SM

SM

SM

SM

SM

SM

SM

    </fieldset>
    <fieldset id='AM' name='tasks' class="task">
      <legend>Task 4</legend>

AM

AM

AM

AM

    </fieldset>
    <fieldset id='RC' name='tasks' class="task">
      <legend>Task 5</legend>

RC

RC

RC

RC

RC

RC

RC

RC

RC

RC

RC

RC

RC

    </fieldset>

</form>```

Body:
I am trying to build a Form that is dynamic. I have the form sections built.
In the Header of the form, there is a dropdown option, with five option's that are relevant to five sections of the form. I want to hide all sections until a dropdown option is selected, revealing the relevant section.

I'm trying to do this without Jquery, as I'm trying to grow my javascript skills

    Date of Requests

     <input type="date" class="form-control" id="issueSeverityInput">

        Tasks
         <select class="form-control" id="issueSeverityInput">
          <option value="CO">Task 1</option>
          <option value="ASM">task 2</option>
          <option value="SM">task 3</option>
          <option value="AM">Task 4</option>
          <option value="RC">Task 5</option>
        </select>

test

     var select = document.getElementById('TOR'),
     onChange = function(event) {
    var shown = this.options[this.selectedIndex].value == "SM";

    document.getElementById('hidden_div').style.display = shown ? 'block'
  : 'none';
};

Body:
JavaScript

There a couple of issues with the present JS:

Issue #1

 An on-event property needs to be suffixed to an object by dot notation and must be lowercase. A comma operator just includes the declaration of select and then fails.

var select = document.getElementById('TOR'),
onChange = function(event) {...

 First declare a variable to reference a DOM Object, then use dot notation to bind the on-event property to the variable.

var select = document.getElementById('TOR');
select.onchange = function(event) {...

Issue #2

 I'm assuming that the next line was to assign the value of currently selected option because the next line uses it...sort of...I think. Anyways a == is for comparing two loosely typed values (which means that a string "3" can be duck-typed to a number 3). Assigning only one value out of five possibilities defeats the purpose of using a select.

var shown = this.options[this.selectedIndex].value == "SM";

 A select can be accessed directly to get the value of the currently selected option. The use and reuse of variables is an important and fundamental paradigm in programming. So reuse what you already have. Note a specific value is not assigned ("SM") -- instead the value of whatever will be selected is assigned to shown.

var shown = select.value;

Issue #3

The last line is syntactically correct yet it is wrong in that it belies what the rest of the code will end as. Referencing #id is fine in of itself but having multiple tags that are similar in purpose and design should be grouped. Class and in forms name attributes should be used for groups. document.querySelectorAll() can be used for collecting multiple tags into groups called NodeLists or HTML Collections (slight difference between them). Being that you have a form, the following demo employs a few special Web APIs that specialize in form tags and form controls. Here's a list of references of what was used for the demo, details on what's happening line by line is commented in the demo:

HTMLFormElement API - Accessing <form> tags.

HTMLFormControlsCollection and .elements property - Accessing that <form> tags form controls.

classList property - Manipulate the class attribute.

There are a substantial amount of changes to the OP code (just about everything but basic function.) Of note is that the option values are changed to index numbers in order to facilitate efficiency and flexibility by use of generic values.

Demo

// Reference the form
const main = document.forms.main;
/*
Collect all form controls into a NodeList (input, output,
textarea, select, button, fieldset) nested within form#main.
*/
const x = main.elements;
/*
A - Pass Event Object
B - Get the value of select#TOR (e.target always points to the
    clicked, changed, hovered, etc tag) and convert it into a real
    number.
C - Collect all form controls [name=tasks] into a NodeList
    (x.tasks).
D - Loop through the NodeList and remove .show class from each
    tag of NodeList (fieldset[name=tasks])
E - if the value from line #B is NOT -1...
F - Assign class .show to the fieldset within the NodeList at the
    indexed position of the value from line #B
*/
function menu(e) { //A
  const selected = Number(e.target.value); //B
  const tasks = x.tasks; //C

  for (let t = 0; t < tasks.length; t++) { //D
    tasks[t].classList.remove('show'); //D
  }
  if (selected != -1) { //E
    tasks[selected].classList.add('show'); //F
  }
}

// Register select#TOR to the change event, menu() is the callback
x.TOR.onchange = menu;

:root {
  font: 700 2.5vw/1.2 Verdana;
}

html,
body {
  width: 100%;
  height: 100%;
}

body {
  overflow-x: hidden;
  overflow-y: scroll;
}

#main {
  width: 100vw;
  height: 100vh;
}

section.task {
  position: relative;
  min-width: 300px;
  height: 100vh;
  margin: 0 auto;
  padding: 5vh 2vw;
}

fieldset.task {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  width: 85%;
  margin: 2vh auto 5vh 1vw;
  visibility: collapse;
  transform: scaleY(0);
  transform-origin: top;
}

fieldset.task.show {
  z-index: 1;
  visibility: visible;
  transform: scaleY(1);
  transition: 0.4s transform ease-out
}

input,
output,
select,
button {
  display: inline-block;
  font: inherit;
  height: 6vh;
  line-height: 6vh;
  vertical-align: middle;
  padding: 0 3px
}

#date0 {
  height: 7vh;
  line-height: 7vh;
  width: 30vw;
}

#TOR {
  height: 8vh;
  line-height: 8vh;
}

<form id='main'>
  <header class='menu'>
    <label for="date0">Date of Requests</label>
    <input id="date0" name='date' class="date" type="date">
    <label for="TOR">Tasks</label>
    <select id="TOR" class="menu">
      <option value='-1' selected>Choose a Task</option>
      <option value="0">Task 1</option>
      <option value="1">Task 2</option>
      <option value="2">Task 3</option>
      <option value="3">Task 4</option>
      <option value="4">Task 5</option>
    </select>
  </header>
  <section class='task'>
    <fieldset id='CO' name='tasks' class="task show">
      <legend>Task 1</legend>
      <p>CO</p>
      <p>CO</p>
      <p>CO</p>
      <p>CO</p>
    </fieldset>
    <fieldset id='ASM' name='tasks' class="task">
      <legend>Task 2</legend>
      <p>ASM</p>
      <p>ASM</p>
      <p>ASM</p>
      <p>ASM</p>
      <p>ASM</p>
      <p>ASM</p>
    </fieldset>
    <fieldset id='SM' name='tasks' class="task">
      <legend>Task 3</legend>
      <p>SM</p>
      <p>SM</p>
      <p>SM</p>
      <p>SM</p>
      <p>SM</p>
      <p>SM</p>
      <p>SM</p>
      <p>SM</p>
    </fieldset>
    <fieldset id='AM' name='tasks' class="task">
      <legend>Task 4</legend>
      <p>AM</p>
      <p>AM</p>
      <p>AM</p>
      <p>AM</p>
    </fieldset>
    <fieldset id='RC' name='tasks' class="task">
      <legend>Task 5</legend>
      <p>RC</p>
      <p>RC</p>
      <p>RC</p>
      <p>RC</p>
      <p>RC</p>
      <p>RC</p>
      <p>RC</p>
      <p>RC</p>
      <p>RC</p>
      <p>RC</p>
      <p>RC</p>
      <p>RC</p>
      <p>RC</p>
    </fieldset>
  </section>
</form>


问:
Consuming a REST Service with SAS
This is sort of an odd question.  I know that SAS has a PROC SOAP for consuming web services.  I wonder if anyone has any experience consuming XML from a REST resource using SAS?</p>

答:
I haven't had specific experience with REST APIs from SAS, but I've worked with similar web-based services.

You can use the filename url engine to access arbitrary URLs and read the results back.  YMMV as far as compatibility with particular REST APIs and XML output goes.

Alternatively, you could use system calls to programs like wget or curl to download the XML into a file, then parse the input using SAS' xml engine.

ContentLicense: CC BY-SA 2.5

Title: Consuming a REST Service with SAS

OwnerDisplayName: Rog


问:
Multiple Upload tool, script or plugin?

I'm trying to make an upload function in this website I'm working on, but till now no succes.

I tried using Plupload, but can't get it to work. Same goes for Uploadify, can't find any tutorial or good explanation in how to install these plugins in your webpage.

Does anybody know a good and easy to use multiple upload tool I can easily implement in the page?

Thanks in advance!

答: Try https://github.com/valums/file-uploader, has a nice readme, and supports drag and drop in some browsers.</p>

Title: Multiple Upload tool, script or plugin?


问:
Binary Classification Model Inaccurate
I'm doing Binary Classification in the form of a XOR gate using ML.NET and SdcaLogisticRegression.

The problem I have is that the model outputs inaccurate predictions for the inputs I give it. For example it predicts a value of 0 with probability 0.459 for inputs 0.8 and 0.2.

Could you please look if my code or algorithm are not suitable for making a XOR Gate?

I trained the model with various amounts of training data and received similar results every time (between 200 and 1M rows in the training data file).

```<code>IDataView trainingData = context.Data.LoadFromTextFile<XorInput>(trainDataFile, separatorChar: ',', hasHeader: true);

IDataView testData = context.Data.LoadFromTextFile<XorInput>(testDataFile, separatorChar: ',', hasHeader: true);

var trainingPipeline = context.Transforms.Concatenate("Features", "Inputs").Append(context.BinaryClassification.Trainers.SdcaLogisticRegression(labelColumnName: "Label", featureColumnName: "Features"));

ITransformer trainedModel = trainingPipeline.Fit(trainingData);

XorInput sampleInput = new XorInput { Inputs = new float[] {0.8f, 0.2f } };

var predEngine = context.Model.CreatePredictionEngine<XorInput, XorOutputPrediction>(trainedModel);

var resultprediction = predEngine.Predict(sampleInput);

Console.WriteLine($"=============== Single Prediction  ===============");
Console.WriteLine($"Inputs: {sampleInput.Inputs[0]}, {sampleInput.Inputs[1]}  | Prediction: {(Convert.ToInt16(resultprediction.Prediction))} | Probability: {resultprediction.Probability} ");
Console.WriteLine($"==================================================");
</code>```

Just for reference, my classes XorInput and XorOutputPrediction look like this:

```<code>public class XorInput
    {
        [LoadColumn(0), ColumnName("Label")]
        public bool Label;

        [LoadColumn(1,2)]
        [VectorType(2)]
        //[ColumnName("Features")]
        public float[] Inputs;
    }

    public class XorOutputPrediction
    {
        [ColumnName("PredictedLabel")]
        public bool Prediction { get; set; }

        public float Probability { get; set; }

        public float Score { get; set; }
    }
</code>```

The data contained in trainDataFile and testDataFile looks like this:

```<code>0,  0.9173474,  0.8329648
0,  0.4942033,  0.1281894
0,  0.4558121,  0.1869916
1,  0.738331,   0.4427712
0,  0.8739759,  0.5859472
1,  0.7447554,  0.1089314
1,  0.2433814,  0.6192696
</code>```

For input values of 0.8 and 0.2 I expect an output prediction of 1.

答: I switched the training algorithm to Fast Forest and got the accuracy up to 99.97% with correct outputs.</p>

Title: Binary Classification Model Inaccurate

Body:
I'm doing Binary Classification in the form of a XOR gate using ML.NET and SdcaLogisticRegression.

The problem I have is that the model outputs inaccurate predictions for the inputs I give it. For example it predicts a value of 0 with probability 0.459 for inputs 0.8 and 0.2.

Could you please look if my code or algorithm are not suitable for making a XOR Gate?

I trained the model with various amounts of training data and received similar results every time (between 200 and 1M rows in the training data file).

IDataView trainingData = context.Data.LoadFromTextFile<XorInput>(trainDataFile, separatorChar: ',', hasHeader: true);

IDataView testData = context.Data.LoadFromTextFile<XorInput>(testDataFile, separatorChar: ',', hasHeader: true);

var trainingPipeline = context.Transforms.Concatenate("Features", "Inputs").Append(context.BinaryClassification.Trainers.SdcaLogisticRegression(labelColumnName: "Label", featureColumnName: "Features"));

ITransformer trainedModel = trainingPipeline.Fit(trainingData);

XorInput sampleInput = new XorInput { Inputs = new float[] {0.8f, 0.2f } };

var predEngine = context.Model.CreatePredictionEngine<XorInput, XorOutputPrediction>(trainedModel);

var resultprediction = predEngine.Predict(sampleInput);

Console.WriteLine($"=============== Single Prediction  ===============");
Console.WriteLine($"Inputs: {sampleInput.Inputs[0]}, {sampleInput.Inputs[1]}  | Prediction: {(Convert.ToInt16(resultprediction.Prediction))} | Probability: {resultprediction.Probability} ");
Console.WriteLine($"==================================================");

Just for reference, my classes XorInput and XorOutputPrediction look like this:

public class XorInput
    {
        [LoadColumn(0), ColumnName("Label")]
        public bool Label;

        [LoadColumn(1,2)]
        [VectorType(2)]
        //[ColumnName("Features")]
        public float[] Inputs;
    }

    public class XorOutputPrediction
    {
        [ColumnName("PredictedLabel")]
        public bool Prediction { get; set; }

        public float Probability { get; set; }

        public float Score { get; set; }
    }

The data contained in trainDataFile and testDataFile looks like this:

0,  0.9173474,  0.8329648
0,  0.4942033,  0.1281894
0,  0.4558121,  0.1869916
1,  0.738331,   0.4427712
0,  0.8739759,  0.5859472
1,  0.7447554,  0.1089314
1,  0.2433814,  0.6192696

For input values of 0.8 and 0.2 I expect an output prediction of 1.


问:
Is it possile to cast two different class but having the same attributes?
I have two classes. ClassA and CLassB, they don't have any relation but they both have the same attributes. Is it possible to cast them or I have to set the attributes one by one?</p>

答:
Use Json serialization/deserialization, e.g. with Gson,

    import com.google.gson.Gson;

    static Gson gson = new Gson();

    Class2 transform (final Class1 original) {
        return gson.fromJson(gson.toJson(original), Class2.class);
    }
```

This also works recursively.

Body:
Use Json serialization/deserialization, e.g. with Gson,

    import com.google.gson.Gson;

    static Gson gson = new Gson();

    Class2 transform (final Class1 original) {
        return gson.fromJson(gson.toJson(original), Class2.class);
    }

This also works recursively.


问:
Broken tab navigation in popup with WPF user control hosted inside Winforms in default AppDomain
I have a WPF user control that uses a Popup. This control is a plugin and can be loaded in the main AppDomain or in a separate AppDomain, and it is hosted in a Winforms form using ElementHost. When the plugin is loaded in the main AppDomain, and the popup is opened, tabbing between the fields of the popup instead moves focus to the first control of the popup windows parent. When it is loaded in a new AppDomain, the tab behavior works as expected/desired (it cycles through the controls in the popup window).

I have read through many similar, but not quite the same, questions here on SO and elsewhere, but none of the suggestions have helped.

It appears that the tab message is getting handled in the AddInHost (which comes from my use of FrameworkElementAdapters to marshal the WPF control across domain boundaries in out-of-domain case). My ultimate goal is to implement this as a Managed Add-in Framework addin, but I have pared that WAY down to simplify the repro.

In case it helps to have a more complete context, I have a git repo of the simplified repro

What can I do to make this behavior consistent?

WpfUserControl.xaml

```<code><UserControl x:Class="MyPlugin.WpfUserControl"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         mc:Ignorable="d" Background="White">
    <Grid Margin="5">
        <Grid.RowDefinitions>
            <RowDefinition Height="28" />
            <RowDefinition Height="28" />
            <RowDefinition Height="28" />
        </Grid.RowDefinitions>

        <TextBox Grid.Row="0" Margin="3" />

        <Button x:Name="DropDownButton" Grid.Row="1" Margin="3" HorizontalAlignment="Left" MinWidth="100" Content="Drop Down" Click="DropDownButton_OnClick" />
        <Popup Grid.Row="1" x:Name="Popup1" Placement="Right" StaysOpen="True" PlacementTarget="{Binding ElementName=DropDownButton}">
            <Border BorderBrush="Black" BorderThickness="1">
                <Grid Background="White">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition />
                        <ColumnDefinition />
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition />
                        <RowDefinition />
                        <RowDefinition />
                    </Grid.RowDefinitions>

                    <Label Content="Username:" Grid.Row="0" Grid.Column="0" Margin="3" />
                    <TextBox Grid.Row="0" Grid.Column="1" Margin="3" MinWidth="150" />

                    <Label Content="Password:" Grid.Row="1" Grid.Column="0" Margin="3" />
                    <TextBox Grid.Row="1" Grid.Column="1" Margin="3" MinWidth="150" />

                    <Button x:Name="SaveButton" Grid.Row="2" Grid.Column="1" Margin="3" HorizontalAlignment="Right"
                                            Content="Save" Click="SaveButton_OnClick" />
                </Grid>
            </Border>
        </Popup>

        <Button x:Name="DoSomethingButton" Grid.Row="2" Margin="3" HorizontalAlignment="Left" MinWidth="100" Content="Do Something" />
    </Grid>
</UserControl>
</code>```

Plugin.cs

public class Plugin : MarshalByRefObject
{
    public INativeHandleContract CreateWpfUserControl()
    {
        return FrameworkElementAdapters.ViewToContractAdapter(new WpfUserControl());
    }
}
```

<p><strong>MainForm.cs (selected bits)</strong></p>

<pre class="lang-cs prettyprint-override"><code>private void LoadPlugin(bool loadInSameAppDomain)
{
    AppDomain appDomain;
    if (loadInSameAppDomain)
    {
        appDomain = AppDomain.CurrentDomain;
    }
    else
    {
        var appDomainName = Guid.NewGuid().ToString();
        _appDomain = AppDomain.CreateDomain(appDomainName, AppDomain.CurrentDomain.Evidence, new AppDomainSetup
        {
            ApplicationName = appDomainName,
            ApplicationBase = AppDomain.CurrentDomain.BaseDirectory,
            PrivateBinPath = AppDomain.CurrentDomain.BaseDirectory
        });
        appDomain = _appDomain;
    }

    _plugin = (Plugin)appDomain.CreateInstanceAndUnwrap("MyPlugin", "MyPlugin.Plugin");
}

private void loadPluginButton_Click(object sender, EventArgs e)
{
    LoadPlugin(appDomainCheckBox.Checked);

    var pluginControl = FrameworkElementAdapters.ContractToViewAdapter(_plugin.CreateWpfUserControl());
    elementHost1.Child = pluginControl;

    UpdateUi(true);
}
</code>```

答: My somewhat educated, though by no means authoritative, guess is that the issue is that WinForms and WPF expect to have exclusive access to the top window's message pump. Running each in its own AppDomain gives each exclusive control of a parent window and its message pump.</p>

Body:
I have a WPF user control that uses a Popup. This control is a plugin and can be loaded in the main AppDomain or in a separate AppDomain, and it is hosted in a Winforms form using ElementHost. When the plugin is loaded in the main AppDomain, and the popup is opened, tabbing between the fields of the popup instead moves focus to the first control of the popup windows parent. When it is loaded in a new AppDomain, the tab behavior works as expected/desired (it cycles through the controls in the popup window).

I have read through many similar, but not quite the same, questions here on SO and elsewhere, but none of the suggestions have helped.

It appears that the tab message is getting handled in the AddInHost (which comes from my use of FrameworkElementAdapters to marshal the WPF control across domain boundaries in out-of-domain case). My ultimate goal is to implement this as a Managed Add-in Framework addin, but I have pared that WAY down to simplify the repro.

In case it helps to have a more complete context, I have a git repo of the simplified repro

What can I do to make this behavior consistent?

WpfUserControl.xaml

<UserControl x:Class="MyPlugin.WpfUserControl"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         mc:Ignorable="d" Background="White">
    <Grid Margin="5">
        <Grid.RowDefinitions>
            <RowDefinition Height="28" />
            <RowDefinition Height="28" />
            <RowDefinition Height="28" />
        </Grid.RowDefinitions>

        <TextBox Grid.Row="0" Margin="3" />

        <Button x:Name="DropDownButton" Grid.Row="1" Margin="3" HorizontalAlignment="Left" MinWidth="100" Content="Drop Down" Click="DropDownButton_OnClick" />
        <Popup Grid.Row="1" x:Name="Popup1" Placement="Right" StaysOpen="True" PlacementTarget="{Binding ElementName=DropDownButton}">
            <Border BorderBrush="Black" BorderThickness="1">
                <Grid Background="White">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition />
                        <ColumnDefinition />
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition />
                        <RowDefinition />
                        <RowDefinition />
                    </Grid.RowDefinitions>

                    <TextBox Grid.Row="0" Grid.Column="1" Margin="3" MinWidth="150" />

                    <TextBox Grid.Row="1" Grid.Column="1" Margin="3" MinWidth="150" />

                    <Button x:Name="SaveButton" Grid.Row="2" Grid.Column="1" Margin="3" HorizontalAlignment="Right"
                                            Content="Save" Click="SaveButton_OnClick" />
                </Grid>
            </Border>
        </Popup>

        <Button x:Name="DoSomethingButton" Grid.Row="2" Margin="3" HorizontalAlignment="Left" MinWidth="100" Content="Do Something" />
    </Grid>
</UserControl>

Plugin.cs

public class Plugin : MarshalByRefObject
{
    public INativeHandleContract CreateWpfUserControl()
    {
        return FrameworkElementAdapters.ViewToContractAdapter(new WpfUserControl());
    }
}

MainForm.cs (selected bits)

private void LoadPlugin(bool loadInSameAppDomain)
{
    AppDomain appDomain;
    if (loadInSameAppDomain)
    {
        appDomain = AppDomain.CurrentDomain;
    }
    else
    {
        var appDomainName = Guid.NewGuid().ToString();
        _appDomain = AppDomain.CreateDomain(appDomainName, AppDomain.CurrentDomain.Evidence, new AppDomainSetup
        {
            ApplicationName = appDomainName,
            ApplicationBase = AppDomain.CurrentDomain.BaseDirectory,
            PrivateBinPath = AppDomain.CurrentDomain.BaseDirectory
        });
        appDomain = _appDomain;
    }

    _plugin = (Plugin)appDomain.CreateInstanceAndUnwrap("MyPlugin", "MyPlugin.Plugin");
}

private void loadPluginButton_Click(object sender, EventArgs e)
{
    LoadPlugin(appDomainCheckBox.Checked);

    var pluginControl = FrameworkElementAdapters.ContractToViewAdapter(_plugin.CreateWpfUserControl());
    elementHost1.Child = pluginControl;

    UpdateUi(true);
}


问:
How to fix error of saving file Laravel using File facade?
I get the following error:

```<code>{"errors":"Method Illuminate\\Filesystem\\Filesystem::create does not exist."}
</code>```

Imports are:

```<code>use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;
</code>```

Code is:

```<code>$created = File::create(["path" => $path.$filename]);
</code>```

答:
If you will look to an official laravel API, there is no such method ::create on File facade.

https://laravel.com/api/5.8/Illuminate/Filesystem/Filesystem.html

What are you trying to achieve ?

If you want to create a new file use ::put method:

```<code>int|bool put(string $path, string $contents, bool $lock = false)
</code>```

look at API link that I've provided. Or check official docs

Body:
I get the following error:

{"errors":"Method Illuminate\\Filesystem\\Filesystem::create does not exist."}

Imports are:

use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;

Code is:

$created = File::create(["path" => $path.$filename]);

Body:
If you will look to an official laravel API, there is no such method ::create on File facade.

https://laravel.com/api/5.8/Illuminate/Filesystem/Filesystem.html

What are you trying to achieve ?

If you want to create a new file use ::put method:

int|bool put(string $path, string $contents, bool $lock = false)

look at API link that I've provided. Or check official docs


问:
Can't figure out data binding in Kotlin
Recently I started developing apps in Android studio via Kotlin, because Java seemed a bit harder. I built my first app and now, for the second, I wanna try out data binding. I follow a Udacity tutorial and there it says that I have to include dataBinding{ enabled=True } which I did.

The problem is that when I try to import com.android.AppName.databinding.ActivityMainBinding
the name is red, even though I declared the variable below, in the onCreate
Everything related to data binding is red pretty much.

I can't figure out what's the problem. Any suggestion would help. Thanks!

答:
You have to use kapt if you're using it with kotlin:</p>

```<code>apply plugin: 'kotlin-kapt'

android {
   ...
   dataBinding {
       enabled true
   }
}

dependencies {
   ...
   kapt 'com.android.databinding:compiler:3.1.3'
}
</code>```

Title: Can't figure out data binding in Kotlin

Body:
You have to use kapt if you're using it with kotlin:

apply plugin: 'kotlin-kapt'

android {
   ...
   dataBinding {
       enabled true
   }
}

dependencies {
   ...
   kapt 'com.android.databinding:compiler:3.1.3'
}


问:
How can I create a command line tool to do this from this code
Suppose the code is stored as '__main__.py' under my project's root. And I want to be able to run the code at command line as:

```<code> processor [arg1 arg2 ...]
</code>```

When I tried to run it at command line:

```<code>processor
</code>```

it shows:

```<code>bash: processor: command not found
</code>```

How to make this code to be runnable with the command 'processor ...'? I saw some similar others' code, but can't get it to work.

```<code>def create_argument_parser() -> argparse.ArgumentParser:
        """Parse all the command line arguments."""

        parser = argparse.ArgumentParser(
            prog="processor",
            formatter_class=argparse.ArgumentDefaultsHelpFormatter,
            description="Some helpful info...",
        )

        parser.add_argument(
            "--version",
            action="store_true",
            default=argparse.SUPPRESS,
            help="Print installed version",
        )

        ...

        return parser

    def main() -> None:

        arg_parser = create_argument_parser()
        cmdline_arguments = arg_parser.parse_args()

    if __name__ == "__main__":
        main()
</code>```

答:
Either:

Create an alias in your ~/.bashrc file:
    alias process='python /path/to/the/script'

Or

Add the project to the $PATH variable (again in the ~/.bashrc file)
export PATH=$PATH:/path/to/the/script/parent/directory

And change permissions to allow the script to be run
chmod +x script

Add #!/bin/python to the top of the script

Then you can call the script by just typing the name of the script, in your case __init__.py

Body:
Suppose the code is stored as '__main__.py' under my project's root. And I want to be able to run the code at command line as:

 processor [arg1 arg2 ...]

When I tried to run it at command line:

processor

it shows:

bash: processor: command not found

How to make this code to be runnable with the command 'processor ...'? I saw some similar others' code, but can't get it to work.

def create_argument_parser() -> argparse.ArgumentParser:
        """Parse all the command line arguments."""

        parser = argparse.ArgumentParser(
            prog="processor",
            formatter_class=argparse.ArgumentDefaultsHelpFormatter,
            description="Some helpful info...",
        )

        parser.add_argument(
            "--version",
            action="store_true",
            default=argparse.SUPPRESS,
            help="Print installed version",
        )

        ...

        return parser

    def main() -> None:

        arg_parser = create_argument_parser()
        cmdline_arguments = arg_parser.parse_args()

    if __name__ == "__main__":
        main()


问:
iPhone login screen problem
I have a large application. It has a lot of tables and navigation between them. I started a project as a 'NavigationBasedProject' (xcode template). But now I need to add login at the start of the application. So here what I did so far:
In 'didFinishLaunchingWithOptions' I added:

```<code>loginViewController = [[LoginViewController alloc]init];
        [loginViewController.view setFrame:CGRectMake(0, 0, 320, 480)];
        [self.window.rootViewController presentModalViewController:loginViewController animated:NO];
</code>```

When user data are valid I dismiss login screen like this:

```<code>[self.loginViewController dismissModalViewControllerAnimated:YES];
</code>```

User can also logout from application. And then I present login screen again like this:

```<code>[self.window.rootViewController presentModalViewController:loginViewController animated:NO];
</code>```

And this works. But text fields on login screen are still filled with data that user enter to login. And I am afraid that I have some memory issue here. How to remove login screen completely from memory when user logs in. I don't use GUI designer I connect everything from code.
Also I wonder is it good idea to make login screen and modal view?

答:
Did u release loginViewcontroller after presenting.</p>

```<code>loginViewController = [[LoginViewController alloc]init];
        [loginViewController.view setFrame:CGRectMake(0, 0, 320, 480)];
        [self.window.rootViewController presentModalViewController:loginViewController animated:NO];
[loginViewController release];
</code>```

Title: iPhone login screen problem

Body:
I have a large application. It has a lot of tables and navigation between them. I started a project as a 'NavigationBasedProject' (xcode template). But now I need to add login at the start of the application. So here what I did so far:
In 'didFinishLaunchingWithOptions' I added:

loginViewController = [[LoginViewController alloc]init];
        [loginViewController.view setFrame:CGRectMake(0, 0, 320, 480)];
        [self.window.rootViewController presentModalViewController:loginViewController animated:NO];

When user data are valid I dismiss login screen like this:

[self.loginViewController dismissModalViewControllerAnimated:YES];

User can also logout from application. And then I present login screen again like this:

[self.window.rootViewController presentModalViewController:loginViewController animated:NO];

And this works. But text fields on login screen are still filled with data that user enter to login. And I am afraid that I have some memory issue here. How to remove login screen completely from memory when user logs in. I don't use GUI designer I connect everything from code.
Also I wonder is it good idea to make login screen and modal view?

Body:
Did u release loginViewcontroller after presenting.

loginViewController = [[LoginViewController alloc]init];
        [loginViewController.view setFrame:CGRectMake(0, 0, 320, 480)];
        [self.window.rootViewController presentModalViewController:loginViewController animated:NO];
[loginViewController release];


问:
How does PSP (Rocket Software product) improves performance of Mainframe job
Performance Essential (PSP, Rocket Software offering) reduces the CPU time, I/O for a COBOL program program. How can we do it manually without using their product to calculate optimal balance between memory and speed for Cobol program?

One of the Cobol program is running longer (35 min). When, I increased the CI size from 4096 to 8192 for one of the VSAM file, then noticed significant improvement in CPU time from 35 minutes to 36 seconds.

Also, after enabling PSP, the CPU time gets reduced to 41 seconds. I found on their documentation that PSP reduced the I/O and enhances buffering to achieve that. Does that means, is PSP modifying the CI size for all VSAM files and block size for Non VSAM? Also, how the buffer space requirement is being calculated for a Cobol program? What are the different ways to calculate the buffer space (total space taken by a program) taken by a Cobol program?

Earlier:

```<code>CISZ ( 4096)
</code>```

After:

```<code>CISZ ( 8192 )
</code>```

答:
According to their website the product Rocket Performance Essentials

Rocket Performance Essential Systems automatically adjusts the buffers
  to allow more I/O to flow at a given time without rewriting
  applications or JCL. This reduces the number of I/O dramatically while
  increasing and freeing system resource to provide maximum utilization

The net is that larger buffer sizes require less system overhead as you are reading and writing larger blocks of data with reduced I/O overhead.  Also, you are waiting less for I/O wait time so your elapsed time is reduced as well.

For details on all the methods Performance Essentials administers I’d look further into their technical documentation on their website.

You can achieve the same performance but you will need to continuously keep up.  The advantage of a tool like this is it optimizes automagically for you.

Body:
Performance Essential (PSP, Rocket Software offering) reduces the CPU time, I/O for a COBOL program program. How can we do it manually without using their product to calculate optimal balance between memory and speed for Cobol program?

One of the Cobol program is running longer (35 min). When, I increased the CI size from 4096 to 8192 for one of the VSAM file, then noticed significant improvement in CPU time from 35 minutes to 36 seconds.

Also, after enabling PSP, the CPU time gets reduced to 41 seconds. I found on their documentation that PSP reduced the I/O and enhances buffering to achieve that. Does that means, is PSP modifying the CI size for all VSAM files and block size for Non VSAM? Also, how the buffer space requirement is being calculated for a Cobol program? What are the different ways to calculate the buffer space (total space taken by a program) taken by a Cobol program?

Earlier:

CISZ ( 4096)

After:

CISZ ( 8192 )


问:
Higher-order function composition notation
I'm working with this higher-order compose function:

```<code>fun <T, U, V> higherCompose(): ((U) -> V) -> ((T) -> U) -> (T) -> V =
    { f ->
        { g ->
            { x -> f(g(x)) }
        }
    }
</code>```

And the application:

```<code> val cos = higherCompose<Double, Double, Double>()()
{ x: Double -> Math.sin(x)}() { x : Double -> Math.PI/2  - x }
</code>```

I do understand what we're trying to achieve here mathematically. But what I'm struggling with is notation and the programming meaning:

What exactly is

```<code>higherCompose<Double>()
</code>```

And why do we apply so strangely values to it:

```<code>1. () ()
2. { function1} { function 1}
</code>```

答:
Here's how this notation is parsed and what the function calls are:

```<code>higherCompose<Double, Double, Double>()() { x -> Math.sin(x) }() { x -> Math.PI/2  - x }
|                                    ^| ^ ^^^^^^^^^^^^^^^^^^^| ^ ^^^^^^^^^^^^^^^^^^^^^^|
|                                    1| 2          3         | 4           5           |
|_____________________________________|______________________|_________________________|
| first call                          | second call          | third call              |
</code>```

This is the initial no-argument call to higherCompose that returns a value of exactly the higherCompose's return type, ((U) -> V) -> ((T) -> U) -> (T) -> V, with the three type parameters substituted with Double.

These parentheses are simply used to resolve parsing ambiguity. Kotlin allows calling a function with a lambda in either of the forms: f({ }), f() { }, f { }. If you remove the parentheses, the lambda marked as (3) will be treated as an argument to the first call. One way to solve this ambiguity is to add () to tell the compiler that it's the (1)'s return value that is invoked and not higherCompose

Therefore, this lambda is passed as the ((U) -> V) argument to the higherCompose's result type, producing ((T) -> U) -> (T) -> V.

These parentheses are added because Kotlin does not allow calling a return value of a call with a lambda outside parentheses (f() { }) directly with another lambda: f() { } { } is prohibited, but adding another pair of parentheses between the lambdas solves this: f() { }() { } means an invocation of the f's result with a lambda.

This lambda is passed as the ((T) -> U) argument to the (3)'s result type, and the result of this call is (T) -> V

You can get a much less cryptic version of this expression if you pass all the lambdas inside parentheses (the f({ }) form instead of f() { } or f { }):

```<code>higherCompose<Double, Double, Double>()({ x -> Math.sin(x) })({ x -> Math.PI / 2 - x })
</code>```

See: Lambda Expressions and Anonymous Functions in the language reference.

Body:
I'm working with this higher-order compose function:

fun <T, U, V> higherCompose(): ((U) -> V) -> ((T) -> U) -> (T) -> V =
    { f ->
        { g ->
            { x -> f(g(x)) }
        }
    }

And the application:

 val cos = higherCompose<Double, Double, Double>()()
{ x: Double -> Math.sin(x)}() { x : Double -> Math.PI/2  - x }

I do understand what we're trying to achieve here mathematically. But what I'm struggling with is notation and the programming meaning:

What exactly is

higherCompose<Double>()

And why do we apply so strangely values to it:

1. () ()
2. { function1} { function 1}

Body:
Here's how this notation is parsed and what the function calls are:

higherCompose<Double, Double, Double>()() { x -> Math.sin(x) }() { x -> Math.PI/2  - x }
|                                    ^| ^ ^^^^^^^^^^^^^^^^^^^| ^ ^^^^^^^^^^^^^^^^^^^^^^|
|                                    1| 2          3         | 4           5           |
|_____________________________________|______________________|_________________________|
| first call                          | second call          | third call              |

This is the initial no-argument call to higherCompose that returns a value of exactly the higherCompose's return type, ((U) -> V) -> ((T) -> U) -> (T) -> V, with the three type parameters substituted with Double.

These parentheses are simply used to resolve parsing ambiguity. Kotlin allows calling a function with a lambda in either of the forms: f({ }), f() { }, f { }. If you remove the parentheses, the lambda marked as (3) will be treated as an argument to the first call. One way to solve this ambiguity is to add () to tell the compiler that it's the (1)'s return value that is invoked and not higherCompose

Therefore, this lambda is passed as the ((U) -> V) argument to the higherCompose's result type, producing ((T) -> U) -> (T) -> V.

These parentheses are added because Kotlin does not allow calling a return value of a call with a lambda outside parentheses (f() { }) directly with another lambda: f() { } { } is prohibited, but adding another pair of parentheses between the lambdas solves this: f() { }() { } means an invocation of the f's result with a lambda.

This lambda is passed as the ((T) -> U) argument to the (3)'s result type, and the result of this call is (T) -> V

You can get a much less cryptic version of this expression if you pass all the lambdas inside parentheses (the f({ }) form instead of f() { } or f { }):

higherCompose<Double, Double, Double>()({ x -> Math.sin(x) })({ x -> Math.PI / 2 - x })

See: Lambda Expressions and Anonymous Functions in the language reference.


问:
Unexpectedly found nill while trying to unwrap label from a custom Collection View Cell
I've created a custom Collection View Cell class which is as simple as this:

import UIKit

class AchievementCollectionViewCell: UICollectionViewCell {
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var achieveLabel: UILabel!
}
```

<p>Outlets are connected to corresponding items in prototype cell. Apparently when I try to assign text and an image to this outlets I get an error <code>Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value</code></p>

<p>Here is the code I use: </p>

<pre class="lang-swift prettyprint-override"><code>func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionViewCell", for: indexPath) as! AchievementCollectionViewCell
        // Configure the cell
        let achievement = achievementList[indexPath.row]
        cell.achieveLabel.text = achievement.name

        return cell
}
</code>```

Debugger shows that both imageView and achieveLabel are nill when I reference them in the code above. How can I fix it?

答: You are probably saying self.collectionView?.register for your cell type somewhere. If so, delete that line. You must not register the cell if you are getting it from the storyboard.

Body:
I've created a custom Collection View Cell class which is as simple as this:

import UIKit

class AchievementCollectionViewCell: UICollectionViewCell {
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var achieveLabel: UILabel!
}

Outlets are connected to corresponding items in prototype cell. Apparently when I try to assign text and an image to this outlets I get an error Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value

Here is the code I use:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionViewCell", for: indexPath) as! AchievementCollectionViewCell
        // Configure the cell
        let achievement = achievementList[indexPath.row]
        cell.achieveLabel.text = achievement.name

        return cell
}

Debugger shows that both imageView and achieveLabel are nill when I reference them in the code above. How can I fix it?


问:
why identical() return true on two strings
I'm new to Dart. The documentation say: "To test whether two objects x and y represent the same thing, use the == operator. (In the rare case where you need to know whether two objects are the exact same object, use the identical() function instead.)"

So, if type this code:

var foo = 'bar';
var baz = 'bar';
print(identical(foo, baz));
```

If i've well understood, foo and bar do not reference the same object. So identical() must return false, isn't it ?
But it's not the case, at least in DartPad.

Where is the problem.

答:
For several built-in "literals", you will always get identical true for equal values.

bool

String

int

double (I think)

Body:
I'm new to Dart. The documentation say: "To test whether two objects x and y represent the same thing, use the == operator. (In the rare case where you need to know whether two objects are the exact same object, use the identical() function instead.)"

So, if type this code:

var foo = 'bar';
var baz = 'bar';
print(identical(foo, baz));

If i've well understood, foo and bar do not reference the same object. So identical() must return false, isn't it ?
But it's not the case, at least in DartPad.

Where is the problem.


问:
Why aren't my landscape resources getting generated by ionic cordova referesh?
I'm trying to generate a set of splash screens and icons for my app.

When I run iconic cordova references it generates 40 images based on my base splash and icon png's. However there are 60 images that need to be updated.

What am I doing wrong?

答:
If you have an orientation setup for your application in the config.xml file, only the files for the relevant orientations are generated.

In this specific example, removing the following "portrait" orientation temporarily:

```<code><preference name="Orientation" value="portrait" />
</code>```

allows for the landscape images to be generated. That gets 56/60 - the remainder being iPad specific images, where I presume there's a similar solution.

That said, the landscape images "should" be irrelevant in a portrait only application.

Body:
If you have an orientation setup for your application in the config.xml file, only the files for the relevant orientations are generated.

In this specific example, removing the following "portrait" orientation temporarily:

<preference name="Orientation" value="portrait" />

allows for the landscape images to be generated. That gets 56/60 - the remainder being iPad specific images, where I presume there's a similar solution.

That said, the landscape images "should" be irrelevant in a portrait only application.


问:
How to slice by checkng a list of conditions in Pandas
You can slice the dataframe by a equality check

```<code>df[df['column'] == 'key']
</code>```

How do I slice the dataframe via a check into a set?

```<code>df[df['column'] in set(['key', 'key2', key3'])]
</code>```

答:
```<code>df[df["column"].isin(["key1", "key2", "key3"])]
</code>```

This will do it.

Body:
You can slice the dataframe by a equality check

df[df['column'] == 'key']

How do I slice the dataframe via a check into a set?

df[df['column'] in set(['key', 'key2', key3'])]

Body:
df[df["column"].isin(["key1", "key2", "key3"])]

This will do it.


问:
Laravel integer v biginteger in foreign keys
I'm trying to assign big integers in my columns but it won't allow me to define the relationship unless I change it to standard integer.  No biggy, but would be interested to know why this throws up migration errors for me.

MIGRATION (working)

```<code>public function up()
{
    //create the table
    Schema::create(self::TBL_eportfoliouservalues, function($table){
        $table->engine = 'InnoDB';
        $table->increments('id');
        $table->integer('user')->unsigned()->index();
        $table->integer('document')->unsigned()->index();
        $table->integer('section')->unsigned()->index();
        $table->integer('element')->unsigned()->index();
        $table->integer('parent');
        $table->text('value');

        // foreign indexes
        $table->foreign('user')->references('id')->on('users')->onDelete('cascade')->onUpdate('cascade');
        $table->foreign('document')->references('id')->on('eportfoliodocuments')->onDelete('cascade')->onUpdate('cascade');
        $table->foreign('section')->references('id')->on('eportfoliosections')->onDelete('cascade')->onUpdate('cascade');
        $table->foreign('element')->references('id')->on('eportfolioformelements')->onDelete('cascade')->onUpdate('cascade');
    });
}
</code>```

MIGRATION (not working)

```<code>public function up()
    {
        //create the table
        Schema::create(self::TBL_eportfoliouservalues, function($table){
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->bigInteger('user')->unsigned()->index();
            $table->bigInteger('document')->unsigned()->index();
            $table->bigInteger('section')->unsigned()->index();
            $table->bigInteger('element')->unsigned()->index();
            $table->bigInteger('parent');
            $table->text('value');

            // foreign indexes
            $table->foreign('user')->references('id')->on('users')->onDelete('cascade')->onUpdate('cascade');
            $table->foreign('document')->references('id')->on('eportfoliodocuments')->onDelete('cascade')->onUpdate('cascade');
            $table->foreign('section')->references('id')->on('eportfoliosections')->onDelete('cascade')->onUpdate('cascade');
            $table->foreign('element')->references('id')->on('eportfolioformelements')->onDelete('cascade')->onUpdate('cascade');
        });
    }
</code>```

ERROR

```<code>  [Exception]
  SQLSTATE[HY000]: General error: 1005 Can't create table 'drillers.#sql-1a4_2c2' (errno: 150) (SQL:
   alter table `eportfoliouservalues` add constraint eportfoliouservalues_user_foreign foreign key (
  `user`) references `users` (`id`) on delete cascade on update cascade) (Bindings: array (
  ))
</code>```

答:
If  primary key in tableOne migration (by default it is ) is BigInteger
 So the foreign key in tableTwo migration should be bigInteger with unsigned() function.

Codes for example.

Migration for tableOne

```<code>        public function up()
        {
        Schema::create('tableOne', function (Blueprint $table) {
        $table->bigIncrements('id');
        }
</code>```

Migration for tableTwo

```<code>        public function up()
        {
        Schema::create('tableTwo', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->bigInteger('fk_id')->unsigned()->nullable() ;
        $table->bigInteger('fk_id')->default(20)->change();
        $table->foreign('fk_id')->references('id')->on('tableOne');
        }
</code>```

Hope this helps someone.

Body:
I'm trying to assign big integers in my columns but it won't allow me to define the relationship unless I change it to standard integer.  No biggy, but would be interested to know why this throws up migration errors for me.

MIGRATION (working)

public function up()
{
    //create the table
    Schema::create(self::TBL_eportfoliouservalues, function($table){
        $table->engine = 'InnoDB';
        $table->increments('id');
        $table->integer('user')->unsigned()->index();
        $table->integer('document')->unsigned()->index();
        $table->integer('section')->unsigned()->index();
        $table->integer('element')->unsigned()->index();
        $table->integer('parent');
        $table->text('value');

        // foreign indexes
        $table->foreign('user')->references('id')->on('users')->onDelete('cascade')->onUpdate('cascade');
        $table->foreign('document')->references('id')->on('eportfoliodocuments')->onDelete('cascade')->onUpdate('cascade');
        $table->foreign('section')->references('id')->on('eportfoliosections')->onDelete('cascade')->onUpdate('cascade');
        $table->foreign('element')->references('id')->on('eportfolioformelements')->onDelete('cascade')->onUpdate('cascade');
    });
}

MIGRATION (not working)

public function up()
    {
        //create the table
        Schema::create(self::TBL_eportfoliouservalues, function($table){
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->bigInteger('user')->unsigned()->index();
            $table->bigInteger('document')->unsigned()->index();
            $table->bigInteger('section')->unsigned()->index();
            $table->bigInteger('element')->unsigned()->index();
            $table->bigInteger('parent');
            $table->text('value');

            // foreign indexes
            $table->foreign('user')->references('id')->on('users')->onDelete('cascade')->onUpdate('cascade');
            $table->foreign('document')->references('id')->on('eportfoliodocuments')->onDelete('cascade')->onUpdate('cascade');
            $table->foreign('section')->references('id')->on('eportfoliosections')->onDelete('cascade')->onUpdate('cascade');
            $table->foreign('element')->references('id')->on('eportfolioformelements')->onDelete('cascade')->onUpdate('cascade');
        });
    }

ERROR

  [Exception]
  SQLSTATE[HY000]: General error: 1005 Can't create table 'drillers.#sql-1a4_2c2' (errno: 150) (SQL:
   alter table `eportfoliouservalues` add constraint eportfoliouservalues_user_foreign foreign key (
  `user`) references `users` (`id`) on delete cascade on update cascade) (Bindings: array (
  ))

Body:
If  primary key in tableOne migration (by default it is ) is BigInteger
 So the foreign key in tableTwo migration should be bigInteger with unsigned() function.

Codes for example.

Migration for tableOne

        public function up()
        {
        Schema::create('tableOne', function (Blueprint $table) {
        $table->bigIncrements('id');
        }

Migration for tableTwo

        public function up()
        {
        Schema::create('tableTwo', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->bigInteger('fk_id')->unsigned()->nullable() ;
        $table->bigInteger('fk_id')->default(20)->change();
        $table->foreign('fk_id')->references('id')->on('tableOne');
        }

Hope this helps someone.


问:
How does `gradle install` generate the `pom.xml` files
When I run gradle install it generates nice pom.xml files in every subproject.

Where can I see the source code that accomplishes that?

As per Maven plugin documentation, there's something about the Upload task, but its documentation and the source code yield nothing concrete.

答:
You can add gradle-maven-VERSION.jar to your dependencies and debug the plugin yourself. The corresponding source code sits in your gradle installation, or on github: https://github.com/gradle/gradle/tree/master/subprojects/maven/src/main/java/org/gradle/api/publication/maven/internal

To give you a head start: bulk of the code sits in DefaultMavenPom class.
It is created in DefaultMavenPomFactory.create() with some dummy values:

MavenProject.EMPTY_PROJECT_GROUP_ID

MavenProject.EMPTY_PROJECT_ARTIFACT_ID

MavenProject.EMPTY_PROJECT_VERSION

Then, AbstractMavenResolver.publish(IvyModulePublishMetadata moduleVersion) is called,
which, among others:

Fills in basic pom data based on actual artifact in DefaultArtifactPom.assignArtifactValuesToPom()

Fills in dependencies - they are filled in with DefaultMavenPom.getGeneratedDependencies()

Writes generated file


问:
Python/Flask mysql cursor: Why it doesn't work?
```<code>from flask import Flask
from flask_mysqldb import MySQL

app = Flask(__name__)
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = 'password'
app.config['MYSQL_DB'] = 'todoapp'
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
mysql = MySQL(app)
cur = mysql.connection.cursor()

if __name__ == '__main__':
    app.run()
</code>```

There is error which is displayed after executing program:

cur = mysql.connection.cursor()

AttributeError: 'NoneType' object has no attribute 'cursor'.

According to documentaction it should work. I use Ubuntu 16.04, I have installed MySQL and it works properly. Could anyone explain why it doesn't work?

答:
The problem is in :

```<code>app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
</code>```

Looking at flaskext.mysql source , that feature is not yet implemented .

And since flaskext.mysql is using pymysql  , you can use DictCursor from pymysql.cursors

Example :

```<code>from flaskext.mysql import MySQL
from flask import Flask
from pymysql import cursors

app=Flask(__name__)

mysql = MySQL(cursorclass=cursors.DictCursor)
mysql.init_app(app)
cursor = mysql.connect().cursor()
</code>```

Body:
from flask import Flask
from flask_mysqldb import MySQL

app = Flask(__name__)
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = 'password'
app.config['MYSQL_DB'] = 'todoapp'
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
mysql = MySQL(app)
cur = mysql.connection.cursor()

if __name__ == '__main__':
    app.run()

There is error which is displayed after executing program:

cur = mysql.connection.cursor()

AttributeError: 'NoneType' object has no attribute 'cursor'.

According to documentaction it should work. I use Ubuntu 16.04, I have installed MySQL and it works properly. Could anyone explain why it doesn't work?

Body:
The problem is in :

app.config['MYSQL_CURSORCLASS'] = 'DictCursor'

Looking at flaskext.mysql source , that feature is not yet implemented .

And since flaskext.mysql is using pymysql  , you can use DictCursor from pymysql.cursors

Example :

from flaskext.mysql import MySQL
from flask import Flask
from pymysql import cursors

app=Flask(__name__)

mysql = MySQL(cursorclass=cursors.DictCursor)
mysql.init_app(app)
cursor = mysql.connect().cursor()


问:
A delegating constructor cannot have other mem-initializers - error
I'm trying to do something like in the code below. I'm getting error like in the question title from VS. Can anybody tells me what's wrong?</p>

```<code>class A
{
public:
    int x;
    A(int x = 15)
    {
        this->x = x;
    }
};

class B : public A
{
public:
    int a,b,c;

    B(int a, int b, int c)
    {
        this->a = a;
        this->b = b;
        this->c = c;
    }

    B(int a, int b, int c, int x) : A(x), /*here is error*/B(a,b,c)
    {

    }
};
</code>```

答:
In your 4-parameter constructor for B, you can't construct the base class A, then delegate to another constructor.  That other constructor would also construct A, potentially causing all kinds of havoc.

You'll either need to duplicate the initialization of B's members, put them in a helper function, or delegate from the 3-parameter function to the 4-parameter function (providing the proper value for the 4th parameter which is passed to the constructor for A).

```<code>B(int a, int b, int c): B(a, b, c, 15)
{
}
</code>```

Body:
I'm trying to do something like in the code below. I'm getting error like in the question title from VS. Can anybody tells me what's wrong?

class A
{
public:
    int x;
    A(int x = 15)
    {
        this->x = x;
    }
};

class B : public A
{
public:
    int a,b,c;

    B(int a, int b, int c)
    {
        this->a = a;
        this->b = b;
        this->c = c;
    }

    B(int a, int b, int c, int x) : A(x), /*here is error*/B(a,b,c)
    {

    }
};

Body:
In your 4-parameter constructor for B, you can't construct the base class A, then delegate to another constructor.  That other constructor would also construct A, potentially causing all kinds of havoc.

You'll either need to duplicate the initialization of B's members, put them in a helper function, or delegate from the 3-parameter function to the 4-parameter function (providing the proper value for the 4th parameter which is passed to the constructor for A).

B(int a, int b, int c): B(a, b, c, 15)
{
}


问:
How can I iterate over an enum?
I just noticed that you can not use standard math operators on an enum such as ++ or +=.

So what is the best way to iterate through all of the values in a C++ enum?

答:
enum class A {
    a0=0, a3=3, a4=4
};
constexpr std::array ALL_A {A::a0, A::a3, A::a4}; // constexpr is important here

for(A a: ALL_A) {
  if(a==A::a0 || a==A::a4) std::cout << static_cast<int>(a);
}
```

A constexpr std::array can iterate even non-sequential enums without the array being instantiated by the compiler. This depends on things like the compiler's optimization heuristics and whether you take the array's address.

In my experiments, I found that g++ 9.1 with -O3 will optimize away the above array if there are 2 non-sequential values or quite a few sequential values (I tested up to 6). But it only does this if you have an if statement. (I tried a statement that compared an integer value greater than all the elements in a sequential array and it inlined the iteration despite none being excluded, but when I left out the if statement, the values were put in memory.) It also inlined 5 values from a non-sequential enum in [one case|https://godbolt.org/z/XuGtoc]. I suspect this odd behavior is due to deep heuristics having to do with caches and branch prediction.

Here is a link to a simple test iteration on godbolt that demonstrates the array does not always get instantiated.

The price of this technique is writing the enum elements twice and keeping the two lists in sync.

OwnerDisplayName: Adam

Title: How can I iterate over an enum?

Body:
enum class A {
    a0=0, a3=3, a4=4
};
constexpr std::array<A, 3> ALL_A {A::a0, A::a3, A::a4}; // constexpr is important here

for(A a: ALL_A) {
  if(a==A::a0 || a==A::a4) std::cout << static_cast<int>(a);
}

A constexpr std::array can iterate even non-sequential enums without the array being instantiated by the compiler. This depends on things like the compiler's optimization heuristics and whether you take the array's address.

In my experiments, I found that g++ 9.1 with -O3 will optimize away the above array if there are 2 non-sequential values or quite a few sequential values (I tested up to 6). But it only does this if you have an if statement. (I tried a statement that compared an integer value greater than all the elements in a sequential array and it inlined the iteration despite none being excluded, but when I left out the if statement, the values were put in memory.) It also inlined 5 values from a non-sequential enum in [one case|https://godbolt.org/z/XuGtoc]. I suspect this odd behavior is due to deep heuristics having to do with caches and branch prediction.

Here is a link to a simple test iteration on godbolt that demonstrates the array does not always get instantiated.

The price of this technique is writing the enum elements twice and keeping the two lists in sync.


问:
Long transaction in WebSphere 6.1 results in OutOfMemoryException
I’m running a synchronization / batch job (synchronizeXXX() that inserts 111821 records in an Oracle database using Hibernate 3.2.5GA / Spring 2.5.6 in one long running transaction (>4 hours) but it fails after approx. 2 hours / 50000 records with an OutOfMemory exception.

Although i do clear and flush every 20 inserts, it still looks like Hibernate/Websphere/Spring (?) is holding on to a gazillion objects in the session.

The funny thing is:  the memory usage is initially normal, but after approx. 20/30 minutes the memory usage starts to increase and grows until the OutOfMemory occurs (not shown in PDF because it was scrolled out/cleared or something). I tried upgrading Hibernate from 3.2.5
to 3.3.2GA but the same problem remained.
When I increase the max heap size, the OutOfMemory just comes later.

I googled and found some ‘similar’ issues, but they used Hibernate to manage the transaction instead of Spring, so I guess the fix  mentioned is not relevant to me(?). See Simular issues

I analysed the heap dumps and did some analysis with the IBM Support Agent 4.1. All results/screenshots and more details are included in a PDF: see OutOfMemory analysis (PDF 586KB)

Any help is appreciated!

答:
Even if you are doing clears and flush from time to time the Hibernate session and transaction is still open and clear doesn't seem to work as it should in your case.

The options here seem to be:

a) Use stateless session: http://docs.jboss.org/hibernate/core/3.3/reference/en/html/batch.html

b) Use SQL queries so hibernate cannot hold anything

c) Use several transactions

There is no great solution here, so just value the best option for you :(


问:
How to detect hand palm and its orientation (like facing outwards)?
I am working on a hand detection project. There are many good project on web to do this, but what I need is a specific hand pose detection. It needs a totally open palm and the whole palm face to outwards, like the image below:

The first hand faces to inwards, so it will not be detected, and the right one faces to outwards, it will be detected. Now I can detect hand with OpenCV. but how to tell the hand orientation?

答:
Take a look at what leap frog has done with the oculus rift. I'm not sure what they're using internally to segment hand poses, but there is another paper that produces hand poses effectively. If you have a stereo camera setup, you can use this paper's methods: https://arxiv.org/pdf/1610.07214.pdf.

The only promising solutions I've seen for mono camera train on large datasets.


问:
How to recheck required input fields in JavaScript/HTML5
I'm trying to stay away from JQuery for this one (nothing against JQuery, I just don't want to load a huge library into this project for something small like this).

I'm curious how I might tell HTML5 to recheck all the required input fields in a given form. For example, I have this form (albeit slightly more complicated but you get the point):

```<code><form action="here" onsubmit="check()">
    <input required name="something">
    <input type="submit">
</form>
</code>```

If I don't have anything in that required field, HTML5 shows a popup error, something to the effect of "Please fill in this required field". What is stopping the user from putting in a single space, or some nonsense character like % or >? I'd like to partially validate this client-side (in addition to server side) so it isn't particularly inconvenient when the page redirects to the form submission page and then shows the error, and then goes back to the form, prompting the user to enter everything over again.

Assuming in my onsubmit function check I've removed all whitespace and/or nonsense characters from the ends of the string, how can that function then tell HTML5 to recheck the form to see if the required fields are still not empty?

答:
try to use regexp pattern (e.g. exclude white chars: [^\s]*, allow only letters [A-Za-z]*, ...)

<form action="here" onsubmit="check()">
    <input required pattern="[^\s]*" name="something" >
    <input type="submit">
</form>```

Body:
I'm trying to stay away from JQuery for this one (nothing against JQuery, I just don't want to load a huge library into this project for something small like this).

I'm curious how I might tell HTML5 to recheck all the required input fields in a given form. For example, I have this form (albeit slightly more complicated but you get the point):

<form action="here" onsubmit="check()">
    <input required name="something">
    <input type="submit">
</form>

If I don't have anything in that required field, HTML5 shows a popup error, something to the effect of "Please fill in this required field". What is stopping the user from putting in a single space, or some nonsense character like % or >? I'd like to partially validate this client-side (in addition to server side) so it isn't particularly inconvenient when the page redirects to the form submission page and then shows the error, and then goes back to the form, prompting the user to enter everything over again.

Assuming in my onsubmit function check I've removed all whitespace and/or nonsense characters from the ends of the string, how can that function then tell HTML5 to recheck the form to see if the required fields are still not empty?


问:
Ionic 4: How to overflow div from Ionic Header or Toolbar?

I want create a drop down menu or popover within ionic toolbar. I tried with several ways but can not solve. Its always hidden like bellow,

I trying css like bellow,

```<code>.popover{
   border: 1px solid black;
   height: 350px;
   width: 150px;
   position: absolute;
   z-index: 99999999;
   background: yellow;
}

ion-header{
  contain: none;
}
ion-toolbar{
  contain: none;
}
</code>```

Please give me a suggestion or an alternative idea. Please do not give any predictive answer if you are not familiar with ionic.

答:
Just use ion-menu, its a build in ionic component

https://ionicframework.com/docs/api/menu

There is also ion-popover

You should look at the ionic docs before posting on stack

Body:
I want create a drop down menu or popover within ionic toolbar. I tried with several ways but can not solve. Its always hidden like bellow,

I trying css like bellow,

.popover{
   border: 1px solid black;
   height: 350px;
   width: 150px;
   position: absolute;
   z-index: 99999999;
   background: yellow;
}

ion-header{
  contain: none;
}
ion-toolbar{
  contain: none;
}

Please give me a suggestion or an alternative idea. Please do not give any predictive answer if you are not familiar with ionic.