问:
are there any memory leaks in this code?
I have successfully created a UITableView/UITableViewCell that is able to slide up and down and adjusting the height to show options. To see what this means, I have created a video here. The code is as follows:

```<code>- (void)swipe:(UISwipeGestureRecognizer *)recognizer direction:(UISwipeGestureRecognizerDirection)direction
{
    if (recognizer && recognizer.state == UIGestureRecognizerStateEnded)
    {
        // Get the table view cell where the swipe occured
        CGPoint location = [recognizer locationInView:self.tableView];
        NSIndexPath* indexPath = [self.tableView indexPathForRowAtPoint:location];
        MyCell* cell = (MyCell *) [self.tableView cellForRowAtIndexPath:indexPath];

        [self.tableView beginUpdates];

        //removing the options view at the other cell before adding a new one

        if (global != nil && global.row != indexPath.row){
            [sideSwipeView removeFromSuperview];
            sideSwipeView = nil;
        }

        //options already exist, we need to remove it
        if (sideSwipeView != nil){
            [sideSwipeView removeFromSuperview];
            sideSwipeView = nil;
            slide = NO;
        } else {
            //options do not exist and therefore we need to add it
            NSArray * buttonData = [[NSArray arrayWithObjects:
                                     [NSDictionary dictionaryWithObjectsAndKeys:@"Mark Read", @"title", @"mark.png", @"image", nil],
                                     [NSDictionary dictionaryWithObjectsAndKeys:@"Track", @"title", @"play.png", @"image", nil],
                                     nil] retain];

            NSMutableArray * buttons = [[NSMutableArray alloc] initWithCapacity:buttonData.count];
            sideSwipeView = [[UIView alloc] initWithFrame:CGRectMake(0, cell.frame.size.height-25, 320, 25)];
            [sideSwipeView setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin];
            [sideSwipeView setBackgroundColor:[UIColor colorWithPatternImage: [UIImage imageNamed:@"dotted-pattern.png"]]];
            [sideSwipeView setTag:-10];

            CGFloat leftEdge = BUTTON_LEFT_MARGIN;
            for (NSDictionary* buttonInfo in buttonData)
            {
                if (!([[buttonInfo objectForKey:@"title"] isEqualToString:@"Mark Read"] && [[[topics objectAtIndex:indexPath.row] unread] intValue] == 0))
                {

                    UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];

                    button.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleTopMargin;

                    UIImage* buttonImage = [UIImage imageNamed:[buttonInfo objectForKey:@"image"]];
                    if ([[topics objectAtIndex:indexPath.row] tracked] && [[buttonInfo objectForKey:@"title"] isEqualToString:@"Track"]){
                        buttonImage = [UIImage imageNamed:@"pause.png"];
                        [button setSelected:YES];
                    } else {
                        [button setSelected:NO];
                    }
                    button.frame = CGRectMake(leftEdge, 0, buttonImage.size.width, buttonImage.size.height);

                    UIImage* grayImage = [self imageFilledWith:[UIColor colorWithWhite:0.9 alpha:1.0] using:buttonImage];
                    [button setImage:grayImage forState:UIControlStateNormal];

                    if ([[buttonInfo objectForKey:@"title"] isEqualToString:@"Mark Read"]){
                        [button addTarget:self action:@selector(markRead:) forControlEvents:UIControlEventTouchUpInside];
                    } else if ([[buttonInfo objectForKey:@"title"] isEqualToString:@"Track"]){
                        [button addTarget:self action:@selector(track:) forControlEvents:UIControlEventTouchUpInside];
                    }
                    [button setTag:indexPath.row];
                    [buttons addObject:button];

                    [sideSwipeView addSubview:button];

                    leftEdge = leftEdge + buttonImage.size.width + BUTTON_SPACING;
                }
            }

            [cell.contentView addSubview:sideSwipeView];
            [sideSwipeView release];
            global = indexPath;
            slide = YES;

        }
        [self.tableView endUpdates];
        [self.tableView deselectRowAtIndexPath:indexPath animated:YES];

    }
}
</code>```

However, I am not confident that the code is memory correct (i.e: ther's no memory leak and I am not misusing anything). I am mostly not confident in the sideSwipeView alloc, dealloc, and setting it up to nil. I think the others are fine. Can someone give me any pointers?

Profiler result:

答: The clang static analyzer is good for finding simple leaks but it won't catch them all. I've found that it's worth profiling your code and simply watching the allocations. Perform simple functions in your application and if you see things increasing, and not reducing as expected, a leak is the likely cause. Another indicator can be unexpected errors and crashes coming from classes you would expect to have been deallocated. Debug logging can also pick things up if you see messages coming from classes that should have cleared.</p>

Body:
I have successfully created a UITableView/UITableViewCell that is able to slide up and down and adjusting the height to show options. To see what this means, I have created a video here. The code is as follows:

- (void)swipe:(UISwipeGestureRecognizer *)recognizer direction:(UISwipeGestureRecognizerDirection)direction
{
    if (recognizer && recognizer.state == UIGestureRecognizerStateEnded)
    {
        // Get the table view cell where the swipe occured
        CGPoint location = [recognizer locationInView:self.tableView];
        NSIndexPath* indexPath = [self.tableView indexPathForRowAtPoint:location];
        MyCell* cell = (MyCell *) [self.tableView cellForRowAtIndexPath:indexPath];

        [self.tableView beginUpdates];

        //removing the options view at the other cell before adding a new one

        if (global != nil && global.row != indexPath.row){
            [sideSwipeView removeFromSuperview];
            sideSwipeView = nil;
        }

        //options already exist, we need to remove it
        if (sideSwipeView != nil){
            [sideSwipeView removeFromSuperview];
            sideSwipeView = nil;
            slide = NO;
        } else {
            //options do not exist and therefore we need to add it
            NSArray * buttonData = [[NSArray arrayWithObjects:
                                     [NSDictionary dictionaryWithObjectsAndKeys:@"Mark Read", @"title", @"mark.png", @"image", nil],
                                     [NSDictionary dictionaryWithObjectsAndKeys:@"Track", @"title", @"play.png", @"image", nil],
                                     nil] retain];

            NSMutableArray * buttons = [[NSMutableArray alloc] initWithCapacity:buttonData.count];
            sideSwipeView = [[UIView alloc] initWithFrame:CGRectMake(0, cell.frame.size.height-25, 320, 25)];
            [sideSwipeView setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin];
            [sideSwipeView setBackgroundColor:[UIColor colorWithPatternImage: [UIImage imageNamed:@"dotted-pattern.png"]]];
            [sideSwipeView setTag:-10];

            CGFloat leftEdge = BUTTON_LEFT_MARGIN;
            for (NSDictionary* buttonInfo in buttonData)
            {
                if (!([[buttonInfo objectForKey:@"title"] isEqualToString:@"Mark Read"] && [[[topics objectAtIndex:indexPath.row] unread] intValue] == 0))
                {

                    UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];

                    button.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleTopMargin;

                    UIImage* buttonImage = [UIImage imageNamed:[buttonInfo objectForKey:@"image"]];
                    if ([[topics objectAtIndex:indexPath.row] tracked] && [[buttonInfo objectForKey:@"title"] isEqualToString:@"Track"]){
                        buttonImage = [UIImage imageNamed:@"pause.png"];
                        [button setSelected:YES];
                    } else {
                        [button setSelected:NO];
                    }
                    button.frame = CGRectMake(leftEdge, 0, buttonImage.size.width, buttonImage.size.height);

                    UIImage* grayImage = [self imageFilledWith:[UIColor colorWithWhite:0.9 alpha:1.0] using:buttonImage];
                    [button setImage:grayImage forState:UIControlStateNormal];

                    if ([[buttonInfo objectForKey:@"title"] isEqualToString:@"Mark Read"]){
                        [button addTarget:self action:@selector(markRead:) forControlEvents:UIControlEventTouchUpInside];
                    } else if ([[buttonInfo objectForKey:@"title"] isEqualToString:@"Track"]){
                        [button addTarget:self action:@selector(track:) forControlEvents:UIControlEventTouchUpInside];
                    }
                    [button setTag:indexPath.row];
                    [buttons addObject:button];

                    [sideSwipeView addSubview:button];

                    leftEdge = leftEdge + buttonImage.size.width + BUTTON_SPACING;
                }
            }

            [cell.contentView addSubview:sideSwipeView];
            [sideSwipeView release];
            global = indexPath;
            slide = YES;

        }
        [self.tableView endUpdates];
        [self.tableView deselectRowAtIndexPath:indexPath animated:YES];

    }
}

However, I am not confident that the code is memory correct (i.e: ther's no memory leak and I am not misusing anything). I am mostly not confident in the sideSwipeView alloc, dealloc, and setting it up to nil. I think the others are fine. Can someone give me any pointers?

Profiler result:


来源: stackexchange

问:
how to display specify object value from JSON in laravel table view blade
i manage to display certain value but not manage for another value in blade table...I want to display value

```<code>description
</code>```

which is inside

irel__com_access_level

from my json response

....here is my response json with code

```<code>{
            "ID": "cust1",
            "PWD": "W6ph5Mm5Pz8GgiULbPgzG37mj9g=",
            "NICK_NAME": "CUST1",
            "PWD_INVALID_HIT": "0",
            "PWD_CREATE_DT": "2019/07/22 15:57:15",
            "INSTITUTION_ID": "C01",
            "ACL_ID": "L04",
            "LOGIN_DT": "2019/07/22 15:57:15",
            "LOGIN_STS_ID": "N",
            "STS_ID": "C08",
            "TYPE_ID": "U00",
            "UPD_DT": "2019/07/22 15:57:15",
            "EMAIL_ID": "cust1@gmail.com",
            "PHONE_NO_ID": "0",
            "HP_ID": "0                        ",
            "CRT_DATE_DELETED": null,
            "irel__com_access_level": {
                "ID": "L04",
                "DESCRIPTION": "CUSTOMER",   // i want to display this
                "IS_CREATE": "Y",
                "IS_READ": "Y",
                "IS_UPDATE": "Y",
                "IS_DELETE": "N",
                "STS_ID": "R01",
                "UPD_ID": "shukrimb",
                "UPD_DT": "2018/06/26 11:15:10"
            },

        },

</code>```

in my controller

```<code> public function index()
    {

        $response =  $this->client->get('getUserIndex')->getBody();
        $content = json_decode($response->getContents());

        return view('configuration.comuserprofiles.ComUserProfilesList', ['content' => $content->data]);

    }

</code>```

my blade file

```<code> @foreach($content as $i=>$user)
                        @php
                            $currentRecordno = 1;
                        @endphp
                        <tr>
                            <td>{{ $currentRecordno + $i }}</td>
                            <td>{{ $user->ID }}</td>
                            <td>{{ $user->NICK_NAME }}</td>
                            <td>{{ $user->PWD_INVALID_HIT }}</td>
                            <td>{{ $user->???? }}  </td>
</code>```

答:
in your Controller do this:

```<code>public function index()
    {

        $response =  $this->client->get('getUserIndex')->getBody();
        $content = json_decode($response->getContents(), true); //true convert your JSON to array

        return view('configuration.comuserprofiles.ComUserProfilesList', ['content' => $content->data]);

    }
</code>```

then in your Blade you can reach this in this way:

```<code>$user['irel__com_access_level']['DESCRIPTION']
</code>```

ContentLicense: CC BY-SA 4.0

Body:
i manage to display certain value but not manage for another value in blade table...I want to display value

description

which is inside

irel__com_access_level

from my json response

....here is my response json with code

{
            "ID": "cust1",
            "PWD": "W6ph5Mm5Pz8GgiULbPgzG37mj9g=",
            "NICK_NAME": "CUST1",
            "PWD_INVALID_HIT": "0",
            "PWD_CREATE_DT": "2019/07/22 15:57:15",
            "INSTITUTION_ID": "C01",
            "ACL_ID": "L04",
            "LOGIN_DT": "2019/07/22 15:57:15",
            "LOGIN_STS_ID": "N",
            "STS_ID": "C08",
            "TYPE_ID": "U00",
            "UPD_DT": "2019/07/22 15:57:15",
            "EMAIL_ID": "cust1@gmail.com",
            "PHONE_NO_ID": "0",
            "HP_ID": "0                        ",
            "CRT_DATE_DELETED": null,
            "irel__com_access_level": {
                "ID": "L04",
                "DESCRIPTION": "CUSTOMER",   // i want to display this
                "IS_CREATE": "Y",
                "IS_READ": "Y",
                "IS_UPDATE": "Y",
                "IS_DELETE": "N",
                "STS_ID": "R01",
                "UPD_ID": "shukrimb",
                "UPD_DT": "2018/06/26 11:15:10"
            },

        },

in my controller

 public function index()
    {

        $response =  $this->client->get('getUserIndex')->getBody();
        $content = json_decode($response->getContents());

        return view('configuration.comuserprofiles.ComUserProfilesList', ['content' => $content->data]);

    }

my blade file

 @foreach($content as $i=>$user)
                        @php
                            $currentRecordno = 1;
                        @endphp

                            {{ $currentRecordno + $i }}
                            {{ $user->ID }}
                            {{ $user->NICK_NAME }}
                            {{ $user->PWD_INVALID_HIT }}
                            {{ $user->???? }}

Body:
in your Controller do this:

public function index()
    {

        $response =  $this->client->get('getUserIndex')->getBody();
        $content = json_decode($response->getContents(), true); //true convert your JSON to array

        return view('configuration.comuserprofiles.ComUserProfilesList', ['content' => $content->data]);

    }

then in your Blade you can reach this in this way:

$user['irel__com_access_level']['DESCRIPTION']


问:
Is anyone else integrating Spring Actuator endpoints with New Relic? Or is this redundant?
I think New Relic does not have the httptrace/info/metrics that spring actuator has. So I am planning to use Spring Actuator endpoints in New Relic. Do other people do this? Or does New Relic have some way to show httptrace/info/metrics without exposing endpoints collecting httptrace/info/metrics info?</p>

答:
You don't really integrate an actuator with new relic, but rather micrometer which is an under-the-hood implementation of the metrics in spring boot 2 applications.

Spring boot actuator's metrics endpoint indeed can show the data (that is relevant for the current time snapshot) maintained by the micrometer, but that's only for your convenience.

In general you should configure micrometer to integrate with New Relic (which is a perfectly valid use case of course, and yes, many people use integrations like this, I used to do this with data dog, prometheus in my career for example).

The tutorial of integration micrometer-new-relic integration can be found Here


问:
Typescript & Electron exports is not defined
I'm trying to run my simple electron app. I use Typescript as a development language which compiles into JavaScript. When I run the app I get the following error:

```<code>ReferenceError: exports is not defined[Learn More]
file:///Users/ahmet/Documents/JumbleUp-Desktop/dist/Login/Login.js:5
exports.__esModule = true;
</code>```

My login.ts file looks like this

```<code>    import firebase from "firebase";

firebase.auth().onAuthStateChanged(function(user) {
    if (user) {
        location.replace("index.html");
    } else {
        location.replace("login.html");
    }
  });
function login() {
    const userEmail = (document.getElementById("inputEmail") as HTMLInputElement).value;
    const userPassword = (document.getElementById("inputPassword") as HTMLInputElement).value;

    firebase.auth().createUserWithEmailAndPassword(userEmail, userPassword).catch(function(error) {
        // Handle Errors here.
        var errorCode = error.code;
        var errorMessage = error.message;
        // ...

        window.alert("Alert : " + errorMessage);
      });
}
</code>```

and here my tsconfig file

```<code>{
    "compilerOptions": {
      "module": "commonjs",
      "noImplicitAny": true,
      "sourceMap": true,
      "esModuleInterop": true,
      "outDir": "dist",
      "baseUrl": ".",
      "paths": {
        "*": ["node_modules/*"]
      }
    },
    "include": [
      "src/**/*"
    ]
  }
</code>```

答:
I've encountered the same problem. For me the problem was not in the way the files are transpiled, but by how they were included in the project in index.html.

Changing:

```

<p>to</p>

<pre class="lang-html prettyprint-override"><code><script>
   require("./main.js")
</script>
</code>```

in index.html

solved it for me

Body:
I'm trying to run my simple electron app. I use Typescript as a development language which compiles into JavaScript. When I run the app I get the following error:

ReferenceError: exports is not defined[Learn More]
file:///Users/ahmet/Documents/JumbleUp-Desktop/dist/Login/Login.js:5
exports.__esModule = true;

My login.ts file looks like this

    import firebase from "firebase";

firebase.auth().onAuthStateChanged(function(user) {
    if (user) {
        location.replace("index.html");
    } else {
        location.replace("login.html");
    }
  });
function login() {
    const userEmail = (document.getElementById("inputEmail") as HTMLInputElement).value;
    const userPassword = (document.getElementById("inputPassword") as HTMLInputElement).value;

    firebase.auth().createUserWithEmailAndPassword(userEmail, userPassword).catch(function(error) {
        // Handle Errors here.
        var errorCode = error.code;
        var errorMessage = error.message;
        // ...

        window.alert("Alert : " + errorMessage);
      });
}

and here my tsconfig file

{
    "compilerOptions": {
      "module": "commonjs",
      "noImplicitAny": true,
      "sourceMap": true,
      "esModuleInterop": true,
      "outDir": "dist",
      "baseUrl": ".",
      "paths": {
        "*": ["node_modules/*"]
      }
    },
    "include": [
      "src/**/*"
    ]
  }

Body:
I've encountered the same problem. For me the problem was not in the way the files are transpiled, but by how they were included in the project in index.html.

Changing:

<script src="./main.js"></script>

to

<script>
   require("./main.js")
</script>

in index.html

solved it for me


问:
Is there a place to test if code is ES5 compliant / safe?
Sometimes I'd like to know if the code I'm writing is ES5 compliant/safe or not.

Example: this would fail because of the arrow function.

```<code>() => "something";
</code>```

I know Babel could take care of this. But sometimes I would like to test some cases.

Is there a place where I could do this?

答:
Try ESlint, https://eslint.org/demo. You can disable advanced rules and stick to the basics.

For example, with an arrow function on ES5: https://eslint.org/demo#eyJ0ZXh0IjoiKCkgPT4gXCJzb21ldGhpbmdcIjsiLCJvcHRpb25zIjp7InBhcnNlck9wdGlvbnMiOnsiZWNtYVZlcnNpb24iOjUsInNvdXJjZVR5cGUiOiJzY3JpcHQiLCJlY21hRmVhdHVyZXMiOnt9fSwicnVsZXMiOnt9LCJlbnYiOnt9fX0=

It could also be automated as part of a build/ci script.

Body:
Sometimes I'd like to know if the code I'm writing is ES5 compliant/safe or not.

Example: this would fail because of the arrow function.

() => "something";

I know Babel could take care of this. But sometimes I would like to test some cases.

Is there a place where I could do this?


问:
Thread in Android
I have an example like this:

```<code>package android.uiexample;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.widget.RadioGroup.OnCheckedChangeListener;

public class BasicViewsExampleActivity  extends Activity
{

private static int progress = 0;
private ProgressBar progressBar;
private int progressStatus = 0;
private Handler handler = new Handler();

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.basic_views);

    progressBar = (ProgressBar) findViewById(R.id.progressbar);

    //---do some work in background thread---
    new Thread(new Runnable()
    {
        public void run()
        {
            //---do some work here---
            while (progressStatus < 10)
            {
                progressStatus = doSomeWork();
            }

            //---hides the progress bar---
            handler.post(new Runnable()
            {
                public void run()
                {
                    progressBar.setVisibility(View.GONE);
                }
            });

        }

        //---do some long lasting work here---
        private int doSomeWork()
        {
            try {
                //---simulate doing some work---
                Thread.sleep(500);
            } catch (InterruptedException e)
            {
                e.printStackTrace();
            }
            return ++progress;
        }

    }).start();
}
</code>```

}

In this example, it use Handler to post a Runable to exc progressBar.setVisibility(View.GONE);. I don't know why i can't call progressBar.setVisibility(View.GONE); directly:

```<code>            //---do some work here---
            while (progressStatus < 10)
            {
                progressStatus = doSomeWork();
            }

            //---hides the progress bar---
            progressBar.setVisibility(View.GONE);
</code>```

Anybody can tell me why i can't?

答: changing the progressBar visibility is a UI operation.  All UI operations must be done on the UI thread.</p>

ContentLicense: CC BY-SA 3.0

Title: Thread in Android

Body:
I have an example like this:

package android.uiexample;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.widget.RadioGroup.OnCheckedChangeListener;

public class BasicViewsExampleActivity  extends Activity
{

private static int progress = 0;
private ProgressBar progressBar;
private int progressStatus = 0;
private Handler handler = new Handler();

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.basic_views);

    progressBar = (ProgressBar) findViewById(R.id.progressbar);

    //---do some work in background thread---
    new Thread(new Runnable()
    {
        public void run()
        {
            //---do some work here---
            while (progressStatus < 10)
            {
                progressStatus = doSomeWork();
            }

            //---hides the progress bar---
            handler.post(new Runnable()
            {
                public void run()
                {
                    progressBar.setVisibility(View.GONE);
                }
            });

        }

        //---do some long lasting work here---
        private int doSomeWork()
        {
            try {
                //---simulate doing some work---
                Thread.sleep(500);
            } catch (InterruptedException e)
            {
                e.printStackTrace();
            }
            return ++progress;
        }

    }).start();
}

}

In this example, it use Handler to post a Runable to exc progressBar.setVisibility(View.GONE);. I don't know why i can't call progressBar.setVisibility(View.GONE); directly:

            //---do some work here---
            while (progressStatus < 10)
            {
                progressStatus = doSomeWork();
            }

            //---hides the progress bar---
            progressBar.setVisibility(View.GONE);

Anybody can tell me why i can't?


问:
Extract rows with duplicates entries in one column satisfying a given condition in another column
I have a sample dataframe with duplicate entries in the first column given below:

```<code>df <- data.frame(ID=c(rep(101,3),rep(102,2),103,rep(104,3)),Type=c(2,1,1,1,2,1,3,1,2),sex=c(0,0,0,1,1,1,0,0,0))
df
  ID Type sex
1 101    2   0
2 101    1   0
3 101    1   0
4 102    1   1
5 102    2   1
6 103    1   1
7 104    3   0
8 104    1   0
9 104    2   0
</code>```

Question: For each variable 'ID', I want the rows to start from where the first occurrence of the variable 'Type' is 1 (i.e. Type=1).

I know for each ID, the position satisfying the condition Type=1 using the code below:

```<code>aggregate(df$Type,list(ID=df$ID),function(x) match(1,x))
 ID x
1 101 2
2 102 1
3 103 1
4 104 2
</code>```

but I have not been able to solve the problem.

Desired Output: The output should look like this:

```<code>df.result <- data.frame(ID=c(101,101,102,102,103,104,104),Type=c(1,1,1,2,1,1,2),sex=c(0,0,1,1,1,0,0))
df.result
 ID Type sex
1 101    1   0
2 101    1   0
3 102    1   1
4 102    2   1
5 103    1   1
6 104    1   0
7 104    2   0
</code>```

Thanks!

答:
We can use match with slice

```<code>library(dplyr)
df %>% group_by(ID) %>% slice(match(1, Type) : n())

#    ID  Type   sex
#  <dbl> <dbl> <dbl>
#1   101     1     0
#2   101     1     0
#3   102     1     1
#4   102     2     1
#5   103     1     1
#6   104     1     0
#7   104     2     0
</code>```

Or using filter

```<code>df %>% group_by(ID) %>% filter(row_number() >= match(1, Type))
</code>```

In base R, we can use ave like :

```<code>subset(df, as.logical(ave(Type, ID, FUN = function(x) seq_along(x) >= match(1, x))))
</code>```

Body:
I have a sample dataframe with duplicate entries in the first column given below:

df <- data.frame(ID=c(rep(101,3),rep(102,2),103,rep(104,3)),Type=c(2,1,1,1,2,1,3,1,2),sex=c(0,0,0,1,1,1,0,0,0))
df
  ID Type sex
1 101    2   0
2 101    1   0
3 101    1   0
4 102    1   1
5 102    2   1
6 103    1   1
7 104    3   0
8 104    1   0
9 104    2   0

Question: For each variable 'ID', I want the rows to start from where the first occurrence of the variable 'Type' is 1 (i.e. Type=1).

I know for each ID, the position satisfying the condition Type=1 using the code below:

aggregate(df$Type,list(ID=df$ID),function(x) match(1,x))
 ID x
1 101 2
2 102 1
3 103 1
4 104 2

but I have not been able to solve the problem.

Desired Output: The output should look like this:

df.result <- data.frame(ID=c(101,101,102,102,103,104,104),Type=c(1,1,1,2,1,1,2),sex=c(0,0,1,1,1,0,0))
df.result
 ID Type sex
1 101    1   0
2 101    1   0
3 102    1   1
4 102    2   1
5 103    1   1
6 104    1   0
7 104    2   0

Thanks!

Body:
We can use match with slice

library(dplyr)
df %>% group_by(ID) %>% slice(match(1, Type) : n())

#    ID  Type   sex
#  <dbl> <dbl> <dbl>
#1   101     1     0
#2   101     1     0
#3   102     1     1
#4   102     2     1
#5   103     1     1
#6   104     1     0
#7   104     2     0

Or using filter

df %>% group_by(ID) %>% filter(row_number() >= match(1, Type))

In base R, we can use ave like :

subset(df, as.logical(ave(Type, ID, FUN = function(x) seq_along(x) >= match(1, x))))


问:
How to select inputs elements in divs which not hidden?
How can I select an array of input and select elements that are not hidden from the form below, using jQuery?

```<code>  <form class="FORM_1">
    <div class="a" style="display:inline-block><input id="A"/></div>

    <div class="a" style="display:none"><input id="B"/></div>

    <div class="a"><select id="C"/></div>
    <div class="a"style="display:none"><select id="D"/></div>

    <div class="a style="display:inline-block"><input id="F"/></div>
   </form>
</code>```

I tried with code below but it doesn't work how I need.

```<code>$('.FORM_1 input, .FORM_1 select').prop('display', 'inline-block').each(function(index){
  var input = $(this);
  console.log('Type: ' + input.attr('type'));
});
</code>```

答:
Use is(":visible") to select visible elements

```<code>$('.FORM_1 input:visible, .FORM_1 select:visible').addClass('YourStuff');
</code>```

Below code is enough to display the elements, If you want display inline block, assign in css first as inline block and add display none as inline like below

```<code>input, select {
  display: inline-block;
}
</code>```

Then in html

```<code><input style="display: none;" />
</code>```

Then in JS

```<code>$('.FORM_1 input, .FORM_1 select').show();
</code>```

Body:
How can I select an array of input and select elements that are not hidden from the form below, using jQuery?

  <form class="FORM_1">

<input id="A"/>

<input id="B"/>

<select id="C"/>

<select id="D"/>

<input id="F"/>

   </form>

I tried with code below but it doesn't work how I need.

$('.FORM_1 input, .FORM_1 select').prop('display', 'inline-block').each(function(index){
  var input = $(this);
  console.log('Type: ' + input.attr('type'));
});

Body:
Use is(":visible") to select visible elements

$('.FORM_1 input:visible, .FORM_1 select:visible').addClass('YourStuff');

Below code is enough to display the elements, If you want display inline block, assign in css first as inline block and add display none as inline like below

input, select {
  display: inline-block;
}

Then in html

<input style="display: none;" />

Then in JS

$('.FORM_1 input, .FORM_1 select').show();


问:
Retrieving the selected values from Bootstrap dual list in asp.net core
I am building a web app using .NET core 2.1. In one of the views there are multiple select lists, each contains thousands of items for the user to choose from so I decided to use bootstrap dual list (https://www.virtuosoft.eu/code/bootstrap-duallistbox/). I have 2 issues with this setup:
1- When I hit the submit button, the model coming to the post action method does not contain the items selected by the user in the dual lists (The items in the right hand side of the list)
2- I need to save the items selected by the user so he can have the same list each time he logs in the app (The original not selected list is populated from the database with all the items shown regardless to the user selections from last time he used the app)
Here is my code:

ViewModel.cs:

```<code>public ViewModel()
{
    TradeList = new List<DimTrade>();
    LocationList = new List<DimLocation>();
}
public List<DimTrade> TradeList { get; set; }
public List<DimLocation> LocationList { get; set; }
</code>```

cshtml:

```<code><div class="col-8">
    <select id="ddlTrade" class="form-control" asp-for="@Model.TradeList" asp-items="@(new SelectList(Model.TradeList, "TradeKey", "Name"))"
            placeholder="Please select" multiple="multiple" name="TradeList"></select>
</div>

<div class="col-8">
    <select id="ddlLocation" class="form-control" asp-for="@Model.LocationList" asp-items="@(new SelectList(Model.LocationList, "LocationKey", "Name"))"
            placeholder="Please select" multiple="multiple" name="LocationList"></select>
</div>
<scaript>
    $('[name=TradeList]').bootstrapDualListbox();
    $('[name=LocationList]').bootstrapDualListbox();
</script>
</code>```

Post action method:

```<code>public IActionResult Edit(ViewModel model)
{
    if (ModelState.IsValid)
    {
         // Process the model
    }
    return View(model);
</code>```

The problem is that the TradeList and LoactionList objects are always null.

I appreciate your help with both issues

答:
You could use jquery to get all selected options' value and text , then pass them to edit action:

```<code><div class="col-8">
    <select id="ddlTrade" class="form-control" asp-for="@Model.TradeList" asp-items="@(new SelectList(Model.TradeList, "TradeKey", "Name"))"
            placeholder="Please select" multiple="multiple" name="TradeList"></select>
</div>
<div class="col-8">
    <select id="ddlLocation" class="form-control" asp-for="@Model.LocationList" asp-items="@(new SelectList(Model.LocationList, "LocationKey", "Name"))"
            placeholder="Please select" multiple="multiple" name="LocationList"></select>
</div>
<div class="col-6">
    <input class="btn btn-primary" type="button" value="submit" id="showValue" />
</div>
<script>
    $('[name=TradeList]').bootstrapDualListbox();
    $('[name=LocationList]').bootstrapDualListbox();
</script>
<script>
    $(function () {
        $("#showValue").click(function () {
            var TradeList = [];
            var LocationList = [];
            $("[id*=-selected-list_TradeList] option").each(function () {
                var Trade = {
                    TradeKey: $(this).val(),
                    Name: $(this).text()
                };
                TradeList.push(Trade);
            });
            $("[id*=-selected-list_LocationList] option").each(function () {
                var Location = {
                    LocationKey: $(this).val(),
                    Name: $(this).text()
                };
                LocationList.push(Location);
            });
            var model = {
                TradeList: TradeList,
                LocationList: LocationList
            }
            $.ajax({
                type: 'post',
                dataType: 'json',
                url: '/DualListbox/Edit',
                data: model,
                success: function (data) {
                }
            });
        });
    })
</script>
</code>```

Result:

Body:
I am building a web app using .NET core 2.1. In one of the views there are multiple select lists, each contains thousands of items for the user to choose from so I decided to use bootstrap dual list (https://www.virtuosoft.eu/code/bootstrap-duallistbox/). I have 2 issues with this setup:
1- When I hit the submit button, the model coming to the post action method does not contain the items selected by the user in the dual lists (The items in the right hand side of the list)
2- I need to save the items selected by the user so he can have the same list each time he logs in the app (The original not selected list is populated from the database with all the items shown regardless to the user selections from last time he used the app)
Here is my code:

ViewModel.cs:

public ViewModel()
{
    TradeList = new List<DimTrade>();
    LocationList = new List<DimLocation>();
}
public List<DimTrade> TradeList { get; set; }
public List<DimLocation> LocationList { get; set; }

cshtml:

    <select id="ddlTrade" class="form-control" asp-for="@Model.TradeList" asp-items="@(new SelectList(Model.TradeList, "TradeKey", "Name"))"
            placeholder="Please select" multiple="multiple" name="TradeList"></select>

    <select id="ddlLocation" class="form-control" asp-for="@Model.LocationList" asp-items="@(new SelectList(Model.LocationList, "LocationKey", "Name"))"
            placeholder="Please select" multiple="multiple" name="LocationList"></select>

<scaript>
    $('[name=TradeList]').bootstrapDualListbox();
    $('[name=LocationList]').bootstrapDualListbox();
</script>

Post action method:

public IActionResult Edit(ViewModel model)
{
    if (ModelState.IsValid)
    {
         // Process the model
    }
    return View(model);

The problem is that the TradeList and LoactionList objects are always null.

I appreciate your help with both issues

Body:
You could use jquery to get all selected options' value and text , then pass them to edit action:

<div class="col-8">
    <select id="ddlTrade" class="form-control" asp-for="@Model.TradeList" asp-items="@(new SelectList(Model.TradeList, "TradeKey", "Name"))"
            placeholder="Please select" multiple="multiple" name="TradeList"></select>
</div>
<div class="col-8">
    <select id="ddlLocation" class="form-control" asp-for="@Model.LocationList" asp-items="@(new SelectList(Model.LocationList, "LocationKey", "Name"))"
            placeholder="Please select" multiple="multiple" name="LocationList"></select>
</div>
<div class="col-6">
    <input class="btn btn-primary" type="button" value="submit" id="showValue" />
</div>
<script>
    $('[name=TradeList]').bootstrapDualListbox();
    $('[name=LocationList]').bootstrapDualListbox();
</script>
<script>
    $(function () {
        $("#showValue").click(function () {
            var TradeList = [];
            var LocationList = [];
            $("[id*=-selected-list_TradeList] option").each(function () {
                var Trade = {
                    TradeKey: $(this).val(),
                    Name: $(this).text()
                };
                TradeList.push(Trade);
            });
            $("[id*=-selected-list_LocationList] option").each(function () {
                var Location = {
                    LocationKey: $(this).val(),
                    Name: $(this).text()
                };
                LocationList.push(Location);
            });
            var model = {
                TradeList: TradeList,
                LocationList: LocationList
            }
            $.ajax({
                type: 'post',
                dataType: 'json',
                url: '/DualListbox/Edit',
                data: model,
                success: function (data) {
                }
            });
        });
    })
</script>

Result:


问:
PHP Codeigniter, error: Array to string conversion on renaming uploaded file
I got an error on file upload in Codeigniter when I try to rename image file. In local server is work fine, but in live server upload success but it showing error:  Array to string conversion and undefined index: userfiles which is pointed to this line:

```<code>$image_name = "image-slider" . date("Y-m-d-h-i-sa").$_FILES["userfiles"]['name'];
</code>```

on model file.

This my controler:

```<code>public function uploadImages()
{
    $result = $this->M_images->uploadImages();

    if($result){
        $this->session->set_flashdata('upload_success_msg', 'Upload Success!');
    }
    else
    {
        $this->session->set_flashdata('upload_error_msg', 'Upload Error!');
    }

    redirect(base_url('backend/homepage/C_images'));
}
</code>```

And this is my model:

```<code>public function uploadImages()
{
    $image_name = "image-slider" . date("Y-m-d-h-i-sa").$_FILES["userfiles"]['name'];

    $upload = array(
        'slider_title' => $this->input->post("slider-title"),
        'slider_alt' => $this->input->post("slider-alt"),
        'slider_link' => $this->input->post("slider-url"),
        'slider_desc' => $this->input->post("slider-description")
    );

    $config['upload_path'] = "./assets/uploads/sliders";
    $config['allowed_types'] = 'gif|jpeg|jpg|png';
    $config['overwrite'] = TRUE;
    $config['file_name'] = $image_name;

    $this->load->library('upload', $config);
    if ( ! $this->upload->do_upload('slider-file'))
    {
        $this->db->insert($this->tableslider, $upload);
        return $this->db->insert_id();
    }
    else
    {
        $data = $this->upload->data();
        $upload['slider_file'] = $data['file_name'];
        $this->db->insert($this->tableslider, $upload);
        return $this->db->insert_id();
    }
}
</code>```

Where am I doing wrong?

答:
Problem is in your variable change $upload into $upload_data

Before that check the files are posted or not to check  undefined index

```<code>public function uploadImages(){
print_r($_FILES);exit; /*Comment after checked  */

 $image_name = "image-slider" . date("Y-m-d-h-i-sa").$_FILES["userfiles"]['name'];
 $upload_data = array(
    'slider_title' => $this->input->post("slider-title"),
    'slider_alt' => $this->input->post("slider-alt"),
    'slider_link' => $this->input->post("slider-url"),
    'slider_desc' => $this->input->post("slider-description")
);

    $config['upload_path'] = "./assets/uploads/sliders";
    $config['allowed_types'] = 'gif|jpeg|jpg|png';
    $config['overwrite'] = TRUE;
    $config['file_name'] = $image_name;

    $this->load->library('upload', $config);

 if ( ! $this->upload->do_upload('slider-file')){
    $this->db->insert($this->tableslider, $upload_data);
    return $this->db->insert_id();
}else{
    $data = $this->upload->data();
    $upload_data['slider_file'] = $data['file_name'];
    $this->db->insert($this->tableslider, $upload_data);
    return $this->db->insert_id();
  }
}
</code>```

Body:
I got an error on file upload in Codeigniter when I try to rename image file. In local server is work fine, but in live server upload success but it showing error:  Array to string conversion and undefined index: userfiles which is pointed to this line:

$image_name = "image-slider" . date("Y-m-d-h-i-sa").$_FILES["userfiles"]['name'];

on model file.

This my controler:

public function uploadImages()
{
    $result = $this->M_images->uploadImages();

    if($result){
        $this->session->set_flashdata('upload_success_msg', 'Upload Success!');
    }
    else
    {
        $this->session->set_flashdata('upload_error_msg', 'Upload Error!');
    }

    redirect(base_url('backend/homepage/C_images'));
}

And this is my model:

public function uploadImages()
{
    $image_name = "image-slider" . date("Y-m-d-h-i-sa").$_FILES["userfiles"]['name'];

    $upload = array(
        'slider_title' => $this->input->post("slider-title"),
        'slider_alt' => $this->input->post("slider-alt"),
        'slider_link' => $this->input->post("slider-url"),
        'slider_desc' => $this->input->post("slider-description")
    );

    $config['upload_path'] = "./assets/uploads/sliders";
    $config['allowed_types'] = 'gif|jpeg|jpg|png';
    $config['overwrite'] = TRUE;
    $config['file_name'] = $image_name;

    $this->load->library('upload', $config);
    if ( ! $this->upload->do_upload('slider-file'))
    {
        $this->db->insert($this->tableslider, $upload);
        return $this->db->insert_id();
    }
    else
    {
        $data = $this->upload->data();
        $upload['slider_file'] = $data['file_name'];
        $this->db->insert($this->tableslider, $upload);
        return $this->db->insert_id();
    }
}

Where am I doing wrong?

Body:
Problem is in your variable change $upload into $upload_data

Before that check the files are posted or not to check  undefined index

public function uploadImages(){
print_r($_FILES);exit; /*Comment after checked  */

 $image_name = "image-slider" . date("Y-m-d-h-i-sa").$_FILES["userfiles"]['name'];
 $upload_data = array(
    'slider_title' => $this->input->post("slider-title"),
    'slider_alt' => $this->input->post("slider-alt"),
    'slider_link' => $this->input->post("slider-url"),
    'slider_desc' => $this->input->post("slider-description")
);

    $config['upload_path'] = "./assets/uploads/sliders";
    $config['allowed_types'] = 'gif|jpeg|jpg|png';
    $config['overwrite'] = TRUE;
    $config['file_name'] = $image_name;

    $this->load->library('upload', $config);

 if ( ! $this->upload->do_upload('slider-file')){
    $this->db->insert($this->tableslider, $upload_data);
    return $this->db->insert_id();
}else{
    $data = $this->upload->data();
    $upload_data['slider_file'] = $data['file_name'];
    $this->db->insert($this->tableslider, $upload_data);
    return $this->db->insert_id();
  }
}


问:
How to include tsconfig.json in prod build?
In tsconfig.json I included "resolveJsonModule": true.

Locally, when I start the app with npm run webpack:dev everything goes smoothly.

However, while executing npm run webpack:prod it fails with: but '--resolveJsonModule' is not used.

So I guess the prod build doesn't take into account tsconfig file.

I believe the issue may lay somewhere in webpack.js files but I cannot find a specific place or variable.

Here are the aliases for run builds:

```<code>"webpack:dev": "npm run webpack-dev-server -- --config webpack/webpack.dev.js --inline --hot --port=9060 --watch-content-base --env.stats=minimal",
"webpack:dev-verbose": "npm run webpack-dev-server -- --config webpack/webpack.dev.js --inline --hot --port=9060 --watch-content-base --profile --progress --env.stats=normal",
"webpack:build:main": "npm run webpack -- --config webpack/webpack.dev.js --env.stats=minimal",
"webpack:build": "npm run cleanup && npm run webpack:build:main",
"webpack:prod:main": "npm run webpack -- --config webpack/webpack.prod.js --profile",
"webpack:prod": "npm run cleanup && npm run webpack:prod:main && npm run clean-www",
"webpack:test": "npm run test",
"webpack-dev-server": "node --max_old_space_size=4096 node_modules/webpack-dev-server/bin/webpack-dev-server.js",
"webpack": "node --max_old_space_size=4096 node_modules/webpack/bin/webpack.js"
</code>```

答: Prod build uses tsconfig-aot.json as you can see in webpack/webpack.prod.js, make sure you add "resolveJsonModule": true to this file as well.

Body:
In tsconfig.json I included "resolveJsonModule": true.

Locally, when I start the app with npm run webpack:dev everything goes smoothly.

However, while executing npm run webpack:prod it fails with: but '--resolveJsonModule' is not used.

So I guess the prod build doesn't take into account tsconfig file.

I believe the issue may lay somewhere in webpack.js files but I cannot find a specific place or variable.

Here are the aliases for run builds:

"webpack:dev": "npm run webpack-dev-server -- --config webpack/webpack.dev.js --inline --hot --port=9060 --watch-content-base --env.stats=minimal",
"webpack:dev-verbose": "npm run webpack-dev-server -- --config webpack/webpack.dev.js --inline --hot --port=9060 --watch-content-base --profile --progress --env.stats=normal",
"webpack:build:main": "npm run webpack -- --config webpack/webpack.dev.js --env.stats=minimal",
"webpack:build": "npm run cleanup && npm run webpack:build:main",
"webpack:prod:main": "npm run webpack -- --config webpack/webpack.prod.js --profile",
"webpack:prod": "npm run cleanup && npm run webpack:prod:main && npm run clean-www",
"webpack:test": "npm run test",
"webpack-dev-server": "node --max_old_space_size=4096 node_modules/webpack-dev-server/bin/webpack-dev-server.js",
"webpack": "node --max_old_space_size=4096 node_modules/webpack/bin/webpack.js"


问:
localhost refuses to connect - ERR_CONNECTION_REFUSED
I have a simple MVC web application where javascript code sends ajax requests to the controller and the controller sends back responses.

I built the app 2 years ago and everything used to work fine. Now I tried to run the app again locally and met with the following problem:
whenever an Ajax request is sent from the frontend to the controller (running on localhost), the localhost refuses to connect and I get an ERR_CONNECTION_REFUSED message in (chrome's) javascript-console. (In Safari's javascript-console I get the following error message: "Failed to load resource: Could not connect to the server.")

I'm running the app using NetBeans 11.2. My NetBeans IDE uses GlassFish as server:

I removed the Glassfish server from NetBeans IDE, deleted its folder in my home directory and then added the Glassfish server again in my NetBeans IDE (which also entailed downloading the the newest version of the Glassfish server).

Still, the server refuses to accept any requests from the frontend.

I also tried using Payara Server (version 5.193). That didn't make a difference either.

The frontend itself looks fine at first glance by the way. That is, going to http://localhost:8080/myapp loads the frontend of the app. However, any dynamic features of the app don't work because the server refuses to accept any Ajax requests coming from the frontend (and initiated through mouse clicks).

How can I fix this?

I think I found the reason for the problem:

In my javascript-file I have the following line of code:

```<code>var url = "http://localhost:8080/myapp/Controller";
</code>```

The variable "url" is passed to all the AJAX requests sent to localhost.
But here is the crazy thing: the AJAX requests are not sent to "http://localhost:8080/myapp/Controller" but to "http://localhost:8081/myapp/Controller" !!!!!

What the hell is going on here?!

答: Did you use port 8081 before and then changed the variable "url" to the new port 8080? In this case, maybe the variable is still set to the old value in the cache. Restart your computer and see whether this fixes the problem. </p>

Body:
I have a simple MVC web application where javascript code sends ajax requests to the controller and the controller sends back responses.

I built the app 2 years ago and everything used to work fine. Now I tried to run the app again locally and met with the following problem:
whenever an Ajax request is sent from the frontend to the controller (running on localhost), the localhost refuses to connect and I get an ERR_CONNECTION_REFUSED message in (chrome's) javascript-console. (In Safari's javascript-console I get the following error message: "Failed to load resource: Could not connect to the server.")

I'm running the app using NetBeans 11.2. My NetBeans IDE uses GlassFish as server:

I removed the Glassfish server from NetBeans IDE, deleted its folder in my home directory and then added the Glassfish server again in my NetBeans IDE (which also entailed downloading the the newest version of the Glassfish server).

Still, the server refuses to accept any requests from the frontend.

I also tried using Payara Server (version 5.193). That didn't make a difference either.

The frontend itself looks fine at first glance by the way. That is, going to http://localhost:8080/myapp loads the frontend of the app. However, any dynamic features of the app don't work because the server refuses to accept any Ajax requests coming from the frontend (and initiated through mouse clicks).

How can I fix this?

I think I found the reason for the problem:

In my javascript-file I have the following line of code:

var url = "http://localhost:8080/myapp/Controller";

The variable "url" is passed to all the AJAX requests sent to localhost.
But here is the crazy thing: the AJAX requests are not sent to "http://localhost:8080/myapp/Controller" but to "http://localhost:8081/myapp/Controller" !!!!!

What the hell is going on here?!


问:
GraphQL Asynchronous query results
I'm trying to implement a batch query interface with GraphQL. I can get a request to work synchronously without issue, but I'm not sure how to approach making the result asynchronous. Basically, I want to be able to kick off the query and return a pointer of sorts to where the results will eventually be when the query is done. I'd like to do this because the queries can sometimes take quite a while.

In REST, this is trivial. You return a 202 and return a Location header pointing to where the client can go to fetch the result. GraphQL as a specification does not seem to have this notion; it appears to always want requests to be handled synchronously.

Is there any convention for doing things like this in GraphQL? I very much like the query specification but I'd prefer to not leave the client HTTP connection open for up to a few minutes while a large query is executed on the backend. If anything happens to kill that connection the entire query would need to be retried, even if the results themselves are durable.

答:
What you're trying to do is not solved easily in a spec-compliant way. Apollo introduced the idea of a @defer directive that does pretty much what you're looking for but it's still an experimental feature. I believe Relay Modern is trying to do something similar.

The idea is effectively the same -- the client uses a directive to mark a field or fragment as deferrable. The server resolves the request but leaves the deferred field null. It then sends one or more patches to the client with the deferred data. The client is able to apply the initial request and the patches separately to its cache, triggering the appropriate UI changes each time as usual.

Title: GraphQL Asynchronous query results


问:
404 Page while running Spring and angular in same port
I created Spring boot + angular 8 application which was running succesfully in two different port like 8080 and 4200 without any issues. Then I decided to run the application in same port (8080). I ran ng build --prod and got the dist folder. Moved that Dist folder into the spring application and the folder looked like this image

The corresponding pom.xml is as follows

```<code>  <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-resources-plugin</artifactId>
            <version>3.0.2</version>
            <configuration>
                  <outputDirectory>${project.build.directory}/target/classes/static/</outputDirectory >
                  <resources>
                      <resource>
                          <directory>${project.build.directory}/fleetManagement/dist/fleetManagement</directory >
                      </resource>
                  </resources>
                <nonFilteredFileExtensions>
                    <nonFilteredFileExtension>woff</nonFilteredFileExtension>
                    <nonFilteredFileExtension>ttf</nonFilteredFileExtension>
                    <nonFilteredFileExtension>woff2</nonFilteredFileExtension>
                    <nonFilteredFileExtension>eot</nonFilteredFileExtension>
                    <nonFilteredFileExtension>swf</nonFilteredFileExtension>
                    <nonFilteredFileExtension>ico</nonFilteredFileExtension>
                    <nonFilteredFileExtension>png</nonFilteredFileExtension>
                    <nonFilteredFileExtension>svg</nonFilteredFileExtension>
                    <nonFilteredFileExtension>jpg</nonFilteredFileExtension>
                    <nonFilteredFileExtension>jpeg</nonFilteredFileExtension>
                </nonFilteredFileExtensions>
            </configuration>
        </plugin>
</code>```

When I ran the aplication and hit http://localhost:8080 - it goes to HTTP Status 404 – Not Found
but the api's are still running , like http://localhost:8080/api/vehicles - provide json data from backend

My application.properties file as follows,

```<code>server.servlet.context-path=/api
server.port=8080
</code>```

答:
What is happening

When deploying your application and copying your ressources inside the src/main/ressources folder, you then expect Spring to render the front app for you. But Spring is a server, and as a server, it serves you given the configuration you gave him.

By using server.servlet.context-path=/api, you tell Spring : Everything will be prefixed by "/api"... Therefor, if you try requesting : http://localhost:8080/, Spring will tell you it knows nothing about such a URL, because for him, everything is supposed to be prefixed by /api...

So naturally, you would say : Then, let's access http://localhost:8080/api. But it is not that easy... I don't know yet exactly what is going on, but I guess you have index.html file inside your src/main/resources or src/main/resources/public... and when you try to access http://localhost:8080/api it will try to lookup for a file index.html inside src/main/resources/{public}/api/index.html... And it doesn't find any. Hence the exception.

Temporary solution

I've faced a similar issue with VueJS and Spring Boot. Without loosing too much time, my solution was to remove the properties server.servlet.context-path=/api and manually prefixing my controller with the annotation @RequestMapping.

```<code>@RestController
@RequestMapping("/api")
public class MyController {
    ...
}
</code>```

It should do the trick, but I am not a big fan.

Body:
I created Spring boot + angular 8 application which was running succesfully in two different port like 8080 and 4200 without any issues. Then I decided to run the application in same port (8080). I ran ng build --prod and got the dist folder. Moved that Dist folder into the spring application and the folder looked like this image

The corresponding pom.xml is as follows

  <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-resources-plugin</artifactId>
            <version>3.0.2</version>
            <configuration>
                  <outputDirectory>${project.build.directory}/target/classes/static/</outputDirectory >
                  <resources>
                      <resource>
                          <directory>${project.build.directory}/fleetManagement/dist/fleetManagement</directory >
                      </resource>
                  </resources>
                <nonFilteredFileExtensions>
                    <nonFilteredFileExtension>woff</nonFilteredFileExtension>
                    <nonFilteredFileExtension>ttf</nonFilteredFileExtension>
                    <nonFilteredFileExtension>woff2</nonFilteredFileExtension>
                    <nonFilteredFileExtension>eot</nonFilteredFileExtension>
                    <nonFilteredFileExtension>swf</nonFilteredFileExtension>
                    <nonFilteredFileExtension>ico</nonFilteredFileExtension>
                    <nonFilteredFileExtension>png</nonFilteredFileExtension>
                    <nonFilteredFileExtension>svg</nonFilteredFileExtension>
                    <nonFilteredFileExtension>jpg</nonFilteredFileExtension>
                    <nonFilteredFileExtension>jpeg</nonFilteredFileExtension>
                </nonFilteredFileExtensions>
            </configuration>
        </plugin>

When I ran the aplication and hit http://localhost:8080 - it goes to HTTP Status 404 – Not Found
but the api's are still running , like http://localhost:8080/api/vehicles - provide json data from backend

My application.properties file as follows,

server.servlet.context-path=/api
server.port=8080

Body:
What is happening

When deploying your application and copying your ressources inside the src/main/ressources folder, you then expect Spring to render the front app for you. But Spring is a server, and as a server, it serves you given the configuration you gave him.

By using server.servlet.context-path=/api, you tell Spring : Everything will be prefixed by "/api"... Therefor, if you try requesting : http://localhost:8080/, Spring will tell you it knows nothing about such a URL, because for him, everything is supposed to be prefixed by /api...

So naturally, you would say : Then, let's access http://localhost:8080/api. But it is not that easy... I don't know yet exactly what is going on, but I guess you have index.html file inside your src/main/resources or src/main/resources/public... and when you try to access http://localhost:8080/api it will try to lookup for a file index.html inside src/main/resources/{public}/api/index.html... And it doesn't find any. Hence the exception.

Temporary solution

I've faced a similar issue with VueJS and Spring Boot. Without loosing too much time, my solution was to remove the properties server.servlet.context-path=/api and manually prefixing my controller with the annotation @RequestMapping.

@RestController
@RequestMapping("/api")
public class MyController {
    ...
}

It should do the trick, but I am not a big fan.


问:
Enable Google Account Picker on Web
How can i enable Google account picker on Web like the one on this website in the top right corner:

Link - https://timesofindia.indiatimes.com/india/boarding-pass-stamping-may-soon-be-passe/articleshow/65140775.cms

I tried to find documentation on Google but came up empty.

It's running in an iframe with src starting from: https://smartlock.google.com/iframe/request?client=https%3A%2F%2Ftimesofindia.indiatimes.com&renderMode=navPopout

What is this service called and where can i find it's documentation?

答:
This is called Google Yolo which was supposed to be a one-click sign-in/ sign-up solution. It is no longer available, most probably due to the security concerns - https://neerajsinha.com/google-one-tap-yolo/

Update Dec 23, 2020:
It looks like Google has reintroduced Google Yolo by the name of One Tap. So you can now get more information here - https://developers.google.com/identity/one-tap/web

Title: Enable Google Account Picker on Web


问:
How do you execute a method only if another one has been run?
I have a choice for the user in Main using a switch. Depending on what the user chooses, several choices later, the program will either end or not. At least, that is what I'm trying to accomplish.

```<code>//This is in Main
string[] menyVal2 = new string[] {"Go to the hotel room", "Go to the dining hall"};
            string title2 = "text";
            int choice2 = menu(menuChoice2, title2);

            switch (choice2)
            {
                case 0:
                    hotelRoom();
                    break;
                case 1:
                    diningHall();
                    break;
            }
</code>```

Many lines of code later...

```<code>public static void save()
        {
            Console.Clear();
            string[] menuChoice = {"Chapter 2", "Back to start"};
            string title = "text";

            int choice = menu(menuChoice, title);
            switch (val)
            {
                case 0:
                    if (hotelRoom = true) //this if-statement does not work
                    {
                        withoutCross();
                    }
                    else if (diningHall = true)
                    {
                        withCross();
                    }
                    break;
                case 1:
                    Main(new string[] { });
                    break;
            }
        }
</code>```

答:
When I understand your title of the question correctly, then this is a solution:

Make the return type of the method bool and fill it to a variable.

```<code>bool isMethodExecuted = MyMethod();
</code>```

Later you can check with a if-Statement, if the method is executed:

```<code>if(isMethodExecuted)
    MyOtherMethod();
</code>```

Body:
I have a choice for the user in Main using a switch. Depending on what the user chooses, several choices later, the program will either end or not. At least, that is what I'm trying to accomplish.

//This is in Main
string[] menyVal2 = new string[] {"Go to the hotel room", "Go to the dining hall"};
            string title2 = "text";
            int choice2 = menu(menuChoice2, title2);

            switch (choice2)
            {
                case 0:
                    hotelRoom();
                    break;
                case 1:
                    diningHall();
                    break;
            }

Many lines of code later...

public static void save()
        {
            Console.Clear();
            string[] menuChoice = {"Chapter 2", "Back to start"};
            string title = "text";

            int choice = menu(menuChoice, title);
            switch (val)
            {
                case 0:
                    if (hotelRoom = true) //this if-statement does not work
                    {
                        withoutCross();
                    }
                    else if (diningHall = true)
                    {
                        withCross();
                    }
                    break;
                case 1:
                    Main(new string[] { });
                    break;
            }
        }

Body:
When I understand your title of the question correctly, then this is a solution:

Make the return type of the method bool and fill it to a variable.

bool isMethodExecuted = MyMethod();

Later you can check with a if-Statement, if the method is executed:

if(isMethodExecuted)
    MyOtherMethod();


问:
MS Access SQL Query for time In/Out attendance
HI,

I'm doing a project which involves time and attendance management. When I download data from the biometric reader, I got the records in the following format,

Lunch Break & Work Time Problem

Attendance Log Table Name: dbo_CHECKINOUT
The user Table name is: dbo_USERINFO

```<code>+---------+-----------------------+
| USERID  |       CHECKTIME       |
+---------+-----------------------+
|       5 | 2/16/2020 9:33:08 AM  |
|       2 | 2/16/2020 9:57:48 AM  |
|       3 | 2/16/2020 10:07:31 AM |
|       4 | 2/16/2020 10:36:01 AM |
|       1 | 2/16/2020 11:10:10 AM |
|       3 | 2/16/2020 1:45:15 PM  |
|       5 | 2/16/2020 1:57:46 PM  |
|       2 | 2/16/2020 1:58:19 PM  |
|       3 | 2/16/2020 2:17:46 PM  |
|       2 | 2/16/2020 2:33:39 PM  |
|       5 | 2/16/2020 2:48:26 PM  |
|       1 | 2/16/2020 7:51:57 PM  |
|       3 | 2/16/2020 9:29:20 PM  |
|       5 | 2/16/2020 9:29:25 PM  |
|       2 | 2/16/2020 9:29:29 PM  |
|       4 | 2/16/2020 9:29:46 PM  |
|       5 | 2/17/2020 9:31:47 AM  |
|       3 | 2/17/2020 10:15:13 AM |
|       4 | 2/17/2020 10:28:54 AM |
|       1 | 2/17/2020 11:28:17 AM |
+---------+-----------------------+
</code>```

I want to show the above records as follows, (the Log_In, LB_Out, LB_In, Log_Out, WorkTime and LunchBreak are based on 'time')
Someone from StackOverFlow helped me out to make this query

```<code>SELECT t.userid, dbo_USERINFO.NAME, DateValue(t.checktime) AS [date],
Max(IIf(t.counter=0,t.checktime,Null)) AS Log_In,
Max(IIf(t.counter=1,t.checktime)) AS LB_Out,
Max(IIf(t.counter=2,t.checktime,Null)) AS LB_In,
Max(IIf(t.counter=3,t.checktime)) AS Log_Out,
Format((Log_In-LB_Out)+(LB_In-Log_Out),"hh:nn:ss") AS WorkTime,
Format(LB_In-LB_Out,"hh:nn:ss") AS LunchBreak
FROM (
    SELECT t.*,
      (select count(*) from dbo_CHECKINOUT where userid = t.userid and datevalue(checktime) = datevalue(t.checktime) and checktime < t.checktime) AS [counter] FROM dbo_CHECKINOUT AS t)  AS t INNER JOIN dbo_USERINFO ON t.USERID=dbo_USERINFO.USERID
GROUP BY t.userid, dbo_USERINFO.NAME, DateValue(t.checktime);
</code>```

Results:

```<code>userid      date         Log_In        LB_Out        LB_In       Log_Out    WorkTime    LunchBreak
1           16-Feb-20   11:10:10 AM   7:51:57 PM
1           17-Feb-20   11:28:17 AM
2           16-Feb-20   9:57:48 AM    1:58:19 PM    2:33:39 PM  9:29:29 PM  10:56:21     00:35:20
3           16-Feb-20   10:07:31 AM   1:45:15 PM    2:17:46 PM  9:29:20 PM  10:49:18     00:32:31
3           17-Feb-20   10:15:13 AM
4           16-Feb-20   10:36:01 AM   9:29:46 PM
4           17-Feb-20   10:28:54 AM
5           16-Feb-20   9:33:08 AM    1:57:46 PM    2:48:26 PM  9:29:25 PM  11:05:37     00:50:40
5           17-Feb-20   9:31:47 AM
</code>```

Now the problem is, as you can see Userid:1 & Userid: 4 doesn't have a LunchBreak. So their 1st log would be Log_In & 2nd Log would be as a Log_Out & total work time would be between 1st(Log_In) & 2nd(Log_Out).

Please help to make this possible for me.

答:
This fancy query will return the lunch breaks:

SELECT
    dbo_UserInfo.UserId,
    DateValue([CheckTime]) AS [Date],
    TimeValue(Min([CheckTime])) AS LogIn,

    (Select Max(TimeValue(T.CheckTime))
    From dbo_UserInfo As T
    Where T.UserId = dbo_UserInfo.UserId
    And DateValue(T.CheckTime) = DateValue(dbo_UserInfo.CheckTime)
    And T.CheckTime >
        (Select Min(S.CheckTime)
        From dbo_UserInfo As S
        Where S.UserId = dbo_UserInfo.UserId
        And DateValue(S.CheckTime) = DateValue(dbo_UserInfo.CheckTime))) As LogOut,

    (Select Min(TimeValue(T.CheckTime))
    From dbo_UserInfo As T
    Where T.UserId = dbo_UserInfo.UserId
    And DateValue(T.CheckTime) = DateValue(dbo_UserInfo.CheckTime)
    And T.CheckTime >
        (Select Min(S.CheckTime)
        From dbo_UserInfo As S
        Where S.UserId = dbo_UserInfo.UserId
        And DateValue(S.CheckTime) = DateValue(dbo_UserInfo.CheckTime))
    And T.CheckTime <
        (Select Max(S.CheckTime)
        From dbo_UserInfo As S
        Where S.UserId = dbo_UserInfo.UserId
        And DateValue(S.CheckTime) = DateValue(dbo_UserInfo.CheckTime))
    Having Count(*) > 1) As LBIn,

    (Select Max(TimeValue(T.CheckTime))
    From dbo_UserInfo As T
    Where T.UserId = dbo_UserInfo.UserId
    And DateValue(T.CheckTime) = DateValue(dbo_UserInfo.CheckTime)
    And T.CheckTime >
        (Select Min(S.CheckTime)
        From dbo_UserInfo As S
        Where S.UserId = dbo_UserInfo.UserId
        And DateValue(S.CheckTime) = DateValue(dbo_UserInfo.CheckTime))
    And T.CheckTime <
        (Select Max(S.CheckTime)
        From dbo_UserInfo As S
        Where S.UserId = dbo_UserInfo.UserId
        And DateValue(S.CheckTime) = DateValue(dbo_UserInfo.CheckTime))
    Having Count(*) > 1) As LBOut
FROM
    dbo_UserInfo
GROUP BY
    dbo_UserInfo.UserId,
    DateValue([CheckTime]);
```

From this you can easily calculate the work hours.

Revised output:

Body:
HI,

I'm doing a project which involves time and attendance management. When I download data from the biometric reader, I got the records in the following format,

Lunch Break & Work Time Problem

Attendance Log Table Name: dbo_CHECKINOUT
The user Table name is: dbo_USERINFO

+---------+-----------------------+
| USERID  |       CHECKTIME       |
+---------+-----------------------+
|       5 | 2/16/2020 9:33:08 AM  |
|       2 | 2/16/2020 9:57:48 AM  |
|       3 | 2/16/2020 10:07:31 AM |
|       4 | 2/16/2020 10:36:01 AM |
|       1 | 2/16/2020 11:10:10 AM |
|       3 | 2/16/2020 1:45:15 PM  |
|       5 | 2/16/2020 1:57:46 PM  |
|       2 | 2/16/2020 1:58:19 PM  |
|       3 | 2/16/2020 2:17:46 PM  |
|       2 | 2/16/2020 2:33:39 PM  |
|       5 | 2/16/2020 2:48:26 PM  |
|       1 | 2/16/2020 7:51:57 PM  |
|       3 | 2/16/2020 9:29:20 PM  |
|       5 | 2/16/2020 9:29:25 PM  |
|       2 | 2/16/2020 9:29:29 PM  |
|       4 | 2/16/2020 9:29:46 PM  |
|       5 | 2/17/2020 9:31:47 AM  |
|       3 | 2/17/2020 10:15:13 AM |
|       4 | 2/17/2020 10:28:54 AM |
|       1 | 2/17/2020 11:28:17 AM |
+---------+-----------------------+

I want to show the above records as follows, (the Log_In, LB_Out, LB_In, Log_Out, WorkTime and LunchBreak are based on 'time')
Someone from StackOverFlow helped me out to make this query

SELECT t.userid, dbo_USERINFO.NAME, DateValue(t.checktime) AS [date],
Max(IIf(t.counter=0,t.checktime,Null)) AS Log_In,
Max(IIf(t.counter=1,t.checktime)) AS LB_Out,
Max(IIf(t.counter=2,t.checktime,Null)) AS LB_In,
Max(IIf(t.counter=3,t.checktime)) AS Log_Out,
Format((Log_In-LB_Out)+(LB_In-Log_Out),"hh:nn:ss") AS WorkTime,
Format(LB_In-LB_Out,"hh:nn:ss") AS LunchBreak
FROM (
    SELECT t.*,
      (select count(*) from dbo_CHECKINOUT where userid = t.userid and datevalue(checktime) = datevalue(t.checktime) and checktime < t.checktime) AS [counter] FROM dbo_CHECKINOUT AS t)  AS t INNER JOIN dbo_USERINFO ON t.USERID=dbo_USERINFO.USERID
GROUP BY t.userid, dbo_USERINFO.NAME, DateValue(t.checktime);

Results:

userid      date         Log_In        LB_Out        LB_In       Log_Out    WorkTime    LunchBreak
1           16-Feb-20   11:10:10 AM   7:51:57 PM
1           17-Feb-20   11:28:17 AM
2           16-Feb-20   9:57:48 AM    1:58:19 PM    2:33:39 PM  9:29:29 PM  10:56:21     00:35:20
3           16-Feb-20   10:07:31 AM   1:45:15 PM    2:17:46 PM  9:29:20 PM  10:49:18     00:32:31
3           17-Feb-20   10:15:13 AM
4           16-Feb-20   10:36:01 AM   9:29:46 PM
4           17-Feb-20   10:28:54 AM
5           16-Feb-20   9:33:08 AM    1:57:46 PM    2:48:26 PM  9:29:25 PM  11:05:37     00:50:40
5           17-Feb-20   9:31:47 AM

Now the problem is, as you can see Userid:1 & Userid: 4 doesn't have a LunchBreak. So their 1st log would be Log_In & 2nd Log would be as a Log_Out & total work time would be between 1st(Log_In) & 2nd(Log_Out).

Please help to make this possible for me.

Body:
This fancy query will return the lunch breaks:

SELECT
    dbo_UserInfo.UserId,
    DateValue([CheckTime]) AS [Date],
    TimeValue(Min([CheckTime])) AS LogIn,

    (Select Max(TimeValue(T.CheckTime))
    From dbo_UserInfo As T
    Where T.UserId = dbo_UserInfo.UserId
    And DateValue(T.CheckTime) = DateValue(dbo_UserInfo.CheckTime)
    And T.CheckTime >
        (Select Min(S.CheckTime)
        From dbo_UserInfo As S
        Where S.UserId = dbo_UserInfo.UserId
        And DateValue(S.CheckTime) = DateValue(dbo_UserInfo.CheckTime))) As LogOut,

    (Select Min(TimeValue(T.CheckTime))
    From dbo_UserInfo As T
    Where T.UserId = dbo_UserInfo.UserId
    And DateValue(T.CheckTime) = DateValue(dbo_UserInfo.CheckTime)
    And T.CheckTime >
        (Select Min(S.CheckTime)
        From dbo_UserInfo As S
        Where S.UserId = dbo_UserInfo.UserId
        And DateValue(S.CheckTime) = DateValue(dbo_UserInfo.CheckTime))
    And T.CheckTime <
        (Select Max(S.CheckTime)
        From dbo_UserInfo As S
        Where S.UserId = dbo_UserInfo.UserId
        And DateValue(S.CheckTime) = DateValue(dbo_UserInfo.CheckTime))
    Having Count(*) > 1) As LBIn,

    (Select Max(TimeValue(T.CheckTime))
    From dbo_UserInfo As T
    Where T.UserId = dbo_UserInfo.UserId
    And DateValue(T.CheckTime) = DateValue(dbo_UserInfo.CheckTime)
    And T.CheckTime >
        (Select Min(S.CheckTime)
        From dbo_UserInfo As S
        Where S.UserId = dbo_UserInfo.UserId
        And DateValue(S.CheckTime) = DateValue(dbo_UserInfo.CheckTime))
    And T.CheckTime <
        (Select Max(S.CheckTime)
        From dbo_UserInfo As S
        Where S.UserId = dbo_UserInfo.UserId
        And DateValue(S.CheckTime) = DateValue(dbo_UserInfo.CheckTime))
    Having Count(*) > 1) As LBOut
FROM
    dbo_UserInfo
GROUP BY
    dbo_UserInfo.UserId,
    DateValue([CheckTime]);

From this you can easily calculate the work hours.

Revised output:


问:
document.execCommand of insertText not working in IE
I am trying to so hard to dig out the solution to my problem from last week. document.execCommand('insertText', false, emo) this code line is working for all browser except IE (Internet Explorer
11). For IE, I have written the method insertTextAtCursor which is inserting always first in content editable.

My problem is, How could I insert the text into contentEditable at the cursor point for IE? Thanks in advance.

```<code>var insertTextAtCursor = function (html) {
    var sel, range;
    if (window.getSelection) {
      // IE9 and non-IE
      sel = window.getSelection();
      if (sel.getRangeAt && sel.rangeCount) {
        range = sel.getRangeAt(0);
        range.deleteContents();

        // Range.createContextualFragment() would be useful here but is
        // non-standard and not supported in all browsers (IE9, for one)
        var el = document.createElement("div");
        el.innerText = html;
        var frag = document.createDocumentFragment(), node, lastNode;
        while ((node = el.firstChild)) {
          lastNode = frag.appendChild(node);
        }
        range.insertNode(frag);

        // Preserve the selection
        if (lastNode) {
          range = range.cloneRange();
          range.setStartAfter(lastNode);
          range.collapse(false);
          sel.removeAllRanges();
          sel.addRange(range);
        }
      }
    } else if (document.selection && document.selection.type != "Control") {
      // IE < 9
      document.selection.createRange().pasteHTML(html);
    }
  };
</code>```

答:
document.execCommand('insertText', false, emo)

Not found the above code from the insertTextAtCursor function, when and where you are using the insertTextAtCursor function and the execCommand method? From this article, it seems that the execCommand method support IE browser. And, I have create a sample using your code, it seems that everything works well, please check it:

```<code><div id="thing" contenteditable="true" style="width:200px; border :1px solid black; cursor:pointer">
    this is a some random foo bar jumps over a stick test
</div>

<input type="button" value="Add" onclick="insertTextAtCursor('aaaa');" />
<script>
    var insertTextAtCursor = function (html) {
        var sel, range;
        if (window.getSelection) {
            // IE9 and non-IE
            sel = window.getSelection();
            if (sel.getRangeAt && sel.rangeCount) {
                range = sel.getRangeAt(0);
                range.deleteContents();

                // Range.createContextualFragment() would be useful here but is
                // non-standard and not supported in all browsers (IE9, for one)
                var el = document.createElement("div");
                el.innerText = html;
                var frag = document.createDocumentFragment(), node, lastNode;
                while ((node = el.firstChild)) {
                    lastNode = frag.appendChild(node);
                }
                range.insertNode(frag);

                // Preserve the selection
                if (lastNode) {
                    range = range.cloneRange();
                    range.setStartAfter(lastNode);
                    range.collapse(false);
                    sel.removeAllRanges();
                    sel.addRange(range);
                }
            }
        } else if (document.selection && document.selection.type != "Control") {
            // IE < 9
            document.selection.createRange().pasteHTML(html);
        }
    };
</script>
</code>```

The output as below:

Body:
I am trying to so hard to dig out the solution to my problem from last week. document.execCommand('insertText', false, emo) this code line is working for all browser except IE (Internet Explorer
11). For IE, I have written the method insertTextAtCursor which is inserting always first in content editable.

My problem is, How could I insert the text into contentEditable at the cursor point for IE? Thanks in advance.

var insertTextAtCursor = function (html) {
    var sel, range;
    if (window.getSelection) {
      // IE9 and non-IE
      sel = window.getSelection();
      if (sel.getRangeAt && sel.rangeCount) {
        range = sel.getRangeAt(0);
        range.deleteContents();

        // Range.createContextualFragment() would be useful here but is
        // non-standard and not supported in all browsers (IE9, for one)
        var el = document.createElement("div");
        el.innerText = html;
        var frag = document.createDocumentFragment(), node, lastNode;
        while ((node = el.firstChild)) {
          lastNode = frag.appendChild(node);
        }
        range.insertNode(frag);

        // Preserve the selection
        if (lastNode) {
          range = range.cloneRange();
          range.setStartAfter(lastNode);
          range.collapse(false);
          sel.removeAllRanges();
          sel.addRange(range);
        }
      }
    } else if (document.selection && document.selection.type != "Control") {
      // IE < 9
      document.selection.createRange().pasteHTML(html);
    }
  };

Body:
document.execCommand('insertText', false, emo)

Not found the above code from the insertTextAtCursor function, when and where you are using the insertTextAtCursor function and the execCommand method? From this article, it seems that the execCommand method support IE browser. And, I have create a sample using your code, it seems that everything works well, please check it:

<div id="thing" contenteditable="true" style="width:200px; border :1px solid black; cursor:pointer">
    this is a some random foo bar jumps over a stick test
</div>

<input type="button" value="Add" onclick="insertTextAtCursor('aaaa');" />
<script>
    var insertTextAtCursor = function (html) {
        var sel, range;
        if (window.getSelection) {
            // IE9 and non-IE
            sel = window.getSelection();
            if (sel.getRangeAt && sel.rangeCount) {
                range = sel.getRangeAt(0);
                range.deleteContents();

                // Range.createContextualFragment() would be useful here but is
                // non-standard and not supported in all browsers (IE9, for one)
                var el = document.createElement("div");
                el.innerText = html;
                var frag = document.createDocumentFragment(), node, lastNode;
                while ((node = el.firstChild)) {
                    lastNode = frag.appendChild(node);
                }
                range.insertNode(frag);

                // Preserve the selection
                if (lastNode) {
                    range = range.cloneRange();
                    range.setStartAfter(lastNode);
                    range.collapse(false);
                    sel.removeAllRanges();
                    sel.addRange(range);
                }
            }
        } else if (document.selection && document.selection.type != "Control") {
            // IE < 9
            document.selection.createRange().pasteHTML(html);
        }
    };
</script>

The output as below:


问:
Can I prevent onFling() and onDown() from both firing?
I'm detecting both the onDown() and onFling() gestures for two different purposes, both work.

Within onDown() a sound is to be played, while during onFling() a swipe is detected and a swipe related action is taken - no sound should be played during the onFling() gesture.

The problem is that the onDown() sound is being fired when I perform a swiping motion or when onFling() is fired.

My current onDown() gesture looks like:

```<code>@Override
public boolean onDown(MotionEvent e) {

    playSound();

    return true;
}
</code>```

My onFling() looks like:

```<code>@Override
public boolean onFling(MotionEvent downEvent, MotionEvent moveEvent, float velocityX, float velocityY) {
    boolean result = false;

    float diffY = moveEvent.getY() - downEvent.getY();
    float diffX = moveEvent.getX() - downEvent.getX();

    // which was greater? movement across Y or X
    if( Math.abs(diffX) > Math.abs(diffY) ) {

        // right or left swipe
        if( Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {

            doSomethingCool();

            result = true;

        }
    } else {
        // up or down swipe
        if( Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {

            doSomethingCool();

            result = true;
        }
    }

    return result;
}
</code>```

I've checked the GestureDetector class to see if onDown() could have multiple parameters like onDown(MotionEvent downEvent, MotionEvent moveEvent) but that isn't possible.

I've tried using MotionEvent constants (both ACTION_DOWN and ACTION_MOVE) within onDown() to eliminate swipes/flings as a possible option:

```<code>@Override
public boolean onDown(MotionEvent e) {

    if(e.getAction() == e.ACTION_DOWN) {
        playSound();
        return true;
    }

    return false;
}
</code>```

However that hasn't worked. Is this something that is just unavoidable?

I understand that in order to perform a "flinging" motion, you must first put your finger down... but I'm hoping there's a way to double check that a users finger is down and NOT actually in motion (swiping/flinging).

Thanks in advance!

答:
Using onSingleTapUp and onDoubleTap replce onDown.

I think it can avoid trigger onFling.

Body:
I'm detecting both the onDown() and onFling() gestures for two different purposes, both work.

Within onDown() a sound is to be played, while during onFling() a swipe is detected and a swipe related action is taken - no sound should be played during the onFling() gesture.

The problem is that the onDown() sound is being fired when I perform a swiping motion or when onFling() is fired.

My current onDown() gesture looks like:

@Override
public boolean onDown(MotionEvent e) {

    playSound();

    return true;
}

My onFling() looks like:

@Override
public boolean onFling(MotionEvent downEvent, MotionEvent moveEvent, float velocityX, float velocityY) {
    boolean result = false;

    float diffY = moveEvent.getY() - downEvent.getY();
    float diffX = moveEvent.getX() - downEvent.getX();

    // which was greater? movement across Y or X
    if( Math.abs(diffX) > Math.abs(diffY) ) {

        // right or left swipe
        if( Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {

            doSomethingCool();

            result = true;

        }
    } else {
        // up or down swipe
        if( Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {

            doSomethingCool();

            result = true;
        }
    }

    return result;
}

I've checked the GestureDetector class to see if onDown() could have multiple parameters like onDown(MotionEvent downEvent, MotionEvent moveEvent) but that isn't possible.

I've tried using MotionEvent constants (both ACTION_DOWN and ACTION_MOVE) within onDown() to eliminate swipes/flings as a possible option:

@Override
public boolean onDown(MotionEvent e) {

    if(e.getAction() == e.ACTION_DOWN) {
        playSound();
        return true;
    }

    return false;
}

However that hasn't worked. Is this something that is just unavoidable?

I understand that in order to perform a "flinging" motion, you must first put your finger down... but I'm hoping there's a way to double check that a users finger is down and NOT actually in motion (swiping/flinging).

Thanks in advance!


问:
Git discard all changes
Hi folks I am new developer trying to learn.

I use git desktop where you right click on a file and select discard changes, if you don't want to add that file into commit. It revert it back to its original state.

Now I am working in terminal how can I do that in terminal?

By mistake I added some changes into a file and I don't want to keep those changes. Please help.

Please, I am not an advanced user therefore kindly keep it as simple as possible. I have not made any commit on that machine yet.

I am only interested in I googled it but could not find a simple layman'ish answer.

答:
There are multiple ways to do it. I will mention the simplest of all.
It has 2 step:

Unstage the file to latest/current commit. Only required if the the changes to the file is staged.

git reset HEAD <file>

Undo the file changes.

git checkout <file>

Title: Git discard all changes


问:
Fastest image drawing method on iPhone
I am trying to draw images to the iphone screen by changing the images of a UIImageView in a loop. But since there was no much response on the screen than two or three images being drawn and skipping others I need another method.

I am trying to show 80 png images that are 320*480 in size at 30 images per second.

Please suggest the fastest method to do this. And some sample code if available.

Thanks

答:
The fastest drawing method on the iPhone is OpenGL ES. :)
If you make some texture atlases with your images you'll achieve what you want.</p>

ContentLicense: CC BY-SA 2.5

Title: Fastest image drawing method on iPhone


问:
Jenkins - matrix jobs - variables on different slaves overwrite each other?
I think i dont get how matrix builds work. When i set some variable in some stage depending on which node i run, then on rest of the stage sometimes this variable is set as it should and sometimes it gets values from other nodes (axes). In example below its like job which runs on ub18-1 sometimes has VARIABLE1='Linux node' and sometimes is VARIABLE1='Windows node'. Or gitmethod sometimes it is created from LinuxGitInfo and sometimes WindowsGitInfo.

Source i based on
https://jenkins.io/doc/book/pipeline/syntax/#declarative-matrix

Script almost exactly the same as real one

```<code>@Library('firstlibrary') _
import mylib.shared.*
pipeline {
    parameters {
        booleanParam name: 'AUTO', defaultValue: true, description: 'Auto mode sets some parameters for every slave separately'
        choice(name: 'SLAVE_NAME', choices:['all', 'ub18-1','win10'],description:'Run on specific platform')
        string(name: 'BRANCH',defaultValue: 'master', description: 'Preferably common label for entire group')
        booleanParam name: 'SONAR', defaultValue: false, description: 'Scan and gateway'
        booleanParam name: 'DEPLOY', defaultValue: false, description: 'Deploy to Artifactory'

    }

    agent none

    stages{
        stage('BuildAndTest'){
            matrix{
                agent {
                    label "$NODE"
                }
                when{ anyOf{
                    expression { params.SLAVE_NAME == 'all'}
                    expression { params.SLAVE_NAME == env.NODE}
                }}
                axes{
                    axis{
                        name 'NODE'
                        values 'ub18-1', 'win10'
                    }
                }
                stages{
                    stage('auto mode'){
                        when{
                            expression { return params.AUTO }
                        }
                        steps{
                            echo "Setting parameters for each slave"
                            script{
                                nodeLabelsList = env.NODE_LABELS.split()

                                if (nodeLabelsList.contains('ub18-1')){
                                    println("Setting params for ub18-1");
                                    VARIABLE1 = 'Linux node'
                                }

                                if (nodeLabelsList.contains('win10')){
                                    println("Setting params for Win10");
                                    VARIABLE1 = 'Windows node'
                                }

                                if (isUnix()){
                                    gitmethod = new LinuxGitInfo(this,env)
                                } else {
                                    gitmethod = new WindowsGitInfo(this, env)
                                }
                            }
                        }
                    }

                    stage('GIT') {
                        steps {
                            checkout scm
                        }
                    }

                    stage('Info'){
                        steps{
                            script{
                                sh 'printenv'

                                echo "branch: " +  env.BRANCH_NAME
                                echo "SLAVE_NAME: " + env.NODE_NAME
                                echo VARIABLE1

                                gitinfo = new GitInfo(gitmethod)
                                gitinfo.init()
                                echo gitinfo.author
                                echo gitinfo.id
                                echo gitinfo.msg
                                echo gitinfo.buildinfo
                            }
                        }
                    }

                    stage('install'){
                        steps{
                            sh 'make install'
                        }
                    }

                    stage('test'){
                        steps{
                            sh 'make test'
                        }
                    }

                }
            }
        }

    }
}
</code>```

答:
Ok i solved the problem by defining variables maps with node/slave names as keys. Some friend even suggested to define variables in yml/json file in repository and parse them. Maybe i will, but so far this works well

example:

before the pipelines

```<code>def DEPLOYmap = [
    'ub18-1': false,
    'win10': true
    ]
</code>```

in stages

```<code>when {
        equals expected: true, actual: DEPLOYmap[NODE]
     }
</code>```

Body:
I think i dont get how matrix builds work. When i set some variable in some stage depending on which node i run, then on rest of the stage sometimes this variable is set as it should and sometimes it gets values from other nodes (axes). In example below its like job which runs on ub18-1 sometimes has VARIABLE1='Linux node' and sometimes is VARIABLE1='Windows node'. Or gitmethod sometimes it is created from LinuxGitInfo and sometimes WindowsGitInfo.

Source i based on
https://jenkins.io/doc/book/pipeline/syntax/#declarative-matrix

Script almost exactly the same as real one

@Library('firstlibrary') _
import mylib.shared.*
pipeline {
    parameters {
        booleanParam name: 'AUTO', defaultValue: true, description: 'Auto mode sets some parameters for every slave separately'
        choice(name: 'SLAVE_NAME', choices:['all', 'ub18-1','win10'],description:'Run on specific platform')
        string(name: 'BRANCH',defaultValue: 'master', description: 'Preferably common label for entire group')
        booleanParam name: 'SONAR', defaultValue: false, description: 'Scan and gateway'
        booleanParam name: 'DEPLOY', defaultValue: false, description: 'Deploy to Artifactory'

    }

    agent none

    stages{
        stage('BuildAndTest'){
            matrix{
                agent {
                    label "$NODE"
                }
                when{ anyOf{
                    expression { params.SLAVE_NAME == 'all'}
                    expression { params.SLAVE_NAME == env.NODE}
                }}
                axes{
                    axis{
                        name 'NODE'
                        values 'ub18-1', 'win10'
                    }
                }
                stages{
                    stage('auto mode'){
                        when{
                            expression { return params.AUTO }
                        }
                        steps{
                            echo "Setting parameters for each slave"
                            script{
                                nodeLabelsList = env.NODE_LABELS.split()

                                if (nodeLabelsList.contains('ub18-1')){
                                    println("Setting params for ub18-1");
                                    VARIABLE1 = 'Linux node'
                                }

                                if (nodeLabelsList.contains('win10')){
                                    println("Setting params for Win10");
                                    VARIABLE1 = 'Windows node'
                                }

                                if (isUnix()){
                                    gitmethod = new LinuxGitInfo(this,env)
                                } else {
                                    gitmethod = new WindowsGitInfo(this, env)
                                }
                            }
                        }
                    }

                    stage('GIT') {
                        steps {
                            checkout scm
                        }
                    }

                    stage('Info'){
                        steps{
                            script{
                                sh 'printenv'

                                echo "branch: " +  env.BRANCH_NAME
                                echo "SLAVE_NAME: " + env.NODE_NAME
                                echo VARIABLE1

                                gitinfo = new GitInfo(gitmethod)
                                gitinfo.init()
                                echo gitinfo.author
                                echo gitinfo.id
                                echo gitinfo.msg
                                echo gitinfo.buildinfo
                            }
                        }
                    }

                    stage('install'){
                        steps{
                            sh 'make install'
                        }
                    }

                    stage('test'){
                        steps{
                            sh 'make test'
                        }
                    }

                }
            }
        }

    }
}

Body:
Ok i solved the problem by defining variables maps with node/slave names as keys. Some friend even suggested to define variables in yml/json file in repository and parse them. Maybe i will, but so far this works well

example:

before the pipelines

def DEPLOYmap = [
    'ub18-1': false,
    'win10': true
    ]

in stages

when {
        equals expected: true, actual: DEPLOYmap[NODE]
     }