问:
Low FPS with OpenCV VideoCapture
I am trying to display a video stream with OpenCV, but I am having horrible problems with framerate. My video source can put out a maximum of 60 fps, but I have limited it to 30. The issue is I am receiving it at about 2fps

I have simplified my program down as far as possible to make it easier to read:

```<code>#include "opencv2/core/core.hpp"
#include "opencv2/calib3d/calib3d.hpp"
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <stdio.h>

using namespace cv;
using namespace std;

int main(int argc, char* argv[])
{

    Mat image1;
    int k;

     const char* right_cam_gst = "nvcamerasrc sensor-id=0 ! video/x-raw(memory:NVMM),\
                                              width=(int)640,\
                                              height=(int)360,\
                                              format=(string)I420,\
                                              framerate=(fraction)30/1 ! nvvidconv flip-method=2 ! video/x-raw,\
                                              format=(string)I420 ! videoconvert ! video/x-raw,\
                                              format=(string)BGR ! appsink";

    VideoCapture cap1 = VideoCapture(right_cam_gst);

   for (;;)
    {
       cap1 >> image1;

       imshow("image1", image1);

       if(waitKey(1) == 27)
        break;
    }

}
</code>```

This should grab and display the image as fast as the stream can allow. right?

Thanks for the help guys!

EDIT Looks like if I simply display an image as fast as possible, it only shows at about 1fps. This is eliminating the camera entirely.

SYSTEM: ubuntu on nvidia Jetson TX1

答:
Found the answer! Looks like even though my ethernet connection was fast, it was somehow using the server for computing. (Not sure how). See this post: https://devtalk.nvidia.com/default/topic/1025856/very-slow-framerate-jetson-tx1-and-opencv/?offset=8

I disabled the Xserver and plugged straight in, and I got full 60 FPS.

Title: Low FPS with OpenCV VideoCapture

Body:
I am trying to display a video stream with OpenCV, but I am having horrible problems with framerate. My video source can put out a maximum of 60 fps, but I have limited it to 30. The issue is I am receiving it at about 2fps

I have simplified my program down as far as possible to make it easier to read:

#include "opencv2/core/core.hpp"
#include "opencv2/calib3d/calib3d.hpp"
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <stdio.h>

using namespace cv;
using namespace std;

int main(int argc, char* argv[])
{

    Mat image1;
    int k;

     const char* right_cam_gst = "nvcamerasrc sensor-id=0 ! video/x-raw(memory:NVMM),\
                                              width=(int)640,\
                                              height=(int)360,\
                                              format=(string)I420,\
                                              framerate=(fraction)30/1 ! nvvidconv flip-method=2 ! video/x-raw,\
                                              format=(string)I420 ! videoconvert ! video/x-raw,\
                                              format=(string)BGR ! appsink";

    VideoCapture cap1 = VideoCapture(right_cam_gst);

   for (;;)
    {
       cap1 >> image1;

       imshow("image1", image1);

       if(waitKey(1) == 27)
        break;
    }

}

This should grab and display the image as fast as the stream can allow. right?

Thanks for the help guys!

EDIT Looks like if I simply display an image as fast as possible, it only shows at about 1fps. This is eliminating the camera entirely.

SYSTEM: ubuntu on nvidia Jetson TX1


来源: stackexchange

问:
Unable to start debugging. The startup project could not be launched. VS2015
I have started a new console project in VS2015. I only have this code :

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SautinSoft;

namespace PdfParser
{
    class Program
    {
        static void Main(string[] args)
        {

            string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            SautinSoft.PdfFocus f = new PdfFocus();
            f.OpenPdf(@"path:\abc.pdf");

            if (f.PageCount > 0)
                f.ToExcel(@"path:\abc.xls");
        }
    }
}
</code>```

When I try to run, I get this :

Unable to start debugging. The startup project could not be launched.
  Verify debug settings for the startup project.

How can I fix this? Thanks.

答: Close the Visual Studio and re-open it again.</p>

ContentLicense: CC BY-SA 3.0

Body:
I have started a new console project in VS2015. I only have this code :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SautinSoft;

namespace PdfParser
{
    class Program
    {
        static void Main(string[] args)
        {

            string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            SautinSoft.PdfFocus f = new PdfFocus();
            f.OpenPdf(@"path:\abc.pdf");

            if (f.PageCount > 0)
                f.ToExcel(@"path:\abc.xls");
        }
    }
}

When I try to run, I get this :

Unable to start debugging. The startup project could not be launched.
  Verify debug settings for the startup project.

How can I fix this? Thanks.


问:
Efficient algorithm for comparing elements in the same list
I have a list of BaseBallGame objects with start and end time. I need to make sure that each game are happening at a separate time so that a user can watch the live stream of all the game.

I have an algorithm of O(n^2). I need to at least make it nlog(n).
Can someone give me a pointer on how we can improve the performance of my implementation?

```<code>public class GameTime {

    public static Boolean canViewAll(Collection<BaseBallGame> baseBallGames) {

        List<BaseBallGame> games_list = (List<BaseBallGame>) baseBallGames;
        boolean isOverlap = false;

        for (int i = 0; i < games_list(); i++) {

            for (int j = i + 1; j < games_list(); j++) {

                Date startA = games_list(i).getStart();
                Date endA = games_list(i).getEnd();
                Date startB = games_list(j).getStart();
                Date endB = games_list(j).getEnd();

                boolean isStartABeforeEndB = (startA.compareTo(endB)) < 0;
                boolean isEndAAfterStartB = (endA.compareTo(startB)) > 0;

                boolean isCurrentPairOverlap = false;

                isCurrentPairOverlap = isStartABeforeEndB && isEndAAfterStartB;

                if (isCurrentPairOverlap) {
                    isOverlap = true;
                }
            }
        }
        return !isOverlap;
    }

    boolean overlap(Date start1, Date end1, Date start2, Date end2){
        return start1.getTime() <= end2.getTime() && start2.getTime() <= end1.getTime();
    }

    public static void main(String[] args) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("y-M-d H:m");

        ArrayList<BaseBallGame> baseBallGames = new ArrayList<BaseBallGame>();
        baseBallGames.add(new BaseBallGame(sdf.parse("2015-01-01 20:00"), sdf.parse("2015-01-01 21:30")));
        baseBallGames.add(new BaseBallGame(sdf.parse("2015-01-01 21:30"), sdf.parse("2015-01-01 23:00")));
        baseBallGames.add(new BaseBallGame(sdf.parse("2015-01-01 23:10"), sdf.parse("2015-01-01 23:30")));

        System.out.println(GameTime.canViewAll(baseBallGames));
    }
}

class BaseBallGame {
    private Date start, end;

    public BaseBallGame(Date start, Date end) {
        this.start = start;
        this.end = end;
    }

    public Date getStart() {
        return this.start;
    }

    public Date getEnd() {
        return this.end;
    }

}
</code>```

答:
What if you were to sort the list using a Comparator and then iterate through the list once and see if any times overlap?

Java Array Sorting Algorithm: java.util.Arrays uses mergesort for objects that implement Comparable or use a Comparator.

Merge sort algorithm is average/best/worst case nlog(n). Then, the one iteration through would be negligible.

Body:
I have a list of BaseBallGame objects with start and end time. I need to make sure that each game are happening at a separate time so that a user can watch the live stream of all the game.

I have an algorithm of O(n^2). I need to at least make it nlog(n).
Can someone give me a pointer on how we can improve the performance of my implementation?

public class GameTime {

    public static Boolean canViewAll(Collection<BaseBallGame> baseBallGames) {

        List<BaseBallGame> games_list = (List<BaseBallGame>) baseBallGames;
        boolean isOverlap = false;

        for (int i = 0; i < games_list(); i++) {

            for (int j = i + 1; j < games_list(); j++) {

                Date startA = games_list(i).getStart();
                Date endA = games_list(i).getEnd();
                Date startB = games_list(j).getStart();
                Date endB = games_list(j).getEnd();

                boolean isStartABeforeEndB = (startA.compareTo(endB)) < 0;
                boolean isEndAAfterStartB = (endA.compareTo(startB)) > 0;

                boolean isCurrentPairOverlap = false;

                isCurrentPairOverlap = isStartABeforeEndB && isEndAAfterStartB;

                if (isCurrentPairOverlap) {
                    isOverlap = true;
                }
            }
        }
        return !isOverlap;
    }

    boolean overlap(Date start1, Date end1, Date start2, Date end2){
        return start1.getTime() <= end2.getTime() && start2.getTime() <= end1.getTime();
    }

    public static void main(String[] args) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("y-M-d H:m");

        ArrayList<BaseBallGame> baseBallGames = new ArrayList<BaseBallGame>();
        baseBallGames.add(new BaseBallGame(sdf.parse("2015-01-01 20:00"), sdf.parse("2015-01-01 21:30")));
        baseBallGames.add(new BaseBallGame(sdf.parse("2015-01-01 21:30"), sdf.parse("2015-01-01 23:00")));
        baseBallGames.add(new BaseBallGame(sdf.parse("2015-01-01 23:10"), sdf.parse("2015-01-01 23:30")));

        System.out.println(GameTime.canViewAll(baseBallGames));
    }
}

class BaseBallGame {
    private Date start, end;

    public BaseBallGame(Date start, Date end) {
        this.start = start;
        this.end = end;
    }

    public Date getStart() {
        return this.start;
    }

    public Date getEnd() {
        return this.end;
    }

}


问:
AWS IAM policy for more than one bucket
What is advisable when one needs an IAM policy for more than two buckets? Bucket names are pretty different from one another.

Combine all the access and put it in one IAM policy?

Create n number of polices for n buckets?

If 1 is the answer, can someone help with an example of read/write permissions on two buckets 1. bucket-a 2. bucket-b

答:
Are you creating IAM User Policies or S3 Bucket Policies? I will assume S3 bucket policies for this answer.

S3 buckets can only have one policy applied at a time.

This S3 bucket policy will grant anonymous access to read (get) and write (put) objects for two buckets. Note, the anonymous users will not be able to list objects.

```<code>{
  "Version":"2012-10-17",
  "Statement":[
    {
      "Sid":"AddPerm",
      "Effect":"Allow",
      "Principal": "*",
      "Action":[
           "s3:GetObject",
           "s3:PutObject"
      ],
      "Resource":[
          "arn:aws:s3:::bucket-a/*",
          "arn:aws:s3:::bucket-b/*"
      ]
    }
  ]
}
</code>```

Specifying Permissions in a Policy

Title: AWS IAM policy for more than one bucket

Body:
Are you creating IAM User Policies or S3 Bucket Policies? I will assume S3 bucket policies for this answer.

S3 buckets can only have one policy applied at a time.

This S3 bucket policy will grant anonymous access to read (get) and write (put) objects for two buckets. Note, the anonymous users will not be able to list objects.

{
  "Version":"2012-10-17",
  "Statement":[
    {
      "Sid":"AddPerm",
      "Effect":"Allow",
      "Principal": "*",
      "Action":[
           "s3:GetObject",
           "s3:PutObject"
      ],
      "Resource":[
          "arn:aws:s3:::bucket-a/*",
          "arn:aws:s3:::bucket-b/*"
      ]
    }
  ]
}

Specifying Permissions in a Policy


问:
Why does the infobox in my MSN Map not close?
I'm having a bit of trouble with this map, invoked by the "View our interactive map" button in the middle of the content area.

If you double click a point such as 8 which causes a zoom and then afterwards it causes the info box to appear, the hide logic is wrong.

If you try to close the x, it will fail. This is probably because the user clicked too fast and the map thinks its in zoom mode when infact it should be in info box mode.

Has anyone ran into this issue before? Looks like I have to mess around with window.ero.hide and some other functions.. because map.HideInfoBox doesn't hide the map.

EDIT: The script used is here. I did not code it, but the relevant bit has:

```<code>onclick="EnableEroHide();map.HideInfoBox();changePin();return false;"
</code>```

The map.HideInfoBox() should hide the info box.

答: The issue was that the hide function was being overridden by an empty function(){return;}. I had to save a reference to the hide function and invoke it manually.

ContentLicense: CC BY-SA 2.5

Body:
I'm having a bit of trouble with this map, invoked by the "View our interactive map" button in the middle of the content area.

If you double click a point such as 8 which causes a zoom and then afterwards it causes the info box to appear, the hide logic is wrong.

If you try to close the x, it will fail. This is probably because the user clicked too fast and the map thinks its in zoom mode when infact it should be in info box mode.

Has anyone ran into this issue before? Looks like I have to mess around with window.ero.hide and some other functions.. because map.HideInfoBox doesn't hide the map.

EDIT: The script used is here. I did not code it, but the relevant bit has:

onclick="EnableEroHide();map.HideInfoBox();changePin();return false;"

The map.HideInfoBox() should hide the info box.


问:
Python OrderedDicts equal to a tolerance
I have 100 OrderedDicts like,

```<code>foo =  OrderedDict({
    'a': -0.1011,
    'b': 3.2022,
    'c': 0.0
})
</code>```

where some of them are likely to be equal. For a list of 100 dicts like foo, I would like to find the indices of the unique items, where a given item is unique if its values are not equal to the values of any other dict, to a tolerance of 0.01. Importantly we can assume the order of the keys for all OrderedDicts in the list are the same. So I could do np.isclose(foo.values(), baz.values(), atol=0.01), but I'd have to loop through 10000 times to compare them all; actually less b/c I could on-the-fly ignore those that are found to be redundant. But is there a more efficient approach to doing this?

Another approach is something like: uniques = {tuple(x.values()) for x in list_of_ord_dicts}, but how could I incorporate a tolerance here?

答:
If stuff is the list of dicts and I want my tolerance to be d decimals:

```<code>import numpy as np
_, ind = np.unique(np.array([np.round(s.values(), d) for s in stuff]), axis=0, return_index=True)
</code>```

where ind are the indices of stuff referencing the unique dicts.

Body:
I have 100 OrderedDicts like,

foo =  OrderedDict({
    'a': -0.1011,
    'b': 3.2022,
    'c': 0.0
})

where some of them are likely to be equal. For a list of 100 dicts like foo, I would like to find the indices of the unique items, where a given item is unique if its values are not equal to the values of any other dict, to a tolerance of 0.01. Importantly we can assume the order of the keys for all OrderedDicts in the list are the same. So I could do np.isclose(foo.values(), baz.values(), atol=0.01), but I'd have to loop through 10000 times to compare them all; actually less b/c I could on-the-fly ignore those that are found to be redundant. But is there a more efficient approach to doing this?

Another approach is something like: uniques = {tuple(x.values()) for x in list_of_ord_dicts}, but how could I incorporate a tolerance here?

Body:
If stuff is the list of dicts and I want my tolerance to be d decimals:

import numpy as np
_, ind = np.unique(np.array([np.round(s.values(), d) for s in stuff]), axis=0, return_index=True)

where ind are the indices of stuff referencing the unique dicts.


问:
Segmentation fault when using array
```<code>#include <stdio.h>

typedef struct StockDetail {
    char* name;
    int code;
    int price;

} Stock;

int main(void)
{
    Stock a[200]; int i; int b;
    for(i=0; i<20 ; i++ )
    {
        printf("Stock %i\n",i+1);
        printf("Name:");
        scanf("%s",a[i].name);
        printf("Code:");
        scanf("%i",&a[i].code);
        printf("Name:");
        scanf("%i",&a[i].price);

    }

    printf("Maximum price of the stock:");
    scanf("%i", &b);

    for(i=0; i<20 ; i++)
    {
        if(a[i].price<=b)
        {
            printf("%s\n",a[i].name);
        }
    }
}
</code>```

Hi, I'm trying to implement a program that reads 20 stock details such as name, code and price and then ask the user to input a maximum price and print out the stock that cost less than the price. The code looks fine but when I tried to run it gave "segmentation fault" error line.

答:
```<code>scanf("%s",a[i].name);
</code>```

Here you are taking input in name which is just char* it does not have memory alloted to it, you can declare it as char array with sufficient size or allocate memory with malloc before taking input in it

Title: Segmentation fault when using array

Body:
#include <stdio.h>

typedef struct StockDetail {
    char* name;
    int code;
    int price;

} Stock;

int main(void)
{
    Stock a[200]; int i; int b;
    for(i=0; i<20 ; i++ )
    {
        printf("Stock %i\n",i+1);
        printf("Name:");
        scanf("%s",a[i].name);
        printf("Code:");
        scanf("%i",&a[i].code);
        printf("Name:");
        scanf("%i",&a[i].price);

    }

    printf("Maximum price of the stock:");
    scanf("%i", &b);

    for(i=0; i<20 ; i++)
    {
        if(a[i].price<=b)
        {
            printf("%s\n",a[i].name);
        }
    }
}

Hi, I'm trying to implement a program that reads 20 stock details such as name, code and price and then ask the user to input a maximum price and print out the stock that cost less than the price. The code looks fine but when I tried to run it gave "segmentation fault" error line.

Body:
scanf("%s",a[i].name);

Here you are taking input in name which is just char* it does not have memory alloted to it, you can declare it as char array with sufficient size or allocate memory with malloc before taking input in it


问:
Inserting labels in box plot in R on a 45 degree angle?
Is there any way in the boxplot() command to rotate the labels at a 45-degree angle? </p>

<p>I realize the las=2 command rotates them to be perpendicular to the x axis, but I was hoping to have them at 45 degrees. </p>

答:
How about the following:

```<code># Some sample data
x <- list(x = rnorm(100, 2), y = rnorm(100, 4));
# Plot without x axis
boxplot(x, xaxt = "n");
# Add axis labels rotated by 45 degrees
text(seq_along(x), par("usr")[3] - 0.5, labels = names(x), srt = 45, adj = 1, xpd = TRUE);
</code>```

PS. Or easier/cleaner in ggplot:

```<code>require(ggplot2);
require(reshape2);
df <- melt(x);
ggplot(df, aes(L1, value)) + geom_boxplot() + theme(axis.text.x = element_text(angle = 45, hjust = 1));
</code>```

Body:
Is there any way in the boxplot() command to rotate the labels at a 45-degree angle?

I realize the las=2 command rotates them to be perpendicular to the x axis, but I was hoping to have them at 45 degrees.

Body:
How about the following:

# Some sample data
x <- list(x = rnorm(100, 2), y = rnorm(100, 4));
# Plot without x axis
boxplot(x, xaxt = "n");
# Add axis labels rotated by 45 degrees
text(seq_along(x), par("usr")[3] - 0.5, labels = names(x), srt = 45, adj = 1, xpd = TRUE);

PS. Or easier/cleaner in ggplot:

require(ggplot2);
require(reshape2);
df <- melt(x);
ggplot(df, aes(L1, value)) + geom_boxplot() + theme(axis.text.x = element_text(angle = 45, hjust = 1));


问:
Exporting hundreds of thousands of records with ColdFusion
Using ColdFusion 9.0.1, I need to export hundreds of thousands of database records to Excel XLSX or CSV (XLSX is preferred). This must be done on demand. So far I've tried using cfspreadsheet but it chokes when exporting more than a couple thousand rows in the XLSX format. However, exporting to XLS works fine (of course there is a ~65,000 row limit).

What are my options to export so many records? Theoretically the users could need to export as many as one million records. I'm also using SQL Server 2008 R2 -- is there a way to somehow export the records to a file there and then send the file through CF to the user? What options do I have? Thanks.

答:
As you've discovered, doing this with ColdFusion's <cfspreadsheet/> tag fails because it builds the entire document in memory, which leads to JVM OutOfMemory errors. What you need is something that buffers output to disk so you don't run out of memory. This suggests CSV, which is far easier to buffer. I imagine there are ways to do it with Excel as well, but I don't know them.

So two options for you:

use a Java library

use ColdFusion's fileOpen(), fileWrite(), fileClose() methods

I'll cover each in turn.

Java Libary

opencsv is my preference. This assumes of course you know how to setup a .jar on the ColdFusion classpath. If you do then it's a matter using its APIs to open a file and specify data for each line. It's really quite simple. Check its docs for examples.

ColdFusion Methods

Be forewarned there be dragons here.

If you are exporting numbers or strings that do not contain any double quotes or commas you can probably do this. If not, figuring out what to escape and how is why you use a library in the first place. Code is roughly as such:

```<code><!--- query to get whatever data you're working with --->

<cfset csvFile = fileOpen(filePath, 'read')>
<cfloop query="yourQuery">
    <cfset csvRow = ""><!--- construct a csv row here from the query row --->
    <cfset fileWrite(csvFile, csvRow)>
</cfloop>

<cfset fileClose(csvFile)>
</code>```

If the query data you're working with is also large you may be dealing with a nested loop to chunk it out.

Body:
As you've discovered, doing this with ColdFusion's <cfspreadsheet/> tag fails because it builds the entire document in memory, which leads to JVM OutOfMemory errors. What you need is something that buffers output to disk so you don't run out of memory. This suggests CSV, which is far easier to buffer. I imagine there are ways to do it with Excel as well, but I don't know them.

So two options for you:

use a Java library

use ColdFusion's fileOpen(), fileWrite(), fileClose() methods

I'll cover each in turn.

Java Libary

opencsv is my preference. This assumes of course you know how to setup a .jar on the ColdFusion classpath. If you do then it's a matter using its APIs to open a file and specify data for each line. It's really quite simple. Check its docs for examples.

ColdFusion Methods

Be forewarned there be dragons here.

If you are exporting numbers or strings that do not contain any double quotes or commas you can probably do this. If not, figuring out what to escape and how is why you use a library in the first place. Code is roughly as such:

<!--- query to get whatever data you're working with --->

<cfset csvFile = fileOpen(filePath, 'read')>
<cfloop query="yourQuery">
    <cfset csvRow = ""><!--- construct a csv row here from the query row --->
    <cfset fileWrite(csvFile, csvRow)>
</cfloop>

<cfset fileClose(csvFile)>

If the query data you're working with is also large you may be dealing with a nested loop to chunk it out.


答:
You do not allocate any space for your Stock.name.  Use a char[100] or allocate some space.

something like:

```<code>for(i=0; i<20 ; i++ )
{
    char tempname[100];
    printf("Stock %i\n",i+1);
    printf("Name:");
    scanf("%s",tempname);
    a[i].name=strdup(tempname);
</code>```

Don't forget to free it!

Otherwise declare

```<code>typedef struct StockDetail {
char name[100];
int code;
int price;

} Stock;
</code>```

Title: Segmentation fault when using array

Body:
You do not allocate any space for your Stock.name.  Use a char[100] or allocate some space.

something like:

for(i=0; i<20 ; i++ )
{
    char tempname[100];
    printf("Stock %i\n",i+1);
    printf("Name:");
    scanf("%s",tempname);
    a[i].name=strdup(tempname);

Don't forget to free it!

Otherwise declare

typedef struct StockDetail {
char name[100];
int code;
int price;

} Stock;


问:
Feature APK's and Android Instant Apps
According to this doc : https://developer.android.com/topic/instant-apps/overview.html#features
In case I want to make a modular app with installable feature, can I use instant app to imitate the behavior of a module ? I want a base app with very basic features and installable modules to fit perfectly the needs of users. It could be a plus if modules can be found on the play store too.

Thanks if you have more info about it or if Google have another way to archieve this :)

答:
As per my understanding, Instant Apps is basically the main installable-app broken down to lite-modularized apps that are accessed via URLs and loaded automatically without the need to go to the Play Store to install the entire app. For more understanding please also have a look at
Overview of Android Instant Apps and  Introduction to Android Instant Apps (Google I/O '17)</p>

Title: Feature APK's and Android Instant Apps


问:
Importing sharedModule in App and in every Module angular 2
I am a little confused with how a shared module is imported is used in angular 2 and looking for some clarification.

So when i create  a SharedModule class with imported components and modules which i also export to reuse. I imported the SharedModule into my app.module so: 1. it will be there on app load. 2. so i don't have to import it in other feature modules.

I noticed that even though i imported in my app.module but when i would run my application i get the error message that either i am missing a component or reference to a module. So i end up importing the shared module in all my feature modules. I thought by placing it in the app.module that i wouldn't have to import it in my other modules?

答:
I thought by placing it in the app.module that i wouldn't have to import it in my other modules?

No, any modules imported into AppModule don't become available to any other Modules also imported by AppModule. If you want to have a SharedModule's exported Pipes/Components/Directives available to a feature module, the SharedModule will have to be imported into that feature module explicitly. The advantage of this is that you have all your exported components in ONE module, so even if you had to import the SharedModule into 10 Feature Modules, you'd only have to make 1 import, as opposed to importing each Component/Directive/Pipe etc individually in each of those 10 feature modules.

For further reference, check out the official docs.


问:
How can I get the name of a form in my directive?
I'm getting the ngModel name, but I also want to get the name of the form to which the element with the "validacion" directive belongs.

I strictly need to get the name of the form to which the HTML element belongs. I can have several forms so I need a dynamic solution. thank you very much

```<code>.directive('validacion', function ($timeout,$rootScope,validacionCampos,$compile) {

      return {
          restrict: 'AE',
          require: 'ngModel',

          link: function (scope, element, attrs, ngModel) {
                  if (!ngModel){
                          console.log("no hay modal")
                  return;
          }
</code>```

答:
You can get form name using ng-form in pure AngularJS way like below:

```<code><ng-form name="myForm">
   <input type="text" name="cityInput">
</ng-form>
</code>```

In JavaScript you can print:

```<code>  console.log($scope.myForm);
</code>```

Body:
I'm getting the ngModel name, but I also want to get the name of the form to which the element with the "validacion" directive belongs.

I strictly need to get the name of the form to which the HTML element belongs. I can have several forms so I need a dynamic solution. thank you very much

.directive('validacion', function ($timeout,$rootScope,validacionCampos,$compile) {

      return {
          restrict: 'AE',
          require: 'ngModel',

          link: function (scope, element, attrs, ngModel) {
                  if (!ngModel){
                          console.log("no hay modal")
                  return;
          }

Body:
You can get form name using ng-form in pure AngularJS way like below:

<ng-form name="myForm">
   <input type="text" name="cityInput">
</ng-form>

In JavaScript you can print:

  console.log($scope.myForm);


问:
javascript spin wheel 'prize' selection based on percentage
I have created a spin wheel using the code below

```<code><script>
var spinWheel = new Winwheel({
    'numSegments' : 4,
    'segments'    :
    [
        {'fillStyle' : '#eae56f', 'text' : 'Prize 1'},
        {'fillStyle' : '#89f26e', 'text' : 'Prize 2'},
        {'fillStyle' : '#7de6ef', 'text' : 'Prize 3'},
        {'fillStyle' : '#e7706f', 'text' : 'Prize 4'}
    ]
});
</code>```

I'm using this JS library
http://dougtesting.net/winwheel/examples/basic_code_wheel

What I want to do is to create a function that will let me be more in control of the result after the 'wheel' has spun? If you have a solution or can point me to an existing script I would appreciate it. Thank you!

答:
As mentioned by Vj-, there is the ability to control the result of the spin, and this is done by setting the stopAngle of the animation before the spinning starts.

This tutorial http://dougtesting.net/winwheel/docs/tut14_setting_the_prize details 2 ways of doing this.

The first is calculating this in some JavaScript code on the page, the other - and more secure way - is having a server side process calculate this and return the number of the prize to be won by the user. The server side process could also do things like updating a database to record the prize won etc.

Also as Vj- says, a quick and easy way to make a selection based on percentage is to pick a random number between 1 and 100 and then depending on the number selecting the segment. If segment 1 should be won 50% of the time, then if the number is between 1 and 50 segment 1 is selected.

If segment 2 should be won 25% of the time then if the random number is between 51 and 75 segment 2 is selected as the winner and so forth.


问:
how to get innerHtml of body without an iframe with jquery
I have page with html something like this

```<code><body><iframe ></iframe><div id="menu">......</div>.....</body>
</code>```

I want to get the innerHTML of the body but without the iframe? How can i do that in jquery?

答:
```<code>$(document).ready(function(){
    $('body').not('iframe').html();
});
</code>```

that should get everything in the body but the iframe. you'll probably want to store that in a variable or something for reference later

Body:
I have page with html something like this

......
.....

I want to get the innerHTML of the body but without the iframe? How can i do that in jquery?

Body:
$(document).ready(function(){
    $('body').not('iframe').html();
});

that should get everything in the body but the iframe. you'll probably want to store that in a variable or something for reference later


问:
Implementing ngOnChange to capture old and current value in Angular2
I was trying to implement ngOnChanges() to capture previous and current value. The function I have implemented works fine. I am able to see previous and current value in the console but I am getting this error even though my code is compiling successfully. I am getting the same error for "propertyName", "change", "current" and "previous". If I use 'const' instead of 'let' then my function doesn't work. Please help!!

Code:

```<code>import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';

@Component({
selector: 'app-simple',
templateUrl: './simple.component.html'
})
export class SimpleComponent implements OnChanges {
  @Input() simpleInput: string;

  ngOnChanges(changes: SimpleChanges) {
    for (let propertyName in changes) {
    let change = changes[propertyName];
    let current = JSON.stringify(change.currentValue);
    let previous = JSON.stringify(change.previousValue);
    console.log(propertyName + ' : currentvalue ' + current + ', previousvalue ' + previous);
    }
  }
}
</code>```

答:
There is another way to iterate array. Using of in advanced for loop.
Try using for (let propertyName of  changes){}
This might help you.

Edit1:
If a variable is never reassigned, using the const declaration is better.
https://eslint.org/docs/rules/prefer-const
Try like this:

```<code>ngOnChanges(changes: SimpleChanges) {
for (const propertyName in changes) {
  if (changes[propertyName]) {
    const change = changes[propertyName];
    const current = JSON.stringify(change.currentValue);
    const previous = JSON.stringify(change.previousValue);
    console.log(propertyName + ' : currentvalue ' + current + ', previousvalue ' + previous);
  }
</code>```

}
  }

Body:
I was trying to implement ngOnChanges() to capture previous and current value. The function I have implemented works fine. I am able to see previous and current value in the console but I am getting this error even though my code is compiling successfully. I am getting the same error for "propertyName", "change", "current" and "previous". If I use 'const' instead of 'let' then my function doesn't work. Please help!!

Code:

import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';

@Component({
selector: 'app-simple',
templateUrl: './simple.component.html'
})
export class SimpleComponent implements OnChanges {
  @Input() simpleInput: string;

  ngOnChanges(changes: SimpleChanges) {
    for (let propertyName in changes) {
    let change = changes[propertyName];
    let current = JSON.stringify(change.currentValue);
    let previous = JSON.stringify(change.previousValue);
    console.log(propertyName + ' : currentvalue ' + current + ', previousvalue ' + previous);
    }
  }
}

Body:
There is another way to iterate array. Using of in advanced for loop.
Try using for (let propertyName of  changes){}
This might help you.

Edit1:
If a variable is never reassigned, using the const declaration is better.
https://eslint.org/docs/rules/prefer-const
Try like this:

ngOnChanges(changes: SimpleChanges) {
for (const propertyName in changes) {
  if (changes[propertyName]) {
    const change = changes[propertyName];
    const current = JSON.stringify(change.currentValue);
    const previous = JSON.stringify(change.previousValue);
    console.log(propertyName + ' : currentvalue ' + current + ', previousvalue ' + previous);
  }

}
  }


问:
How to rotate image selected row and unrotate image unselected row
I have problem liked this:

I have some row, when i click row 0, it expanded and dropdown image rotate. when i click row 1, it expand row 1 and unexpand row 0, dropdown image in row 0 back to normal (down arrow), and dropdown image in row 1 rotate (up arrow).

Here is my code so far:

```<code>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let cell = self.tableView.cellForRow(at: indexPath) as! PaymentMethodCell
    let clickedRow = indexPath.row
    if indexPath.row == selectedRow{
        print("yang muncul selectedRow = -1")
        if cell.isSelected {
            selectedRow = -1
            print("This cell is deselected :\(selectedRow)")
            cell.ivExpand.transform = CGAffineTransform(rotationAngle: (180.0 * CGFloat.pi) * 180.0)
        }else{
            selectedRow = indexPath.row
            cell.ivExpand.transform = CGAffineTransform(rotationAngle: (180.0 * CGFloat.pi) / 180.0)
        }
    }else{
        if cell.isSelected {
            selectedRow = indexPath.row
            print("This cell is selected :\(selectedRow)")
            cell.ivExpand.transform = CGAffineTransform(rotationAngle: (180.0 * CGFloat.pi) / 180.0)
        }else{
            selectedRow = -1
            cell.ivExpand.transform = CGAffineTransform(rotationAngle: (180.0 * CGFloat.pi) * 180.0)
        }
        cell.lblclickedsubcell.text="00"
        print("cell.lblclickedsubcell.text:\(String(describing: cell.lblclickedsubcell.text!))")
    }
    tableView.reloadData()
}
</code>```

but the result is after i expand row 0 and then click row 1, row 0 unexpand and row 1 expanded. But dropdown image in row 0 still not back to normal (down arrow). it still as up arrow.

Here is cellForRowAt :

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCell(withIdentifier: "PaymentMethodCell", for: indexPath) as! PaymentMethodCell
    cell.ivPaymentMeyhod.contentMode = UIViewContentMode.scaleAspectFit
    cell.ivPaymentMeyhod.contentMode = UIViewContentMode.left
    cell.ivPaymentMeyhod.clipsToBounds=false
    //cell.ivPaymentMeyhod.kf.setImage(with: url!)
    cell.ivPaymentMeyhod.image = UIImage(named: "\(PaymentImageArray[indexPath.item])")
    let clickedRow = indexPath.row
    cell.lblclickedRow.text = "\(indexPath.row)"
    let ContractNumber = "\(contractnumber!)"
    if(CustomUserDefaults.shared.isGuest() || ContractNumber==""){
        cell.lblContractNumber.text = ""
        cell.lblContractAmount.text = ""
    }else{
        cell.lblContractNumber.text = "\(contractnumber!)"
        cell.lblContractAmount.text = "\(contractamount!)"
    }
    if(clickedRow==0){
        cell.tableView.isHidden=true
        cell.XibView.isHidden=false
        let AlfaIndoView = HowToPayView.AlfaIndoNib()
        let cellwidth = cell.XibView.bounds.width
        print("cellwidth:\(cellwidth)")
        cell.XibView.addSubview(AlfaIndoView)
        AlfaIndoView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
        AlfaIndoView.frame.size.width = cellwidth
    }else if(clickedRow==1){
        cell.tableView.isHidden=true
        cell.XibView.isHidden=false
        let POSindonesiaView = HowToPayView.POSindonesiaNib()
        let cellwidth = cell.XibView.bounds.width
        print("cellwidth:\(cellwidth)")
        cell.XibView.addSubview(POSindonesiaView)
        POSindonesiaView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
        POSindonesiaView.frame.size.width = cellwidth
    }else if(clickedRow==2){
        cell.tableView.isHidden=false
        cell.XibView.isHidden=true
        cell.setUpTable()
    }else if(clickedRow==3){
        cell.tableView.isHidden=false
        cell.XibView.isHidden=true
        cell.setUpTable()
    }else if(clickedRow==4){
        cell.tableView.isHidden=false
        cell.XibView.isHidden=true
        cell.setUpTable()
    }else if(clickedRow==5){
        cell.tableView.isHidden=false
        cell.XibView.isHidden=true
        cell.setUpTable()
    }else if(clickedRow==6){
        cell.tableView.isHidden=true
        cell.XibView.isHidden=false
        let ATMbersamaView = HowToPayView.ATMbersamaNib()
        let cellwidth = cell.XibView.bounds.width
        print("cellwidth:\(cellwidth)")
        cell.XibView.addSubview(ATMbersamaView)
        ATMbersamaView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
        ATMbersamaView.frame.size.width = cellwidth
    }
    return cell
}
</code>```

Help me, please to repair this code

答:
It would be clearer if we could see your cellForRow code. As far as I can see, you are calling reloadData() at the end, so your cells are getting re-rendered, so you have to handle the arrow's orientations in your cellForRow code. So in pseudocode form, it would be a bit like the following:

In didSelect function:

```<code>selectedIndexPath = indexPath
//...other related statements
</code>```

In cellForRow function:

```<code>if indexPath == selectedIndexPath {
    //rotate arrow down
    //other relevant code
}
else {
    //rotate arrow up
    //other relevant code
}
</code>```

Body:
I have problem liked this:

I have some row, when i click row 0, it expanded and dropdown image rotate. when i click row 1, it expand row 1 and unexpand row 0, dropdown image in row 0 back to normal (down arrow), and dropdown image in row 1 rotate (up arrow).

Here is my code so far:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let cell = self.tableView.cellForRow(at: indexPath) as! PaymentMethodCell
    let clickedRow = indexPath.row
    if indexPath.row == selectedRow{
        print("yang muncul selectedRow = -1")
        if cell.isSelected {
            selectedRow = -1
            print("This cell is deselected :\(selectedRow)")
            cell.ivExpand.transform = CGAffineTransform(rotationAngle: (180.0 * CGFloat.pi) * 180.0)
        }else{
            selectedRow = indexPath.row
            cell.ivExpand.transform = CGAffineTransform(rotationAngle: (180.0 * CGFloat.pi) / 180.0)
        }
    }else{
        if cell.isSelected {
            selectedRow = indexPath.row
            print("This cell is selected :\(selectedRow)")
            cell.ivExpand.transform = CGAffineTransform(rotationAngle: (180.0 * CGFloat.pi) / 180.0)
        }else{
            selectedRow = -1
            cell.ivExpand.transform = CGAffineTransform(rotationAngle: (180.0 * CGFloat.pi) * 180.0)
        }
        cell.lblclickedsubcell.text="00"
        print("cell.lblclickedsubcell.text:\(String(describing: cell.lblclickedsubcell.text!))")
    }
    tableView.reloadData()
}

but the result is after i expand row 0 and then click row 1, row 0 unexpand and row 1 expanded. But dropdown image in row 0 still not back to normal (down arrow). it still as up arrow.

Here is cellForRowAt :

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCell(withIdentifier: "PaymentMethodCell", for: indexPath) as! PaymentMethodCell
    cell.ivPaymentMeyhod.contentMode = UIViewContentMode.scaleAspectFit
    cell.ivPaymentMeyhod.contentMode = UIViewContentMode.left
    cell.ivPaymentMeyhod.clipsToBounds=false
    //cell.ivPaymentMeyhod.kf.setImage(with: url!)
    cell.ivPaymentMeyhod.image = UIImage(named: "\(PaymentImageArray[indexPath.item])")
    let clickedRow = indexPath.row
    cell.lblclickedRow.text = "\(indexPath.row)"
    let ContractNumber = "\(contractnumber!)"
    if(CustomUserDefaults.shared.isGuest() || ContractNumber==""){
        cell.lblContractNumber.text = ""
        cell.lblContractAmount.text = ""
    }else{
        cell.lblContractNumber.text = "\(contractnumber!)"
        cell.lblContractAmount.text = "\(contractamount!)"
    }
    if(clickedRow==0){
        cell.tableView.isHidden=true
        cell.XibView.isHidden=false
        let AlfaIndoView = HowToPayView.AlfaIndoNib()
        let cellwidth = cell.XibView.bounds.width
        print("cellwidth:\(cellwidth)")
        cell.XibView.addSubview(AlfaIndoView)
        AlfaIndoView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
        AlfaIndoView.frame.size.width = cellwidth
    }else if(clickedRow==1){
        cell.tableView.isHidden=true
        cell.XibView.isHidden=false
        let POSindonesiaView = HowToPayView.POSindonesiaNib()
        let cellwidth = cell.XibView.bounds.width
        print("cellwidth:\(cellwidth)")
        cell.XibView.addSubview(POSindonesiaView)
        POSindonesiaView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
        POSindonesiaView.frame.size.width = cellwidth
    }else if(clickedRow==2){
        cell.tableView.isHidden=false
        cell.XibView.isHidden=true
        cell.setUpTable()
    }else if(clickedRow==3){
        cell.tableView.isHidden=false
        cell.XibView.isHidden=true
        cell.setUpTable()
    }else if(clickedRow==4){
        cell.tableView.isHidden=false
        cell.XibView.isHidden=true
        cell.setUpTable()
    }else if(clickedRow==5){
        cell.tableView.isHidden=false
        cell.XibView.isHidden=true
        cell.setUpTable()
    }else if(clickedRow==6){
        cell.tableView.isHidden=true
        cell.XibView.isHidden=false
        let ATMbersamaView = HowToPayView.ATMbersamaNib()
        let cellwidth = cell.XibView.bounds.width
        print("cellwidth:\(cellwidth)")
        cell.XibView.addSubview(ATMbersamaView)
        ATMbersamaView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
        ATMbersamaView.frame.size.width = cellwidth
    }
    return cell
}

Help me, please to repair this code

Body:
It would be clearer if we could see your cellForRow code. As far as I can see, you are calling reloadData() at the end, so your cells are getting re-rendered, so you have to handle the arrow's orientations in your cellForRow code. So in pseudocode form, it would be a bit like the following:

In didSelect function:

selectedIndexPath = indexPath
//...other related statements

In cellForRow function:

if indexPath == selectedIndexPath {
    //rotate arrow down
    //other relevant code
}
else {
    //rotate arrow up
    //other relevant code
}


问:
Facebook login error with https
I got this error message when login with facebook.

100 Message: Error validating verification code. Please make sure your redirect_uri is identical to the one you used in the OAuth dialog request

Redirect url with http working fine but with https I'm getting above error message.

Please help.

Thanks

答:
You will need to update your redirect url to include https.

For example https://localhost:8080

Title: Facebook login error with https


问:
GetProperties() to return all properties for an interface inheritance hierarchy
Assuming the following hypothetical inheritance hierarchy:

```<code>public interface IA
{
  int ID { get; set; }
}

public interface IB : IA
{
  string Name { get; set; }
}
</code>```

Using reflection and making the following call:

```<code>typeof(IB).GetProperties(BindingFlags.Public | BindingFlags.Instance)
</code>```

will only yield the properties of interface IB, which is "Name".

If we were to do a similar test on the following code,

```<code>public abstract class A
{
  public int ID { get; set; }
}

public class B : A
{
  public string Name { get; set; }
}
</code>```

the call typeof(B).GetProperties(BindingFlags.Public | BindingFlags.Instance) will return an array of PropertyInfo objects for "ID" and "Name".

Is there an easy way to find all the properties in the inheritance hierarchy for interfaces as in the first example?

答:
Responding to @douglas and @user3524983, the following should answer the OP's question:

```<code>    static public IEnumerable<PropertyInfo> GetPropertiesAndInterfaceProperties(this Type type, BindingFlags bindingAttr = BindingFlags.Public | BindingFlags.Instance)
    {
        if (!type.IsInterface) {
            return type.GetProperties( bindingAttr);
        }

        return type.GetInterfaces().Union(new Type[] { type }).SelectMany(i => i.GetProperties(bindingAttr)).Distinct();
    }
</code>```

or, for an individual property:

```<code>    static public PropertyInfo GetPropertyOrInterfaceProperty(this Type type, string propertyName, BindingFlags bindingAttr = BindingFlags.Public|BindingFlags.Instance)
    {
        if (!type.IsInterface) {
            return type.GetProperty(propertyName, bindingAttr);
        }

        return type.GetInterfaces().Union(new Type[] { type }).Select(i => i.GetProperty( propertyName, bindingAttr)).Distinct().Where(propertyInfo => propertyInfo != null).Single();
    }
</code>```

OK next time I'll debug it before posting instead of after :-)

OwnerDisplayName: sduplooy

Body:
Assuming the following hypothetical inheritance hierarchy:

public interface IA
{
  int ID { get; set; }
}

public interface IB : IA
{
  string Name { get; set; }
}

Using reflection and making the following call:

typeof(IB).GetProperties(BindingFlags.Public | BindingFlags.Instance)

will only yield the properties of interface IB, which is "Name".

If we were to do a similar test on the following code,

public abstract class A
{
  public int ID { get; set; }
}

public class B : A
{
  public string Name { get; set; }
}

the call typeof(B).GetProperties(BindingFlags.Public | BindingFlags.Instance) will return an array of PropertyInfo objects for "ID" and "Name".

Is there an easy way to find all the properties in the inheritance hierarchy for interfaces as in the first example?

LastEditorDisplayName: Ray Hayes

Body:
Responding to @douglas and @user3524983, the following should answer the OP's question:

    static public IEnumerable<PropertyInfo> GetPropertiesAndInterfaceProperties(this Type type, BindingFlags bindingAttr = BindingFlags.Public | BindingFlags.Instance)
    {
        if (!type.IsInterface) {
            return type.GetProperties( bindingAttr);
        }

        return type.GetInterfaces().Union(new Type[] { type }).SelectMany(i => i.GetProperties(bindingAttr)).Distinct();
    }

or, for an individual property:

    static public PropertyInfo GetPropertyOrInterfaceProperty(this Type type, string propertyName, BindingFlags bindingAttr = BindingFlags.Public|BindingFlags.Instance)
    {
        if (!type.IsInterface) {
            return type.GetProperty(propertyName, bindingAttr);
        }

        return type.GetInterfaces().Union(new Type[] { type }).Select(i => i.GetProperty( propertyName, bindingAttr)).Distinct().Where(propertyInfo => propertyInfo != null).Single();
    }

OK next time I'll debug it before posting instead of after :-)


问:
How to pass a variable in R to a system command?
I have a file that I read like this:

```<code>input.bed <- as.data.frame(read.table("lamina_filtered.bed", header = FALSE, sep = "\t",
    stringsAsFactors = FALSE, quote = ""));
</code>```

I'm trying to invoke a system command . I referred to a previous question where the answer suggested using either sprintf or paste, but both give me same error:

```<code>system(sprintf("/usr/local/bin/KentUtils/bedToPsl %s hg38.chom.sizes inp_hg38.psl", input.bed));

system(paste("/usr/local/bin/KentUtils/bedToPsl  hg38.chom.sizes " , input.bed," inp_hg38.psl"));
</code>```

I get this error:

```<code>/bin/sh: -c: line 0: syntax error near unexpected token `('
/bin/sh: -c: line 0: `/usr/local/bin/KentUtils/bedToPsl c("chr1", "chr1",         "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", '
</code>```

This is a sample of the input.bed it's a simple bed fileR:

```<code>   V1       V2       V3
1 chr1 11323785 11617177
2 chr1 12645605 13926923
3 chr1 14750216 15119039
4 chr1 18102157 19080189
5 chr1 29491029 30934636
6 chr1 33716472 35395979
</code>```

答:
Look closely at you error.  The command you're trying to execute is something like:

```<code>/usr/local/.../bedToPsl c("chr1","chr1","chr1") ...
</code>```

You used paste to stick a data.frame into a system command.  Your OS can't understand R data structures.  Given that your question doesn't include details about what that system call is supposed to receive it's impossible to tell you how to fix this.  But here are some possibilities

Scalar Value - you probably need to do something like input.bed$V1[1] to only pass in one string.  Make sure it's quoted (or not) as appropriate

File - often system commands are intended to receive a file path. In this case, you can skip loading in your data at all and just pass the file name.

Body:
I have a file that I read like this:

input.bed <- as.data.frame(read.table("lamina_filtered.bed", header = FALSE, sep = "\t",
    stringsAsFactors = FALSE, quote = ""));

I'm trying to invoke a system command . I referred to a previous question where the answer suggested using either sprintf or paste, but both give me same error:

system(sprintf("/usr/local/bin/KentUtils/bedToPsl %s hg38.chom.sizes inp_hg38.psl", input.bed));

system(paste("/usr/local/bin/KentUtils/bedToPsl  hg38.chom.sizes " , input.bed," inp_hg38.psl"));

I get this error:

/bin/sh: -c: line 0: syntax error near unexpected token `('
/bin/sh: -c: line 0: `/usr/local/bin/KentUtils/bedToPsl c("chr1", "chr1",         "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", '

This is a sample of the input.bed it's a simple bed fileR:

   V1       V2       V3
1 chr1 11323785 11617177
2 chr1 12645605 13926923
3 chr1 14750216 15119039
4 chr1 18102157 19080189
5 chr1 29491029 30934636
6 chr1 33716472 35395979

Body:
Look closely at you error.  The command you're trying to execute is something like:

/usr/local/.../bedToPsl c("chr1","chr1","chr1") ...

You used paste to stick a data.frame into a system command.  Your OS can't understand R data structures.  Given that your question doesn't include details about what that system call is supposed to receive it's impossible to tell you how to fix this.  But here are some possibilities

Scalar Value - you probably need to do something like input.bed$V1[1] to only pass in one string.  Make sure it's quoted (or not) as appropriate

File - often system commands are intended to receive a file path. In this case, you can skip loading in your data at all and just pass the file name.


问:
Android - EditText to StringArray stored in xml
Ive been attempting to work out how to take the text from an edittext box and move it into a string array located in strings.xml.

Basically its a user form which the user fills in, onClick it adds the information to the database and is then viewable in a listview. The listview and everything works fine but i cant work out to put in information using edittext boxes.

Any hints or techniques would be very much appreciated.

Thanks

答: You want to take user input for an edit text, and put it in strings.xml? You can't do that.  String resources are for static strings, not things that will change at runtime.  You should look at other data storage options, like shared preferences. See data storage.</p>


问:
Using Hex with SByte for Negative Values
I'm trying to define an enum with an SByte data type (for binary-interop with some accompanying firmware). I have something like below:

```<code>Public Enum Codes AS SByte
   IDLE = &H0
   IN_PROGRESS = &H1
   DONE = &H2

   SOME_ERROR = &H80
   SOME_OTHER_ERROR = &H81
End Enum
</code>```

Unfortunately the two error codes result in a compile time error: "Constant expression not representable in type 'SByte'."

Obviously it is attempting to treat these values as integers first and then convert them to SByte. As an integer 0x80 = 128. Since the range for an SByte is [-128, 127], this value is too large for an SByte.

If I use -(&H80) this is resolved. However, this doesn't work for -&H81 since this translates into -(129) instead of -127....

I could just use the decimal representations of these numbers to get around this, but I'd prefer to use hexadecimal (even with VBs horrible prefix) as this is consistent with the underlying assembly code.

So... if anyone knows the proper syntax for negative SByte values using hexadecimal I would appreciate it!

答:
When you enter code such as:

```<code>Dim sb as SByte = -127
</code>```

the assigned value is referred to as an integer (Int32) literal.  If you what to use the hexadecimal literal notation to produce an equivalent value, you must use the hexadecimal value for -127.

```<code>Dim sb as SByte = &HFFFFFF81 ' = -127
</code>```

You can shorten it a bit, if you instruct the compiler to read the hexadecimal value a short integer (Int16) by appending the type suffix character "S"

```<code>Dim sb as SByte = &HFF81S ' = -127
</code>```

As an aide in determining the hexadecimal notation for a value, you can use the VB Hex function in VS's "immediate window" to determine the characters to enter.

i.e.: `?Hex(-127)

will yield:  "FFFFFF81"

Body:
I'm trying to define an enum with an SByte data type (for binary-interop with some accompanying firmware). I have something like below:

Public Enum Codes AS SByte
   IDLE = &H0
   IN_PROGRESS = &H1
   DONE = &H2

   SOME_ERROR = &H80
   SOME_OTHER_ERROR = &H81
End Enum

Unfortunately the two error codes result in a compile time error: "Constant expression not representable in type 'SByte'."

Obviously it is attempting to treat these values as integers first and then convert them to SByte. As an integer 0x80 = 128. Since the range for an SByte is [-128, 127], this value is too large for an SByte.

If I use -(&H80) this is resolved. However, this doesn't work for -&H81 since this translates into -(129) instead of -127....

I could just use the decimal representations of these numbers to get around this, but I'd prefer to use hexadecimal (even with VBs horrible prefix) as this is consistent with the underlying assembly code.

So... if anyone knows the proper syntax for negative SByte values using hexadecimal I would appreciate it!

Body:
When you enter code such as:

Dim sb as SByte = -127

the assigned value is referred to as an integer (Int32) literal.  If you what to use the hexadecimal literal notation to produce an equivalent value, you must use the hexadecimal value for -127.

Dim sb as SByte = &HFFFFFF81 ' = -127

You can shorten it a bit, if you instruct the compiler to read the hexadecimal value a short integer (Int16) by appending the type suffix character "S"

Dim sb as SByte = &HFF81S ' = -127

As an aide in determining the hexadecimal notation for a value, you can use the VB Hex function in VS's "immediate window" to determine the characters to enter.

i.e.: `?Hex(-127)

will yield:  "FFFFFF81"


问:
Find unparented test cases in TFS or MTM
I want to find a list of test cases that do not have any parent User Story for those. I used a migrator tool and uploaded a bunch of test cases from excel to TFS. I lost the test case IDs.

I need to link those test cases to their respective User Stories. So, is there any query that I can run to find the list of test cases that do not have a parent User Story to those?

I cannot query based on created date because these are imported over a period time and there were other team members who were writing hundred of test cases and linking it to the User Stories as well.

Any suggestion, please?

答: You can use the type of quer: work items and direct links to list all the Test cases which not have a parent User Story to those. See below screenshot:


问:
Parse Nested array string to array
I have a sample nested array string as below:

```<code>const content = `[
  {
    type: 'paragraph',
    content: 'How do I remove a particular element from an array in JavaScript?',
  },
  {
    type: 'paragraph',
    content: 'How do I remove a particular element from an array in JavaScript?',
  },
  {
    type: 'image',
    src: 'http://upload.sample.com/2016/0407/1460024231806.jpg',
    meta: {
      alt: 'Parse String to Float or Int',
      title: 'Parse String to Float or Int',
      caption: 'Parse String to Float or Int',
    },
  }
]`;
</code>```

As it is a string, I use the JSON.parse() method to parse it to an array, but it throws this error:

VM926:3 Uncaught SyntaxError: Unexpected token t in JSON at position 10

Is there some way to parse this string array to an array?

答:
Stringified JSON usually has double quotes for all the keys.
Also extra commas(,s) should be discarded for it to be a valid json.</p>

```<code>const content = `[
  {
    "type": "paragraph",
    "content": "How do I remove a particular element from an array in JavaScript?"
  },
  {
    "type": "paragraph",
    "content": "How do I remove a particular element from an array in JavaScript?"
  },
  {
    "type": "image",
    "src": "http://upload.sample.com/2016/0407/1460024231806.jpg",
    "meta": {
      "alt": "Parse String to Float or Int",
      "title": "Parse String to Float or Int",
      "caption": "Parse String to Float or Int"
    }
  }
]`;
</code>```

Title: Parse Nested array string to array

Body:
I have a sample nested array string as below:

const content = `[
  {
    type: 'paragraph',
    content: 'How do I remove a particular element from an array in JavaScript?',
  },
  {
    type: 'paragraph',
    content: 'How do I remove a particular element from an array in JavaScript?',
  },
  {
    type: 'image',
    src: 'http://upload.sample.com/2016/0407/1460024231806.jpg',
    meta: {
      alt: 'Parse String to Float or Int',
      title: 'Parse String to Float or Int',
      caption: 'Parse String to Float or Int',
    },
  }
]`;

As it is a string, I use the JSON.parse() method to parse it to an array, but it throws this error:

VM926:3 Uncaught SyntaxError: Unexpected token t in JSON at position 10

Is there some way to parse this string array to an array?

Body:
Stringified JSON usually has double quotes for all the keys.
Also extra commas(,s) should be discarded for it to be a valid json.

const content = `[
  {
    "type": "paragraph",
    "content": "How do I remove a particular element from an array in JavaScript?"
  },
  {
    "type": "paragraph",
    "content": "How do I remove a particular element from an array in JavaScript?"
  },
  {
    "type": "image",
    "src": "http://upload.sample.com/2016/0407/1460024231806.jpg",
    "meta": {
      "alt": "Parse String to Float or Int",
      "title": "Parse String to Float or Int",
      "caption": "Parse String to Float or Int"
    }
  }
]`;


问:
How to write the user type php code in HTML parameter?
First of all sorry for the title.

This is the code I have written but there is a problem, So decided to come here.

What I want actually that Whatever I type in the value parameter it should be reflected back in the value parameter( for XSS ). But I didn't succeed. Can anyone suggest me something?

```<code><style>body {
    background-color: #000000;
}
</style>
<center><title>  </title>
<h1 style="color:blue;"><u></u></h1><br>

<center><form style="color:red"; action="xss3.php" method="POST"><center>

<b>Advance search:</b>  <input type="text" name="q" id="test" value="<?php echo ($_POST['test']);?>">

<input type="submit" name="search" value="search"><br><br>
</code>```

答:
This might be you want:

```<code><style>body {
    background-color: #000000;
}
</style>
<center><title>  </title>
<h1 style="color:blue;"><u></u></h1><br>

<center>
// Redirect on same page with action="#". you can change
<form style="color:red"; action="#" method="POST">
<center>
<b>Advance search:</b>
<input type="text" name="q" id="test" value="
// Check btn submit
<?php if (isset($_REQUEST['search'])) {
    # use name of field instead of id
    echo $_POST['q'];
} ?>">
<input type="submit" name="search" value="search"><br><br>
</code>```

Make sure, you cant access posted value with the ID. you must need to use name instead of id. Here, i used same file for recieve requested data. you can copy the same file namely xss.php and put the logic there.

Hope this will help you! Greetings!

Body:
First of all sorry for the title.

This is the code I have written but there is a problem, So decided to come here.

What I want actually that Whatever I type in the value parameter it should be reflected back in the value parameter( for XSS ). But I didn't succeed. Can anyone suggest me something?

<title>  </title>

<form style="color:red"; action="xss3.php" method="POST">

Advance search:  <input type="text" name="q" id="test" value="<?php echo ($_POST['test']);?>">

<input type="submit" name="search" value="search">

Body:
This might be you want:

<style>body {
    background-color: #000000;
}
</style>
<center><title>  </title>
<h1 style="color:blue;"><u></u></h1><br>

<center>
// Redirect on same page with action="#". you can change
<form style="color:red"; action="#" method="POST">
<center>
<b>Advance search:</b>
<input type="text" name="q" id="test" value="
// Check btn submit
<?php if (isset($_REQUEST['search'])) {
    # use name of field instead of id
    echo $_POST['q'];
} ?>">
<input type="submit" name="search" value="search"><br><br>

Make sure, you cant access posted value with the ID. you must need to use name instead of id. Here, i used same file for recieve requested data. you can copy the same file namely xss.php and put the logic there.

Hope this will help you! Greetings!


问:
React/JSX attrs w/strings vs braces
The docs say that a JSX attributes with strings are the same as attributes with braces...

<Thing attr='val' /> === <Thing attr={'val'} />

I thought I read something that said only use braces when needed because strings are more performant, but I can't find the reference now. Is there an evaluation cost for braces?

答:
JSX is actually parsing it to a JS object anyway, so it's either string creation overhead for the parser or string creation overhead in your component. It's trivial either way. With a string literal, though, it's just visually noisy in the code. It only really serves a purpose if the val is a variable or expression.

There is, however, a perfomance hit in a templating engine, such as that employed by the new interpolated strings. E.g.:

```<code>`It is a ${'cat'}`
</code>```

would be slower than:

```<code>`It is a dog`
</code>```

which should be slower still than just a plain literal:

```<code>'It is a dog'
</code>```

I'll leave it as an exercise for the reader to find the interpolation part in the JSX engine. ;) https://github.com/jsx/JSX/tree/master/src

Title: React/JSX attrs w/strings vs braces

Body:
JSX is actually parsing it to a JS object anyway, so it's either string creation overhead for the parser or string creation overhead in your component. It's trivial either way. With a string literal, though, it's just visually noisy in the code. It only really serves a purpose if the val is a variable or expression.

There is, however, a perfomance hit in a templating engine, such as that employed by the new interpolated strings. E.g.:

`It is a ${'cat'}`

would be slower than:

`It is a dog`

which should be slower still than just a plain literal:

'It is a dog'

I'll leave it as an exercise for the reader to find the interpolation part in the JSX engine. ;) https://github.com/jsx/JSX/tree/master/src


问:
Displaying and sizing a grayscale from a QImage in Qt
I have been able to display an image in a label in Qt using something like the following:

```<code>transformPixels(0,0,1,imheight,imwidth,1);//sets unsigned char** imageData

unsigned char* fullCharArray = new unsigned char[imheight * imwidth];
     for (int i = 0 ; i < imheight ; i++)
         for (int j = 0 ; j < imwidth ; j++)
                fullCharArray[(i*imwidth)+j] = imageData[i][j];

QImage *qi = new QImage(fullCharArray, imwidth, imheight, QImage::Format_RGB32);

ui->viewLabel->setPixmap(QPixmap::fromImage(*qi,Qt::AutoColor));
</code>```

So fullCharArray is an array of unsigned chars that have been mapped from the 2D array imageData, in other words, it is imheight * imwidth bytes.

The problem is, it seems like only a portion of my image is showing in the label. The image is very large. I would like to display the full image, scaled down to fit in the label, with the aspect ratio preserved.

Also, that QImage format was the only one I could find that seemed to give me a close representation of the image I am wanting to display, is that what I should expect? I am only using one byte per pixel (unsigned char - values from 0 to 255), and it seems liek RGB32 doesnt make much sense for that data type, but none of the other ones displayed anything remotely correct

edit:
Following dan gallaghers advice, I implemented this code:

```<code>QImage *qi = new QImage(fullCharArray, imwidth, imheight, QImage::Format_RGB32);
int labelWidth = ui->viewLabel->width();
int labelHeight = ui->viewLabel->height();

QImage small = qi->scaled(labelWidth, labelHeight,Qt::KeepAspectRatio);
ui->viewLabel->setPixmap(QPixmap::fromImage(small,Qt::AutoColor));
</code>```

But this causes my program to "unexpectedly finish" with code 0

答:
QImage has a scaled member.  So you want to change your setPixmap call to something like:

```<code>QImage small = qi->scaled(labelWidth, labelHeight, Qt::KeepAspectRatio);
ui->viewLabel->setPixmap(QPixmap::fromImage(small, Qt::AutoColor);
</code>```

Note that scaled does not modify the original image qi; it returns a new QImage that is a scaled copy of the original.

Re-Edit:

To convert from 1-byte grayscale to 4-byte RGB grayscale:

```<code> QImage qi = new QImage(imwidth, imheight, QImage::Format_RGB32);
 for (int i = 0; i < imheight; i++)
 {
     for (int j = 0; j < imwidth; j++)
     {
         qi->setPixel(i, j, QRgb(imageData[i][j], imageData[i][j], imageData[i][j]));
     }
 }
</code>```

Then scale qi and use the scaled copy as the pixmap for viewLabel.

Body:
I have been able to display an image in a label in Qt using something like the following:

transformPixels(0,0,1,imheight,imwidth,1);//sets unsigned char** imageData

unsigned char* fullCharArray = new unsigned char[imheight * imwidth];
     for (int i = 0 ; i < imheight ; i++)
         for (int j = 0 ; j < imwidth ; j++)
                fullCharArray[(i*imwidth)+j] = imageData[i][j];

QImage *qi = new QImage(fullCharArray, imwidth, imheight, QImage::Format_RGB32);

ui->viewLabel->setPixmap(QPixmap::fromImage(*qi,Qt::AutoColor));

So fullCharArray is an array of unsigned chars that have been mapped from the 2D array imageData, in other words, it is imheight * imwidth bytes.

The problem is, it seems like only a portion of my image is showing in the label. The image is very large. I would like to display the full image, scaled down to fit in the label, with the aspect ratio preserved.

Also, that QImage format was the only one I could find that seemed to give me a close representation of the image I am wanting to display, is that what I should expect? I am only using one byte per pixel (unsigned char - values from 0 to 255), and it seems liek RGB32 doesnt make much sense for that data type, but none of the other ones displayed anything remotely correct

edit:
Following dan gallaghers advice, I implemented this code:

QImage *qi = new QImage(fullCharArray, imwidth, imheight, QImage::Format_RGB32);
int labelWidth = ui->viewLabel->width();
int labelHeight = ui->viewLabel->height();

QImage small = qi->scaled(labelWidth, labelHeight,Qt::KeepAspectRatio);
ui->viewLabel->setPixmap(QPixmap::fromImage(small,Qt::AutoColor));

But this causes my program to "unexpectedly finish" with code 0

Body:
QImage has a scaled member.  So you want to change your setPixmap call to something like:

QImage small = qi->scaled(labelWidth, labelHeight, Qt::KeepAspectRatio);
ui->viewLabel->setPixmap(QPixmap::fromImage(small, Qt::AutoColor);

Note that scaled does not modify the original image qi; it returns a new QImage that is a scaled copy of the original.

Re-Edit:

To convert from 1-byte grayscale to 4-byte RGB grayscale:

 QImage qi = new QImage(imwidth, imheight, QImage::Format_RGB32);
 for (int i = 0; i < imheight; i++)
 {
     for (int j = 0; j < imwidth; j++)
     {
         qi->setPixel(i, j, QRgb(imageData[i][j], imageData[i][j], imageData[i][j]));
     }
 }

Then scale qi and use the scaled copy as the pixmap for viewLabel.


问:
Return object from list while looping java 8
Is there some straight forward way to return object from list which map to condition we passed.

Ex :

```<code>public enum CarType {
    TOYOTA,
    NISSAN,
    UNKNOWN;

    public static CarType getByName(String name) {
        for (CarType carType : values()) {
            if (carType.name().equals(name)) {
                return carType;
            }
        }
        return UNKNOWN;
    }
}
</code>```

Is there some another way support by java 8 below method and for loop I have used.

```<code>public static CarType getByName(String name) {
    for (CarType carType : values()) {
        if (carType.name().equals(name)) {
            return carType;
        }
    }
    return UNKNOWN;
}
</code>```

答:
Something like this with findFirst and orElse as :

```<code>return Arrays.stream(values())
               .filter(carType -> carType.name().equals(name))
               .findFirst().orElse(CarType.UNKNOWN);
</code>```

Body:
Is there some straight forward way to return object from list which map to condition we passed.

Ex :

public enum CarType {
    TOYOTA,
    NISSAN,
    UNKNOWN;

    public static CarType getByName(String name) {
        for (CarType carType : values()) {
            if (carType.name().equals(name)) {
                return carType;
            }
        }
        return UNKNOWN;
    }
}

Is there some another way support by java 8 below method and for loop I have used.

public static CarType getByName(String name) {
    for (CarType carType : values()) {
        if (carType.name().equals(name)) {
            return carType;
        }
    }
    return UNKNOWN;
}

Body:
Something like this with findFirst and orElse as :

return Arrays.stream(values())
               .filter(carType -> carType.name().equals(name))
               .findFirst().orElse(CarType.UNKNOWN);


答:
Is there an evaluation cost for braces

Yes, As you can see anything inside {} will be considered as javascript code, so that will be executed , if you just want to assign the string then
just simply use the attr='val' rather than attr={'val'}

but if you have assignment condition based then you can use attr={'val'}

like

```<code>attr={ (condition) ? 'val1' : 'val2'}
</code>```

I Hope , this will clear your thoughts.

For more details :

https://reactjs.org/docs/jsx-in-depth.html

Here you can read behind the scenes of string interpolation and speed performance :

https://koukia.ca/string-interpolation-vs-string-format-string-concat-and-string-builder-performance-benchmarks-c1dad38032a

Title: React/JSX attrs w/strings vs braces

Body:
The docs say that a JSX attributes with strings are the same as attributes with braces...

<Thing attr='val' /> === <Thing attr={'val'} />

I thought I read something that said only use braces when needed because strings are more performant, but I can't find the reference now. Is there an evaluation cost for braces?

Body:
Is there an evaluation cost for braces

Yes, As you can see anything inside {} will be considered as javascript code, so that will be executed , if you just want to assign the string then
just simply use the attr='val' rather than attr={'val'}

but if you have assignment condition based then you can use attr={'val'}

like

attr={ (condition) ? 'val1' : 'val2'}

I Hope , this will clear your thoughts.

For more details :

https://reactjs.org/docs/jsx-in-depth.html

Here you can read behind the scenes of string interpolation and speed performance :

https://koukia.ca/string-interpolation-vs-string-format-string-concat-and-string-builder-performance-benchmarks-c1dad38032a


答:
Try with .clone:

```<code>$(document.body)
    .clone()
    .find('iframe')
        .remove()
    .end()
    .html();
</code>```

Title: how to get innerHtml of body without an iframe with jquery

Body:
I have page with html something like this

......
.....

I want to get the innerHTML of the body but without the iframe? How can i do that in jquery?

Body:
Try with .clone:

$(document.body)
    .clone()
    .find('iframe')
        .remove()
    .end()
    .html();


问:
R results in full width with Rmarkdown/tufte_handout
I'm writing some course material using Rmarkdown and the tufte package. However, some of the R outputs I'd like to have in the document have a width larger than the width of the handout (see the summary of a lm model in the example below). I cannot manage to make these R outputs occupy the full width of the page (I'd like to have something similar to the fig.fullwidth chunk argument for figures).

I know there is a fullwidth environment but it having a R chunk inside this environment prevents pandoc to build the pdf due to the leading hashes in front of R output (Removing these hashes by specifying the chunk argument comment=NA produce a pdf but the formatting of the R output is lost).

Is there a way to have R output fullwidth ?

Thanks for help.

Below is a minimal example

```<code>---
title: "My minimal example"
link-citations: yes
output:
   tufte::tufte_handout:
    latex_engine: xelatex
---

```{r setup, include=FALSE}
library(tufte)
# invalidate cache when the tufte version changes
knitr::opts_chunk$set(tidy = FALSE, cache.extra =
packageVersion('tufte'))
options(htmltools.dir.version = FALSE)
```

This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph.

```{r lm}
model = lm(dist~speed,data=cars)
summary(model)
```

\begin{fullwidth}
This is a fullwidth. paragraph. This is a fullwidth. paragraph. This is a fullwidth. paragraph. This is a fullwidth. paragraph. This is a fullwidth. paragraph. This is a fullwidth. paragraph. This is a fullwidth. paragraph. This is a fullwidth. paragraph. This is a fullwidth. paragraph. This is a fullwidth. paragraph.
\end{fullwidth}
</code>```

答:
This is my first answer here and more of an ad-hoc solution than a real fullwidth solution for output.

I faced this problem too and eventually solved it by concatenating the output with cat(). I then tried to make it more general by using capture.output(), but unfortunately I did not get that to work.

This completely disregards the main width, but unfortunately it is not an optimal solution, since it also does not respect the full page width and requires you to copy-paste the output:

```<code>---
title: "My minimal example"
output: tufte::tufte_handout
---

# Not fullwidth:
```{r, echo = FALSE}
model <- lm(dist ~ speed, data = cars)
summary(model)
```

# Not fullwidth:
```{r, echo = FALSE}
out <- capture.output(summary(model))
cat(out, sep = "\n")
```

# Fullwidth:
```{r, echo = FALSE}
cat("Call:
lm(formula = dist ~ speed, data = cars)

Residuals:
    Min      1Q  Median      3Q     Max
-29.069  -9.525  -2.272   9.215  43.201

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept) -17.5791     6.7584  -2.601   0.0123 *
speed         3.9324     0.4155   9.464 1.49e-12 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 15.38 on 48 degrees of freedom
Multiple R-squared:  0.6511,    Adjusted R-squared:  0.6438
F-statistic: 89.57 on 1 and 48 DF,  p-value: 1.49e-12")
```
</code>```

If anyone has a suggestion to make the capture.output() version work, please let me know.

Body:
I'm writing some course material using Rmarkdown and the tufte package. However, some of the R outputs I'd like to have in the document have a width larger than the width of the handout (see the summary of a lm model in the example below). I cannot manage to make these R outputs occupy the full width of the page (I'd like to have something similar to the fig.fullwidth chunk argument for figures).

I know there is a fullwidth environment but it having a R chunk inside this environment prevents pandoc to build the pdf due to the leading hashes in front of R output (Removing these hashes by specifying the chunk argument comment=NA produce a pdf but the formatting of the R output is lost).

Is there a way to have R output fullwidth ?

Thanks for help.

Below is a minimal example

---
title: "My minimal example"
link-citations: yes
output:
   tufte::tufte_handout:
    latex_engine: xelatex
---

```{r setup, include=FALSE}
library(tufte)
# invalidate cache when the tufte version changes
knitr::opts_chunk$set(tidy = FALSE, cache.extra =
packageVersion('tufte'))
options(htmltools.dir.version = FALSE)
```

This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph.

```{r lm}
model = lm(dist~speed,data=cars)
summary(model)
```

\begin{fullwidth}
This is a fullwidth. paragraph. This is a fullwidth. paragraph. This is a fullwidth. paragraph. This is a fullwidth. paragraph. This is a fullwidth. paragraph. This is a fullwidth. paragraph. This is a fullwidth. paragraph. This is a fullwidth. paragraph. This is a fullwidth. paragraph. This is a fullwidth. paragraph.
\end{fullwidth}

Body:
This is my first answer here and more of an ad-hoc solution than a real fullwidth solution for output.

I faced this problem too and eventually solved it by concatenating the output with cat(). I then tried to make it more general by using capture.output(), but unfortunately I did not get that to work.

This completely disregards the main width, but unfortunately it is not an optimal solution, since it also does not respect the full page width and requires you to copy-paste the output:

---
title: "My minimal example"
output: tufte::tufte_handout
---

# Not fullwidth:
```{r, echo = FALSE}
model <- lm(dist ~ speed, data = cars)
summary(model)
```

# Not fullwidth:
```{r, echo = FALSE}
out <- capture.output(summary(model))
cat(out, sep = "\n")
```

# Fullwidth:
```{r, echo = FALSE}
cat("Call:
lm(formula = dist ~ speed, data = cars)

Residuals:
    Min      1Q  Median      3Q     Max
-29.069  -9.525  -2.272   9.215  43.201

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept) -17.5791     6.7584  -2.601   0.0123 *
speed         3.9324     0.4155   9.464 1.49e-12 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 15.38 on 48 degrees of freedom
Multiple R-squared:  0.6511,    Adjusted R-squared:  0.6438
F-statistic: 89.57 on 1 and 48 DF,  p-value: 1.49e-12")
```

If anyone has a suggestion to make the capture.output() version work, please let me know.


问:
What’s the term for a website that allows you to use tabs to jump to different sections?
I’m using a template from W3Schools. It allows you to jump to different pages when you click a tab.

What’s the term for that? I can’t find it, and I don’t know how the code works for it.

答:
They are called Single Page Sites or less commonly One Page Scrolling Sites. The way of navigation that you are referring to and/or using is a common feature.

Reference: https://www.awwwards.com/websites/single-page/


答:
You can use a stream this way:

```<code>public static CarType getByName(String name) {
    return Arrays.stream(values())
            .filter(carType -> carType.name().equals(name))
            .findFirst()
            .orElse(UNKNOWN);
}
</code>```

BTW, when using IntellliJ (I am not affiliated to them ;)), it offers you an option to do this conversion automatically.

Title: Return object from list while looping java 8

Body:
You can use a stream this way:

public static CarType getByName(String name) {
    return Arrays.stream(values())
            .filter(carType -> carType.name().equals(name))
            .findFirst()
            .orElse(UNKNOWN);
}

BTW, when using IntellliJ (I am not affiliated to them ;)), it offers you an option to do this conversion automatically.


问:
Need help to display inputs of a Java's form on an other frame
So I'm tryin to enter some Datas in a form and stock them to display them in a array when i click of the button "Show" but i don't know how can i do that.

Here's my form :

```<code>import java.awt.*;
import java.awt.event.*;

public class test {
    public static void main(String[] args) {
        Frame frm=new Frame("Add employee");
        Label lbl = new Label();
        frm.add(lbl);
        frm.setSize(350,200);
        frm.setVisible(true);
        frm.addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent e){
                System.exit(0);
            }
        });
        Panel p = new Panel();
        Panel p1 = new Panel();
        Label jFirstName = new Label("first name");
        TextField lFirstName = new TextField(20);
        Label jLastName =new Label("last name");
        TextField lLastName=new TextField(20);
        Label jAge= new Label("Age");
        TextField lAge = new TextField(20);
        Label jDate =new Label("Date");
        TextField lDate=new TextField(20);
        Label jType = new Label("employee type");
        TextField lType = new TextField(20);
        p.setLayout(new GridLayout(7,1));

        p.add(jFirstName);
        p.add(lFirstName);
        p.add(jLastName);
        p.add(lLastName);
        p.add(jAge);
        p.add(lAge);
        p.add(jDate);
        p.add(lDate);
        p.add(jType);
        p.add(lType);

        Button Submit=new Button("Submit");
        p.add(Submit);
        p1.add(p);
        frm.add(p1,BorderLayout.NORTH);
    }
}
</code>```

Do you have any idea ?

答:
Try below code. I started with your code and modified it. Few things I'd suggest/point:

Consider using Swing instead of AWT (e.g. JFrame instead of Frame). Swing is richer.
Try to break code into separate classes than writing everything in main() method.
I removed panel p1 because it was redundant.

```<code>public class Test
{
  public static void main(String[] args)
  {
    final Frame frm=new Frame("Add employee");
    Label lbl = new Label();
    frm.add(lbl);
    frm.setSize(350,200);
    frm.setVisible(true);
    frm.addWindowListener(new WindowAdapter(){
      public void windowClosing(WindowEvent e){
        System.exit(0);
      }
    });
    Panel p = new Panel();
    //Panel p1 = new Panel();
    final Label jFirstName = new Label("first name");
    final TextField lFirstName = new TextField(20);
    final Label jLastName =new Label("last name");
    final TextField lLastName=new TextField(20);
    final Label jAge= new Label("Age");
    final TextField lAge = new TextField(20);
    final Label jDate =new Label("Date");
    final TextField lDate=new TextField(20);
    final Label jType = new Label("employee type");
    final TextField lType = new TextField(20);
    p.setLayout(new GridLayout(7,1));

    p.add(jFirstName);
    p.add(lFirstName);
    p.add(jLastName);
    p.add(lLastName);
    p.add(jAge);
    p.add(lAge);
    p.add(jDate);
    p.add(lDate);
    p.add(jType);
    p.add(lType);

    Button Submit=new Button("Submit");

    Submit.addActionListener(new ActionListener()
    {
      @Override
      public void actionPerformed(ActionEvent e)
      {
        String[] formData = new String[5];
        formData[0] = jFirstName.getText() + ": " + lFirstName.getText();
        formData[1] = jFirstName.getText() + ": " + lLastName.getText();
        formData[2] = jAge.getText() + ": " + lAge.getText();
        formData[3] = jDate.getText() + ": " + lDate.getText();
        formData[4] = jType.getText() + ": " + lType.getText();

        TextArea textArea = new TextArea();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < formData.length; i++)
        {
          sb.append(formData[i]);
          sb.append("\n");
        }
        textArea.setText(sb.toString());

        final Dialog dialog = new Dialog(frm, "Form Data");
        dialog.setModal(true);
        dialog.addWindowListener(new WindowAdapter()
        {
          @Override
          public void windowClosing(WindowEvent e)
          {
            dialog.setVisible(false);
          }
        });
        dialog.add(textArea);
        dialog.pack();
        dialog.setVisible(true);
      }
    });

    p.add(Submit);
    //p1.add(p);
    frm.add(/*p1*/p,BorderLayout.NORTH);
  }
}
</code>```

Body:
So I'm tryin to enter some Datas in a form and stock them to display them in a array when i click of the button "Show" but i don't know how can i do that.

Here's my form :

import java.awt.*;
import java.awt.event.*;

public class test {
    public static void main(String[] args) {
        Frame frm=new Frame("Add employee");
        Label lbl = new Label();
        frm.add(lbl);
        frm.setSize(350,200);
        frm.setVisible(true);
        frm.addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent e){
                System.exit(0);
            }
        });
        Panel p = new Panel();
        Panel p1 = new Panel();
        Label jFirstName = new Label("first name");
        TextField lFirstName = new TextField(20);
        Label jLastName =new Label("last name");
        TextField lLastName=new TextField(20);
        Label jAge= new Label("Age");
        TextField lAge = new TextField(20);
        Label jDate =new Label("Date");
        TextField lDate=new TextField(20);
        Label jType = new Label("employee type");
        TextField lType = new TextField(20);
        p.setLayout(new GridLayout(7,1));

        p.add(jFirstName);
        p.add(lFirstName);
        p.add(jLastName);
        p.add(lLastName);
        p.add(jAge);
        p.add(lAge);
        p.add(jDate);
        p.add(lDate);
        p.add(jType);
        p.add(lType);

        Button Submit=new Button("Submit");
        p.add(Submit);
        p1.add(p);
        frm.add(p1,BorderLayout.NORTH);
    }
}

Do you have any idea ?

Body:
Try below code. I started with your code and modified it. Few things I'd suggest/point:

Consider using Swing instead of AWT (e.g. JFrame instead of Frame). Swing is richer.
Try to break code into separate classes than writing everything in main() method.
I removed panel p1 because it was redundant.

public class Test
{
  public static void main(String[] args)
  {
    final Frame frm=new Frame("Add employee");
    Label lbl = new Label();
    frm.add(lbl);
    frm.setSize(350,200);
    frm.setVisible(true);
    frm.addWindowListener(new WindowAdapter(){
      public void windowClosing(WindowEvent e){
        System.exit(0);
      }
    });
    Panel p = new Panel();
    //Panel p1 = new Panel();
    final Label jFirstName = new Label("first name");
    final TextField lFirstName = new TextField(20);
    final Label jLastName =new Label("last name");
    final TextField lLastName=new TextField(20);
    final Label jAge= new Label("Age");
    final TextField lAge = new TextField(20);
    final Label jDate =new Label("Date");
    final TextField lDate=new TextField(20);
    final Label jType = new Label("employee type");
    final TextField lType = new TextField(20);
    p.setLayout(new GridLayout(7,1));

    p.add(jFirstName);
    p.add(lFirstName);
    p.add(jLastName);
    p.add(lLastName);
    p.add(jAge);
    p.add(lAge);
    p.add(jDate);
    p.add(lDate);
    p.add(jType);
    p.add(lType);

    Button Submit=new Button("Submit");

    Submit.addActionListener(new ActionListener()
    {
      @Override
      public void actionPerformed(ActionEvent e)
      {
        String[] formData = new String[5];
        formData[0] = jFirstName.getText() + ": " + lFirstName.getText();
        formData[1] = jFirstName.getText() + ": " + lLastName.getText();
        formData[2] = jAge.getText() + ": " + lAge.getText();
        formData[3] = jDate.getText() + ": " + lDate.getText();
        formData[4] = jType.getText() + ": " + lType.getText();

        TextArea textArea = new TextArea();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < formData.length; i++)
        {
          sb.append(formData[i]);
          sb.append("\n");
        }
        textArea.setText(sb.toString());

        final Dialog dialog = new Dialog(frm, "Form Data");
        dialog.setModal(true);
        dialog.addWindowListener(new WindowAdapter()
        {
          @Override
          public void windowClosing(WindowEvent e)
          {
            dialog.setVisible(false);
          }
        });
        dialog.add(textArea);
        dialog.pack();
        dialog.setVisible(true);
      }
    });

    p.add(Submit);
    //p1.add(p);
    frm.add(/*p1*/p,BorderLayout.NORTH);
  }
}


问:
npm install: Error: EACCES: permission denied, mkdir
I attempted to do a  sudo npm install -g appium on Mac OS 10.12.5.

I get this error:

info Chromedriver Install Installing Chromedriver version '2.30' for platform 'mac' and architecture '64'

info Chromedriver Install Opening temp file to write chromedriver_mac64 to...

Error: EACCES: permission denied, mkdir

'/usr/local/lib/node_modules/appium/node_modules/appium-chromedriver/2017820-44752-12jfqpb.z2hd'

npm ERR! code ELIFECYCLE

npm ERR! errno 1

npm ERR! appium-chromedriver@3.0.1 install: node install-npm.js
  npm ERR! Exit status 1
  npm ERR!

this is not a dup question, as this install attempt was with sudo, as the other one was not.

答:
sudo npm install -g appium --unsafe-perm=true --allow-root

Worked for me

ContentLicense: CC BY-SA 4.0


问:
Get the value of the excess textbox into another box
i have textbox1 and textbox2.

and textbox3 were user input the value of 101.

& i want to print out in textbox2 the excess value of textbox1.

```<code> <input type="text" name="textbox1" readonly="readonly" value="">

    <input type="text" name="textbox2" readonly="readonly" value="">

    <input type="text" name="textbox3" value="">
</code>```

if the user type 101 in textbox3
the textbox1 only print 100
the textbox2 will print only the excess value 1

How can I achieve this ?

Thanks

答:
Here is a sample snipppet to help you:

function checkAndPerformCalculation() {
  var enteredVal = document.getElementById('textbox3').value;
  document.getElementById('textbox1').value = 100;
  document.getElementById('textbox2').value = enteredVal - 100;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" name="textbox1" id="textbox1" readonly="readonly" value="">

<input type="text" name="textbox2" id="textbox2" readonly="readonly" value="">

<input type="text" name="textbox3" id="textbox3" value="" onKeyup="checkAndPerformCalculation()"></code>```

Body:
i have textbox1 and textbox2.

and textbox3 were user input the value of 101.

& i want to print out in textbox2 the excess value of textbox1.

 <input type="text" name="textbox1" readonly="readonly" value="">

    <input type="text" name="textbox2" readonly="readonly" value="">

    <input type="text" name="textbox3" value="">

if the user type 101 in textbox3
the textbox1 only print 100
the textbox2 will print only the excess value 1

How can I achieve this ?

Thanks

Body:
Here is a sample snipppet to help you:

function checkAndPerformCalculation() {
  var enteredVal = document.getElementById('textbox3').value;
  document.getElementById('textbox1').value = 100;
  document.getElementById('textbox2').value = enteredVal - 100;
}

<input type="text" name="textbox1" id="textbox1" readonly="readonly" value="">

<input type="text" name="textbox2" id="textbox2" readonly="readonly" value="">

<input type="text" name="textbox3" id="textbox3" value="" onKeyup="checkAndPerformCalculation()">


问:
SQL Set Question
How can I make the following sql statement part of the "SET" in my query? I want to pull out a list in a column and have my "SET" run against that. That way my "SET" isn't just one variable but rather a list to run against. Make sence? </p>

```<code>DECLARE @Item as char(32)
declare @result varchar(max);
SET @Item = '034100-3JK';
</code>```

<p>I want to use something like the following to have it query against instead of the 034100-3JK: </p>

```<code>select distinct
        a.t_sitm as StartItem
from
        ttibom010101 as a
        INNER JOIN ttiitm001101 as b on a.t_sitm = b.t_item
where
        b.t_ctyp != 'TOP'
        and b.t_ctyp != 'SUB'
</code>```

答:
```<code>DECLARE @Item as char(32)
select distinct       @Item = a.t_sitm as StartItem
from          ttibom010101 as a
INNER JOIN ttiitm001101 as b
   on a.t_sitm = b.t_item
where  b.t_ctyp != 'TOP' and b.t_ctyp != 'SUB'
</code>```

Note this will only work correctly if the query wil never return more than one result. If you can havve multipel results, declare a table varaiable instead of a scalar varaible and insert into the table varaiable insted and then use it as a join in later processing.

Title: SQL Set Question

Body:
How can I make the following sql statement part of the "SET" in my query? I want to pull out a list in a column and have my "SET" run against that. That way my "SET" isn't just one variable but rather a list to run against. Make sence?

DECLARE @Item as char(32)
declare @result varchar(max);
SET @Item = '034100-3JK';

I want to use something like the following to have it query against instead of the 034100-3JK:

select distinct
        a.t_sitm as StartItem
from
        ttibom010101 as a
        INNER JOIN ttiitm001101 as b on a.t_sitm = b.t_item
where
        b.t_ctyp != 'TOP'
        and b.t_ctyp != 'SUB'

Body:
DECLARE @Item as char(32)
select distinct       @Item = a.t_sitm as StartItem
from          ttibom010101 as a
INNER JOIN ttiitm001101 as b
   on a.t_sitm = b.t_item
where  b.t_ctyp != 'TOP' and b.t_ctyp != 'SUB'

Note this will only work correctly if the query wil never return more than one result. If you can havve multipel results, declare a table varaiable instead of a scalar varaible and insert into the table varaiable insted and then use it as a join in later processing.