问:
EditText not scrollable inside NestedScrollView
Layout: I have an EditText and 2 RecyclerViews inside a NestedScrollView, which are not visible (visibility=gone)

<androidx.coordinatorlayout.widget.CoordinatorLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    //... toolbar

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <androidx.core.widget.NestedScrollView
            android:id="@+id/scrollView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginBottom="?attr/actionBarSize"
            android:fillViewport="true"
            android:scrollbars="vertical">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">

                <EditText
                    android:id="@+id/editText"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:backgroundTint="@android:color/transparent"
                    android:gravity="top"
                    android:inputType="textMultiLine|textCapSentences"
                    android:padding="@dimen/activity_margin"
                    android:singleLine="false" />

                <androidx.recyclerview.widget.RecyclerView
                    android:id="@+id/rv_items"
                    android:padding="@dimen/activity_margin"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:scrollbars="vertical"
                    android:visibility="gone" />

                <androidx.recyclerview.widget.RecyclerView
                    android:id="@+id/rv_Labels"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:padding="12dp"
                    android:visibility="gone" />

            </LinearLayout>

        </androidx.core.widget.NestedScrollView>

    </LinearLayout>

    <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:id="@+id/coordinator_layout"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_gravity="bottom"
        android:layout_marginBottom="?actionBarSize" />

    <com.google.android.material.bottomnavigation.BottomNavigationView
            //...
    />

</androidx.coordinatorlayout.widget.CoordinatorLayout>
```
<p><strong>The problem:</strong> When I enter more text than the height of the screen, the EditText is scrolled down to where the cursor is. But when I try to scroll up, nothing happens. Here's a screen recording I made.</p>
<p>Can't scroll:</p>
<ul>
<li>after entering/pasting long text for the 1st time.</li>
</ul>
<p>Can scroll:</p>
<ul>
<li>after reopening the activity with text already entered</li>
<li>after closing the keyboard</li>
<li>after closing the keyboard and opening it again</li>
</ul>
<p><strong>Searching for similar problems yielded:</strong></p>
<ul>
<li>EditText not scrollable inside ScrollView</li>
<li>Enable Scrollable EditText within a ScrollView and ViewFlipper</li>
<li>... and other results with the same answer:</li>
</ul>
<p>...</p>
```editText.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (v.getId() == R.id.editText) {
            v.getParent().requestDisallowInterceptTouchEvent(true);
            switch (event.getAction() & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_UP:
                v.getParent().requestDisallowInterceptTouchEvent(false);
                break;
            }
        }
        return false;
    }
});
```

That solution doesn't work:

The questions are about ScrollViews, not NestedScrollViews. And NestedScrollView is one of the proposed solutions (which I already use)

When I add the above code, the EditText is sort of scrollable, but only when the keyboard is shown. If it is not, then it's impossible to scroll - trying to scroll causes text to be selected.

Scrolling (with the keyboard open) moves the cursor.

Please let me know if you need any more info or if I've missed anything. Thank you!

答:
The answer is actually simpler than I thought.
After pasting your xml (and making the necessary changes for it to build - missing dimens. etc...) I just changed the height of your EditText to wrap_content and the bug was gone.

The answer lies here:
Comparing the measurements of the EditText at different points in time, on the left with height=match_parent and on the right with height=wrap_content

On the left:
The EditText is drawn on screen empty with a certain size, you paste the text and it's size doesn't change. Showing/Hiding the keyboard is one important event in the life of a screen, it's called a configuration change this causes elements to be measured again and re-drawn.

On the right:
If you change the height of the EditText to wrap_content it will force a measure and re-draw immediately after insertion.

Hope this helps :)

Body:
Layout: I have an EditText and 2 RecyclerViews inside a NestedScrollView, which are not visible (visibility=gone)

<androidx.coordinatorlayout.widget.CoordinatorLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    //... toolbar

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <androidx.core.widget.NestedScrollView
            android:id="@+id/scrollView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginBottom="?attr/actionBarSize"
            android:fillViewport="true"
            android:scrollbars="vertical">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">

                <EditText
                    android:id="@+id/editText"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:backgroundTint="@android:color/transparent"
                    android:gravity="top"
                    android:inputType="textMultiLine|textCapSentences"
                    android:padding="@dimen/activity_margin"
                    android:singleLine="false" />

                <androidx.recyclerview.widget.RecyclerView
                    android:id="@+id/rv_items"
                    android:padding="@dimen/activity_margin"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:scrollbars="vertical"
                    android:visibility="gone" />

                <androidx.recyclerview.widget.RecyclerView
                    android:id="@+id/rv_Labels"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:padding="12dp"
                    android:visibility="gone" />

            </LinearLayout>

        </androidx.core.widget.NestedScrollView>

    </LinearLayout>

    <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:id="@+id/coordinator_layout"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_gravity="bottom"
        android:layout_marginBottom="?actionBarSize" />

    <com.google.android.material.bottomnavigation.BottomNavigationView
            //...
    />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

The problem: When I enter more text than the height of the screen, the EditText is scrolled down to where the cursor is. But when I try to scroll up, nothing happens. Here's a screen recording I made.

Can't scroll:

after entering/pasting long text for the 1st time.

Can scroll:

after reopening the activity with text already entered

after closing the keyboard

after closing the keyboard and opening it again

Searching for similar problems yielded:

EditText not scrollable inside ScrollView

Enable Scrollable EditText within a ScrollView and ViewFlipper

... and other results with the same answer:

...

editText.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (v.getId() == R.id.editText) {
            v.getParent().requestDisallowInterceptTouchEvent(true);
            switch (event.getAction() & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_UP:
                v.getParent().requestDisallowInterceptTouchEvent(false);
                break;
            }
        }
        return false;
    }
});

That solution doesn't work:

The questions are about ScrollViews, not NestedScrollViews. And NestedScrollView is one of the proposed solutions (which I already use)

When I add the above code, the EditText is sort of scrollable, but only when the keyboard is shown. If it is not, then it's impossible to scroll - trying to scroll causes text to be selected.

Scrolling (with the keyboard open) moves the cursor.

Please let me know if you need any more info or if I've missed anything. Thank you!


来源: stackexchange

问:
PHPMailer codes won't send a message to an email in GoDaddy
I have a project that needs to be done and our group life is on the line with this problem occurs to us. The problem is that it won't send a message to an email. In xampp localhost this phpmailer script works but after uploading to godaddy it happens to have some sort of problem. I tried various fix/solution with the forums I'd seen here in godaddy and still it won't work. For example like changing the host, port, smtp's auth and secure, and etc. Could somebody out there help me to find a fix for this even godaddy help support? I've been going at it for the past 2 weeks. Am I missing something? Do I have something to configure in cPanel? This is the script I made but it is just for a trial.</p>

```<code><?php

if(isset($_POST['register'])) {
try{
require ('phpmailer/PHPMailerAutoload.php');
$mail = new PHPMailer();
$mail->isSMTP();
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'ssl';
$mail->Host = 'smtpout.secureserver.net';
$mail->Port = '465';
$mail->isHTML();
$mail->Username = 'msatwebsite@gmail.com';
$mail->Password = '***************';
$mail->SetFrom('no-reply@webmaster');
$mail->Subject ='MSU-MSAT Alumni Registration Confirmation';
$mail->Body = 'hello lagudas 3' ;
$mail->AddAddress('glysalagudas@gmail.com');
$mail->Send();
echo "Message Sent OK\n";
} catch (phpmailerException $e) {
echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
echo $e->getMessage();
}
}
?>
</code>```

答:
Try using these lines of code in the beginning of your script if you haven't already, and make sure the directory is correct :-)</p>

```<code>use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

require_once 'PHPMailer/src/Exception.php';
require_once 'PHPMailer/src/PHPMailer.php';
require_once 'PHPMailer/src/SMTP.php';
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a project that needs to be done and our group life is on the line with this problem occurs to us. The problem is that it won't send a message to an email. In xampp localhost this phpmailer script works but after uploading to godaddy it happens to have some sort of problem. I tried various fix/solution with the forums I'd seen here in godaddy and still it won't work. For example like changing the host, port, smtp's auth and secure, and etc. Could somebody out there help me to find a fix for this even godaddy help support? I've been going at it for the past 2 weeks. Am I missing something? Do I have something to configure in cPanel? This is the script I made but it is just for a trial.

<?php

if(isset($_POST['register'])) {
try{
require ('phpmailer/PHPMailerAutoload.php');
$mail = new PHPMailer();
$mail->isSMTP();
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'ssl';
$mail->Host = 'smtpout.secureserver.net';
$mail->Port = '465';
$mail->isHTML();
$mail->Username = 'msatwebsite@gmail.com';
$mail->Password = '***************';
$mail->SetFrom('no-reply@webmaster');
$mail->Subject ='MSU-MSAT Alumni Registration Confirmation';
$mail->Body = 'hello lagudas 3' ;
$mail->AddAddress('glysalagudas@gmail.com');
$mail->Send();
echo "Message Sent OK\n";
} catch (phpmailerException $e) {
echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
echo $e->getMessage();
}
}
?>

Body:
Try using these lines of code in the beginning of your script if you haven't already, and make sure the directory is correct :-)

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

require_once 'PHPMailer/src/Exception.php';
require_once 'PHPMailer/src/PHPMailer.php';
require_once 'PHPMailer/src/SMTP.php';


问:
Get the caption of optionbutton and checkbox when enabled
I want to get the caption of optionbutton and checkbox when value is true.

I have this code. I'm getting an error under the next.

```<code>    Dim c As Control, str As String
    Dim d As Control, ctr As String

    For each c in Userform1.Controls
        For each d in Userform1.Controls
            If TypeName(c) ="OptionButton" Then
                If TypeName(d) = "CheckBox" Then
                    str = str & IIf(c = True, c.Caption & vbCrLf, "")
                    ctr = ctr & IIf(d= True, d.Caption & vbCrLf, "")
                End If
            End If
        Next c
    Next d
    TextBox2.Value = "PV:" & str & ctr
End sub
</code>```

答:
Try following sub. Hope it will help you.</p>

```<code>Private Sub CommandButton1_Click()
Dim c As Control, str As String, ctr As String

    For Each c In UserForm1.Controls
        If TypeName(c) = "OptionButton" Then
            If c = True Then
                str = str & c.Caption & vbCrLf
            End If
        End If

        If TypeName(c) = "CheckBox" Then
            If c = True Then
                ctr = ctr & c.Caption & vbCrLf
            End If
        End If
    Next c
    'TextBox2.Value = "PV:" & str & ctr
    MsgBox "PV: " & str & ctr
End Sub
</code>```

Body:
I want to get the caption of optionbutton and checkbox when value is true.

I have this code. I'm getting an error under the next.

    Dim c As Control, str As String
    Dim d As Control, ctr As String

    For each c in Userform1.Controls
        For each d in Userform1.Controls
            If TypeName(c) ="OptionButton" Then
                If TypeName(d) = "CheckBox" Then
                    str = str & IIf(c = True, c.Caption & vbCrLf, "")
                    ctr = ctr & IIf(d= True, d.Caption & vbCrLf, "")
                End If
            End If
        Next c
    Next d
    TextBox2.Value = "PV:" & str & ctr
End sub

Body:
Try following sub. Hope it will help you.

Private Sub CommandButton1_Click()
Dim c As Control, str As String, ctr As String

    For Each c In UserForm1.Controls
        If TypeName(c) = "OptionButton" Then
            If c = True Then
                str = str & c.Caption & vbCrLf
            End If
        End If

        If TypeName(c) = "CheckBox" Then
            If c = True Then
                ctr = ctr & c.Caption & vbCrLf
            End If
        End If
    Next c
    'TextBox2.Value = "PV:" & str & ctr
    MsgBox "PV: " & str & ctr
End Sub


问:
Spring Controller - Testing to receive nested dto with multipartfile inside with postman
I'm working on a service which accepts a DTO in a POST method and creates an entity based on that DTO. Nested inside is a multipart file, which is going to be an image used by the entity that will be created.

Using postman to test my backend, I keep receiving an seemingly empty DTO. The three logs inside the controller return null, 0 and null respectively.

This is how I setup my data, which I am quite sure is the problem:

I converted my image into a base64 string, which as far as I know is the only way I can post a nested image.

Code

Controller

```<code>@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<InventoryComponentDto> create(@ModelAttributee InventoryComponentDto request) {

    System.out.println(request.getDescription());
    System.out.println(request.getMinimal_supply());
    System.out.println(request.getComponent());

    InventoryComponentDto result = inventoryComponentService.create(request);
    if (result == null) {
        return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST);
    }

    return ResponseEntity.ok(result);
}
</code>```

InventoryComponentDto

```<code>public class InventoryComponentDto {

    private ComponentDto component;

    private String description;

    private Date createdAt;

    private Date updatedAt;

    private int minimal_supply;

    private int supply;

}
</code>```

ComponentDto

```<code>public class ComponentDto {

    private Long id;

    private int number;

    private String name;

    private FileDto image;

}
</code>```

FileDto

```<code>public class FileDto {

    private String name;

    private String type;

    private String url;

    private MultipartFile data;

}
</code>```

What would be the way for me to adequately create my dto in postman, including an image?

Update

```<code>"status": 400,
"error": "Bad Request",
"message": "JSON parse error: (was java.lang.NullPointerException); nested exception is com.fasterxml.jackson.databind.JsonMappingException: (was java.lang.NullPointerException) (through reference chain: com.package.MCI.dto.InventoryComponentDto[\"component\"]->com.package.MCI.dto.ComponentDto[\"image\"])",
"trace": "org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: (was java.lang.NullPointerException); nested...
</code>```

答:
You need to create a custom jackson deserializer.

//CustomDeserializer

import java.io.IOException;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItem;

import org.springframework.util.Base64Utils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

public class CustomDeserializer extends StdDeserializer<FileDTO> {

    public CustomDeserializer() {
        super(FileDTO.class);
    }

    protected CustomDeserializer(Class<?> vc) {
        super(vc);
    }

    @Override
    public FileDTO deserialize(JsonParser jsonParser,
            DeserializationContext deserializationContext)
            throws IOException, JsonProcessingException {

        JsonNode node = jsonParser.getCodec().readTree(jsonParser);
        String name = node.get("name").asText();
        String url = node.get("url").asText();
        String type = "." + node.get("type").asText();
        String fileBase64 = node.get("data").asText();

        byte[] fileBytes = Base64Utils.decodeFromString(fileBase64);

        FileItem fileItem = new DiskFileItem(name, "image/jpg", false, name + type,
                fileBytes.length, null);
        fileItem.getOutputStream().write(fileBytes);
        fileItem.getOutputStream().flush();
        MultipartFile file = new CommonsMultipartFile(fileItem);
        fileItem.getOutputStream().close();

        FileDTO fileDTO = new FileDTO();
        fileDTO.setName(name);
        fileDTO.setUrl(url);
        fileDTO.setType(type);
        fileDTO.setData(file);

        return fileDTO;

    }

}

```

<p>And use it like:  </p>

<pre class="lang-java prettyprint-override"><code>//FileDTO

@JsonDeserialize(using = CustomDeserializer.class)
public class FileDTO {

</code>```

You need these two dependencies:

<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.2</version>
</dependency>
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.5</version>
</dependency>
```

Body:
I'm working on a service which accepts a DTO in a POST method and creates an entity based on that DTO. Nested inside is a multipart file, which is going to be an image used by the entity that will be created.

Using postman to test my backend, I keep receiving an seemingly empty DTO. The three logs inside the controller return null, 0 and null respectively.

This is how I setup my data, which I am quite sure is the problem:

I converted my image into a base64 string, which as far as I know is the only way I can post a nested image.

Code

Controller

@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<InventoryComponentDto> create(@ModelAttributee InventoryComponentDto request) {

    System.out.println(request.getDescription());
    System.out.println(request.getMinimal_supply());
    System.out.println(request.getComponent());

    InventoryComponentDto result = inventoryComponentService.create(request);
    if (result == null) {
        return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST);
    }

    return ResponseEntity.ok(result);
}

InventoryComponentDto

public class InventoryComponentDto {

    private ComponentDto component;

    private String description;

    private Date createdAt;

    private Date updatedAt;

    private int minimal_supply;

    private int supply;

}

ComponentDto

public class ComponentDto {

    private Long id;

    private int number;

    private String name;

    private FileDto image;

}

FileDto

public class FileDto {

    private String name;

    private String type;

    private String url;

    private MultipartFile data;

}

What would be the way for me to adequately create my dto in postman, including an image?

Update

"status": 400,
"error": "Bad Request",
"message": "JSON parse error: (was java.lang.NullPointerException); nested exception is com.fasterxml.jackson.databind.JsonMappingException: (was java.lang.NullPointerException) (through reference chain: com.package.MCI.dto.InventoryComponentDto[\"component\"]->com.package.MCI.dto.ComponentDto[\"image\"])",
"trace": "org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: (was java.lang.NullPointerException); nested...

Body:
You need to create a custom jackson deserializer.

//CustomDeserializer

import java.io.IOException;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItem;

import org.springframework.util.Base64Utils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

public class CustomDeserializer extends StdDeserializer<FileDTO> {

    public CustomDeserializer() {
        super(FileDTO.class);
    }

    protected CustomDeserializer(Class<?> vc) {
        super(vc);
    }

    @Override
    public FileDTO deserialize(JsonParser jsonParser,
            DeserializationContext deserializationContext)
            throws IOException, JsonProcessingException {

        JsonNode node = jsonParser.getCodec().readTree(jsonParser);
        String name = node.get("name").asText();
        String url = node.get("url").asText();
        String type = "." + node.get("type").asText();
        String fileBase64 = node.get("data").asText();

        byte[] fileBytes = Base64Utils.decodeFromString(fileBase64);

        FileItem fileItem = new DiskFileItem(name, "image/jpg", false, name + type,
                fileBytes.length, null);
        fileItem.getOutputStream().write(fileBytes);
        fileItem.getOutputStream().flush();
        MultipartFile file = new CommonsMultipartFile(fileItem);
        fileItem.getOutputStream().close();

        FileDTO fileDTO = new FileDTO();
        fileDTO.setName(name);
        fileDTO.setUrl(url);
        fileDTO.setType(type);
        fileDTO.setData(file);

        return fileDTO;

    }

}

And use it like:

//FileDTO

@JsonDeserialize(using = CustomDeserializer.class)
public class FileDTO {

You need these two dependencies:

<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.2</version>
</dependency>
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.5</version>
</dependency>


问:
Can't pass data from home to results_page by Navigator.push() method
There is a problem with this flutter app, and I cant find the solution as there is no error. what happens is when it navigates from home to the result page, the calculations doesn't happen or the values are not sent I don't understand what's happening here. Any help is much appreciated. here is the link to the git repo https://github.com/TauqeerAli/bmi-calculator-flutter2

Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => ResultsPage(
                        bmiResult: calc.calculateBMI(),
                        resultText: calc.getResult(),
                        interpretation: calc.getInterpretation(),
                      ),

There are no error messages. That is the problem.

答:
I checked the repo ,The calculation indeed happens but gives the wrong answer

in calculator_brain.dart you need to replace the method

```<code> String calculateBMI() {
    _bmi = weight / pow(height, 2);
    return _bmi.toStringAsFixed(1);
  }
</code>```

with

```<code> String calculateBMI() {
    _bmi = weight / pow(height/100, 2);
    return _bmi.toStringAsFixed(1);
  }
</code>```

to get the right answer. as the formula takes height in meters not in centimeters.

Body:
I checked the repo ,The calculation indeed happens but gives the wrong answer

in calculator_brain.dart you need to replace the method

 String calculateBMI() {
    _bmi = weight / pow(height, 2);
    return _bmi.toStringAsFixed(1);
  }

with

 String calculateBMI() {
    _bmi = weight / pow(height/100, 2);
    return _bmi.toStringAsFixed(1);
  }

to get the right answer. as the formula takes height in meters not in centimeters.


问:
Any way to have Flask session store in local storage instead of a cookie?
I would rather store the session information for a website on local Storage instead of a cookie.  So as flask would not send a cookie.

Can this be done?

答:
I can't flask
But you can distinguish the client through client IP and UA or other forms, and conserve the relevant information of the client.

Another way is to return token like a client, and each subsequent client request needs to contain (via get or post) the token.

But these two methods are not completely reliable.


问:
The Google Services Plugin cannot function without it. File google-services.json is missing.
File google-services.json is missing. The Google Services Plugin cannot function without it.
 Searched Location:
C:\Users\Aman\Desktop\balcony\balcony\Module_SDK\src\nullnull\debug\google-services.json
C:\Users\Aman\Desktop\balcony\balcony\Module_SDK\src\debug\nullnull\google-services.json
C:\Users\Aman\Desktop\balcony\balcony\Module_SDK\src\nullnull\google-services.json
C:\Users\Aman\Desktop\balcony\balcony\Module_SDK\src\debug\google-services.json
C:\Users\Aman\Desktop\balcony\balcony\Module_SDK\src\nullnullDebug\google-services.json
C:\Users\Aman\Desktop\balcony\balcony\Module_SDK\google-services.json</p>

答:
just change in the build.gradle the line

```<code>compile fileTree (dir: 'libs', include: ['* .jar'])
</code>```

to

```<code>implementation fileTree(dir: 'libs', include: ['*.jar'])
</code>```

and ready, your mistake will be corrected!

Body:
just change in the build.gradle the line

compile fileTree (dir: 'libs', include: ['* .jar'])

to

implementation fileTree(dir: 'libs', include: ['*.jar'])

and ready, your mistake will be corrected!


问:
twitter and facebook connect in rails
Excuse I need a tutorial for twitter and facebook connect.

The user can register in my site or enter through twitter or facebook login access data

How i could implement this functionality if I am using rails 2.3.8 and RESTful authentication?

I need the model for database (how save this information and its relationships) and implement in my page.

Example: http://www.myntmarket.com/

I find a tutorial with restful authentication and facebooker but facebooker is deprecated. So i find facebooker2. somebody could explain me how can i use this plugin.

Thanks in advance and excuse me my syntax in english.

答: Do you need to stay with Rails 2? Otherwise, Omniauth and Rails 3 would be an option, I have a fully functional demo on Github: https://github.com/markusproske/omniauth_pure</p>

ContentLicense: CC BY-SA 3.0

Title: twitter and facebook connect in rails


问:
How do I annotate rust variables' data type without assignment?
I'm new to rust, and I'd like to declare a typed variable without initializing it. Is this possible in Rust? If so, is it advisable or are there better, more rustacean-y ways to do it?

I'm looking at the following code from rustlings which fails to compile because it can't infer the type of x:

    let x;
    if x == 10 {
        println!("Ten!");
    }
```

<p>So, I tried this:</p>

<pre class="lang-rust prettyprint-override"><code>let x: i32;
</code>```

however, now the compiler will throw an error on the comparison line saying that x hadn't been declared.

This works fine, but I was left wondering if one can declare the type without an assignment.

let x: i32 = 10;
```

Or is the correct way to do it involve designing your code to avoid such situations in the first place? I come from a C background and I'm probably a little too comfortable with being lazy with types.

答:
In rust, the type of a variable is usually inferred from the context.

The context can include any of the following:

The type of the value being assigned:

let x = String::new(); //x is now a String
```

<ul>
<li>The return type of the function being called:</li>
</ul>

<pre class="lang-rust prettyprint-override"><code>fn foo() -> usize {
    40
}
let x = foo(); //x is now usize
</code>```

But if you don't have a type to infer, as in there is no assignment to the variable:

let x;
```

<p>Then rust cannot infer the type. Therefore, it will get mad at you. </p>

<p>Another problem that needs to be addressed in this answer; the fact that rust doesn't allow the reading of uninitialized variables. The following value, <code>x</code> is uninitialized:</p>

```let x: u32;
```

<p>Reading the value of an uninitialized <code>u32</code> probably wouldn't do too much, but consider the following:</p>

```struct MyString {
    ptr: *const u8,
    len: usize,
    cap: usize,
}
```

If we were to provide a safe wrapper around this, this would be perfectly fine, after all, this is essentially what the stdlib String boils down to. But, if we were to own an uninitialized MyString and tried to read its contents, we'd end up reading a garbage address from the ptr, and a garbage len and cap. This would lead to reading a garbage pointer, which is undefined behavior, which is rust's #1 priority to eliminate.

So, to recap:

✓ Every variable must have a type determinable at runtime (Including erased types, because those are concrete types too [dyn Trait and impl Trait], but impl Trait is special.)

✓ Every variable must be assigned some kind of value before you can read its value.

✓ Rust tries very hard to eliminate all undefined behavior.

Body:
I'm new to rust, and I'd like to declare a typed variable without initializing it. Is this possible in Rust? If so, is it advisable or are there better, more rustacean-y ways to do it?

I'm looking at the following code from rustlings which fails to compile because it can't infer the type of x:

    let x;
    if x == 10 {
        println!("Ten!");
    }

So, I tried this:

let x: i32;

however, now the compiler will throw an error on the comparison line saying that x hadn't been declared.

This works fine, but I was left wondering if one can declare the type without an assignment.

let x: i32 = 10;

Or is the correct way to do it involve designing your code to avoid such situations in the first place? I come from a C background and I'm probably a little too comfortable with being lazy with types.

Body:
In rust, the type of a variable is usually inferred from the context.

The context can include any of the following:

The type of the value being assigned:

let x = String::new(); //x is now a String

The return type of the function being called:

fn foo() -> usize {
    40
}
let x = foo(); //x is now usize

But if you don't have a type to infer, as in there is no assignment to the variable:

let x;

Then rust cannot infer the type. Therefore, it will get mad at you.

Another problem that needs to be addressed in this answer; the fact that rust doesn't allow the reading of uninitialized variables. The following value, x is uninitialized:

let x: u32;

Reading the value of an uninitialized u32 probably wouldn't do too much, but consider the following:

struct MyString {
    ptr: *const u8,
    len: usize,
    cap: usize,
}

If we were to provide a safe wrapper around this, this would be perfectly fine, after all, this is essentially what the stdlib String boils down to. But, if we were to own an uninitialized MyString and tried to read its contents, we'd end up reading a garbage address from the ptr, and a garbage len and cap. This would lead to reading a garbage pointer, which is undefined behavior, which is rust's #1 priority to eliminate.

So, to recap:

✓ Every variable must have a type determinable at runtime (Including erased types, because those are concrete types too [dyn Trait and impl Trait], but impl Trait is special.)

✓ Every variable must be assigned some kind of value before you can read its value.

✓ Rust tries very hard to eliminate all undefined behavior.


问:
traverse.clearCache is not a function
in https://babeljs.io/ when i want to compile my ES6 code, this error will be shown:

```<code>traverse.clearCache is not a function
</code>```

My code is a simple code like:
let i = 1;

```<code>console.log(i)
</code>```

答: you can untick Minify in the left.it will work.</p>

Title: traverse.clearCache is not a function

Body:
in https://babeljs.io/ when i want to compile my ES6 code, this error will be shown:

traverse.clearCache is not a function

My code is a simple code like:
let i = 1;

console.log(i)


问:
Convert bytes to a string
I captured the standard output of an external program into a bytes object:

>>> from subprocess import *
>>> command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0]
>>>
>>> command_stdout
b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file2\n'
```
<p>I want to convert that to a normal Python string, so that I can print it like this:</p>
<pre class="lang-none prettyprint-override"><code>>>> print(command_stdout)
-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file1
-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file2
</code>```

How do I convert the bytes object to a str with Python 3?

See Best way to convert string to bytes in Python 3? for the other way around.

答:
If you want to convert any bytes, not just string converted to bytes:

```<code>with open("bytesfile", "rb") as infile:
    str = base64.b85encode(imageFile.read())

with open("bytesfile", "rb") as infile:
    str2 = json.dumps(list(infile.read()))
</code>```

This is not very efficient, however. It will turn a 2 MB picture into 9 MB.

OwnerDisplayName: Tomas Sedovic

Title: Convert bytes to a string

Body:
I captured the standard output of an external program into a bytes object:

>>> from subprocess import *
>>> command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0]
>>>
>>> command_stdout
b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file2\n'

I want to convert that to a normal Python string, so that I can print it like this:

>>> print(command_stdout)
-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file1
-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file2

How do I convert the bytes object to a str with Python 3?

See Best way to convert string to bytes in Python 3? for the other way around.

LastEditorDisplayName: J.F. Sebastian

Body:
If you want to convert any bytes, not just string converted to bytes:

with open("bytesfile", "rb") as infile:
    str = base64.b85encode(imageFile.read())

with open("bytesfile", "rb") as infile:
    str2 = json.dumps(list(infile.read()))

This is not very efficient, however. It will turn a 2 MB picture into 9 MB.


问:
Running mpirun with 2 cores/4 threads
I am using mpirun to call an openMDAO code that uses a parallel group which contains 4 subsystems. I can successfully call the code from the terminal as follows.

```<code>mpirun -n 2 python modified_objective.py
</code>```

However since my pc has 2 cores/ 4 threads, I want to use all 4 threads to speed up my code. But i get an error as follows:

There are not enough slots available in the system to satisfy the 4 slots
  that were requested by the application:
    python .
    Either request fewer slots for your application, or make more slots
    available for use.

One of the work around I found online is to use a text rankfile as follows:

```<code>rank 0=localhost slot=0:0
rank 1=localhost slot=0:0
rank 2=localhost slot=0:1
rank 3=localhost slot=0:1
</code>```

and then call the code as follows:

```<code>mpiexec -np 4 -H localhost -rf rankfile python modified_objective.py
</code>```

But this does not seem to work. Is there another way I can use all 4 cores?

Thank you

答:
The solution depends on the specific MPI implementation you have. Its not an OpenMDAO problem at all, but rather a problem with your MPI library. You seem to have seen that already, because you're trying to provide a host file.

I think you just have the wrong option though. Try:

```<code>mpiexec -np 4 -H localhost --hostfile rankfile python modified_objective.py
</code>```

Title: Running mpirun with 2 cores/4 threads

Body:
I am using mpirun to call an openMDAO code that uses a parallel group which contains 4 subsystems. I can successfully call the code from the terminal as follows.

mpirun -n 2 python modified_objective.py

However since my pc has 2 cores/ 4 threads, I want to use all 4 threads to speed up my code. But i get an error as follows:

There are not enough slots available in the system to satisfy the 4 slots
  that were requested by the application:
    python .
    Either request fewer slots for your application, or make more slots
    available for use.

One of the work around I found online is to use a text rankfile as follows:

rank 0=localhost slot=0:0
rank 1=localhost slot=0:0
rank 2=localhost slot=0:1
rank 3=localhost slot=0:1

and then call the code as follows:

mpiexec -np 4 -H localhost -rf rankfile python modified_objective.py

But this does not seem to work. Is there another way I can use all 4 cores?

Thank you

Body:
The solution depends on the specific MPI implementation you have. Its not an OpenMDAO problem at all, but rather a problem with your MPI library. You seem to have seen that already, because you're trying to provide a host file.

I think you just have the wrong option though. Try:

mpiexec -np 4 -H localhost --hostfile rankfile python modified_objective.py


问:
Using JAX-WS: How can I set the user agent property
I've searched on this and found a few near misses.  I've created a java client to consume a web service using JAX-WS.  Is there a way when using JAX to set the HTTP_USER_AGENT value?  I would like to have my web service log when specific clients (mine) access it so I wanted a customized value.

I've seen options where you set it in the system properties but this doesn't seem to work.  The generated JAX classes don't seem to have a direct reference to the connection object so I don't see how I can manipulate those classes.

Any help would be great.
Thanks
ST

答:
Let me question the idea of having HTTP header first.

A more correct (WS-centric) approach is to set SOAP Header, not HTTP header. Consider this: SOAP messages can be delivered not only by HTTP, but by JMS, SMTP or custom transports. By requiring to have user-agent HTTP Header, you unnecessary tie you code to only one transport, albeit currently prevailing.

This is the reason BTW why JAX-WS have no notion of HTTP headers except in handlers.

And (of course) StackOverlow knows how to create SOAP headers.


问:
IOError happened while use requests-html to render a javascript page
I was trying to use the new liberary request-html.
But when i use the render() function to parse a javascript page, it always pop up with the notes as below:

Error in atexit._run_exitfuncs: Traceback (most recent call last):

  File "C:\Program Files
  (x86)\Python36-32\lib\site-packages\pyppeteer\launcher.py", line 201,
  in killChrome
      self._cleanup_tmp_user_data_dir()   File "C:\Program Files (x86)\Python36-32\lib\site-packages\pyppeteer\launcher.py", line 130,
  in _cleanup_tmp_user_data_dir
      raise IOError('Unable to remove Temporary User Data') OSError: Unable to remove Temporary User Data

I tried to solve the problems, but it seems that there is no solution right now. So i kind of hope someone here can help me.

PS: it seems that i can not post it with the tag:requests-html, i do not have enought repution. So, very sorry for that.

答:
Modify the connection.py file

pyppeteer/connection.py

@@ -41,7 +41,7 @@ def init(self, url: str, loop: asyncio.AbstractEventLoop,

```<code>    self.connection: CDPSession
    self._connected = False
    self._ws = websockets.client.connect(
        self._url, max_size=None, loop=self._loop)
        self._url, max_size=None, loop=self._loop, ping_interval=None, ping_timeout=None)
    self._recv_fut = self._loop.create_task(self._recv_loop())
    self._closeCallback: Optional[Callable[[], None]] = None
</code>```

Body:
Modify the connection.py file

pyppeteer/connection.py

@@ -41,7 +41,7 @@ def init(self, url: str, loop: asyncio.AbstractEventLoop,

    self.connection: CDPSession
    self._connected = False
    self._ws = websockets.client.connect(
        self._url, max_size=None, loop=self._loop)
        self._url, max_size=None, loop=self._loop, ping_interval=None, ping_timeout=None)
    self._recv_fut = self._loop.create_task(self._recv_loop())
    self._closeCallback: Optional[Callable[[], None]] = None


问:
Can I remove whitespace from all column names with dplyr?
Multiple column names of a CSV have whitespace in them. I'd like to remove the whitespace from these column names with a single dplyr command.

I've tried:

```<code>mpg %>%
  rename("tr ans" = trans, "mo del" = model) %>%
  rename_if(everything(), contains(" "), str_replace_all(" ", ""))
</code>```

I'd expect to produce the original mpg dataframe, with the whitespaces that I inserted in the second line removed, but I get an error:

```<code>Error: Empty pattern not supported
</code>```

答:
Why not just use sub:

```<code>names(mpg) <- gsub("\\s+", "", names(mpg))
</code>```

Body:
Multiple column names of a CSV have whitespace in them. I'd like to remove the whitespace from these column names with a single dplyr command.

I've tried:

mpg %>%
  rename("tr ans" = trans, "mo del" = model) %>%
  rename_if(everything(), contains(" "), str_replace_all(" ", ""))

I'd expect to produce the original mpg dataframe, with the whitespaces that I inserted in the second line removed, but I get an error:

Error: Empty pattern not supported

Body:
Why not just use sub:

names(mpg) <- gsub("\\s+", "", names(mpg))


问:
Why is snap.data().id not defined?
I can't seem to get the id of the document I'm trying to retrieve.

I have looked at a lot of examples on the web and they all seem to be doing exactly what i'm doing.

```<code>exports.moveToProfile = functions.firestore
  .document("tempProfiles/{id}")
  .onCreate(async (snap, context) => {
    const id = snap.data().id;
    const displayName = snap.data().displayName;

    const profile = await db
      .collection("profiles")
      .doc(id)
      .set({
        displayName: displayName,
        points: 0
      });

    return profile;
  });
</code>```

答: In your code, data is a DocumentSnapshot type object.  As you can see from the linked API documentation, the ID of the document represented by that object is its id property.  data() gives you all of its fields (and the formal doucment ID is not one of them, unless you wrote it as a field.)  So, you can get the ID with data.id.

Title: Why is snap.data().id not defined?

Body:
I can't seem to get the id of the document I'm trying to retrieve.

I have looked at a lot of examples on the web and they all seem to be doing exactly what i'm doing.

exports.moveToProfile = functions.firestore
  .document("tempProfiles/{id}")
  .onCreate(async (snap, context) => {
    const id = snap.data().id;
    const displayName = snap.data().displayName;

    const profile = await db
      .collection("profiles")
      .doc(id)
      .set({
        displayName: displayName,
        points: 0
      });

    return profile;
  });


问:
how to save the index and title of a segmented control in core data
I have a dozen segmented controls. I save the selected index for each one in Core Data. My entity is called Worksheet and each index is saved as an Int. That part works great.

The problem is that I want to display the selected titles in a different view. But I obviously can't just grab the index from Core Data. My new view has no idea what those numbers stand for. I know that CoreData can't save tuples, though, that would make things much easier.

I have tried creating a transformable attribute, and a custom managed object, but the first won't work for tuples, and I can't seem to wrap my head around the second. The title and the index don't seem like they should be separated.

答:
Create a enum for every SegmentedControls with CaseIterable

```<code>enum Planet: String, CustomStringConvertible, CaseIterable {
    case mercury, venus, earth, mars, jupiter, saturn, uranus, neptune
    var description: String {
        return self.rawValue.capitalized
    }
}
</code>```

And use the Planet.allCases array to create the segments for the segmented control

```<code>let segmentedControl = UISegmentedControl(items: Planet.allCases)
</code>```

or

```<code>Planet.allCases.enumerated().forEach {
    segmentedControl.insertSegment(withTitle: $1, at: $0, animated: true)
}
</code>```

When selection changed in the segment control save the selected index in core data.

```<code>@objc func indexChanged(_ sender: UISegmentedControl) {
    print(Planet.allCases[sender.selectedSegmentIndex])
    //save sender.selectedSegmentIndex in core data
}
</code>```

When you want to display the selected titles in a different view, get selected indexes from core data. And get the corresponding string value from the Enum.allCases array

```<code>let selectedPlanetIndex = 5//Index fetched from core data
let selectedPlanetTitle = Planet.allCases[selectedPlanetIndex]//saturn
</code>```

Body:
Create a enum for every SegmentedControls with CaseIterable

enum Planet: String, CustomStringConvertible, CaseIterable {
    case mercury, venus, earth, mars, jupiter, saturn, uranus, neptune
    var description: String {
        return self.rawValue.capitalized
    }
}

And use the Planet.allCases array to create the segments for the segmented control

let segmentedControl = UISegmentedControl(items: Planet.allCases)

or

Planet.allCases.enumerated().forEach {
    segmentedControl.insertSegment(withTitle: $1, at: $0, animated: true)
}

When selection changed in the segment control save the selected index in core data.

@objc func indexChanged(_ sender: UISegmentedControl) {
    print(Planet.allCases[sender.selectedSegmentIndex])
    //save sender.selectedSegmentIndex in core data
}

When you want to display the selected titles in a different view, get selected indexes from core data. And get the corresponding string value from the Enum.allCases array

let selectedPlanetIndex = 5//Index fetched from core data
let selectedPlanetTitle = Planet.allCases[selectedPlanetIndex]//saturn


问:
Indicators constraints (object of type 'generator' has no len())
I'm working in a VRP optimization problem based in a tutorial.
When I add the subtours constraint I get an error.
I was following this tutorial: https://www.youtube.com/watch?v=eMsqsmftWOQ&t=2398s

from docplex.mp.model import Model
mdl = Model('CVRP')

x = mdl.binary_var_dict(arcos, name = 'x')
u = mdl.continuous_var_dict(nodos, ub = Q, name = 'u')
mdl.minimize(mdl.sum(distancia[i,j]*x[i,j] for i,j in arcos))
mdl.add_constraints(mdl.sum(x[i,j] for j in nodos if i!= j) == 1 for i in clientes)
mdl.add_constraints(mdl.sum(x[i,j] for i in nodos if i!= j) == 1 for j in clientes)
mdl.add_indicator_constraints(mdl.indicator_constraint(x[i,j],u[i]+q[j]==u[j]) for i,j in arcos if i!=0 and j!= 0) #This is the line
```

<p>Context:</p>

<pre class="lang-py prettyprint-override"><code>clientes = [x for x in range(1, n+1)]
nodos = [0]+clientes
arcos = {(i,j) for i in nodos for j in nodos if i != j}
Q = 15
</code>```

The error list is:

```<code>C:\Users\Jose Godoy\PycharmProjects\Huevos hermanos\venv\lib\site-packages\docplex\mp\__init__.py:35: RuntimeWarning: docplex is not officially supported on 32 bits. Use it at your own risk.
  warnings.warn("docplex is not officially supported on 32 bits. Use it at your own risk.", RuntimeWarning)
Traceback (most recent call last):

 File "C:/Users/Jose Godoy/PycharmProjects/Huevos hermanos/VRP.py", line 41, in <module>
    mdl.add_indicator_constraints(mdl.indicator_constraint(x[i,j],u[i]+q[j]==u[j]) for i,j in arcos if i!=0 and j!= 0)

File "C:\Users\Jose Godoy\PycharmProjects\Huevos hermanos\venv\lib\site-packages\docplex\mp\model.py", line 3014, in add_indicator_constraints
    ind_indices = self.__engine.create_batch_indicator_constraints(indcts)

  File "C:\Users\Jose Godoy\PycharmProjects\Huevos hermanos\venv\lib\site-packages\docplex\mp\engine.py", line 465, in create_batch_indicator_constraints
    return self.create_batch_cts(indicators)

  File "C:\Users\Jose Godoy\PycharmProjects\Huevos hermanos\venv\lib\site-packages\docplex\mp\engine.py", line 449, in create_batch_cts
    self._increment_cts(len(ct_seq))
TypeError: object of type 'generator' has no len()
</code>```

I think the syntax of the formulation is ok, is the same as the tutorial, so I think is a problem in the library because I get a warning message

```<code>RuntimeWarning: docplex is not officially supported on 32 bits. Use it at your own risk.
  warnings.warn("docplex is not officially supported on 32 bits. Use it at your own risk.", RuntimeWarning)
</code>```

Do you know how can I fix it?

答:
I resolved this.
I added a

```<code>[]
</code>```

So this work for me:

```<code>mdl.add_indicator_constraints(mdl.indicator_constraint([x[i,j],u[i]+q[j]==u[j]) for i,j in arcos if i!=0 and j!= 0]) #This is the line
</code>```

Body:
I'm working in a VRP optimization problem based in a tutorial.
When I add the subtours constraint I get an error.
I was following this tutorial: https://www.youtube.com/watch?v=eMsqsmftWOQ&t=2398s

from docplex.mp.model import Model
mdl = Model('CVRP')

x = mdl.binary_var_dict(arcos, name = 'x')
u = mdl.continuous_var_dict(nodos, ub = Q, name = 'u')
mdl.minimize(mdl.sum(distancia[i,j]*x[i,j] for i,j in arcos))
mdl.add_constraints(mdl.sum(x[i,j] for j in nodos if i!= j) == 1 for i in clientes)
mdl.add_constraints(mdl.sum(x[i,j] for i in nodos if i!= j) == 1 for j in clientes)
mdl.add_indicator_constraints(mdl.indicator_constraint(x[i,j],u[i]+q[j]==u[j]) for i,j in arcos if i!=0 and j!= 0) #This is the line

Context:

clientes = [x for x in range(1, n+1)]
nodos = [0]+clientes
arcos = {(i,j) for i in nodos for j in nodos if i != j}
Q = 15

The error list is:

C:\Users\Jose Godoy\PycharmProjects\Huevos hermanos\venv\lib\site-packages\docplex\mp\__init__.py:35: RuntimeWarning: docplex is not officially supported on 32 bits. Use it at your own risk.
  warnings.warn("docplex is not officially supported on 32 bits. Use it at your own risk.", RuntimeWarning)
Traceback (most recent call last):

 File "C:/Users/Jose Godoy/PycharmProjects/Huevos hermanos/VRP.py", line 41, in <module>
    mdl.add_indicator_constraints(mdl.indicator_constraint(x[i,j],u[i]+q[j]==u[j]) for i,j in arcos if i!=0 and j!= 0)

File "C:\Users\Jose Godoy\PycharmProjects\Huevos hermanos\venv\lib\site-packages\docplex\mp\model.py", line 3014, in add_indicator_constraints
    ind_indices = self.__engine.create_batch_indicator_constraints(indcts)

  File "C:\Users\Jose Godoy\PycharmProjects\Huevos hermanos\venv\lib\site-packages\docplex\mp\engine.py", line 465, in create_batch_indicator_constraints
    return self.create_batch_cts(indicators)

  File "C:\Users\Jose Godoy\PycharmProjects\Huevos hermanos\venv\lib\site-packages\docplex\mp\engine.py", line 449, in create_batch_cts
    self._increment_cts(len(ct_seq))
TypeError: object of type 'generator' has no len()

I think the syntax of the formulation is ok, is the same as the tutorial, so I think is a problem in the library because I get a warning message

RuntimeWarning: docplex is not officially supported on 32 bits. Use it at your own risk.
  warnings.warn("docplex is not officially supported on 32 bits. Use it at your own risk.", RuntimeWarning)

Do you know how can I fix it?

Body:
I resolved this.
I added a

[]

So this work for me:

mdl.add_indicator_constraints(mdl.indicator_constraint([x[i,j],u[i]+q[j]==u[j]) for i,j in arcos if i!=0 and j!= 0]) #This is the line


问:
How to add attributes from variables with a for loop?
So I'm a beginner with python, this is like my 3rd day learning it so I'm sorry if this is too obvious for you.

I'm creating a class called Users() that takes first_name, last_name, user_name and password as arguments and I wan't to assign their values to self with a for loop

I'm first defining __init_ with self and the parameters, and then a for loop that it's like this:

```<code>  def __init__(self, name, lastName, user, password):
   for i in self:
    self.i = i
</code>```

so I don't have to do this

```<code>def __init__(self, name, lastName, user, password):
 self.name     = name
 self.lastName = lastName
 self.user     = user
 self.password = password
</code>```

But it's not working

I get this error:
for i in self:
TypeError: 'Users' object is not iterable

How can I make this work?

答:
As a beginner (and even more as an expert), you should do things in the simplest way. Use the second form:

```<code>def __init__(self, name, lastName, user, password):
    self.name     = name
    self.lastName = lastName
    self.user     = user
    self.password = password
</code>```

That said, Python3.7 introduced dataclasses. So if you're in a hurry to define a class you could do it this way (untested, might have a typo):

```<code>import dataclasses

@dataclasses.dataclass()
class User():
    first_name: str
    last_name: str
    username: str
    password: str

u = User('Bob', 'Marley', 'bm', 'bob')

print(u)
</code>```

Body:
So I'm a beginner with python, this is like my 3rd day learning it so I'm sorry if this is too obvious for you.

I'm creating a class called Users() that takes first_name, last_name, user_name and password as arguments and I wan't to assign their values to self with a for loop

I'm first defining __init_ with self and the parameters, and then a for loop that it's like this:

  def __init__(self, name, lastName, user, password):
   for i in self:
    self.i = i

so I don't have to do this

def __init__(self, name, lastName, user, password):
 self.name     = name
 self.lastName = lastName
 self.user     = user
 self.password = password

But it's not working

I get this error:
for i in self:
TypeError: 'Users' object is not iterable

How can I make this work?

Body:
As a beginner (and even more as an expert), you should do things in the simplest way. Use the second form:

def __init__(self, name, lastName, user, password):
    self.name     = name
    self.lastName = lastName
    self.user     = user
    self.password = password

That said, Python3.7 introduced dataclasses. So if you're in a hurry to define a class you could do it this way (untested, might have a typo):

import dataclasses

@dataclasses.dataclass()
class User():
    first_name: str
    last_name: str
    username: str
    password: str

u = User('Bob', 'Marley', 'bm', 'bob')

print(u)


问:
optimization flag e.g. /O2 = optimize at File / Project / or Solution level?
I have some visual-studio projects :-

B1 (no optimization)

B2 (optimization /O2) : use B1 as static library

B3 (no optimization) : use B1 and B2 as static library

What is the optimization effect on B3/main.cpp?

Would B3 here be compiled faster (and .exe has worse performance) than a case that B3 also /O2 ?

I play with /O2 many times, but still confuse about the results.

I feel that the flag is project-level.

If I expect to not modify B2 often but modify B3 often , it may be better for performance & minimum compile time to set B2 = /O2 & B3 = no optimization. (?)

Sorry if it is a newbie question.  I reluctant to ask it for a few years.

Official reference (useless) : https://learn.microsoft.com/en-us/cpp/build/reference/o1-o2-minimize-size-maximize-speed?view=vs-2019

答:
/O2 is project level flag.

For your project B3 it does not matter optimization levels of libraries being used (B1 and B2). As long as the ABI is the same you can use libraries of different optimizations as mentioned in this answer.

Now let's answer your questions.

Would B3 here be compiled faster (and .exe has worse performance) than a case that B3 also /O2 ?

Optimization flag is about speed and size of binary and not about compilation time. B3 executable will be faster if you specify /O2 to B3

If I expect to not modify B2 often but modify B3 often , it may be
  better for performance & minimum compile time to set B2 = /O2 & B3 =
  no optimization. (?)

Again, optimization flag is not used to reduce compile time. For better performance (speed) of B3 executable compile it with /O2


问:
qtcreator examples not enabled
I installed qtcreator on a Ubuntu 11.10

```<code>sudo apt-get install qtcreator
</code>```

the versions installed are:  QT Creator 2.2.1, QT 4.7.3

When i start qtcreator, to explore QT C++ examples the button is greyed out/disabled and it says Examples not installed.

Neither does qtdemo show any demo/documentation?

Do i have to install examples, doc  separately? If yes, how?

How can i enable examples in qtcreator and documentation in qtdemo?

EDIT:
In response to one answer below from @Murtuza Kabul, I tried many things to point qtcreator to correct qt but could not. So  I did uninstall qtcreator and qt-sdk and reinstalled qt-sdk. So now qtcreator is what comes with qt-sdk . It still says examples not installed.

答:
I had the same problem on Windows 7.
How I solved this:

I open QT Creator.

I select menu-option [Tools]

From there I select [Options...]

From there I select the [Kits] option on the left-hand side

I select the tab [QT Versions]

I click The [Add...] button: to add the QT version that I am using...
... I am presented with a windows-explorer screen to select something...
... I go to the main directory on which QT is installed (in my case: C:\Qt)...
... In the explorer "Search" I enter qmake (without the quotes)...
... There is a single qmake EXECUTABLE file displayed - I double-click it!...
... I press [Apply], then [OK].

Walla - it works! I now have examples!

Title: qtcreator examples not enabled

Body:
I installed qtcreator on a Ubuntu 11.10

sudo apt-get install qtcreator

the versions installed are:  QT Creator 2.2.1, QT 4.7.3

When i start qtcreator, to explore QT C++ examples the button is greyed out/disabled and it says Examples not installed.

Neither does qtdemo show any demo/documentation?

Do i have to install examples, doc  separately? If yes, how?

How can i enable examples in qtcreator and documentation in qtdemo?

EDIT:
In response to one answer below from @Murtuza Kabul, I tried many things to point qtcreator to correct qt but could not. So  I did uninstall qtcreator and qt-sdk and reinstalled qt-sdk. So now qtcreator is what comes with qt-sdk . It still says examples not installed.


问:
TCP - difference between Congestion window and Receive window
I try to understand the difference between Congestion window and Receive window.

As I understand, the receiver window is a buffer where the receiver can get the packets. The same is with the Congestion window which tell us the bound of the Receiver's abilities, and change according to lost packets, etc.

So what is the diffrence between them?

答: Initially, CongWindow is set equal to one packet. It then sends the first packet into the network and waits for an acknowledgment. If the acknowledgment for this packet arrives before the timer runs out, the sender increases CongWindow by one packet and sends out two packets. Once all of these packets are acknowledged before their timeouts, CongWindow is increased by two—one for each of the acknowledged segments. Now the size of CongWindow is four packets, and thus, the sender transmits four packets. Such an exponential increase continues as long as the size of CongWindow is below the threshold and acknowledgments are received before their corresponding timeouts expire.One important difference is that CongWindow changes in size but receive window size is always constant. </p>


问:
Creating a “method” method on an object
Can someone explain me how they are creating a "method" method on an object.</p>

```<code>var foo = {};

foo.method = function(name, cb){
  this[name] = cb;
};
</code>```

答:
They're assigning the key method to a function - that's a method. If you're wondering how the key method is used, it's because it's not a reserved keyword in JavaScript.

The actual method creates a new method with the provided name, and sets it to the cb. (This can also be used to make properties, not just methods).

var foo = {};

foo.method = function(name, cb) {
  this[name] = cb;
};

foo.method("sayHello", () => console.log("Hello!"));
foo.sayHello();```

Title: Creating a “method” method on an object

Body:
Can someone explain me how they are creating a "method" method on an object.

var foo = {};

foo.method = function(name, cb){
  this[name] = cb;
};


问:
How do I add permalinks to headers in kramdown?
I'm building a website with Jekyll and Github-Page written in markdown. I want to make it easy to permalink to headers, the way most online  documentation does.

I want to get a URL with a hash when I click on a header. Is there an easy way to achieve this in Kramdown or in Jekyll's config?

Markdown page

```<code>#### A regular header

A regular sentence.
</code>```

Ideal result

```<code><h4 id="a-regular-header"><a href="#a-regular-header">A regular header</a></h4>
<p>A regular sentence.</p>
</code>```

答:
If you want a GitHub Pages compatible way of doing this without JavaScript, you can get <s>crazy</s> creative with Liquid and carefully parse your rendered HTML as strings and manipulate it as such.

Or you could just use this snippet that does exactly that: https://github.com/allejo/jekyll-anchor-headings

Body:
I'm building a website with Jekyll and Github-Page written in markdown. I want to make it easy to permalink to headers, the way most online  documentation does.

I want to get a URL with a hash when I click on a header. Is there an easy way to achieve this in Kramdown or in Jekyll's config?

Markdown page

#### A regular header

A regular sentence.

Ideal result

A regular header

A regular sentence.


问:
Unable to drop existing master table in sql developer
I was using yeasterday many times Data Pump in Sql Developer Wizard to export and import data. After each export/import a new master table appeared under the "+" button in sql developer(view->dba).
I wanted to drop all this tables(about 10 tables) and I was successfull for all cases, except 2 of them. When I'm writing sql code: drop table x, it shows me error that this tables doesn't exists. It was working fine for every others tables..
When i run query select * from dba_tables where table_name='x' the table is there. I'm writing drop statement as system user.

```<code>  select *
      from dba_tables
     where table_name in ('moj_dump_job'
                        , 'moj_job_data_pump');

OWNER                          TABLE_NAME
------------------------------ ------------------------------
SYSTEM                         moj_dump_job
SYSTEM                         moj_job_data_pump

drop table moj_dump_job;

Error starting at line : 1 in command -
drop table moj_dump_job
Error report -
ORA-00942: table or view does not exist
00942. 00000 -  "table or view does not exist"
*Cause:
*Action:
</code>```

I tired to drop this jobs, but it doesnt't work:

```<code>select owner_name, job_name
  from DBA_DATAPUMP_JOBS;

OWNER_NAME                     JOB_NAME
------------------------------ ------------------------------
SYSTEM                         moj_job_data_pump
SYSTEM                         moj_dump_job

BEGIN
  dbms_scheduler.drop_job(job_name => 'moj_dump_job');
END;

Error starting at line : 13 in command -
BEGIN
  dbms_scheduler.drop_job(job_name => 'moj_dump_job');
END;
Error report -
ORA-27475: "SYSTEM.MOJ_DUMP_JOB" must be a job
ORA-06512: at "SYS.DBMS_ISCHED", line 213
ORA-06512: at "SYS.DBMS_SCHEDULER", line 657
ORA-06512: at line 2
27475. 00000 -  "unknown %s \"%s\".\"%s\""
*Cause:    The specified object did not exist, privileges were not granted,
           or the object was of the wrong type.
*Action:   Specify an object of the correct type on which you have privileges.
</code>```

Do you have any idea what can I do? Using schema name before table name doesn't help.
Best regards, Darek

答:
The reason it was not working cause by default Oracle changes job name to uppercase. To avoid it need use '"my_job"'

As per Oracle doc

Follow SQL naming rules to name Scheduler objects in the
  DBMS_SCHEDULER package. By default, Scheduler object names are
  uppercase unless they are surrounded by double quotes. For example,
  when creating a job, job_name => 'my_job' is the same as job_name =>
  'My_Job' and job_name => 'MY_JOB', but different from job_name =>
  '"my_job"'. These naming rules are also followed in those cases where
  comma-delimited lists of Scheduler object names are used within the
  DBMS_SCHEDULER package.

Body:
I was using yeasterday many times Data Pump in Sql Developer Wizard to export and import data. After each export/import a new master table appeared under the "+" button in sql developer(view->dba).
I wanted to drop all this tables(about 10 tables) and I was successfull for all cases, except 2 of them. When I'm writing sql code: drop table x, it shows me error that this tables doesn't exists. It was working fine for every others tables..
When i run query select * from dba_tables where table_name='x' the table is there. I'm writing drop statement as system user.

  select *
      from dba_tables
     where table_name in ('moj_dump_job'
                        , 'moj_job_data_pump');

OWNER                          TABLE_NAME
------------------------------ ------------------------------
SYSTEM                         moj_dump_job
SYSTEM                         moj_job_data_pump

drop table moj_dump_job;

Error starting at line : 1 in command -
drop table moj_dump_job
Error report -
ORA-00942: table or view does not exist
00942. 00000 -  "table or view does not exist"
*Cause:
*Action:

I tired to drop this jobs, but it doesnt't work:

select owner_name, job_name
  from DBA_DATAPUMP_JOBS;

OWNER_NAME                     JOB_NAME
------------------------------ ------------------------------
SYSTEM                         moj_job_data_pump
SYSTEM                         moj_dump_job

BEGIN
  dbms_scheduler.drop_job(job_name => 'moj_dump_job');
END;

Error starting at line : 13 in command -
BEGIN
  dbms_scheduler.drop_job(job_name => 'moj_dump_job');
END;
Error report -
ORA-27475: "SYSTEM.MOJ_DUMP_JOB" must be a job
ORA-06512: at "SYS.DBMS_ISCHED", line 213
ORA-06512: at "SYS.DBMS_SCHEDULER", line 657
ORA-06512: at line 2
27475. 00000 -  "unknown %s \"%s\".\"%s\""
*Cause:    The specified object did not exist, privileges were not granted,
           or the object was of the wrong type.
*Action:   Specify an object of the correct type on which you have privileges.

Do you have any idea what can I do? Using schema name before table name doesn't help.
Best regards, Darek


问:
Prevent GroovyDefaultMethods join() from shadowing join() method of Java class?
I'm trying to use a Java library in Groovy, but Groovy is overriding one of the methods name join with its own method.

The following code fails:

```<code>%%classpath add mvn
tech.tablesaw tablesaw-core 0.32.6
tech.tablesaw tablesaw-beakerx 0.32.6
com.jimmoores quandl-tablesaw 2.0.0

%import com.jimmoores.quandl.*
%import com.jimmoores.quandl.tablesaw.*
%import tech.tablesaw.api.*

// display Tablesaw tables with BeakerX table display widget
tech.tablesaw.beakerx.TablesawDisplayer.register()

TableSawQuandlSession session = TableSawQuandlSession.create();
Table table1 = session.getDataSet(DataSetRequest.Builder.of("FRED/BCNSDODNS").build());
table1.column("Value").setName("Corporate Credit");
Table table2 = session.getDataSet(DataSetRequest.Builder.of("FRED/CMDEBT").build());
table2.column("Value").setName("Household Credit");
Table result = table1.join("Date").inner(table2, "Date");
</code>```

The error is:

groovy.lang.MissingMethodException: No signature of method: java.lang.String.inner() is applicable for argument types: (tech.tablesaw.api.Table, java.lang.String)

This is strange Table.join(String) returns a DataFrameJoiner: https://static.javadoc.io/tech.tablesaw/tablesaw-core/0.32.6/tech/tablesaw/api/Table.html#join-java.lang.String...-

I think what's happening is that Table is an Iterable<Row> so maybe Groovy is picking up its own join method.

Where it gets really strange is that it works if I switch the Tablesaw version from 0.32.6 to 0.24.9 even though Table also implements Iterable<Row> in that version

Any idea how I can force Groovy to use the join method from the Tablesaw library instead of its own join method?

答:
As per the other answer, this special case can be solved by using explicit typing in the method call. Here is just some more background information on the general topic of GroovyDefaultMethod overriding.

The documentation on this is scarce. Some old email threads relate to these methods coming from DefaultGroovyMethods:

how do methods in DefaultGroovyMethods get applied?

so when we create the ArrayList meta class, we inspect the
  ArrayList class, grab all the methods from it and make our meta methods
  out of it. Then we get the DGM methods list and apply all the methods in
  their depending on inheritance..."

This may explain why you get different results with different Tablesaw versions, depending on the exact inheritance details from Iterable.

Override a method from DefaultGroovyMethods

If you want to do it for the duration of the script, you can use the
  per-instance metaClass to do:

```<code> this.metaClass.println = { Object value ->
      System.out.println "woo $value"
 }
</code>```

From that I believe you can modify the Metaclass of Table to use the method you want to use. Since application of DefaultGroovyMethods also depends in inheritance details, you might also try subclassing Table.

The metaprogramming docs might also help.

Body:
I'm trying to use a Java library in Groovy, but Groovy is overriding one of the methods name join with its own method.

The following code fails:

%%classpath add mvn
tech.tablesaw tablesaw-core 0.32.6
tech.tablesaw tablesaw-beakerx 0.32.6
com.jimmoores quandl-tablesaw 2.0.0

%import com.jimmoores.quandl.*
%import com.jimmoores.quandl.tablesaw.*
%import tech.tablesaw.api.*

// display Tablesaw tables with BeakerX table display widget
tech.tablesaw.beakerx.TablesawDisplayer.register()

TableSawQuandlSession session = TableSawQuandlSession.create();
Table table1 = session.getDataSet(DataSetRequest.Builder.of("FRED/BCNSDODNS").build());
table1.column("Value").setName("Corporate Credit");
Table table2 = session.getDataSet(DataSetRequest.Builder.of("FRED/CMDEBT").build());
table2.column("Value").setName("Household Credit");
Table result = table1.join("Date").inner(table2, "Date");

The error is:

groovy.lang.MissingMethodException: No signature of method: java.lang.String.inner() is applicable for argument types: (tech.tablesaw.api.Table, java.lang.String)

This is strange Table.join(String) returns a DataFrameJoiner: https://static.javadoc.io/tech.tablesaw/tablesaw-core/0.32.6/tech/tablesaw/api/Table.html#join-java.lang.String...-

I think what's happening is that Table is an Iterable<Row> so maybe Groovy is picking up its own join method.

Where it gets really strange is that it works if I switch the Tablesaw version from 0.32.6 to 0.24.9 even though Table also implements Iterable<Row> in that version

Any idea how I can force Groovy to use the join method from the Tablesaw library instead of its own join method?

Body:
As per the other answer, this special case can be solved by using explicit typing in the method call. Here is just some more background information on the general topic of GroovyDefaultMethod overriding.

The documentation on this is scarce. Some old email threads relate to these methods coming from DefaultGroovyMethods:

how do methods in DefaultGroovyMethods get applied?

so when we create the ArrayList meta class, we inspect the
  ArrayList class, grab all the methods from it and make our meta methods
  out of it. Then we get the DGM methods list and apply all the methods in
  their depending on inheritance..."

This may explain why you get different results with different Tablesaw versions, depending on the exact inheritance details from Iterable.

Override a method from DefaultGroovyMethods

If you want to do it for the duration of the script, you can use the
  per-instance metaClass to do:

 this.metaClass.println = { Object value ->
      System.out.println "woo $value"
 }

From that I believe you can modify the Metaclass of Table to use the method you want to use. Since application of DefaultGroovyMethods also depends in inheritance details, you might also try subclassing Table.

The metaprogramming docs might also help.


答:
As @camille metions you can use rename_all

```<code>library(tidyverse)

mpg %>%
  rename("tr ans" = trans, "mo del" = model) %>%
  rename_all(~str_replace_all(., "\\s+", ""))
</code>```

Or rename_at with everything()

```<code>mpg %>%
  rename("tr ans" = trans, "mo del" = model) %>%
  rename_at(vars(everything()), ~str_replace_all(., "\\s+", ""))
</code>```

Title: Can I remove whitespace from all column names with dplyr?

Body:
As @camille metions you can use rename_all

library(tidyverse)

mpg %>%
  rename("tr ans" = trans, "mo del" = model) %>%
  rename_all(~str_replace_all(., "\\s+", ""))

Or rename_at with everything()

mpg %>%
  rename("tr ans" = trans, "mo del" = model) %>%
  rename_at(vars(everything()), ~str_replace_all(., "\\s+", ""))


问:
Creating vector of vectors (2D array) inside a class - Error:C++ requires a type specifier for all declarations
So I have procedurally programmed a way to integrate equations using the Runge-Kutta 4(RK4) method in C++. I am currently trying to create an RK4 class to add more functionality to my program. However, when I set up my 2D arrays in the class, I receive the "C++ requires a type specifier for all declarations" error, that I didn't receive in the original program.

At first, I was using namespace std;, however I came across an answer that said that that was bad programming practice, so I erased that line and called std::vector instead. I also made sure to include the vector library, to no avail.

```<code>#include <iostream>
#include <stdio.h>
#include <math.h>
#include <vector>

class RK4 {
public:
    RK4(double x_i, double y_i, double z_i, double vx_i, double vy_i, double vz_i);
    //time-related stuff
    double dt = 0.01;
    int numtimes = 1000;

    int numvar = 3;
    double mu = 398589590898200.0;

    //setting up variables
    std::vector<vector<double> > position(numtimes,vector<double>(numvar));
    std::vector<vector<double> > velocity(numtimes,vector<double>(numvar));
    std::vector<vector<double> > rk1(numtimes,vector<double>(numvar));
    std::vector<vector<double> > rk2(numtimes,vector<double>(numvar));
    std::vector<vector<double> > rk3(numtimes,vector<double>(numvar));
    std::vector<vector<double> > rk4(numtimes,vector<double>(numvar));
    std::vector<vector<double> > vk1(numtimes,vector<double>(numvar));
    std::vector<vector<double> > vk2(numtimes,vector<double>(numvar));
    std::vector<vector<double> > vk3(numtimes,vector<double>(numvar));
    std::vector<vector<double> > vk4(numtimes,vector<double>(numvar));
</code>```

This is how I constructed the code in my original program, with no problem:

```<code>#include <iostream>
#include <ostream>
#include <cmath>
#include <vector>

using namespace std;

int main(){
// time related things
    //double t_i = 0; // initial time
    double dt = 0.01; // time step
    int numtimes = 10000; // how many steps taken

    vector<vector<double> > position(numtimes,vector<double>(numvar));
    vector<vector<double> > velocity(numtimes,vector<double>(numvar));

    vector<vector<double> > rk1(numtimes,vector<double>(numvar));
    vector<vector<double> > rk2(numtimes,vector<double>(numvar));
    vector<vector<double> > rk3(numtimes,vector<double>(numvar));
    vector<vector<double> > rk4(numtimes,vector<double>(numvar));
    vector<vector<double> > vk1(numtimes,vector<double>(numvar));
    vector<vector<double> > vk2(numtimes,vector<double>(numvar));
    vector<vector<double> > vk3(numtimes,vector<double>(numvar));
    vector<vector<double> > vk4(numtimes,vector<double>(numvar));
}

</code>```

I'm not quite sure why this call worked in my original(procedural) program, but not in my current program.

答:
In a function, you can use parenthesis to pass parameters to the constructor for a variable.  This does not work when specifying default values for member variables.  You have to use uniform initialization.

```<code> std::vector<std::vector<double>> position{numtimes, std::vector<double>(numvar)};
</code>```

This syntax - using curly braces - also works for when declaring variables, and you can use that same line in main to declare the position variable.

One other thing you get with uniform initialization is stronger type safety.  You can't specify a number that won't fit where you're trying to store it.  Where that is an issue in your code is that numtimes is an int, but the first parameter to the constructor for vector is a size_t - some form of unsigned.  So you'll need to change the declaration for numtimes to

```<code>unsigned numtimes = 10000;
</code>```

Note also that you need to put std:: in front of all the vector usages.

Body:
So I have procedurally programmed a way to integrate equations using the Runge-Kutta 4(RK4) method in C++. I am currently trying to create an RK4 class to add more functionality to my program. However, when I set up my 2D arrays in the class, I receive the "C++ requires a type specifier for all declarations" error, that I didn't receive in the original program.

At first, I was using namespace std;, however I came across an answer that said that that was bad programming practice, so I erased that line and called std::vector instead. I also made sure to include the vector library, to no avail.

#include <iostream>
#include <stdio.h>
#include <math.h>
#include <vector>

class RK4 {
public:
    RK4(double x_i, double y_i, double z_i, double vx_i, double vy_i, double vz_i);
    //time-related stuff
    double dt = 0.01;
    int numtimes = 1000;

    int numvar = 3;
    double mu = 398589590898200.0;

    //setting up variables
    std::vector<vector<double> > position(numtimes,vector<double>(numvar));
    std::vector<vector<double> > velocity(numtimes,vector<double>(numvar));
    std::vector<vector<double> > rk1(numtimes,vector<double>(numvar));
    std::vector<vector<double> > rk2(numtimes,vector<double>(numvar));
    std::vector<vector<double> > rk3(numtimes,vector<double>(numvar));
    std::vector<vector<double> > rk4(numtimes,vector<double>(numvar));
    std::vector<vector<double> > vk1(numtimes,vector<double>(numvar));
    std::vector<vector<double> > vk2(numtimes,vector<double>(numvar));
    std::vector<vector<double> > vk3(numtimes,vector<double>(numvar));
    std::vector<vector<double> > vk4(numtimes,vector<double>(numvar));

This is how I constructed the code in my original program, with no problem:

#include <iostream>
#include <ostream>
#include <cmath>
#include <vector>

using namespace std;

int main(){
// time related things
    //double t_i = 0; // initial time
    double dt = 0.01; // time step
    int numtimes = 10000; // how many steps taken

    vector<vector<double> > position(numtimes,vector<double>(numvar));
    vector<vector<double> > velocity(numtimes,vector<double>(numvar));

    vector<vector<double> > rk1(numtimes,vector<double>(numvar));
    vector<vector<double> > rk2(numtimes,vector<double>(numvar));
    vector<vector<double> > rk3(numtimes,vector<double>(numvar));
    vector<vector<double> > rk4(numtimes,vector<double>(numvar));
    vector<vector<double> > vk1(numtimes,vector<double>(numvar));
    vector<vector<double> > vk2(numtimes,vector<double>(numvar));
    vector<vector<double> > vk3(numtimes,vector<double>(numvar));
    vector<vector<double> > vk4(numtimes,vector<double>(numvar));
}

I'm not quite sure why this call worked in my original(procedural) program, but not in my current program.

Body:
In a function, you can use parenthesis to pass parameters to the constructor for a variable.  This does not work when specifying default values for member variables.  You have to use uniform initialization.

 std::vector<std::vector<double>> position{numtimes, std::vector<double>(numvar)};

This syntax - using curly braces - also works for when declaring variables, and you can use that same line in main to declare the position variable.

One other thing you get with uniform initialization is stronger type safety.  You can't specify a number that won't fit where you're trying to store it.  Where that is an issue in your code is that numtimes is an int, but the first parameter to the constructor for vector is a size_t - some form of unsigned.  So you'll need to change the declaration for numtimes to

unsigned numtimes = 10000;

Note also that you need to put std:: in front of all the vector usages.


问:
Support older browsers with gulp
I want to support es6 syntax and new features of javascript all the way to IE11. I am using gulp in my project. Is there any way so that the new javascript gets transpiled to support older browsers?</p>

答:
You can use gulp-babel which is the package of the babeljs transpiler

by installing it like this: (for babel 7)

```<code>$ npm install --save-dev gulp-babel @babel/core @babel/preset-env
</code>```

the basic setup is something like this:

const gulp = require('gulp'),
  babel = require('gulp-babel');

gulp.task('default', () =>
  gulp.src('src/yourJSfile.js')
  .pipe(babel({
    presets: ['@babel/env'] // the minimum presets needed to make gulp-babel work in babel 7 - https://github.com/babel/gulp-babel/tree/v7-maintenance
  }))
  .pipe(gulp.dest('dist'))
);
```

Title: Support older browsers with gulp

Body:
You can use gulp-babel which is the package of the babeljs transpiler

by installing it like this: (for babel 7)

$ npm install --save-dev gulp-babel @babel/core @babel/preset-env

the basic setup is something like this:

const gulp = require('gulp'),
  babel = require('gulp-babel');

gulp.task('default', () =>
  gulp.src('src/yourJSfile.js')
  .pipe(babel({
    presets: ['@babel/env'] // the minimum presets needed to make gulp-babel work in babel 7 - https://github.com/babel/gulp-babel/tree/v7-maintenance
  }))
  .pipe(gulp.dest('dist'))
);


问:
Problem concatenating a character vector in a for loop - only returning the final object
I am trying to loop through a list of data about hospitals in each state and extract the hospital that matches the ranking specified (num argument). I need to return a data frame with two columns, hospitals and states, that gives the hospital in each state with the specified ranking for the specified outcome, so should be 50 rows.

Problem is that I am getting returned a data frame with only one row containing the data from the last state (WY).

I know that my code is working perfectly for what I want until concatenating the character vectors hospitals and states.

```<code>rankall <- function(outcome, num = "best") {
    data <- read.csv("outcome-of-care-measures.csv", colClasses = "character")
    newframe <- as.data.frame(cbind(data[, 2], data[, 7], data[, 11], data[, 17], data[, 23]), stringsAsFactors = F)
    colnames(newframe) <- c("hospital", "state", "heart attack", "heart failure", "pneumonia")
    splitstates <- split(newframe, newframe$state)

    if (sum(outcome == "heart attack" | outcome == "pneumonia" | outcome == "heart failure") == 0) {
        stop("invalid outcome")
    }
    hospitals <- character()
    states <- character()

    for(i in length(splitstates)) {
        orderoutcome <- order(splitstates[[i]][, eval(outcome)], splitstates[[i]][, "hospital"], na.last = TRUE)
        if(num == "best") {
            num2 <- 1
            rank <-orderoutcome[num2]
        } else if(num == "worst") {
            num2 <- length(orderoutcome)
            rank <- orderoutcome[num2]
        } else {
            rank <- orderoutcome[num]
        }
        result <- splitstates[[i]][rank, "hospital"]
        hospitals <- c(hospitals, result)
        states <- c(states, splitstates[[i]][1, "state"])
    }
    return <- data.frame(hospitals, states)
    print(return)
}
</code>```

Expected: data frame with a row for each state

Actual: data frame with one row corresponding to the last state (WY)

答:
Consider re-factoring your code to avoid redundancy in data frame construction, growing vectors in a loop, and bookkeeping required of iterated items.

Instead of for loop use an apply family method, by, the object-oriented wrapper to tapply. This is similar to split + lapply (or in your case split + for) to build final data frame of ranked hospitals across all states.

```<code>rankall <- function(outcome, num = "best") {
    if !(outcome %in% c("heart attack", "pneumonia", "heart failure")) {
        stop("invalid outcome")
    }

    data <- read.csv("outcome-of-care-measures.csv", colClasses = "character")
    newframe <- setNames(data[, c(2,7,11,17,23)],
                         c("hospital", "state", "heart attack", "heart failure", "pneumonia"))

    # ORDER ENTIRE DATA FRAME BY STATE, OUTCOME, AND HOSPITAL
    newframe <- with(newframe, newframe[order(state, df[[outcome]], hospital),]
    row.names(newframe) <- NULL

    # BUILD LIST OF 50 DFs FOR EACH STATE SUBSET
    df_list <- by(newframe, newframe$state, function(sub) {
        # CONDITIONALLY ASSIGN ROW SLICE
        if(num == "best") {
            df <- head(sub, 1)
        } else if(num == "worst") {
            df <- tail(sub, 1)
        } else {
            df <- sub[num,]
        }

        return(df[c("hospital", "state")])
    })

    final_df <- do.call(rbind, unname(df_list))
    row.names(final_df) <- NULL

    return(final_df)
}
</code>```

Rextester demo (with random, seeded data for 5 states)

Body:
I am trying to loop through a list of data about hospitals in each state and extract the hospital that matches the ranking specified (num argument). I need to return a data frame with two columns, hospitals and states, that gives the hospital in each state with the specified ranking for the specified outcome, so should be 50 rows.

Problem is that I am getting returned a data frame with only one row containing the data from the last state (WY).

I know that my code is working perfectly for what I want until concatenating the character vectors hospitals and states.

rankall <- function(outcome, num = "best") {
    data <- read.csv("outcome-of-care-measures.csv", colClasses = "character")
    newframe <- as.data.frame(cbind(data[, 2], data[, 7], data[, 11], data[, 17], data[, 23]), stringsAsFactors = F)
    colnames(newframe) <- c("hospital", "state", "heart attack", "heart failure", "pneumonia")
    splitstates <- split(newframe, newframe$state)

    if (sum(outcome == "heart attack" | outcome == "pneumonia" | outcome == "heart failure") == 0) {
        stop("invalid outcome")
    }
    hospitals <- character()
    states <- character()

    for(i in length(splitstates)) {
        orderoutcome <- order(splitstates[[i]][, eval(outcome)], splitstates[[i]][, "hospital"], na.last = TRUE)
        if(num == "best") {
            num2 <- 1
            rank <-orderoutcome[num2]
        } else if(num == "worst") {
            num2 <- length(orderoutcome)
            rank <- orderoutcome[num2]
        } else {
            rank <- orderoutcome[num]
        }
        result <- splitstates[[i]][rank, "hospital"]
        hospitals <- c(hospitals, result)
        states <- c(states, splitstates[[i]][1, "state"])
    }
    return <- data.frame(hospitals, states)
    print(return)
}

Expected: data frame with a row for each state

Actual: data frame with one row corresponding to the last state (WY)

Body:
Consider re-factoring your code to avoid redundancy in data frame construction, growing vectors in a loop, and bookkeeping required of iterated items.

Instead of for loop use an apply family method, by, the object-oriented wrapper to tapply. This is similar to split + lapply (or in your case split + for) to build final data frame of ranked hospitals across all states.

rankall <- function(outcome, num = "best") {
    if !(outcome %in% c("heart attack", "pneumonia", "heart failure")) {
        stop("invalid outcome")
    }

    data <- read.csv("outcome-of-care-measures.csv", colClasses = "character")
    newframe <- setNames(data[, c(2,7,11,17,23)],
                         c("hospital", "state", "heart attack", "heart failure", "pneumonia"))

    # ORDER ENTIRE DATA FRAME BY STATE, OUTCOME, AND HOSPITAL
    newframe <- with(newframe, newframe[order(state, df[[outcome]], hospital),]
    row.names(newframe) <- NULL

    # BUILD LIST OF 50 DFs FOR EACH STATE SUBSET
    df_list <- by(newframe, newframe$state, function(sub) {
        # CONDITIONALLY ASSIGN ROW SLICE
        if(num == "best") {
            df <- head(sub, 1)
        } else if(num == "worst") {
            df <- tail(sub, 1)
        } else {
            df <- sub[num,]
        }

        return(df[c("hospital", "state")])
    })

    final_df <- do.call(rbind, unname(df_list))
    row.names(final_df) <- NULL

    return(final_df)
}

Rextester demo (with random, seeded data for 5 states)


问:
How can I mount an EFS share to AWS Fargate?
I have an AWS EFS share that I store container logs.

I would like to mount this nfs share (aws efs) to AWS Fargate. Is it possible?

Any supporting documentation link would be appreciated.

答:
EDIT: Since April 2020 this answer is not accurate. This was the situation until Fargate 1.4.0. If you are using earlier versions of Fargate this is still relevant, otherwise see newer answers.

Unfortunately it's not currently possible to use persistent storage with AWS Fargate however progress on this feature can be tracked using the newly launched public roadmap [1] for AWS container services [2]

Your use case seems to suggest logs. Have you considered using the AWSLogs driver [3] and shipping your application logs to CloudWatch Logs?

[1] https://github.com/aws/containers-roadmap/projects/1

[2] https://github.com/aws/containers-roadmap/issues/53

[3] https://docs.aws.amazon.com/AmazonECS/latest/developerguide/using_awslogs.html