问:
body of nestedscrollview overflowed - flutter

I made a page with NestedScrollView, the body of NestedScrollView is a container that holds data from previous requests. but the body of the NestedScrollView is overflowed. The following code:

```<code>NestedScrollView(
          controller: _scrollViewController,
          headerSliverBuilder:
              (BuildContext context, bool innerBoxIsScrolled) {
            return <Widget>[
              SliverAppBar(
                title: new Text(
                  nama,
                  style: TextStyle(color: putih),
                ),
                iconTheme: IconThemeData(color: putih),
                backgroundColor: colorPrimaryDark,
              )
            ];
          },
          body: Container(
            child: Column(
              children: <Widget>[
                Container(
                  color: goldtua,
                  child: Padding(
                    padding: const EdgeInsets.all(12.0),
                    child: Row(
                      mainAxisSize: MainAxisSize.max,
                      children: <Widget>[
                        Text(
                          string.harga,
                          style: TextStyle(color: putih, fontSize: 24.0),
                        ),
                        Text(
                          formatingRupiah(harga),
                          style: TextStyle(color: putih, fontSize: 24.0),
                        ),
                      ],
                    ),
                  ),
                ),
                Expanded(
                  child: Padding(
                    padding: const EdgeInsets.all(16.0),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Row(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Text(
                              string.fasilitas,
                              style: TextStyle(fontSize: 18.0),
                            ),
                            Expanded(
                              child: Text(
                                fasilitas, //this is the result of the request, the text is multiline so it takes up less space
                                style: TextStyle(fontSize: 18.0),
                              ),
                            )
                          ],
                        ),
                        ......
</code>```

Please, can someone tell me where do I do it wrong?

答:
You're getting this error because the size of your content is bigger than the size of the container. That means the Container size is smaller than the size of Column. In order to solve this issue, you should wrap Container with a Scrollable Widget like SingleChildScrollView which will scroll overflowing content and match parents size or available space. You don't need to use Expanded since each item of Column will fill only needed space

```<code>body:
SingleChildScrolView(
            child: Column(
              children: <Widget>[
                Container(
                  color: goldtua,
                  child: Padding(
                    padding: const EdgeInsets.all(12.0),
                    child: Row(
                      mainAxisSize: MainAxisSize.max,
                      children: <Widget>[
                        Text(
                          string.harga,
                          style: TextStyle(color: putih, fontSize: 24.0),
                        ),
                        Text(
                          formatingRupiah(harga),
                          style: TextStyle(color: putih, fontSize: 24.0),
                        ),
                      ],
                    ),
                  ),
                ),
                Expanded(
                  child: Padding(
                    padding: const EdgeInsets.all(16.0),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Row(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Text(
                              string.fasilitas,
                              style: TextStyle(fontSize: 18.0),
                            ),
                            Expanded(
                              child: Text(
                                fasilitas, //this is the result of the request, the text is multiline so it takes up less space
                                style: TextStyle(fontSize: 18.0),
                              ),
                            )
                          ],
                        ),
                        ......
</code>```

Body:
I made a page with NestedScrollView, the body of NestedScrollView is a container that holds data from previous requests. but the body of the NestedScrollView is overflowed. The following code:

NestedScrollView(
          controller: _scrollViewController,
          headerSliverBuilder:
              (BuildContext context, bool innerBoxIsScrolled) {
            return <Widget>[
              SliverAppBar(
                title: new Text(
                  nama,
                  style: TextStyle(color: putih),
                ),
                iconTheme: IconThemeData(color: putih),
                backgroundColor: colorPrimaryDark,
              )
            ];
          },
          body: Container(
            child: Column(
              children: <Widget>[
                Container(
                  color: goldtua,
                  child: Padding(
                    padding: const EdgeInsets.all(12.0),
                    child: Row(
                      mainAxisSize: MainAxisSize.max,
                      children: <Widget>[
                        Text(
                          string.harga,
                          style: TextStyle(color: putih, fontSize: 24.0),
                        ),
                        Text(
                          formatingRupiah(harga),
                          style: TextStyle(color: putih, fontSize: 24.0),
                        ),
                      ],
                    ),
                  ),
                ),
                Expanded(
                  child: Padding(
                    padding: const EdgeInsets.all(16.0),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Row(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Text(
                              string.fasilitas,
                              style: TextStyle(fontSize: 18.0),
                            ),
                            Expanded(
                              child: Text(
                                fasilitas, //this is the result of the request, the text is multiline so it takes up less space
                                style: TextStyle(fontSize: 18.0),
                              ),
                            )
                          ],
                        ),
                        ......

Please, can someone tell me where do I do it wrong?

Body:
You're getting this error because the size of your content is bigger than the size of the container. That means the Container size is smaller than the size of Column. In order to solve this issue, you should wrap Container with a Scrollable Widget like SingleChildScrollView which will scroll overflowing content and match parents size or available space. You don't need to use Expanded since each item of Column will fill only needed space

body:
SingleChildScrolView(
            child: Column(
              children: <Widget>[
                Container(
                  color: goldtua,
                  child: Padding(
                    padding: const EdgeInsets.all(12.0),
                    child: Row(
                      mainAxisSize: MainAxisSize.max,
                      children: <Widget>[
                        Text(
                          string.harga,
                          style: TextStyle(color: putih, fontSize: 24.0),
                        ),
                        Text(
                          formatingRupiah(harga),
                          style: TextStyle(color: putih, fontSize: 24.0),
                        ),
                      ],
                    ),
                  ),
                ),
                Expanded(
                  child: Padding(
                    padding: const EdgeInsets.all(16.0),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Row(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Text(
                              string.fasilitas,
                              style: TextStyle(fontSize: 18.0),
                            ),
                            Expanded(
                              child: Text(
                                fasilitas, //this is the result of the request, the text is multiline so it takes up less space
                                style: TextStyle(fontSize: 18.0),
                              ),
                            )
                          ],
                        ),
                        ......


来源: stackexchange

问:
Redirecting to URL with firebase functions - google cloud functions
I have a trigger function in firebase to perform simple actions when the user registers. I'm trying to redirect the user to create their profile when they sign up. But I can't find a way to do it with firebase trigger functions. Here is my function.

```<code>const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp(functions.config().firebase);

exports.userJoined = functions.auth.user().onCreate(user => {

        const newUser = user.uid;
        console.log(newUser)
        const notification = {
            displayName: '',
            displayImage: 'https://wattleparkkgn.sa.edu.au/wp-content/uploads/2017/06/placeholder-profile-sq.jpg',
            location: '',
            phoneNumber: '',
        }
        const createNotification = (notification => {
            return admin.firestore().collection('Accounts').doc(newUser).set(notification).then(

REDIRECT USER TO ANOTHER PAGE

                )
        })
        return createNotification(notification)

})
</code>```

I need to add to it something that would redirect the user to another page.

答:
You can add a boolean:

```<code>  const notification = {
            displayName: '',
            displayImage: 'https://wattleparkkgn.sa.edu.au/wp-content/uploads/2017/06/placeholder-profile-sq.jpg',
            location: '',
            phoneNumber: '',
            registered : true,
        }
</code>```

Then in the client side, retrieve the data and check if registered is equal to true and redirect the user. Though, it is better to just redirect the user in the client side without needing the trigger function. The onCreate function will get triggered everytime a new user registers to the application. So in the client side, if you have a button that is clicked that will enable the user to register, then you can just redirect in the client side.

In the client side, to redirect just check if user.uid is null or not.

ContentLicense: CC BY-SA 4.0

Body:
I have a trigger function in firebase to perform simple actions when the user registers. I'm trying to redirect the user to create their profile when they sign up. But I can't find a way to do it with firebase trigger functions. Here is my function.

const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp(functions.config().firebase);

exports.userJoined = functions.auth.user().onCreate(user => {

        const newUser = user.uid;
        console.log(newUser)
        const notification = {
            displayName: '',
            displayImage: 'https://wattleparkkgn.sa.edu.au/wp-content/uploads/2017/06/placeholder-profile-sq.jpg',
            location: '',
            phoneNumber: '',
        }
        const createNotification = (notification => {
            return admin.firestore().collection('Accounts').doc(newUser).set(notification).then(

REDIRECT USER TO ANOTHER PAGE

                )
        })
        return createNotification(notification)

})

I need to add to it something that would redirect the user to another page.

Body:
You can add a boolean:

  const notification = {
            displayName: '',
            displayImage: 'https://wattleparkkgn.sa.edu.au/wp-content/uploads/2017/06/placeholder-profile-sq.jpg',
            location: '',
            phoneNumber: '',
            registered : true,
        }

Then in the client side, retrieve the data and check if registered is equal to true and redirect the user. Though, it is better to just redirect the user in the client side without needing the trigger function. The onCreate function will get triggered everytime a new user registers to the application. So in the client side, if you have a button that is clicked that will enable the user to register, then you can just redirect in the client side.

In the client side, to redirect just check if user.uid is null or not.


问:
Python pandas: how to unpack the statsmodel results and create a column in group by dataframe
I am trying to run linear regressions by group and add the results to a new column in the dataframe.
Here is what I'm trying to do.

```<code>df2 = pd.DataFrame.from_dict({'case': ['foo', 'foo', 'foo', 'bar', 'bar'],
                                 'cluster': [1, 1, 1, 1, 1],
                                 'conf': [1, 2, 3, 1, 4],
                                'conf_1': [11, 12, 13, 11, 14]})

def ols_res(df, xcols,  ycol):
    results =  sm.OLS(df[ycol], sm.add_constant(df[xcols])).fit()
    return results.get_influence().cooks_distance[0]

df3 = df2.groupby(['case', 'cluster'])

df3.apply(ols_res, xcols='conf', ycol='conf_1')
</code>```

output I got is :

```<code>case  cluster
bar   1                                                 [nan, nan]
foo   1          [0.42857142857143005, 0.09642857142857146, 10....
dtype: object
</code>```

The size of results for each group is same as number of rows in the group.
I need the above output in following format. Can some one please help me?

```<code>    case    cluster conf    conf_1   result
0   foo      1       1       11      0.42857142857143005
1   foo      1       2       12      0.09642857142857146
2   foo      1       3       13      10....
4   bar      1       1       11      nan
5   bar      1       4       14      nan
</code>```

答:
following worked for me.

```<code>def ols_res_mod(df, xcols,  ycol):
    results =  sm.OLS(df[ycol], sm.add_constant(df[xcols])).fit()
    results.get_influence().cooks_distance[0]
    print(df)
    df['distance'] = results.get_influence().cooks_distance[0]
    return df
</code>```

not sure, whether this is an efficient way or not.

Body:
I am trying to run linear regressions by group and add the results to a new column in the dataframe.
Here is what I'm trying to do.

df2 = pd.DataFrame.from_dict({'case': ['foo', 'foo', 'foo', 'bar', 'bar'],
                                 'cluster': [1, 1, 1, 1, 1],
                                 'conf': [1, 2, 3, 1, 4],
                                'conf_1': [11, 12, 13, 11, 14]})

def ols_res(df, xcols,  ycol):
    results =  sm.OLS(df[ycol], sm.add_constant(df[xcols])).fit()
    return results.get_influence().cooks_distance[0]

df3 = df2.groupby(['case', 'cluster'])

df3.apply(ols_res, xcols='conf', ycol='conf_1')

output I got is :

case  cluster
bar   1                                                 [nan, nan]
foo   1          [0.42857142857143005, 0.09642857142857146, 10....
dtype: object

The size of results for each group is same as number of rows in the group.
I need the above output in following format. Can some one please help me?

    case    cluster conf    conf_1   result
0   foo      1       1       11      0.42857142857143005
1   foo      1       2       12      0.09642857142857146
2   foo      1       3       13      10....
4   bar      1       1       11      nan
5   bar      1       4       14      nan

Body:
following worked for me.

def ols_res_mod(df, xcols,  ycol):
    results =  sm.OLS(df[ycol], sm.add_constant(df[xcols])).fit()
    results.get_influence().cooks_distance[0]
    print(df)
    df['distance'] = results.get_influence().cooks_distance[0]
    return df

not sure, whether this is an efficient way or not.


问:
How to pull from Outlook Address book based on values in Excel (VBA)
I have the following code that works (I found it on a forum):

```<code>Public Sub GetUsers()
Dim myolApp As Outlook.Application
Dim myNameSpace As Namespace
Dim myAddrList As AddressList
Dim myAddrEntries As addressEntry
Dim AliasName As String
Dim i As Integer, r As Integer
Dim EndRow As Integer, n As Integer
Dim myStr As String, c As Range
Dim myPhone As String
'Dim propertyAccessor As Outlook.propertyAccessor  'This only works with 2007 and may help you out

Set myolApp = CreateObject("Outlook.Application")
Set myNameSpace = myolApp.GetNamespace("MAPI")
Set myAddrList = myNameSpace.addressLists("Global Address List")

Dim FullName As String, LastName As String, FirstName As String
Dim StartRow As Integer

EndRow = Cells(Rows.Count, 3).End(xlUp).Row

StartRow = InputBox("At which row should this start?", "Start Row", 4)

For Each c In Range("A" & StartRow & ":A" & CStr(EndRow))
    AliasName = LCase(Trim(c))
    c = AliasName
    Set myAddrEntries = myAddrList.addressEntries(AliasName)

    FullName = myAddrEntries.Name
    FirstName = Trim(Mid(FullName, InStr(FullName, "(") + 1, _
                    InStrRev(FullName, " ") - InStr(FullName, "(")))
    LastName = Right(FullName, Len(FullName) - InStrRev(FullName, " "))
    LastName = Left(LastName, Len(LastName) - 1)

    c.Offset(0, 1) = FirstName
    c.Offset(0, 2) = LastName
    c.Offset(0, 3) = FirstName & " " & LastName
Next c
End Sub
</code>```

When I provide a single name (first or last) it looks for it in the address book and returns the first and last names of the person it found.

I want to provide the enterprise ID of the person, have it look for that and then return other information (location, phone number etc).

I can't figure out how to do that. First of all, I don't know how outlook knows to search only Alias, as far as I can tell that's only declared in local variables. Also, when I try to pull out other information, for example:

```<code>HomeState = myAddrEntries.HomeState
</code>```

I get an error: Object doesn't support this property or method. I don't know what that property would be called - I couldn't find any doc online that showed how properties are named (even when I searched for MAPI docuemntation).

SO, my question is - how can I use this code to search by ID and return other properties such as location, number etc. ALso - how can I generalize that process - is there a list of what those field names are called, is there a way to generate a list?

Thanks!

答:
To dramatically improve Outlook's reliability of looking up AliasName, especially in a large organization, I would cut off everything after last name and first name, such as department designation. This will work perfectly as long as no contacts are selected who share exact first and last names. No need to lowercase. Change this line:

```<code>Set myAddrEntries = myAddrList.addressEntries(AliasName)
</code>```

into:

```<code>' Let's cut off everything after "last name, firstname "
' get position of second blank in string

Dim Pos As Long

Pos = InStr(1, AliasName, " ", vbTextCompare)
Pos = InStr(Pos + 1, AliasName, " ", vbTextCompare)

If Pos > 0 Then
    Set myAddrEntry = myAddrList.addressEntries(Mid(AliasName, 1, Pos - 1))
Else
    Set myAddrEntry = myAddrList.addressEntries(AliasName)
End If
</code>```

This may not be a complete answer to your question, but it's still an important part of the solution.

ContentLicense: CC BY-SA 3.0

Body:
I have the following code that works (I found it on a forum):

Public Sub GetUsers()
Dim myolApp As Outlook.Application
Dim myNameSpace As Namespace
Dim myAddrList As AddressList
Dim myAddrEntries As addressEntry
Dim AliasName As String
Dim i As Integer, r As Integer
Dim EndRow As Integer, n As Integer
Dim myStr As String, c As Range
Dim myPhone As String
'Dim propertyAccessor As Outlook.propertyAccessor  'This only works with 2007 and may help you out

Set myolApp = CreateObject("Outlook.Application")
Set myNameSpace = myolApp.GetNamespace("MAPI")
Set myAddrList = myNameSpace.addressLists("Global Address List")

Dim FullName As String, LastName As String, FirstName As String
Dim StartRow As Integer

EndRow = Cells(Rows.Count, 3).End(xlUp).Row

StartRow = InputBox("At which row should this start?", "Start Row", 4)

For Each c In Range("A" & StartRow & ":A" & CStr(EndRow))
    AliasName = LCase(Trim(c))
    c = AliasName
    Set myAddrEntries = myAddrList.addressEntries(AliasName)

    FullName = myAddrEntries.Name
    FirstName = Trim(Mid(FullName, InStr(FullName, "(") + 1, _
                    InStrRev(FullName, " ") - InStr(FullName, "(")))
    LastName = Right(FullName, Len(FullName) - InStrRev(FullName, " "))
    LastName = Left(LastName, Len(LastName) - 1)

    c.Offset(0, 1) = FirstName
    c.Offset(0, 2) = LastName
    c.Offset(0, 3) = FirstName & " " & LastName
Next c
End Sub

When I provide a single name (first or last) it looks for it in the address book and returns the first and last names of the person it found.

I want to provide the enterprise ID of the person, have it look for that and then return other information (location, phone number etc).

I can't figure out how to do that. First of all, I don't know how outlook knows to search only Alias, as far as I can tell that's only declared in local variables. Also, when I try to pull out other information, for example:

HomeState = myAddrEntries.HomeState

I get an error: Object doesn't support this property or method. I don't know what that property would be called - I couldn't find any doc online that showed how properties are named (even when I searched for MAPI docuemntation).

SO, my question is - how can I use this code to search by ID and return other properties such as location, number etc. ALso - how can I generalize that process - is there a list of what those field names are called, is there a way to generate a list?

Thanks!

Body:
To dramatically improve Outlook's reliability of looking up AliasName, especially in a large organization, I would cut off everything after last name and first name, such as department designation. This will work perfectly as long as no contacts are selected who share exact first and last names. No need to lowercase. Change this line:

Set myAddrEntries = myAddrList.addressEntries(AliasName)

into:

' Let's cut off everything after "last name, firstname "
' get position of second blank in string

Dim Pos As Long

Pos = InStr(1, AliasName, " ", vbTextCompare)
Pos = InStr(Pos + 1, AliasName, " ", vbTextCompare)

If Pos > 0 Then
    Set myAddrEntry = myAddrList.addressEntries(Mid(AliasName, 1, Pos - 1))
Else
    Set myAddrEntry = myAddrList.addressEntries(AliasName)
End If

This may not be a complete answer to your question, but it's still an important part of the solution.


问:
Maintain centre coordinate while pinching MKMapView
If you pinch to zoom in/out in Apple's Maps application while tracking the device's location, the "pan" component of the pinch gesture is ignored and the blue location indicator remains fixed in the centre of the screen. This is not the case when using a plain MKMapView.

Assuming I already have the user's location, how could I achieve this effect? I've tried resetting the centre coordinate in the delegate's regionDid/WillChangeAnimated: methods but they're only called at the start and end of the gesture. I also tried adding a UIPinchGestureRecognizer subclass that resets the centre coordinate when the touches move, but this resulted in rendering glitches.

Edit: For those who are interested, the following works for me.

```<code>// CenterGestureRecognizer.h
@interface CenterGestureRecognizer : UIPinchGestureRecognizer

- (id)initWithMapView:(MKMapView *)mapView;

@end
</code>```

```<code>// CenterGestureRecognizer.m
@interface CenterGestureRecognizer ()

- (void)handlePinchGesture;

@property (nonatomic, assign) MKMapView *mapView;

@end

@implementation CenterGestureRecognizer

- (id)initWithMapView:(MKMapView *)mapView {
  if (mapView == nil) {
    [NSException raise:NSInvalidArgumentException format:@"mapView cannot be nil."];
  }

  if ((self = [super initWithTarget:self action:@selector(handlePinchGesture)])) {
    self.mapView = mapView;
  }

  return self;
}

- (BOOL)canBePreventedByGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer {
  return NO;
}

- (BOOL)canPreventGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer {
  return NO;
}

- (void)handlePinchGesture {
  CLLocation *location = self.mapView.userLocation.location;
  if (location != nil) {
    [self.mapView setCenterCoordinate:location.coordinate];
  }
}

@synthesize mapView;

@end
</code>```

Then simply add it to your MKMapView:

```<code>[self.mapView addGestureRecognizer:[[[CenterGestureRecognizer alloc] initWithMapView:self.mapView] autorelease]];
</code>```

答: Just a guess, but have you tried setting scrollEnabled to NO at the start of regionWillChangeAnimated:?

Body:
If you pinch to zoom in/out in Apple's Maps application while tracking the device's location, the "pan" component of the pinch gesture is ignored and the blue location indicator remains fixed in the centre of the screen. This is not the case when using a plain MKMapView.

Assuming I already have the user's location, how could I achieve this effect? I've tried resetting the centre coordinate in the delegate's regionDid/WillChangeAnimated: methods but they're only called at the start and end of the gesture. I also tried adding a UIPinchGestureRecognizer subclass that resets the centre coordinate when the touches move, but this resulted in rendering glitches.

Edit: For those who are interested, the following works for me.

// CenterGestureRecognizer.h
@interface CenterGestureRecognizer : UIPinchGestureRecognizer

- (id)initWithMapView:(MKMapView *)mapView;

@end

// CenterGestureRecognizer.m
@interface CenterGestureRecognizer ()

- (void)handlePinchGesture;

@property (nonatomic, assign) MKMapView *mapView;

@end

@implementation CenterGestureRecognizer

- (id)initWithMapView:(MKMapView *)mapView {
  if (mapView == nil) {
    [NSException raise:NSInvalidArgumentException format:@"mapView cannot be nil."];
  }

  if ((self = [super initWithTarget:self action:@selector(handlePinchGesture)])) {
    self.mapView = mapView;
  }

  return self;
}

- (BOOL)canBePreventedByGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer {
  return NO;
}

- (BOOL)canPreventGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer {
  return NO;
}

- (void)handlePinchGesture {
  CLLocation *location = self.mapView.userLocation.location;
  if (location != nil) {
    [self.mapView setCenterCoordinate:location.coordinate];
  }
}

@synthesize mapView;

@end

Then simply add it to your MKMapView:

[self.mapView addGestureRecognizer:[[[CenterGestureRecognizer alloc] initWithMapView:self.mapView] autorelease]];


问:
How to make the if statement without repetition of code?
Following is the if statement that execute some part of the code before it checks some condition, it is working fine but it looks very basic and repeated lines.</p>

```<code>    if(allTasks[t].status === "Completed"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","completed");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }else if(allTasks[t].status === "Past Due"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","pastdue");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }else if(allTasks[t].status === "Duetoday"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","duetoday");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }else if(allTasks[t].status === "Onhold"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","onhold");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }else if(allTasks[t].status === "Canceled"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","canceled");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }
</code>```

答:
Try below code this will save your if statements</p>

```<code>var status = allTasks[t].status;
arrow.setAttribute("class","arrow2");
tag.setAttribute("class",status.replace(/ /g,'').toLowerCase());
tag.innerHTML = status;
taskCont.appendChild(tag);
</code>```

Body:
Following is the if statement that execute some part of the code before it checks some condition, it is working fine but it looks very basic and repeated lines.

    if(allTasks[t].status === "Completed"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","completed");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }else if(allTasks[t].status === "Past Due"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","pastdue");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }else if(allTasks[t].status === "Duetoday"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","duetoday");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }else if(allTasks[t].status === "Onhold"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","onhold");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }else if(allTasks[t].status === "Canceled"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","canceled");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }

Body:
Try below code this will save your if statements

var status = allTasks[t].status;
arrow.setAttribute("class","arrow2");
tag.setAttribute("class",status.replace(/ /g,'').toLowerCase());
tag.innerHTML = status;
taskCont.appendChild(tag);


问:
Sharing run configurations in JetBrains Rider
Our team is now trying Rider and we quite like it. We would like to setup some run configurations to run projects and some associated tasks with them (such as running grunt prebuild).

When I setup the configurations, mark them all as "Share through VCS" and add them to git, after restarting Rider the configurations are not loaded. We have ignored everything in .idea/** folder in our .gitignore, except these run configurations in runConfigurations folder.

Is it a problem with .gitignore setup? Or is there some special setting we have to use in order to force Rider to load these configurations?

答: Rider 2019.3.2 saves run configurations as XML files with UTF-8 with BOM encoding. When you change the encoding manually to UTF-8 (without BOM) it starts working and the configurations are loaded as expected.</p>


问:
Subroutine Segmentation Fault
```<code>PROGRAM olaf
IMPLICIT NONE
INTEGER                                  :: i, j, nc, nd,ok,iter
REAL                                     :: alph, bet, chi, ninf1, C1, ninf2, C2
REAL, DIMENSION(:), ALLOCATABLE          :: u,up2
REAL                                     :: E, k, Lc, hc, eps, h, Ld, Cai
INTEGER, DIMENSION(7)                    :: valnc = (/ 10, 50, 100, 500, 1000, 5000, 10000/)

Do iter=1,7
 nc = valnc(iter)
 Ld=0.2*Lc ; nd=((Lc+Ld)/h)-nc;

 E=25. ; k=125. ; hc=0.01 ; eps=0.01 ; Lc=1 ;

 h = Lc/nc ; chi=sqrt((E*hc)/k) ; alph= -(1/h**2) ; bet=(2/h**2)+(k/(E*hc)) ;

 CALL resolution(0,nc,bet,2*alph,alph,2*alph,-2*eps/h,2*eps/h,u)
 Cai=u(nc)
 CALL resolution(nc+1,(nc+nd)+1,-2.0,2.0,1.0,2.0,2.0*eps*h,-2*eps*h,up2,Cai)

 DEALLOCATE(u,up2)
END DO

CONTAINS

SUBROUTINE resolution (n1,n2,a,b1,b,b2,c1,c2,u1,u2)
 INTEGER, INTENT(IN) :: n1,n2
 REAL, INTENT(IN):: a,b1,b,b2,c1,c2
 REAL, INTENT(IN),OPTIONAL :: u2
 REAL, DIMENSION (:),ALLOCATABLE, INTENT(OUT) :: u1
 REAL, DIMENSION(:), ALLOCATABLE          :: Ap, Ae, Aw, bh, Lw, Lp, Ue, y
 INTEGER :: i
 Logical :: Exist

 ALLOCATE(Ap(n1+1:n2), Ae(n1:n2), Aw(n1:n2),bh(n1:n2))
 ALLOCATE(Lw(n1:n2), Lp(n1:n2), Ue(n1:n2), y(n1:n2),u1(n1:n2))

 Aw=0; Ap=0; Ae=0; bh= 0 ; Lw = 0 ; Lp = 0 ; Ue = 0 ; y=0; Lc=0;

 Exist=Present(u2)
 IF(Exist .eqv. .true.)THEN
  u1(n1)=u2
 END IF

DO i = n1,n2
  Ae(i) = b
  Ap(i) = a
  Aw(i) = b
END DO
Ae(n1)=b1
Aw(n2)=b2

bh(n1)=c1
bh(n2)=c2

Lp(n1) = Ap(n1+2)
Ue(n1) = Ae(n1)/Lp(n1)

DO i = n1+1, n2-1
 Lw(i) = Aw(i)
 Lp(i) = Ap(i) - Lw(i)*Ue(i-1)
 Ue(i) = Ae(i)/Lp(i)
END DO

Lw(n2) = Aw(n2)
Lp(n2) = Ap(n2) - Lw(n2)*Ue(n2-1)
y(n1) = bh(n1)/Lp(n1)

DO i = n1, n2
  y(i) = (bh(i) - Lw(i)*y(i-1)) / Lp(i)
END DO

u1(n2) = y(n2)
DO i = n2-1, n1, -1
 u1(i) = y(i) - Ue(i)*u1(i+1)
END DO

DEALLOCATE(Ap, Ae, Aw,bh,Lw, Lp, Ue, y)

END SUBROUTINE

END PROGRAM olaf
</code>```

I'm trying to do an Ah=b decomposition for u and up2 in my program. Nevertheless, up2 is depend on u for it's first value. In order to not repeat the decomposition resolution, i made it into a subroutine but whenever i'm trying to call it in a same loop for both u and up2, i keep getting sigmentation fault which i can't identify.

答:
Please learn about compiler warnings and running time error checking. Using gfortran with the appropriate flags on your program I get:

```<code>ijb@ianbushdesktop ~/work/stack $ gfortran -std=f2003 -Wall -Wextra -fcheck=all -g -O olaf.f90
olaf.f90:13:16:

  Ld=0.2*Lc ; nd=((Lc+Ld)/h)-nc;
                1
Warning: Possible change of value in conversion from REAL(4) to INTEGER(4) at (1) [-Wconversion]
olaf.f90:4:69:

 REAL                                     :: alph, bet, chi, ninf1, C1, ninf2, C2
                                                                     1
Warning: Unused variable ‘c1’ declared at (1) [-Wunused-variable]
olaf.f90:4:80:

 REAL                                     :: alph, bet, chi, ninf1, C1, ninf2, C2
                                                                                1
Warning: Unused variable ‘c2’ declared at (1) [-Wunused-variable]
olaf.f90:3:45:

 INTEGER                                  :: i, j, nc, nd,ok,iter
                                             1
Warning: Unused variable ‘i’ declared at (1) [-Wunused-variable]
olaf.f90:3:48:

 INTEGER                                  :: i, j, nc, nd,ok,iter
                                                1
Warning: Unused variable ‘j’ declared at (1) [-Wunused-variable]
olaf.f90:4:65:

 REAL                                     :: alph, bet, chi, ninf1, C1, ninf2, C2
                                                                 1
Warning: Unused variable ‘ninf1’ declared at (1) [-Wunused-variable]
olaf.f90:4:76:

 REAL                                     :: alph, bet, chi, ninf1, C1, ninf2, C2
                                                                            1
Warning: Unused variable ‘ninf2’ declared at (1) [-Wunused-variable]
olaf.f90:3:59:

 INTEGER                                  :: i, j, nc, nd,ok,iter
                                                           1
Warning: Unused variable ‘ok’ declared at (1) [-Wunused-variable]
olaf.f90:13:0:

  Ld=0.2*Lc ; nd=((Lc+Ld)/h)-nc;

Warning: ‘h’ may be used uninitialized in this function [-Wmaybe-uninitialized]
olaf.f90:6:0:

 REAL                                     :: E, k, Lc, hc, eps, h, Ld, Cai

note: ‘h’ was declared here
ijb@ianbushdesktop ~/work/stack $ ./a.out
At line 51 of file olaf.f90
Fortran runtime error: Index '0' of dimension 1 of array 'ap' below lower bound of 1

Error termination. Backtrace:
#0  0x400f8d in resolution
    at /home/ijb/work/stack/olaf.f90:51
#1  0x401991 in olaf
    at /home/ijb/work/stack/olaf.f90:20
#2  0x401991 in main
    at /home/ijb/work/stack/olaf.f90:11
ijb@ianbushdesktop ~/work/stack $
</code>```

Note two things

You are using h uninitialized. The compiler tells you this in the second to last warning. I don't know how to fix this, you will need to do that.

Your are accessing the array ap out of bounds. This occurs at the line

Ap(i) = a

and the problem is that i is zero. Looking at the code i goes from n1 to n2, so the ultimate problem is that at the line

```<code>  CALL resolution(0,nc,bet,2*alph,alph,2*alph,-2*eps/h,2*eps/h,u)
</code>```

you are passing the value 0 to n1, but you allocate the array ap as

```<code> ALLOCATE(Ap(n1+1:n2), Ae(n1:n2), Aw(n1:n2),bh(n1:n2))
</code>```

which is inconsistent with the above usage of Ap. My complete guess is that the do loop should read

```<code>DO i = n1+1,n2
</code>```

but that is a guess - the problem as presented is due to out of bounds errors in this loop.

Title: Subroutine Segmentation Fault

Body:
PROGRAM olaf
IMPLICIT NONE
INTEGER                                  :: i, j, nc, nd,ok,iter
REAL                                     :: alph, bet, chi, ninf1, C1, ninf2, C2
REAL, DIMENSION(:), ALLOCATABLE          :: u,up2
REAL                                     :: E, k, Lc, hc, eps, h, Ld, Cai
INTEGER, DIMENSION(7)                    :: valnc = (/ 10, 50, 100, 500, 1000, 5000, 10000/)

Do iter=1,7
 nc = valnc(iter)
 Ld=0.2*Lc ; nd=((Lc+Ld)/h)-nc;

 E=25. ; k=125. ; hc=0.01 ; eps=0.01 ; Lc=1 ;

 h = Lc/nc ; chi=sqrt((E*hc)/k) ; alph= -(1/h**2) ; bet=(2/h**2)+(k/(E*hc)) ;

 CALL resolution(0,nc,bet,2*alph,alph,2*alph,-2*eps/h,2*eps/h,u)
 Cai=u(nc)
 CALL resolution(nc+1,(nc+nd)+1,-2.0,2.0,1.0,2.0,2.0*eps*h,-2*eps*h,up2,Cai)

 DEALLOCATE(u,up2)
END DO

CONTAINS

SUBROUTINE resolution (n1,n2,a,b1,b,b2,c1,c2,u1,u2)
 INTEGER, INTENT(IN) :: n1,n2
 REAL, INTENT(IN):: a,b1,b,b2,c1,c2
 REAL, INTENT(IN),OPTIONAL :: u2
 REAL, DIMENSION (:),ALLOCATABLE, INTENT(OUT) :: u1
 REAL, DIMENSION(:), ALLOCATABLE          :: Ap, Ae, Aw, bh, Lw, Lp, Ue, y
 INTEGER :: i
 Logical :: Exist

 ALLOCATE(Ap(n1+1:n2), Ae(n1:n2), Aw(n1:n2),bh(n1:n2))
 ALLOCATE(Lw(n1:n2), Lp(n1:n2), Ue(n1:n2), y(n1:n2),u1(n1:n2))

 Aw=0; Ap=0; Ae=0; bh= 0 ; Lw = 0 ; Lp = 0 ; Ue = 0 ; y=0; Lc=0;

 Exist=Present(u2)
 IF(Exist .eqv. .true.)THEN
  u1(n1)=u2
 END IF

DO i = n1,n2
  Ae(i) = b
  Ap(i) = a
  Aw(i) = b
END DO
Ae(n1)=b1
Aw(n2)=b2

bh(n1)=c1
bh(n2)=c2

Lp(n1) = Ap(n1+2)
Ue(n1) = Ae(n1)/Lp(n1)

DO i = n1+1, n2-1
 Lw(i) = Aw(i)
 Lp(i) = Ap(i) - Lw(i)*Ue(i-1)
 Ue(i) = Ae(i)/Lp(i)
END DO

Lw(n2) = Aw(n2)
Lp(n2) = Ap(n2) - Lw(n2)*Ue(n2-1)
y(n1) = bh(n1)/Lp(n1)

DO i = n1, n2
  y(i) = (bh(i) - Lw(i)*y(i-1)) / Lp(i)
END DO

u1(n2) = y(n2)
DO i = n2-1, n1, -1
 u1(i) = y(i) - Ue(i)*u1(i+1)
END DO

DEALLOCATE(Ap, Ae, Aw,bh,Lw, Lp, Ue, y)

END SUBROUTINE

END PROGRAM olaf

I'm trying to do an Ah=b decomposition for u and up2 in my program. Nevertheless, up2 is depend on u for it's first value. In order to not repeat the decomposition resolution, i made it into a subroutine but whenever i'm trying to call it in a same loop for both u and up2, i keep getting sigmentation fault which i can't identify.

Body:
Please learn about compiler warnings and running time error checking. Using gfortran with the appropriate flags on your program I get:

ijb@ianbushdesktop ~/work/stack $ gfortran -std=f2003 -Wall -Wextra -fcheck=all -g -O olaf.f90
olaf.f90:13:16:

  Ld=0.2*Lc ; nd=((Lc+Ld)/h)-nc;
                1
Warning: Possible change of value in conversion from REAL(4) to INTEGER(4) at (1) [-Wconversion]
olaf.f90:4:69:

 REAL                                     :: alph, bet, chi, ninf1, C1, ninf2, C2
                                                                     1
Warning: Unused variable ‘c1’ declared at (1) [-Wunused-variable]
olaf.f90:4:80:

 REAL                                     :: alph, bet, chi, ninf1, C1, ninf2, C2
                                                                                1
Warning: Unused variable ‘c2’ declared at (1) [-Wunused-variable]
olaf.f90:3:45:

 INTEGER                                  :: i, j, nc, nd,ok,iter
                                             1
Warning: Unused variable ‘i’ declared at (1) [-Wunused-variable]
olaf.f90:3:48:

 INTEGER                                  :: i, j, nc, nd,ok,iter
                                                1
Warning: Unused variable ‘j’ declared at (1) [-Wunused-variable]
olaf.f90:4:65:

 REAL                                     :: alph, bet, chi, ninf1, C1, ninf2, C2
                                                                 1
Warning: Unused variable ‘ninf1’ declared at (1) [-Wunused-variable]
olaf.f90:4:76:

 REAL                                     :: alph, bet, chi, ninf1, C1, ninf2, C2
                                                                            1
Warning: Unused variable ‘ninf2’ declared at (1) [-Wunused-variable]
olaf.f90:3:59:

 INTEGER                                  :: i, j, nc, nd,ok,iter
                                                           1
Warning: Unused variable ‘ok’ declared at (1) [-Wunused-variable]
olaf.f90:13:0:

  Ld=0.2*Lc ; nd=((Lc+Ld)/h)-nc;

Warning: ‘h’ may be used uninitialized in this function [-Wmaybe-uninitialized]
olaf.f90:6:0:

 REAL                                     :: E, k, Lc, hc, eps, h, Ld, Cai

note: ‘h’ was declared here
ijb@ianbushdesktop ~/work/stack $ ./a.out
At line 51 of file olaf.f90
Fortran runtime error: Index '0' of dimension 1 of array 'ap' below lower bound of 1

Error termination. Backtrace:
#0  0x400f8d in resolution
    at /home/ijb/work/stack/olaf.f90:51
#1  0x401991 in olaf
    at /home/ijb/work/stack/olaf.f90:20
#2  0x401991 in main
    at /home/ijb/work/stack/olaf.f90:11
ijb@ianbushdesktop ~/work/stack $

Note two things

You are using h uninitialized. The compiler tells you this in the second to last warning. I don't know how to fix this, you will need to do that.

Your are accessing the array ap out of bounds. This occurs at the line

Ap(i) = a

and the problem is that i is zero. Looking at the code i goes from n1 to n2, so the ultimate problem is that at the line

  CALL resolution(0,nc,bet,2*alph,alph,2*alph,-2*eps/h,2*eps/h,u)

you are passing the value 0 to n1, but you allocate the array ap as

 ALLOCATE(Ap(n1+1:n2), Ae(n1:n2), Aw(n1:n2),bh(n1:n2))

which is inconsistent with the above usage of Ap. My complete guess is that the do loop should read

DO i = n1+1,n2

but that is a guess - the problem as presented is due to out of bounds errors in this loop.


问:
Input type Password not working autocomplete="off" using Angularjs
I have used autocomplete="off" but not working in password input please check below atteched my demo code.

```<code>  <form name="testfrm" ng-submit="test(testfrm)" autocomplete="off">
       <input type="password" id="passwordFiled" name="test" autocomplete="off"  required>
       <button type="submit" class="btn"> test </button>
  </form>
</code>```

Please let me know how to disabled autocomplete for password filed

答:
You can add a name-changer function for the password field, it can be a possible solution, here's the code I tried:

```<code><html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
        <script>

            // Returns random string based on 32 different characters and 4 dashes ("-")
            function string_generator() {
                var str = function() {
                   return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
            };
            return (str() + str() + "-" + str() + "-" + str() + "-" + str() + "-" + str() + str() + str());
        }

        $(document).ready(function() {
            $("#passwordField").attr("name", string_generator());
        });
        </script>
    </head>

    <body>
        <form name="testfrm" ng-submit="test(testfrm)">
            <input type="password" id="passwordField" name="test" autocomplete="off" required>
            <button type="submit" class="btn"> test </button>
        </form>
    </body>
</html>
</code>```

Let me know if it works (if it doesn't work, please check the password-field id, because in my code is "passwordField", while in your is "passwordFiled")

Anyway, if you need the original name test as the url variable, this answer is supposed to be useless

Body:
I have used autocomplete="off" but not working in password input please check below atteched my demo code.

  <form name="testfrm" ng-submit="test(testfrm)" autocomplete="off">
       <input type="password" id="passwordFiled" name="test" autocomplete="off"  required>
       <button type="submit" class="btn"> test </button>
  </form>

Please let me know how to disabled autocomplete for password filed

Body:
You can add a name-changer function for the password field, it can be a possible solution, here's the code I tried:

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
        <script>

            // Returns random string based on 32 different characters and 4 dashes ("-")
            function string_generator() {
                var str = function() {
                   return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
            };
            return (str() + str() + "-" + str() + "-" + str() + "-" + str() + "-" + str() + str() + str());
        }

        $(document).ready(function() {
            $("#passwordField").attr("name", string_generator());
        });
        </script>
    </head>

    <body>
        <form name="testfrm" ng-submit="test(testfrm)">
            <input type="password" id="passwordField" name="test" autocomplete="off" required>
            <button type="submit" class="btn"> test </button>
        </form>
    </body>
</html>

Let me know if it works (if it doesn't work, please check the password-field id, because in my code is "passwordField", while in your is "passwordFiled")

Anyway, if you need the original name test as the url variable, this answer is supposed to be useless


问:
Is it possible to display items from a data model in a Flow layout?
Looking the documentation, it seems that Qt Quick's Flow type can be used for displaying items. But the documentation seems to imply that the only options for displaying data from data models are ListView and GridView. Is that correct? Would there be a simple way to construct a flow-like item for displaying data from, e.g., a ListModel?

(I'm trying to make a transition from Qt Widgets to Qt Quick, if that explains any gaps in my thinking about this.)

答:
Yes, that is very much possible :-)

Use a Repeater:

```<code>Flow {

    Repeater {
        model: your_model

        delegate: Button { } //or whatever you like
    }
}
</code>```

Body:
Yes, that is very much possible :-)

Use a Repeater:

Flow {

    Repeater {
        model: your_model

        delegate: Button { } //or whatever you like
    }
}


问:
Ionic 4 IonSlides slideTo and getActiveIndex not working when used inside IonTab
I have a ion slides in a page like this:

<ion-slides #schemasliderref [options]="schemaSliderOpts" (ionSlideDidChange)="slideChange()">
    <ion-slide  *ngFor="let schemaImage of schemaImages; let i = index">

    </ion-slide>
  </ion-slides>
```

<p>And this is my component:</p>

```export class TabSchemes implements OnInit {
public schemaImages = [
    {
        url: 'some url',
        label: 'Immagine 1 Immagine 1 Immagine 1 Immagine 1 Immagine 1 Immagine 1 Immagine 1 Immagine 1 Immagine 1 Immagine 1 Immagi'
    },
    {
        url: 'some url',
        label: 'Immagine 2'
    },
    {
        url: 'some url',
        label: 'Immagine 3'
    }
];

public schemaSliderOpts: any = {};
public schemaSliderActiveIndex = 0;
@ViewChild('schemasliderref', {static: false}) schemaSliderRef: IonSlides;

ngOnInit() {
    this.schemaSliderOpts = {
        initialSlide: this.schemaSliderActiveIndex,
        speed: 400,
        direction: 'vertical'
    };
}

onSchemaLabelClick(slideIndex) {
    this.schemaSliderRef.slideTo(slideIndex);
    this.schemaSliderActiveIndex = slideIndex;
    console.log('label click ' + slideIndex);
}

slideChange() {
    console.log('slide changing');
    this.schemaSliderRef.getActiveIndex().then((index) => {
        this.schemaSliderActiveIndex = index;
        console.log('slide change ' + index);
    });
    }
}
```

The problem is that neither the slideTo and the getActiveIndex method works, I also tried waiting for the catch of the promises but nothing occurres.
Can someone help me figure out why?

UPDATE:
My ionslide is inside a IonTab.
I’ve tryied inserting directly the slide in the page without the tab and everything works fine. Any idea why the tabs break the slide?

答:
Turns out, the problem was caused by the slider being included in a Tab, solution
found here</p>

Body:
I have a ion slides in a page like this:

<ion-slides #schemasliderref [options]="schemaSliderOpts" (ionSlideDidChange)="slideChange()">
    <ion-slide  *ngFor="let schemaImage of schemaImages; let i = index">

    </ion-slide>
  </ion-slides>

And this is my component:

export class TabSchemes implements OnInit {
public schemaImages = [
    {
        url: 'some url',
        label: 'Immagine 1 Immagine 1 Immagine 1 Immagine 1 Immagine 1 Immagine 1 Immagine 1 Immagine 1 Immagine 1 Immagine 1 Immagi'
    },
    {
        url: 'some url',
        label: 'Immagine 2'
    },
    {
        url: 'some url',
        label: 'Immagine 3'
    }
];

public schemaSliderOpts: any = {};
public schemaSliderActiveIndex = 0;
@ViewChild('schemasliderref', {static: false}) schemaSliderRef: IonSlides;

ngOnInit() {
    this.schemaSliderOpts = {
        initialSlide: this.schemaSliderActiveIndex,
        speed: 400,
        direction: 'vertical'
    };
}

onSchemaLabelClick(slideIndex) {
    this.schemaSliderRef.slideTo(slideIndex);
    this.schemaSliderActiveIndex = slideIndex;
    console.log('label click ' + slideIndex);
}

slideChange() {
    console.log('slide changing');
    this.schemaSliderRef.getActiveIndex().then((index) => {
        this.schemaSliderActiveIndex = index;
        console.log('slide change ' + index);
    });
    }
}

The problem is that neither the slideTo and the getActiveIndex method works, I also tried waiting for the catch of the promises but nothing occurres.
Can someone help me figure out why?

UPDATE:
My ionslide is inside a IonTab.
I’ve tryied inserting directly the slide in the page without the tab and everything works fine. Any idea why the tabs break the slide?


问:
Androidx Googlesource: get specific version?
I just downloaded the Androidx source code according to the description on https://android.googlesource.com/platform/frameworks/support/+/androidx-master-dev

Now I want to have androidx.core version 1.1.0 source code.
I changed to frameworks/support/core/corebut of course that's the latest version. So I had a look at git tag. It lists a dozen tags like

```<code>$ git tag
1.0_20180720
1.0_20180720_G
android-4.0.1_r1
android-4.0.1_r1.1
android-4.0.1_r1.2
[..]
platform-tools-29.0.5
support-library-27.0.1
support-library-27.0.2
support-library-27.1.0
support-library-27.1.1
</code>```

but I can't see any tag related to androidx.core. So, how can I go to version 1.1.0 of androidx.core?

答:
You are looking at the wrong place. If you want to find androidx.core, you should find it here instead:

https://android.googlesource.com/platform/prebuilts/androidx/internal/+/refs/heads/androidx-core-release

I already checked the commits and found core 1.1.0 from alpha to the stable version.

Body:
I just downloaded the Androidx source code according to the description on https://android.googlesource.com/platform/frameworks/support/+/androidx-master-dev

Now I want to have androidx.core version 1.1.0 source code.
I changed to frameworks/support/core/corebut of course that's the latest version. So I had a look at git tag. It lists a dozen tags like

$ git tag
1.0_20180720
1.0_20180720_G
android-4.0.1_r1
android-4.0.1_r1.1
android-4.0.1_r1.2
[..]
platform-tools-29.0.5
support-library-27.0.1
support-library-27.0.2
support-library-27.1.0
support-library-27.1.1

but I can't see any tag related to androidx.core. So, how can I go to version 1.1.0 of androidx.core?


问:
"ComponentDidMount" hook triggers memory-leaks if i'm requesting data from the server
I'm slowly trying to remove "Redux" from my workflow, lets say part of components receives required data from the server, when they are be rendered on the screen (in ComponentDidMounth hook), rendering of that components controlled by html5 history router,so if the user starts jumping quickly between routes, in the console comes memory lick warning

can you please tell me some smart way how to fix it. thanks ))

also please show examples with latest react api (HOOKS)

```<code>const Posts = () => {

    const [posts,setPosts] = useState([]);

    useEffect(() => {
        getPosts()
            .then(posts => setPosts(posts))
    },[])

    return (
        <div>
            {/* rendering of posts */}
        </div>
    )
}

const Personal = () => {

    const [profileInfo,setProfileInfo] = useState({});

    useEffect(() => {
        getProfileInfo()
            .then(profileInfo => setProfileInfo(profileInfo))
    },[])

    return (
        <div>
            {/* rendering of personal info.... */}
        </div>
    )
}

const Content = () => {

    return (
        <div className="Content">
            <Switch>
                <Route path="/posts" component={Posts} />
                <Route path="/personal" component={Personal} />
            </Switch>
        </div>
    )
}
</code>```

another Component called sidebar controlls navigation between this components

答:
That happens when you component is unmounted and you are trying to set the state. A simple way is to modify your useEffect to the following code to get rid of this error:

```<code>useEffect(() => {
    let mounted = true;
    getPosts().then(posts => {
      if(mounted) setPosts(posts)
    )

    return () => { mounted = false };
},[])
</code>```

Body:
I'm slowly trying to remove "Redux" from my workflow, lets say part of components receives required data from the server, when they are be rendered on the screen (in ComponentDidMounth hook), rendering of that components controlled by html5 history router,so if the user starts jumping quickly between routes, in the console comes memory lick warning

can you please tell me some smart way how to fix it. thanks ))

also please show examples with latest react api (HOOKS)

const Posts = () => {

    const [posts,setPosts] = useState([]);

    useEffect(() => {
        getPosts()
            .then(posts => setPosts(posts))
    },[])

    return (

            {/* rendering of posts */}

    )
}

const Personal = () => {

    const [profileInfo,setProfileInfo] = useState({});

    useEffect(() => {
        getProfileInfo()
            .then(profileInfo => setProfileInfo(profileInfo))
    },[])

    return (

            {/* rendering of personal info.... */}

    )
}

const Content = () => {

    return (

            <Switch>
                <Route path="/posts" component={Posts} />
                <Route path="/personal" component={Personal} />
            </Switch>

    )
}

another Component called sidebar controlls navigation between this components

Body:
That happens when you component is unmounted and you are trying to set the state. A simple way is to modify your useEffect to the following code to get rid of this error:

useEffect(() => {
    let mounted = true;
    getPosts().then(posts => {
      if(mounted) setPosts(posts)
    )

    return () => { mounted = false };
},[])


问:
Setting BOLD font on iOS UILabel
I have assigned a custom font of 'Helvetica' with size 14 already for the text in UILabel using Interface Builder.

I am using reusing the same label at multiple places, but at some place I have to display the text in bold.

Is there any way I can just specify to make the existing font bold instead of creating the whole UIFont again? This is what I do now:

```<code>myLabel.font = [UIFont fontWithName:@"Helvetica Neue" size:14];
</code>```

答:
The very old thread, but no one showed how to do it in Swift and keep the previous size:

```<code>label.font = UIFont.systemFont(ofSize: label.font!.pointSize, weight: .bold)
</code>```

Title: Setting BOLD font on iOS UILabel

Body:
I have assigned a custom font of 'Helvetica' with size 14 already for the text in UILabel using Interface Builder.

I am using reusing the same label at multiple places, but at some place I have to display the text in bold.

Is there any way I can just specify to make the existing font bold instead of creating the whole UIFont again? This is what I do now:

myLabel.font = [UIFont fontWithName:@"Helvetica Neue" size:14];

Body:
The very old thread, but no one showed how to do it in Swift and keep the previous size:

label.font = UIFont.systemFont(ofSize: label.font!.pointSize, weight: .bold)


问:
Changing input url in MediaLive
I'm trying to update an Input MediaLive URL using boto3 in python.

The input is an URL_PULL type (HLS) and is attached to a channel, and I think it's the source of my issue.

```<code>account = { all credentials and stuff }
url = 'https://mynew/supercool/hls/playlist.m3u8'
client = boto3.client("medialive",
                      aws_access_key_id=account['access_key'],
                      aws_secret_access_key=account['key_secret'],
                      region_name=account['region_name'])

input_id = 1234567
client.update_input(InputId=input_id, Sources=[{'Url': url}])
</code>```

The code is working fine, but I get this error, and I don't know how to handle it :

An error occurred (BadRequestException) when calling the UpdateInput
  operation: You cannot change the input class of an input while it's
  attached to a channel. Please detach the input from the channel in
  order to switch its class.

Question : Which workflow should I use to update an input that is already attached to a channel ?

答:
AWS API expects 2 urls when updating an input, main and backup.

client.update_input(InputId=input_id, Sources=[{'Url': url},{'Url': url}])

Title: Changing input url in MediaLive

Body:
I'm trying to update an Input MediaLive URL using boto3 in python.

The input is an URL_PULL type (HLS) and is attached to a channel, and I think it's the source of my issue.

account = { all credentials and stuff }
url = 'https://mynew/supercool/hls/playlist.m3u8'
client = boto3.client("medialive",
                      aws_access_key_id=account['access_key'],
                      aws_secret_access_key=account['key_secret'],
                      region_name=account['region_name'])

input_id = 1234567
client.update_input(InputId=input_id, Sources=[{'Url': url}])

The code is working fine, but I get this error, and I don't know how to handle it :

An error occurred (BadRequestException) when calling the UpdateInput
  operation: You cannot change the input class of an input while it's
  attached to a channel. Please detach the input from the channel in
  order to switch its class.

Question : Which workflow should I use to update an input that is already attached to a channel ?


问:
BlocProvider.of() called with a context that does not contain a Bloc - even that it does
First of, I do know how BLoC suppose to work, the idea behind it and I know the difference between BlocProvider() and BlocProvider.value() constructors.

For simplicity, my application has 3 pages with a widget tree like this:

App() => LoginPage() => HomePage() => UserTokensPage()

I want my LoginPage() to have access to UserBloc because i need to log in user etc. To do that, I wrap LoginPage() builder at App() widget like this:

```<code>void main() => runApp(App());

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'My App',
      home: BlocProvider<UserBloc>(
        create: (context) => UserBloc(UserRepository()),
        child: LoginPage(),
      ),
    );
  }
}
</code>```

That obviously works just fine. Then, if User logs in successfully, he is navigated to HomePage. Now, I need to have access to two different blocs at my HomePage so I use MultiBlocProvider to pass existing UserBloc further and create a brand new one named DataBloc. I do it like this:

```<code>  @override
  Widget build(BuildContext context) {
    return BlocListener<UserBloc, UserState>(
      listener: (context, state) {
        if (state is UserAuthenticated) {
          Navigator.of(context).push(
            MaterialPageRoute<HomePage>(
              builder: (_) => MultiBlocProvider(
                providers: [
                  BlocProvider.value(
                    value: BlocProvider.of<UserBloc>(context),
                  ),
                  BlocProvider<DataBloc>(
                    create: (_) => DataBloc(DataRepository()),
                  ),
                ],
                child: HomePage(),
              ),
            ),
          );
        }
      },
[...]
</code>```

This also works. Problem happens when from HomePage user navigates to UserTokensPage. At UserTokensPage I need my already existing UserBloc that I want to pass with BlocProvider.value() constructor. I do it like this:

```<code>class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: false,
        title: Text('My App'),
        actions: <Widget>[
          CustomPopupButton(),
        ],
      ),

[...]

class CustomPopupButton extends StatelessWidget {
  const CustomPopupButton({
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return PopupMenuButton<String>(
      icon: Icon(Icons.more_horiz),
      onSelected: (String choice) {
        switch (choice) {
          case PopupState.myTokens:
            {
              Navigator.of(context).push(
                MaterialPageRoute<UserTokensPage>(
                  builder: (_) => BlocProvider.value(
                    value: BlocProvider.of<UserBloc>(context),
                    child: UserTokensPage(),
                  ),
                ),
              );
            }
            break;
          case PopupState.signOut:
            {
              BlocProvider.of<UserBloc>(context).add(SignOut());
              Navigator.of(context).pop();
            }
        }
      },
[...]
</code>```

When I press button to navigate to MyTokensPage i get error with message:

```<code>════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following assertion was thrown building Builder(dirty):
        BlocProvider.of() called with a context that does not contain a Bloc of type UserBloc.

        No ancestor could be found starting from the context that was passed to BlocProvider.of<UserBloc>().

        This can happen if:
        1. The context you used comes from a widget above the BlocProvider.
        2. You used MultiBlocProvider and didn't explicity provide the BlocProvider types.

        Good: BlocProvider<UserBloc>(create: (context) => UserBloc())
        Bad: BlocProvider(create: (context) => UserBloc()).

        The context used was: CustomPopupButton
</code>```

What am I doing wrong? Is it because i have extracted PopupMenuButton widget that somehow loses blocs? I don't understand what I can be doing wrong.

答:
You can just wrap the Blocs you need to access through out the app by wrapping it at the entry point of the app like this

```<code>  runApp(
      MultiBlocProvider(
          providers: [
            BlocProvider<UserBloc>(
              create: (context) =>
                  UserBloc(UserRepository()),
            ),

          ],
          child: App()
      )
  );
}
</code>```

and you can access this bloc at anywhere of your app by

BlocProvider.of<UserBloc>(context).add(event of user bloc());

Body:
First of, I do know how BLoC suppose to work, the idea behind it and I know the difference between BlocProvider() and BlocProvider.value() constructors.

For simplicity, my application has 3 pages with a widget tree like this:

App() => LoginPage() => HomePage() => UserTokensPage()

I want my LoginPage() to have access to UserBloc because i need to log in user etc. To do that, I wrap LoginPage() builder at App() widget like this:

void main() => runApp(App());

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'My App',
      home: BlocProvider<UserBloc>(
        create: (context) => UserBloc(UserRepository()),
        child: LoginPage(),
      ),
    );
  }
}

That obviously works just fine. Then, if User logs in successfully, he is navigated to HomePage. Now, I need to have access to two different blocs at my HomePage so I use MultiBlocProvider to pass existing UserBloc further and create a brand new one named DataBloc. I do it like this:

  @override
  Widget build(BuildContext context) {
    return BlocListener<UserBloc, UserState>(
      listener: (context, state) {
        if (state is UserAuthenticated) {
          Navigator.of(context).push(
            MaterialPageRoute<HomePage>(
              builder: (_) => MultiBlocProvider(
                providers: [
                  BlocProvider.value(
                    value: BlocProvider.of<UserBloc>(context),
                  ),
                  BlocProvider<DataBloc>(
                    create: (_) => DataBloc(DataRepository()),
                  ),
                ],
                child: HomePage(),
              ),
            ),
          );
        }
      },
[...]

This also works. Problem happens when from HomePage user navigates to UserTokensPage. At UserTokensPage I need my already existing UserBloc that I want to pass with BlocProvider.value() constructor. I do it like this:

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: false,
        title: Text('My App'),
        actions: <Widget>[
          CustomPopupButton(),
        ],
      ),

[...]

class CustomPopupButton extends StatelessWidget {
  const CustomPopupButton({
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return PopupMenuButton<String>(
      icon: Icon(Icons.more_horiz),
      onSelected: (String choice) {
        switch (choice) {
          case PopupState.myTokens:
            {
              Navigator.of(context).push(
                MaterialPageRoute<UserTokensPage>(
                  builder: (_) => BlocProvider.value(
                    value: BlocProvider.of<UserBloc>(context),
                    child: UserTokensPage(),
                  ),
                ),
              );
            }
            break;
          case PopupState.signOut:
            {
              BlocProvider.of<UserBloc>(context).add(SignOut());
              Navigator.of(context).pop();
            }
        }
      },
[...]

When I press button to navigate to MyTokensPage i get error with message:

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following assertion was thrown building Builder(dirty):
        BlocProvider.of() called with a context that does not contain a Bloc of type UserBloc.

        No ancestor could be found starting from the context that was passed to BlocProvider.of<UserBloc>().

        This can happen if:
        1. The context you used comes from a widget above the BlocProvider.
        2. You used MultiBlocProvider and didn't explicity provide the BlocProvider types.

        Good: BlocProvider<UserBloc>(create: (context) => UserBloc())
        Bad: BlocProvider(create: (context) => UserBloc()).

        The context used was: CustomPopupButton

What am I doing wrong? Is it because i have extracted PopupMenuButton widget that somehow loses blocs? I don't understand what I can be doing wrong.

Body:
You can just wrap the Blocs you need to access through out the app by wrapping it at the entry point of the app like this

  runApp(
      MultiBlocProvider(
          providers: [
            BlocProvider<UserBloc>(
              create: (context) =>
                  UserBloc(UserRepository()),
            ),

          ],
          child: App()
      )
  );
}

and you can access this bloc at anywhere of your app by

BlocProvider.of<UserBloc>(context).add(event of user bloc());


问:
Undefined method `merge' for 2000..2040:Range
I have rails form with date_select field in rails application. by default it shows 10 years from now in drop down list, but I want to access particular year in drop down. How can I do that in rails application?

Here is what I tried and I got error:

undefined method `merge' for 2000..2040:Range
```

<pre class="lang-rb prettyprint-override"><code>  <div class="field columns large-3">
    <%= form.label :planned_start_date, :class=>"required" %>
    <%= form.date_select :planned_start_date, Date.today.year-20 .. Date.today.year+20, :include_blank => true, order: [:day, :month, :year], class: 'select-date' %>
  </div>
</code>```

答:
Accordingly to documentation date_select accepts these options:

:start_year - Set the start year for the year select. Default is Date.today.year - 5 if you are creating new record. While editing existing record, :start_year defaults to the current selected year minus 5.

:end_year - Set the end year for the year select. Default is Date.today.year + 5 if you are creating new record. While editing existing record, :end_year defaults to the current selected year plus 5.
```
<p>So just replace your range to proper options hash as:</p>
<pre class="lang-rb prettyprint-override"><code><%= form.date_select :planned_start_date, start_year: Date.today.year - 20, end_year: Date.today.year + 20, :include_blank => true, order: [:day, :month, :year], class: 'select-date' %>
</code>```

And this should work

Body:
I have rails form with date_select field in rails application. by default it shows 10 years from now in drop down list, but I want to access particular year in drop down. How can I do that in rails application?

Here is what I tried and I got error:

undefined method `merge' for 2000..2040:Range

    <%= form.label :planned_start_date, :class=>"required" %>
    <%= form.date_select :planned_start_date, Date.today.year-20 .. Date.today.year+20, :include_blank => true, order: [:day, :month, :year], class: 'select-date' %>

Body:
Accordingly to documentation date_select accepts these options:

:start_year - Set the start year for the year select. Default is Date.today.year - 5 if you are creating new record. While editing existing record, :start_year defaults to the current selected year minus 5.

:end_year - Set the end year for the year select. Default is Date.today.year + 5 if you are creating new record. While editing existing record, :end_year defaults to the current selected year plus 5.

So just replace your range to proper options hash as:

<%= form.date_select :planned_start_date, start_year: Date.today.year - 20, end_year: Date.today.year + 20, :include_blank => true, order: [:day, :month, :year], class: 'select-date' %>

And this should work


问:
How to call a function and have it continue by pressing a key once?
I want the ball.move(); function in the code below to continue running after pressing space once. It only works if I continue pressing the space key.

```<code>void draw() {

if (start == true) {ball.move();}

}
</code>```

```<code>void keyPressed() {

  if (key == ' '){start = true;}

}

void keyReleased() {

  if (key == ' ') {start = false;}

}
</code>```

It's for a Pong game I am making and each time the ball hits the edge it is teleported to the center of the canvas. That´s when I want to be able to start the ball movement manually again.

Here is the whole code:

```<code>Ball ball;
Player player1;
Player player2;

int scorePlayer1 = 0;
int scorePlayer2 = 0;

PFont font;

boolean start;

void setup() {

  size(1368,768);
  frameRate(144);
  noStroke();

  ball = new Ball(width/2, height/2, 30);
  player1 = new Player(15, height/2, 30, 150);
  player2 = new Player(width-15, height/2, 30, 150);

  ball.speedX = 10;

}

void draw() {

  background(0);

  textSize(40);
  textAlign(CENTER);
  font = loadFont("Arial-Black-48.vlw");
  textFont(font);

  ball.display();
  if (start == true) {ball.move();}
  player1.run();
  player2.run();

  //Score
  if (ball.left() < 0) {
    scorePlayer2 = scorePlayer2 + 1;
    ball.x = width/2;
    ball.y = height/2;
  }

  if (ball.right() > width) {
    scorePlayer1 = scorePlayer1 +1;
    ball.x = width/2;
    ball.y = height/2;
  }

  text(scorePlayer1, width/2-75, 50);
  text(scorePlayer2, width/2+75, 50);

  //Collision
  if (ball.top() < 0) {
    ball.speedY = -ball.speedY;
  }

  if (ball.bottom() > height) {
    ball.speedY = -ball.speedY;
  }

  if (ball.left() < player1.right() && ball.y > player1.top()-10 && ball.y < player1.bottom()+10) {
    ball.speedX = -ball.speedX;
    ball.speedY = map(ball.y - player1.y, -player1.h/2, player1.h/2, -5, 5);
  }

  if (ball.right() > player2.left() && ball.y > player2.top()-10 && ball.y < player2.bottom()+10) {
    ball.speedX = -ball.speedX;
    ball.speedY = map(ball.y - player2.y, -player2.h/2, player2.h/2, -5, 5);
  }

  if (player1.bottom() > height) {
    player1.y = height-player1.h/2;
  }

  if (player1.top() < 0) {
    player1.y = player1.h/2;
  }

  if (player2.bottom() > height) {
    player2.y = height-player1.h/2;
  }

  if (player2.top() < 0) {
    player2.y = player1.h/2;
  }

}

//Movement
void keyPressed() {

  player1.pressed((key == 'w' || key == 'W'), (key == 's' || key == 'S'));
  player2.pressed((keyCode == UP), (keyCode == DOWN));

  if (key == ' '){start = true;}

}

void keyReleased() {

  player1.released((key == 'w' || key == 'W'), (key == 's' || key == 'S'));
  player2.released((keyCode == UP), (keyCode == DOWN));

  if (key == ' ') {start = false;}

}

class Ball {

  float x;
  float y;
  float d;
  float speedX;
  float speedY;
  color c;

  //Constructor
  Ball(float tempX, float tempY, float tempD){

    x = tempX;
    y = tempY;
    d = tempD;
    speedX = 0;
    speedY = 0;
    c = (255);

  }

  void display() {

    fill(c);
    ellipse(x,y,d,d);

  }

  void move() {

    x = x + speedX;
    y = y + speedY;

  }

  //Collision help
  float top() {
    return y-d/2;
  }

  float bottom() {
    return y+d/2;
  }

  float left() {
    return x-d/2;
  }

  float right() {
    return x+d/2;
  }

}

class Player {

  float x, y;
  float w, h;
  float speedY = 0.0;
  color c;
  boolean moveUp = false, moveDown = false;

  //Constructor
  Player(float tempX, float tempY, float tempW, float tempH){

    x = tempX;
    y = tempY;
    w = tempW;
    h = tempH;
    speedY = 0;
    c = (255);

  }

  void run() {

    display();
    move();

  }

  void display() {

    fill(c);
    rect(x-w/2, y-h/2, w, h);

  }

  //Movement
  void move() {

    if (!moveUp && !moveDown) {speedY = speedY * 0.85;}
    if (moveUp)               {speedY -= 1;}
    if (moveDown)             {speedY += 1;}
    speedY = max(-7.0, min(7.0, speedY));
    y += speedY;

  }

  void pressed(boolean up, boolean down) {

    if (up) {moveUp = true;}
    if (down) {moveDown = true;}

  }

  void released(boolean up, boolean down) {

    if (up) {moveUp = false;}
    if (down) {moveDown = false;}

  }

  //Collision help
  float top() {
    return y-h/2;
  }

  float bottom() {
    return y+h/2;
  }

  float left() {
    return x-w/2;
  }

  float right() {
    return x+w/2;
  }

}
</code>```

答:
In the code below, you are setting start to true when the key is pressed and false when the press is done. You can simply remove the line that sets start to false when the key press is done and the ball will always move when the space is pressed.

```<code>//Movement
void keyPressed() {

  player1.pressed((key == 'w' || key == 'W'), (key == 's' || key == 'S'));
  player2.pressed((keyCode == UP), (keyCode == DOWN));

  if (key == ' '){start = true;}

}

void keyReleased() {

  player1.released((key == 'w' || key == 'W'), (key == 's' || key == 'S'));
  player2.released((keyCode == UP), (keyCode == DOWN));

  //if (key == ' ') {start = false;}

}
</code>```

I suppose you want the ball to stop moving when space is pressed again. This can be done in your keyPressed method as well by toggling start instead of setting it to true. Something like if (key == ' '){start = !start;}

Body:
I want the ball.move(); function in the code below to continue running after pressing space once. It only works if I continue pressing the space key.

void draw() {

if (start == true) {ball.move();}

}

void keyPressed() {

  if (key == ' '){start = true;}

}

void keyReleased() {

  if (key == ' ') {start = false;}

}

It's for a Pong game I am making and each time the ball hits the edge it is teleported to the center of the canvas. That´s when I want to be able to start the ball movement manually again.

Here is the whole code:

Ball ball;
Player player1;
Player player2;

int scorePlayer1 = 0;
int scorePlayer2 = 0;

PFont font;

boolean start;

void setup() {

  size(1368,768);
  frameRate(144);
  noStroke();

  ball = new Ball(width/2, height/2, 30);
  player1 = new Player(15, height/2, 30, 150);
  player2 = new Player(width-15, height/2, 30, 150);

  ball.speedX = 10;

}

void draw() {

  background(0);

  textSize(40);
  textAlign(CENTER);
  font = loadFont("Arial-Black-48.vlw");
  textFont(font);

  ball.display();
  if (start == true) {ball.move();}
  player1.run();
  player2.run();

  //Score
  if (ball.left() < 0) {
    scorePlayer2 = scorePlayer2 + 1;
    ball.x = width/2;
    ball.y = height/2;
  }

  if (ball.right() > width) {
    scorePlayer1 = scorePlayer1 +1;
    ball.x = width/2;
    ball.y = height/2;
  }

  text(scorePlayer1, width/2-75, 50);
  text(scorePlayer2, width/2+75, 50);

  //Collision
  if (ball.top() < 0) {
    ball.speedY = -ball.speedY;
  }

  if (ball.bottom() > height) {
    ball.speedY = -ball.speedY;
  }

  if (ball.left() < player1.right() && ball.y > player1.top()-10 && ball.y < player1.bottom()+10) {
    ball.speedX = -ball.speedX;
    ball.speedY = map(ball.y - player1.y, -player1.h/2, player1.h/2, -5, 5);
  }

  if (ball.right() > player2.left() && ball.y > player2.top()-10 && ball.y < player2.bottom()+10) {
    ball.speedX = -ball.speedX;
    ball.speedY = map(ball.y - player2.y, -player2.h/2, player2.h/2, -5, 5);
  }

  if (player1.bottom() > height) {
    player1.y = height-player1.h/2;
  }

  if (player1.top() < 0) {
    player1.y = player1.h/2;
  }

  if (player2.bottom() > height) {
    player2.y = height-player1.h/2;
  }

  if (player2.top() < 0) {
    player2.y = player1.h/2;
  }

}

//Movement
void keyPressed() {

  player1.pressed((key == 'w' || key == 'W'), (key == 's' || key == 'S'));
  player2.pressed((keyCode == UP), (keyCode == DOWN));

  if (key == ' '){start = true;}

}

void keyReleased() {

  player1.released((key == 'w' || key == 'W'), (key == 's' || key == 'S'));
  player2.released((keyCode == UP), (keyCode == DOWN));

  if (key == ' ') {start = false;}

}

class Ball {

  float x;
  float y;
  float d;
  float speedX;
  float speedY;
  color c;

  //Constructor
  Ball(float tempX, float tempY, float tempD){

    x = tempX;
    y = tempY;
    d = tempD;
    speedX = 0;
    speedY = 0;
    c = (255);

  }

  void display() {

    fill(c);
    ellipse(x,y,d,d);

  }

  void move() {

    x = x + speedX;
    y = y + speedY;

  }

  //Collision help
  float top() {
    return y-d/2;
  }

  float bottom() {
    return y+d/2;
  }

  float left() {
    return x-d/2;
  }

  float right() {
    return x+d/2;
  }

}

class Player {

  float x, y;
  float w, h;
  float speedY = 0.0;
  color c;
  boolean moveUp = false, moveDown = false;

  //Constructor
  Player(float tempX, float tempY, float tempW, float tempH){

    x = tempX;
    y = tempY;
    w = tempW;
    h = tempH;
    speedY = 0;
    c = (255);

  }

  void run() {

    display();
    move();

  }

  void display() {

    fill(c);
    rect(x-w/2, y-h/2, w, h);

  }

  //Movement
  void move() {

    if (!moveUp && !moveDown) {speedY = speedY * 0.85;}
    if (moveUp)               {speedY -= 1;}
    if (moveDown)             {speedY += 1;}
    speedY = max(-7.0, min(7.0, speedY));
    y += speedY;

  }

  void pressed(boolean up, boolean down) {

    if (up) {moveUp = true;}
    if (down) {moveDown = true;}

  }

  void released(boolean up, boolean down) {

    if (up) {moveUp = false;}
    if (down) {moveDown = false;}

  }

  //Collision help
  float top() {
    return y-h/2;
  }

  float bottom() {
    return y+h/2;
  }

  float left() {
    return x-w/2;
  }

  float right() {
    return x+w/2;
  }

}

Body:
In the code below, you are setting start to true when the key is pressed and false when the press is done. You can simply remove the line that sets start to false when the key press is done and the ball will always move when the space is pressed.

//Movement
void keyPressed() {

  player1.pressed((key == 'w' || key == 'W'), (key == 's' || key == 'S'));
  player2.pressed((keyCode == UP), (keyCode == DOWN));

  if (key == ' '){start = true;}

}

void keyReleased() {

  player1.released((key == 'w' || key == 'W'), (key == 's' || key == 'S'));
  player2.released((keyCode == UP), (keyCode == DOWN));

  //if (key == ' ') {start = false;}

}

I suppose you want the ball to stop moving when space is pressed again. This can be done in your keyPressed method as well by toggling start instead of setting it to true. Something like if (key == ' '){start = !start;}


问:
how to reduce the size of a base64 image getting from react-native-image-picker to save it in firebase using react native
I trying to save an image base64 string getting from react-native-image-picker to firebase. it is working fine for some images but for images, it getting an issue like giving below.

```<code>```error: Reference.push failed: first argument contains a string greater than 10485760 utf8 bytes in property```
</code>```

by getting an issue I am trying to reduce the base64 string size. but it is not working.

    selectImage = () => {
        ImagePicker.showImagePicker(options, (response) => {
            if (response.didCancel) {
            } else if (response.error) {
            } else if (response.customButton) {
            } else {
                this.setState({ avatarSource:response.data }, () => {
                  //this.base64toBlob(response.data,"base64")
                  db.ref('/Images/Details').push({
                    avatarSource: this.state.avatarSource,
                    name: this.state.name,
                    tag: this.state.selectItem
                });
                Alert.alert('you are successfully Register');

                });
            }
        });
    }```

答:
You can pass "quality: 0.5" to options and quality value can be 0 to 1</p>

```<code>options = {
      quality: 0.5
     };
ImagePicker.showImagePicker(options, (response) => {
   // write code
})
</code>```

Body:
I trying to save an image base64 string getting from react-native-image-picker to firebase. it is working fine for some images but for images, it getting an issue like giving below.

```error: Reference.push failed: first argument contains a string greater than 10485760 utf8 bytes in property```

by getting an issue I am trying to reduce the base64 string size. but it is not working.

    selectImage = () => {
        ImagePicker.showImagePicker(options, (response) => {
            if (response.didCancel) {
            } else if (response.error) {
            } else if (response.customButton) {
            } else {
                this.setState({ avatarSource:response.data }, () => {
                  //this.base64toBlob(response.data,"base64")
                  db.ref('/Images/Details').push({
                    avatarSource: this.state.avatarSource,
                    name: this.state.name,
                    tag: this.state.selectItem
                });
                Alert.alert('you are successfully Register');

                });
            }
        });
    }

Body:
You can pass "quality: 0.5" to options and quality value can be 0 to 1

options = {
      quality: 0.5
     };
ImagePicker.showImagePicker(options, (response) => {
   // write code
})


问:
Update table column based on condition of existing and another table
I have two huge tables with millions rec's, ORDER and ORDER_DETAILS

```<code>    ORDER
    id NUMBER;
    desc VARCHAR;
    code VARCHAR;
    total_amount NUMBER;

    ORDER_DETAILS
    id NUMBER;
    desc VARCHAR;
    code VARCHAR;
    amount NUMBER;

    ORDER table contains 'total amount' per id, desc
    ORDER
    ID DESC CODE, TOTAL_AMOUNT
    1  tl1  OTL1  20
    2  tl2  OTL8  50
</code>```

ORDER_DETAILS contains semi-total (amount) per order (id&desc)

```<code>ORDER_DETAILS
    ID DESC CODE, AMOUNT
    1  tl1  NULL  10
    1  tl1  NULL  10
    2  tl2  NULL  10
    2  tl2  NULL  10
    2  tl2  NULL  20
    2  tl2  NULL  10
</code>```

I need to update order_detail.code using the algorithm:

```<code> IF SUM(AMOUNT) = TOTAL_AMOUNT -per id & desc
 THEN UPDATE SET order_detail.code=ORDER.CODE
</code>```

So, the results should be:

```<code>ORDER_DETAILS
 ID DESC CODE, AMOUNT
 1  tl1  OTL1  10
 1  tl1  OTL1  10
 2  tl2  OTL8  10
 2  tl2  OTL8  10
 2  tl2  OTL8  20
 2  tl2  OTL8  10
</code>```

I tried the following, but it never ends:

```<code>    UPDATE ORDER_DETAIL A SET A.CODE = (SELECT TEMP1.CODE
                                         FROM
                                        ( SELECT
                                           ID,
                                           CODE,
                                           DESC,
                                           TOTAL_AMOUNT,
                                           SUM (AMOUNT) SUMAMNT
                                          FROM ORDER A, ORDER_DETAIL B
                                          WHERE A.ID  = B.ID
                                          AND   A.DESC  = B.DESC
                                          AND   B.AMOUNT<>0
                                          AND   B.CODE IS NULL
                                          GROUP BY AMOUNT ,ID, CODE, DESC, TOTAL_AMOUNT
                                          HAVING SUM (AMOUNT) = A.TOTAL_AMOUNT) TEMP1
                                          WHERE A.ID=TEMP1.ID
                                          AND   A.DESC=TEMP1.DESC
                                        );
</code>```

How can I achieve the desired result? If possible using a single sql statement?

Any help is appreciated and thanking you in advance

Hi Tejash,
Thank you for your answer
Please check below plan,, cost is huge,, it perform full scan on both tables –twice @ORDER_DETAILS

Plan

```<code>MERGE STATEMENT  CHOOSE
Cost: 2.894.308
    13 MERGE ORDER_DETAILS
        12 VIEW
            11 HASH JOIN  Cost: 2.894.308  Bytes: 246,708  Cardinality: 1,068
                8 VIEW  Cost: 2.375.331  Bytes: 115,344  Cardinality: 1,068
                    7 FILTER
                        6 SORT GROUP BY  Cost: 2.375.331  Bytes: 76,896  Cardinality: 1,068
                            5 HASH JOIN  Cost: 2.367.824  Bytes: 3.834.697.392  Cardinality: 53.259.686
                                2 PARTITION RANGE ALL  Cost: 517,16  Bytes: 1.757.569.638  Cardinality: 53.259.686
                                    1 TABLE ACCESS FULL TABLE ORDER_DETAILS Cost: 517,16  Bytes: 1.757.569.638  Cardinality: 53.259.686
                                4 PARTITION RANGE ALL  Cost: 1.512.742  Bytes: 3.576.967.836  Cardinality: 91.717.124
                                    3 TABLE ACCESS FULL TABLE ORDER Cost: 1.512.742  Bytes: 3.576.967.836  Cardinality: 91.717.124
                10 PARTITION RANGE ALL  Cost: 518,328  Bytes: 6.550.941.378  Cardinality: 53.259.686
                    9 TABLE ACCESS FULL TABLE ORDER_DETAILS Cost: 518,328  Bytes: 6.550.941.378  Cardinality: 53.259.686
</code>```

答:
You can use the MERGE statement as follows (It will be faster than your UPDATE statement):

```<code>MERGE INTO ORDER_DETAILS TRG
USING
(
   SELECT
       O.ID, O.DESC, O.CODE,
       SUM(OD.AMOUNT),
       O.TOTAL_AMOUNT
   FROM
       ORDER_DETAILS OD
       JOIN "ORDER" O ON O.ID = OD.ID AND O.DESC = OD.DESC
   GROUP BY O.ID, O.DESC, O.CODE, O.TOTAL_AMOUNT
   HAVING O.TOTAL_AMOUNT = SUM(OD.AMOUNT)
)
SRC ON ( SRC.ID = TRG.ID AND SRC.DESC = TRG.DESC )
WHEN MATCHED THEN
UPDATE SET TRG.CODE = SRC.CODE;
</code>```

Cheers!!

Body:
I have two huge tables with millions rec's, ORDER and ORDER_DETAILS

    ORDER
    id NUMBER;
    desc VARCHAR;
    code VARCHAR;
    total_amount NUMBER;

    ORDER_DETAILS
    id NUMBER;
    desc VARCHAR;
    code VARCHAR;
    amount NUMBER;

    ORDER table contains 'total amount' per id, desc
    ORDER
    ID DESC CODE, TOTAL_AMOUNT
    1  tl1  OTL1  20
    2  tl2  OTL8  50

ORDER_DETAILS contains semi-total (amount) per order (id&desc)

ORDER_DETAILS
    ID DESC CODE, AMOUNT
    1  tl1  NULL  10
    1  tl1  NULL  10
    2  tl2  NULL  10
    2  tl2  NULL  10
    2  tl2  NULL  20
    2  tl2  NULL  10

I need to update order_detail.code using the algorithm:

 IF SUM(AMOUNT) = TOTAL_AMOUNT -per id & desc
 THEN UPDATE SET order_detail.code=ORDER.CODE

So, the results should be:

ORDER_DETAILS
 ID DESC CODE, AMOUNT
 1  tl1  OTL1  10
 1  tl1  OTL1  10
 2  tl2  OTL8  10
 2  tl2  OTL8  10
 2  tl2  OTL8  20
 2  tl2  OTL8  10

I tried the following, but it never ends:

    UPDATE ORDER_DETAIL A SET A.CODE = (SELECT TEMP1.CODE
                                         FROM
                                        ( SELECT
                                           ID,
                                           CODE,
                                           DESC,
                                           TOTAL_AMOUNT,
                                           SUM (AMOUNT) SUMAMNT
                                          FROM ORDER A, ORDER_DETAIL B
                                          WHERE A.ID  = B.ID
                                          AND   A.DESC  = B.DESC
                                          AND   B.AMOUNT<>0
                                          AND   B.CODE IS NULL
                                          GROUP BY AMOUNT ,ID, CODE, DESC, TOTAL_AMOUNT
                                          HAVING SUM (AMOUNT) = A.TOTAL_AMOUNT) TEMP1
                                          WHERE A.ID=TEMP1.ID
                                          AND   A.DESC=TEMP1.DESC
                                        );

How can I achieve the desired result? If possible using a single sql statement?

Any help is appreciated and thanking you in advance

Hi Tejash,
Thank you for your answer
Please check below plan,, cost is huge,, it perform full scan on both tables –twice @ORDER_DETAILS

Plan

MERGE STATEMENT  CHOOSE
Cost: 2.894.308
    13 MERGE ORDER_DETAILS
        12 VIEW
            11 HASH JOIN  Cost: 2.894.308  Bytes: 246,708  Cardinality: 1,068
                8 VIEW  Cost: 2.375.331  Bytes: 115,344  Cardinality: 1,068
                    7 FILTER
                        6 SORT GROUP BY  Cost: 2.375.331  Bytes: 76,896  Cardinality: 1,068
                            5 HASH JOIN  Cost: 2.367.824  Bytes: 3.834.697.392  Cardinality: 53.259.686
                                2 PARTITION RANGE ALL  Cost: 517,16  Bytes: 1.757.569.638  Cardinality: 53.259.686
                                    1 TABLE ACCESS FULL TABLE ORDER_DETAILS Cost: 517,16  Bytes: 1.757.569.638  Cardinality: 53.259.686
                                4 PARTITION RANGE ALL  Cost: 1.512.742  Bytes: 3.576.967.836  Cardinality: 91.717.124
                                    3 TABLE ACCESS FULL TABLE ORDER Cost: 1.512.742  Bytes: 3.576.967.836  Cardinality: 91.717.124
                10 PARTITION RANGE ALL  Cost: 518,328  Bytes: 6.550.941.378  Cardinality: 53.259.686
                    9 TABLE ACCESS FULL TABLE ORDER_DETAILS Cost: 518,328  Bytes: 6.550.941.378  Cardinality: 53.259.686

Body:
You can use the MERGE statement as follows (It will be faster than your UPDATE statement):

MERGE INTO ORDER_DETAILS TRG
USING
(
   SELECT
       O.ID, O.DESC, O.CODE,
       SUM(OD.AMOUNT),
       O.TOTAL_AMOUNT
   FROM
       ORDER_DETAILS OD
       JOIN "ORDER" O ON O.ID = OD.ID AND O.DESC = OD.DESC
   GROUP BY O.ID, O.DESC, O.CODE, O.TOTAL_AMOUNT
   HAVING O.TOTAL_AMOUNT = SUM(OD.AMOUNT)
)
SRC ON ( SRC.ID = TRG.ID AND SRC.DESC = TRG.DESC )
WHEN MATCHED THEN
UPDATE SET TRG.CODE = SRC.CODE;

Cheers!!


问:
How to run batch SQL file using c#?
I want to run a big set of SQL statements in one go in c#; this SQL also contains numerous local variables. I tried to run that SQL using ADO.Net but I got an exception: "Cannot declare more than 10000 local variables". Can I run these SQL statements in a batch file (using c#) to avoid this exception/limitation? If yes, how? Is there any better approach?

I am using SQL Server 2008 R2 and C# 4.0.

Looking forward to assistance.

答:
"Cannot declare more than 10000 local variables"

I expect that's a SQL Server limitation (albeit not listed in "Maximum Capacity Specifications for SQL Server"), if correct then all methods of running at a single script will have the same problem.

Better to break it up into smaller pieces—this should also make maintenance much easier.

Title: How to run batch SQL file using c#?


答:
Your problem is that when you release the space bar, it sets the start field to false. Then when the next draw() method is called, it sees that start==false and so doesn't move the ball.

If you remove that line from the keyReleased method, then it should run correctly?

Title: How to call a function and have it continue by pressing a key once?