问:
.net script web services: __type attribute
I'm using a .net script service which is called from client-side script, and it works very nicely.

only problem is- it generates a '__type' attribute for each of the returned objects, which I don't want or need.

I've seen a few posts about this over the web, and as far as I could tell, there are only 'workarounds' for this:

some people suggested hiding the parameter-less c'tor of the return type as 'internal protected',

others suggested not using the [ScriptMethod] tag, and instead JSONfy the result manually  and return a string.

I'm wondering whether there is another, better, solution for this. and by the way- what is this attribute used for, anyway?

I'm enclosing the service method and the generated JSON.

method:

```<code>[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
public IEnumerable<EmployeePO> GetEmployeesForDepartment(int DepartmentId)
{

        return new AdministrationController().GetEmployeesForDepartment(DepartmentId);

}
</code>```

JSON returned:

```<code>{"d":[{"__type":"Application.Controllers.PresentationObjects.EmployeePO","Positions":[{"__type":"Application.Controllers.PresentationObjects.PositionPO","Id":4,"Name":"Employee: 1test Position 1","IsPriority":false,"WarningThreshold":50,"CriticalThreshold":60,"CurrentWaitingTime":-1,"Passengers":[],"Qualifications":[...
</code>```

答:
OK so I ended up taking the advice from Jhon Morrison, posted in the question @Kid linked to-

I defined all the parameter-less constructors on my returned classes as protected internal and that really did the trick.

In cases where I actually needed to create empty objects I created a Factory method, like so:

```<code>public class MyClass
    {
        public int Id { get; set; }
        /*...*/

        public MyClass(int id):
        {
            Id = id;
        }

        public static MyClass CreateNewZonePO()
        {
            return new MyClass();
        }

        //parameterless c'tor for serialization's sake
        //it's protected internal in order to avoid the "__type" attribute when returned from a web service. see http://stackoverflow.com/questions/4958443/net-script-web-services-type-attribute
        protected internal MyClass()
        {

        }
    }
</code>```

@Kid's answer also worked, but it looked cleaner to me this way.

ContentLicense: CC BY-SA 2.5

Body:
I'm using a .net script service which is called from client-side script, and it works very nicely.

only problem is- it generates a '__type' attribute for each of the returned objects, which I don't want or need.

I've seen a few posts about this over the web, and as far as I could tell, there are only 'workarounds' for this:

some people suggested hiding the parameter-less c'tor of the return type as 'internal protected',

others suggested not using the [ScriptMethod] tag, and instead JSONfy the result manually  and return a string.

I'm wondering whether there is another, better, solution for this. and by the way- what is this attribute used for, anyway?

I'm enclosing the service method and the generated JSON.

method:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
public IEnumerable<EmployeePO> GetEmployeesForDepartment(int DepartmentId)
{

        return new AdministrationController().GetEmployeesForDepartment(DepartmentId);

}

JSON returned:

{"d":[{"__type":"Application.Controllers.PresentationObjects.EmployeePO","Positions":[{"__type":"Application.Controllers.PresentationObjects.PositionPO","Id":4,"Name":"Employee: 1test Position 1","IsPriority":false,"WarningThreshold":50,"CriticalThreshold":60,"CurrentWaitingTime":-1,"Passengers":[],"Qualifications":[...

Body:
OK so I ended up taking the advice from Jhon Morrison, posted in the question @Kid linked to-

I defined all the parameter-less constructors on my returned classes as protected internal and that really did the trick.

In cases where I actually needed to create empty objects I created a Factory method, like so:

public class MyClass
    {
        public int Id { get; set; }
        /*...*/

        public MyClass(int id):
        {
            Id = id;
        }

        public static MyClass CreateNewZonePO()
        {
            return new MyClass();
        }

        //parameterless c'tor for serialization's sake
        //it's protected internal in order to avoid the "__type" attribute when returned from a web service. see http://stackoverflow.com/questions/4958443/net-script-web-services-type-attribute
        protected internal MyClass()
        {

        }
    }

@Kid's answer also worked, but it looked cleaner to me this way.


来源: stackexchange

问:
Scrollbar webkit properties with <ul> tag
In my code I have unordered list inside the div and same time I have added scrollbar to that . I want to use webkit properties with this ul.
I tried as below. </p>

```<code>.list > ul ::-webkit-scrollbar {
 width: 12px;
 background-color: #e4e7eb;
 }

.list > ul::-webkit-scrollbar-thumb {
  outline: 1px solid slategrey;
  border-radius: 14px;
  -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,.3);
  background-color: #ffffff;
}

.list > ul ::-webkit-scrollbar-track {
 -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3);
  border-radius: 14px;
  background-color: #e4e7eb;
}
</code>```

<p>"list" is div class name.
But this not work for me. Am I used correct way or any other way to use this?</p>

答:
Use the below css for scroll bar in List div : -

```<code>.list ul {
max-height: 100px;
height: auto;
overflow: auto;
}
</code>```

For your convenience see the js fiddle link:https://jsfiddle.net/harshsetia/z629uxwf/3/

ContentLicense: CC BY-SA 4.0

Body:
In my code I have unordered list inside the div and same time I have added scrollbar to that . I want to use webkit properties with this ul.
I tried as below.

.list > ul ::-webkit-scrollbar {
 width: 12px;
 background-color: #e4e7eb;
 }

.list > ul::-webkit-scrollbar-thumb {
  outline: 1px solid slategrey;
  border-radius: 14px;
  -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,.3);
  background-color: #ffffff;
}

.list > ul ::-webkit-scrollbar-track {
 -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3);
  border-radius: 14px;
  background-color: #e4e7eb;
}

"list" is div class name.
But this not work for me. Am I used correct way or any other way to use this?

Body:
Use the below css for scroll bar in List div : -

.list ul {
max-height: 100px;
height: auto;
overflow: auto;
}

For your convenience see the js fiddle link:https://jsfiddle.net/harshsetia/z629uxwf/3/


问:
SWIFTUI - iOS : Multiple views and transfert data for signup user
I'm trying to create multiple views in swiftui for signup user form. I want to display some information (phone number, password) and when he press a button (NEXT) a new page appear with date of birth (...) and at the end all is send to firebase for create the account.

But I'm a beginner in SWIFT (not in C# or python) and i don't find any tutorial or example to do this. I have a login page and a signup page with animation to go from one page to another, and the function to create an account with firebase, but i can't find how create multiple views in signup page and pass the information between this multiple views.

I have find this to pass information : https://stackoverflow.com/a/41623076
But i want to do this by the best way it can be. Thank you for your help !

答:
You need to follow Combine Framework(Reactive Programming)

Create a Observable Object

```<code>class UserAuth: ObservableObject {
    @Published var userLoggedIn: Bool = false
}
</code>```

Where you create your scene delegate class add your environment object

```<code>func scene(_ scene: UIScene, willConnectTo _: UISceneSession, options _: UIScene.ConnectionOptions) {
    // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
    // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
    // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).

    // Create the SwiftUI view that provides the window contents.
    let userAuth = UserAuth()
    let contentView = AppNavigationView().environmentObject(userAuth)
    // Use a UIHostingController as window root view controller.
    if let windowScene = scene as? UIWindowScene {
        let window = UIWindow(windowScene: windowScene)
        window.rootViewController = UIHostingController(rootView: contentView)
        self.window = window
        window.makeKeyAndVisible()
}
</code>```

update the same environment object in your login class as bellow

```<code>struct LoginView: View {

    @EnvironmentObject var userAuth: UserAuth

    func callWebservicePerformLogin() {
       //update the user auth object which will send updates t
       self.userAuth.userLoggedIn = true
    }
}
</code>```

Listener class

```<code>struct AppNavigationView: View {
    @EnvironmentObject var userAuth: UserAuth

    var body: some View {
        if !userAuth.userLoggedIn {
            return AnyView(LoginView())
        } else {
        return AnyView(PlayerList())
        }
    }
}
</code>```

Body:
You need to follow Combine Framework(Reactive Programming)

Create a Observable Object

class UserAuth: ObservableObject {
    @Published var userLoggedIn: Bool = false
}

Where you create your scene delegate class add your environment object

func scene(_ scene: UIScene, willConnectTo _: UISceneSession, options _: UIScene.ConnectionOptions) {
    // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
    // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
    // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).

    // Create the SwiftUI view that provides the window contents.
    let userAuth = UserAuth()
    let contentView = AppNavigationView().environmentObject(userAuth)
    // Use a UIHostingController as window root view controller.
    if let windowScene = scene as? UIWindowScene {
        let window = UIWindow(windowScene: windowScene)
        window.rootViewController = UIHostingController(rootView: contentView)
        self.window = window
        window.makeKeyAndVisible()
}

update the same environment object in your login class as bellow

struct LoginView: View {

    @EnvironmentObject var userAuth: UserAuth

    func callWebservicePerformLogin() {
       //update the user auth object which will send updates t
       self.userAuth.userLoggedIn = true
    }
}

Listener class

struct AppNavigationView: View {
    @EnvironmentObject var userAuth: UserAuth

    var body: some View {
        if !userAuth.userLoggedIn {
            return AnyView(LoginView())
        } else {
        return AnyView(PlayerList())
        }
    }
}


问:
Breaking down array of objects into separate variables for database storage (React,express,sql server)
I have a stored array of objects within my reactjs application which when console logged looks like this.

```<code>0: {answer: "yes↵", question: "Is the keyboard separate from the screen?", state: "Declined with soloution defined"}
1: {answer: "yes", question: "Does the keyboard tilt?", state: "Accepted"}
2: {answer: "Question declined But not a problem", question: "Is it possible to find a comfortable typing postion?", state: "Accepted"}
3: {answer: "yes", question: "Do you have a good keyboard technique?", state: "Accepted"}
4: {answer: "Question declined But not a problem", question: "Are the characters on the keyboard clear and readable?", state: "Accepted"}
5: {answer: "sgdfgdfgdf", question: "Is your mouse or other pointing device suitable to the task you're using it for?", state: "problem specified"}
6: {answer: "yes", question: "Is the mouse (or other pointing device) located sufficently close to you?  ", state: "Accepted"}
7: {answer: "sdfsdfsdfsd", question: "Is there support for your wrist and forearm when using the mouse(or other pointing device)", state: "Declined with soloution defined"}
8: {answer: "yes", question: "Does the mouse (or other pointing device) work smoothly at a speed that suits you?", state: "Accepted"}
9: {answer: "asdasdas", question: "Can you easily adjust the software settings for speed and accuracy of the pointer?", state: "Declined with soloution defined"}
10: {answer: "asdasdads", question: "Are the characters on your screen clear and readable?", state: "problem specified"}
11: {answer: "yes", question: "Is the text size on your screen confortable to read?", state: "Accepted"}
12: {answer: "asdasdasd", question: "Is the image on your screen free from flicker and jitter?", state: "Declined with soloution defined"}
13: {answer: "asdasdasd", question: "Is your screen's specification suitable for its intended use?", state: "problem specified"}
14: {answer: "yes", question: "Is the brightness and/or contrast on your screen adjustable?", state: "Accepted"}
</code>```

this consists of answer, question and state (state of the answered question not state as in react components)

What I would like to do is pass these through to express so that I can upload them into my SQL database using the npm package mssql. However as these are all stored into the array I'm not sure how to split these up.

Ideally I would love to pass the whole object through to SQL and just store the whole thing in the database e.g (pseudo code)

```<code>insert into table where answer = answer and question = question and state = state
</code>```

Essentially to use this with SQL how would I break these down to be used with my back end or can I pass the whole object with a specific SQL stored procedure.

```<code>create procedure StoreAnswers

@{answer_values}
as

INSERT INTO QuestionResponses
(RUId, QuestionId, Date, QuestionWhenAnswered, QuestionResponse, Accepted, AssignedWorkStation )
VALUES
${answer_values}

</code>```

EDIT

Stored procedure

```<code>create procedure StoreAnswers(@Results varchar(max))
as begin
  insert into QuestionResponses(QuestionResponse, QuestionWhenAnswered, State)
         select substring(value, charindex('{answer: "', value) + 10,  charindex('", ', value, charindex('{answer: "', value) + 10) -  charindex('{answer: "', value) - 10) as answer,
                substring(value, charindex('question: "', value) + 11, charindex('", ', value, charindex('question: "', value) + 11) - charindex('question: "', value) - 11) as question,
                substring(value, charindex('state: "', value) + 8,      charindex('"}', value,  charindex('state: "', value) + 8) -     charindex('state: "', value) - 8) as state
         from string_split(@Results, char(10))
end;
</code>```

How it is passed through to the sql query from express npm

```<code>app.post("/post-question-answers", async (req, res) => {
  console.log("!called");

  let results = req.body.results;

  console.info(results);

  await sql.connect(config, function(err) {
    if (err) console.log(err);

    // create Request object
    var request = new sql.Request();
    request.input("Results", sql.VarChar, results);
    // query to the database and get the records
    request.execute("dbo.StoreAnswers", function(err, recordset) {
      if (err) console.log(err);
      // send records as a response
      res.json(recordset);
    });
  });

  res.statusCode = 400;
  res.statusMessage = "bad request";
  // res.json({ message: "Email Missing" });
});

</code>```

This is the console.info(results)

```<code>[
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is the keyboard separate from the screen?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Does the keyboard tilt?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is it possible to find a comfortable typing postion?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Do you have a good keyboard technique?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Are the characters on the keyboard clear and readable?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: "Is your mouse or other pointing device suitable to the task you're using it for?",
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is the mouse (or other pointing device) located sufficently close to you?  ',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is there support for your wrist and forearm when using the mouse(or other pointing device)',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Does the mouse (or other pointing device) work smoothly at a speed that suits you?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Can you easily adjust the software settings for speed and accuracy of the pointer?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Are the characters on your screen clear and readable?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is the text size on your screen confortable to read?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is the image on your screen free from flicker and jitter?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: "Is your screen's specification suitable for its intended use?",
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is the brightness and/or contrast on your screen adjustable?',
[0]     state: 'Accepted'
[0]   }
[0] ]
</code>```

error

```<code>RequestError: Invalid length parameter passed to the LEFT or SUBSTRING function.
</code>```

答:
why you dont use an orm with your express app

like sequelize
it will make your life easier and remove all the headache of building sql statement in your app

check the documentation for it
https://sequelize.org/

with sequlize in your case

1- create your table in the db

2- make a model in your express app for that table

3- call model.bulkCreate(the whole object)

give it a try

Body:
I have a stored array of objects within my reactjs application which when console logged looks like this.

0: {answer: "yes↵", question: "Is the keyboard separate from the screen?", state: "Declined with soloution defined"}
1: {answer: "yes", question: "Does the keyboard tilt?", state: "Accepted"}
2: {answer: "Question declined But not a problem", question: "Is it possible to find a comfortable typing postion?", state: "Accepted"}
3: {answer: "yes", question: "Do you have a good keyboard technique?", state: "Accepted"}
4: {answer: "Question declined But not a problem", question: "Are the characters on the keyboard clear and readable?", state: "Accepted"}
5: {answer: "sgdfgdfgdf", question: "Is your mouse or other pointing device suitable to the task you're using it for?", state: "problem specified"}
6: {answer: "yes", question: "Is the mouse (or other pointing device) located sufficently close to you?  ", state: "Accepted"}
7: {answer: "sdfsdfsdfsd", question: "Is there support for your wrist and forearm when using the mouse(or other pointing device)", state: "Declined with soloution defined"}
8: {answer: "yes", question: "Does the mouse (or other pointing device) work smoothly at a speed that suits you?", state: "Accepted"}
9: {answer: "asdasdas", question: "Can you easily adjust the software settings for speed and accuracy of the pointer?", state: "Declined with soloution defined"}
10: {answer: "asdasdads", question: "Are the characters on your screen clear and readable?", state: "problem specified"}
11: {answer: "yes", question: "Is the text size on your screen confortable to read?", state: "Accepted"}
12: {answer: "asdasdasd", question: "Is the image on your screen free from flicker and jitter?", state: "Declined with soloution defined"}
13: {answer: "asdasdasd", question: "Is your screen's specification suitable for its intended use?", state: "problem specified"}
14: {answer: "yes", question: "Is the brightness and/or contrast on your screen adjustable?", state: "Accepted"}

this consists of answer, question and state (state of the answered question not state as in react components)

What I would like to do is pass these through to express so that I can upload them into my SQL database using the npm package mssql. However as these are all stored into the array I'm not sure how to split these up.

Ideally I would love to pass the whole object through to SQL and just store the whole thing in the database e.g (pseudo code)

insert into table where answer = answer and question = question and state = state

Essentially to use this with SQL how would I break these down to be used with my back end or can I pass the whole object with a specific SQL stored procedure.

create procedure StoreAnswers

@{answer_values}
as

INSERT INTO QuestionResponses
(RUId, QuestionId, Date, QuestionWhenAnswered, QuestionResponse, Accepted, AssignedWorkStation )
VALUES
${answer_values}

EDIT

Stored procedure

create procedure StoreAnswers(@Results varchar(max))
as begin
  insert into QuestionResponses(QuestionResponse, QuestionWhenAnswered, State)
         select substring(value, charindex('{answer: "', value) + 10,  charindex('", ', value, charindex('{answer: "', value) + 10) -  charindex('{answer: "', value) - 10) as answer,
                substring(value, charindex('question: "', value) + 11, charindex('", ', value, charindex('question: "', value) + 11) - charindex('question: "', value) - 11) as question,
                substring(value, charindex('state: "', value) + 8,      charindex('"}', value,  charindex('state: "', value) + 8) -     charindex('state: "', value) - 8) as state
         from string_split(@Results, char(10))
end;

How it is passed through to the sql query from express npm

app.post("/post-question-answers", async (req, res) => {
  console.log("!called");

  let results = req.body.results;

  console.info(results);

  await sql.connect(config, function(err) {
    if (err) console.log(err);

    // create Request object
    var request = new sql.Request();
    request.input("Results", sql.VarChar, results);
    // query to the database and get the records
    request.execute("dbo.StoreAnswers", function(err, recordset) {
      if (err) console.log(err);
      // send records as a response
      res.json(recordset);
    });
  });

  res.statusCode = 400;
  res.statusMessage = "bad request";
  // res.json({ message: "Email Missing" });
});

This is the console.info(results)

[
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is the keyboard separate from the screen?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Does the keyboard tilt?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is it possible to find a comfortable typing postion?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Do you have a good keyboard technique?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Are the characters on the keyboard clear and readable?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: "Is your mouse or other pointing device suitable to the task you're using it for?",
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is the mouse (or other pointing device) located sufficently close to you?  ',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is there support for your wrist and forearm when using the mouse(or other pointing device)',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Does the mouse (or other pointing device) work smoothly at a speed that suits you?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Can you easily adjust the software settings for speed and accuracy of the pointer?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Are the characters on your screen clear and readable?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is the text size on your screen confortable to read?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is the image on your screen free from flicker and jitter?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: "Is your screen's specification suitable for its intended use?",
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is the brightness and/or contrast on your screen adjustable?',
[0]     state: 'Accepted'
[0]   }
[0] ]

error

RequestError: Invalid length parameter passed to the LEFT or SUBSTRING function.


问:
Extracting indices for data frame rows that have MAX value for named field
I have a data frame that is rather large and I need a good way (explained bellow) to extract indices for rows that have maximum values for a given field, within a certain set of labels. To explain this a bit better, here is an example 10 row data frame:

```<code>      value label
1  5.531637     D
2  5.826498     A
3  8.866210     A
4  1.387978     C
5  8.128505     C
6  7.391311     B
7  1.829392     A
8  4.373273     D
9  7.380244     A
10 6.157304     D
</code>```

To generate:

```<code>structure(list(value = c(5.531637, 5.826498, 8.86621, 1.387978, 8.128505,
7.391311, 1.829392, 4.373273, 7.380244, 6.157304),
label = c("D", "A", "A", "C", "C", "B", "A", "D", "A", "D")),
.Names = c("value", "label"), class = "data.frame", row.names = c(NA, -10L))
</code>```

If I want to know what the index is for rows that have the maximum value per label, I currently use the following code:

```<code>idx <- sapply(split(1:nrow(d), d$label), function(x) {
  x[which.max(d[x,"value"])]
})
</code>```

Generating this answer:

```<code>A  B  C  D
3  6  5 10
</code>```

I have also played around with ddply but have yet to find a better way to do this. By "better" in this case I mean faster (ddply is pretty slow and what I currently use is not far behind) as well as more elegant since the above solution seems way to wordy too me.

答:
Perhaps this may help:

```<code>tapply(seq(dim(d)[1]), d$label, function(rns){rns[which.max(d$value[rns])]} )
</code>```

(note: I got this trick from the code of 'by')

ContentLicense: CC BY-SA 3.0

Body:
I have a data frame that is rather large and I need a good way (explained bellow) to extract indices for rows that have maximum values for a given field, within a certain set of labels. To explain this a bit better, here is an example 10 row data frame:

      value label
1  5.531637     D
2  5.826498     A
3  8.866210     A
4  1.387978     C
5  8.128505     C
6  7.391311     B
7  1.829392     A
8  4.373273     D
9  7.380244     A
10 6.157304     D

To generate:

structure(list(value = c(5.531637, 5.826498, 8.86621, 1.387978, 8.128505,
7.391311, 1.829392, 4.373273, 7.380244, 6.157304),
label = c("D", "A", "A", "C", "C", "B", "A", "D", "A", "D")),
.Names = c("value", "label"), class = "data.frame", row.names = c(NA, -10L))

If I want to know what the index is for rows that have the maximum value per label, I currently use the following code:

idx <- sapply(split(1:nrow(d), d$label), function(x) {
  x[which.max(d[x,"value"])]
})

Generating this answer:

A  B  C  D
3  6  5 10

I have also played around with ddply but have yet to find a better way to do this. By "better" in this case I mean faster (ddply is pretty slow and what I currently use is not far behind) as well as more elegant since the above solution seems way to wordy too me.

Body:
Perhaps this may help:

tapply(seq(dim(d)[1]), d$label, function(rns){rns[which.max(d$value[rns])]} )

(note: I got this trick from the code of 'by')


问:
how to run an optimization problem in different steps?
I have an optimization problem in AMPL. am wondering how I can run my optimization with my own algorithm in different steps? should I use AMPL or python or another software?

Here is what I want to do:

I want to search in feasible reign layer by layer. For example if my problem is in dimension 3, I want to search in 3 layers such as:

```<code>first layer :  x1+x2+x3=1

second layer:  x1+x2+x3=2

third layer:    x1+x2+x3=3
</code>```

in each layer I have some new constraints that will be active when the search is in that layer.
Suppose C1, C2 ,C3 are constraints for layer 1,2 and 3 respectively. I want the problem to be ran as below:

First ran in the first layer and C1 must be active :

```<code>          `x1+x2+x3=1`   and `C1`     are active.  (the constraints C2 ,C3 and 2 other layers are non-active)
</code>```

Then ran in the second layer and C2 must be active:

```<code>          `x1+x2+x3=2`   and `C2`     are active.  (the constraints C1 ,C3 and 2 other layers are non-active)
</code>```

third ran in the third layer and C3 must be active :

```<code>          `x1+x2+x3=3`   and `C3`     are active.  (the constraints C1 ,C2 and 2 other layers are non-active)
</code>```

答:
You can use a script to do this in AMPL. For instance:

```<code>reset;
option solver gurobi;
param n_x := 3;
var x{1..n_x};

param bignum := 1e4;

param layer;
set layers := 1..n_x;

s.t. sum_constraint: x[1] + x[2] + x[3] = layer;

s.t. c1a: x[1] >= (if layer = 1 then 10 else 10-bignum);
s.t. c1b: x[1] <= (if layer = 1 then 10 else 10+bignum);
# on layer 1, constrain x[1] = 10, otherwise leave it effectively unconstrained

s.t. c2a: x[2] >= (if layer = 2 then 20 else 20-bignum);
s.t. c2b: x[2] <= (if layer = 2 then 20 else 20+bignum);

s.t. c3a: x[3] >= (if layer = 3 then 30 else 30-bignum);
s.t. c3b: x[3] <= (if layer = 3 then 30 else 30+bignum);

minimize of: x[1]^2+x[2]^2+x[3]^2;

for {i in layers}{
    let layer := i;
    printf "\nLayer = %1.0f\n", layer;
    solve;
    display x;
}
</code>```

You could also use drop and restore statements to switch constraints on and off, depending on just how much you want to automate it.

Body:
I have an optimization problem in AMPL. am wondering how I can run my optimization with my own algorithm in different steps? should I use AMPL or python or another software?

Here is what I want to do:

I want to search in feasible reign layer by layer. For example if my problem is in dimension 3, I want to search in 3 layers such as:

first layer :  x1+x2+x3=1

second layer:  x1+x2+x3=2

third layer:    x1+x2+x3=3

in each layer I have some new constraints that will be active when the search is in that layer.
Suppose C1, C2 ,C3 are constraints for layer 1,2 and 3 respectively. I want the problem to be ran as below:

First ran in the first layer and C1 must be active :

          `x1+x2+x3=1`   and `C1`     are active.  (the constraints C2 ,C3 and 2 other layers are non-active)

Then ran in the second layer and C2 must be active:

          `x1+x2+x3=2`   and `C2`     are active.  (the constraints C1 ,C3 and 2 other layers are non-active)

third ran in the third layer and C3 must be active :

          `x1+x2+x3=3`   and `C3`     are active.  (the constraints C1 ,C2 and 2 other layers are non-active)

Body:
You can use a script to do this in AMPL. For instance:

reset;
option solver gurobi;
param n_x := 3;
var x{1..n_x};

param bignum := 1e4;

param layer;
set layers := 1..n_x;

s.t. sum_constraint: x[1] + x[2] + x[3] = layer;

s.t. c1a: x[1] >= (if layer = 1 then 10 else 10-bignum);
s.t. c1b: x[1] <= (if layer = 1 then 10 else 10+bignum);
# on layer 1, constrain x[1] = 10, otherwise leave it effectively unconstrained

s.t. c2a: x[2] >= (if layer = 2 then 20 else 20-bignum);
s.t. c2b: x[2] <= (if layer = 2 then 20 else 20+bignum);

s.t. c3a: x[3] >= (if layer = 3 then 30 else 30-bignum);
s.t. c3b: x[3] <= (if layer = 3 then 30 else 30+bignum);

minimize of: x[1]^2+x[2]^2+x[3]^2;

for {i in layers}{
    let layer := i;
    printf "\nLayer = %1.0f\n", layer;
    solve;
    display x;
}

You could also use drop and restore statements to switch constraints on and off, depending on just how much you want to automate it.


问:
I'm unable to understand below c# code fragment
I only have this part of the code. I'm unable to make sense is "next" another method of ptr or is it the random.next method. Just want to know if this is a common code fragment used by experts. </p>

```<code>Node mystery(Node ptr) {
    Node temp;
    Node previous = null;
    while (ptr != null) {
        temp = ptr.next;
        ptr.next = previous;
        previous = ptr;
        ptr = temp;
    }
    return previous;
}

</code>```

答:
You can execute the logic steps by steps, using your debugger or a piece of paper with a pen.

This looks like a linked list. Each node pointing to the next one, the last note pointing to null

```<code>head                    tail
+---+       +---+       +---+
|"A"| next  |"B"| next  |"C"| next
|   |------>|   |------>|   |------> null
+---+       +---+       +---+
</code>```

while (ptr != null) { will loop until the current node is null

The code inside the while scope is a typical swap. Let's execute it steps by steps, considering ptr is the node containing "A", like above

```<code>temp = ptr.next;
</code>```

Now, temp is poiting to the next node.

```<code> ptr
  |
  v
+---+       +---+       +---+
|"A"| next  |"B"| next  |"C"| next
|   |------>|   |------>|   |------> null
+---+       +---+       +---+
              ^
              |
            temp
</code>```

```<code>ptr.next = previous;
</code>```

Now, ptr.next is pointing to previous which was initialized to null. ptr is now de-linked from the list

```<code> ptr
  |
  v
+---+             | +---+       +---+
|"A"| next        | |"B"| next  |"C"| next
|   |------> null | |   |------>|   |------> null
+---+             | +---+       +---+
                  |   ^
                  |   |
                    temp
</code>```

```<code>previous = ptr;
</code>```

Both ptr and previous are pointing to the same node

```<code> ptr
  |
  v
+---+             | +---+       +---+
|"A"| next        | |"B"| next  |"C"| next
|   |------> null | |   |------>|   |------> null
+---+             | +---+       +---+
  ^               |   ^
  |               |   |
previous             temp
</code>```

```<code>ptr = temp;
</code>```

Now, both ptr and temp are pointing to the same node

```<code>                     ptr
                      |
                      v
+---+             | +---+       +---+
|"A"| next        | |"B"| next  |"C"| next
|   |------> null | |   |------>|   |------> null
+---+             | +---+       +---+
  ^               |   ^
  |               |   |
previous             temp
</code>```

Since ptr != null is true, the loop continue :

```<code>temp = ptr.next;

                     ptr
                      |
                      v
+---+             | +---+       +---+
|"A"| next        | |"B"| next  |"C"| next
|   |------> null | |   |------>|   |------> null
+---+             | +---+       +---+
  ^               |               ^
  |               |               |
previous                        temp
</code>```

```<code>temp = ptr.next;
</code>```0

Now, the next item of the current node is the one saved previously (the "A" node) :

```<code>temp = ptr.next;
</code>```1

```<code>temp = ptr.next;
</code>```2

```<code>ptr = temp;

                                  ptr
                                   |
                                   v
+---+        +---+             | +---+
|"B"| next   |"A"| next        | |"C"| next
|   |------> |   |------> null | |   |------> null
+---+        +---+             | +---+
  ^                            |   ^
  |                                |
previous                         temp
</code>```

Since ptr != null is true, the loop continues and the same logic is applied :

```<code>temp = ptr.next;

                                  ptr
                                   |
                                   v
+---+        +---+             | +---+
|"B"| next   |"A"| next        | |"C"| next
|   |------> |   |------> null | |   |------> null
+---+        +---+          ^  | +---+          ^
  ^                         |  |                |
  |                         |                   |
previous                    +-----------------temp
</code>```

```<code>ptr.next = previous;

 ptr
  |
  v
+---+        +---+        +---+
|"C"| next   |"B"| next   |"A"| next
|   |------> |   |------> |   |------> null
+---+        +---+        +---+          ^
               ^                         |
               |                         |
           previous                     temp
</code>```

```<code>previous = ptr;

 ptr
  |
  v
+---+        +---+        +---+
|"C"| next   |"B"| next   |"A"| next
|   |------> |   |------> |   |------> null
+---+        +---+        +---+         ^
  ^                                     |
  |                                     |
previous                               temp
</code>```

```<code>ptr = temp;

                                       ptr
                                        |
+---+        +---+        +---+         |
|"C"| next   |"B"| next   |"A"| next    v
|   |------> |   |------> |   |------> null
+---+        +---+        +---+         ^
  ^                                     |
  |                                     |
previous                               temp
</code>```

Now, while (ptr != null) is false. The loop ends and previous, which is the new head is returned.

This method reverse the order of a linked list and returns the head.

Body:
I only have this part of the code. I'm unable to make sense is "next" another method of ptr or is it the random.next method. Just want to know if this is a common code fragment used by experts.

Node mystery(Node ptr) {
    Node temp;
    Node previous = null;
    while (ptr != null) {
        temp = ptr.next;
        ptr.next = previous;
        previous = ptr;
        ptr = temp;
    }
    return previous;
}

Body:
You can execute the logic steps by steps, using your debugger or a piece of paper with a pen.

This looks like a linked list. Each node pointing to the next one, the last note pointing to null

head                    tail
+---+       +---+       +---+
|"A"| next  |"B"| next  |"C"| next
|   |------>|   |------>|   |------> null
+---+       +---+       +---+

while (ptr != null) { will loop until the current node is null

The code inside the while scope is a typical swap. Let's execute it steps by steps, considering ptr is the node containing "A", like above

temp = ptr.next;

Now, temp is poiting to the next node.

 ptr
  |
  v
+---+       +---+       +---+
|"A"| next  |"B"| next  |"C"| next
|   |------>|   |------>|   |------> null
+---+       +---+       +---+
              ^
              |
            temp

ptr.next = previous;

Now, ptr.next is pointing to previous which was initialized to null. ptr is now de-linked from the list

 ptr
  |
  v
+---+             | +---+       +---+
|"A"| next        | |"B"| next  |"C"| next
|   |------> null | |   |------>|   |------> null
+---+             | +---+       +---+
                  |   ^
                  |   |
                    temp

previous = ptr;

Both ptr and previous are pointing to the same node

 ptr
  |
  v
+---+             | +---+       +---+
|"A"| next        | |"B"| next  |"C"| next
|   |------> null | |   |------>|   |------> null
+---+             | +---+       +---+
  ^               |   ^
  |               |   |
previous             temp

ptr = temp;

Now, both ptr and temp are pointing to the same node

                     ptr
                      |
                      v
+---+             | +---+       +---+
|"A"| next        | |"B"| next  |"C"| next
|   |------> null | |   |------>|   |------> null
+---+             | +---+       +---+
  ^               |   ^
  |               |   |
previous             temp

Since ptr != null is true, the loop continue :

temp = ptr.next;

                     ptr
                      |
                      v
+---+             | +---+       +---+
|"A"| next        | |"B"| next  |"C"| next
|   |------> null | |   |------>|   |------> null
+---+             | +---+       +---+
  ^               |               ^
  |               |               |
previous                        temp

ptr.next = previous;

Now, the next item of the current node is the one saved previously (the "A" node) :

 ptr
  |
  v
+---+        +---+             | +---+
|"B"| next   |"A"| next        | |"C"| next
|   |------> |   |------> null | |   |------> null
+---+        +---+             | +---+
               ^               |   ^
               |                   |
            previous              temp

previous = ptr;

 ptr
  |
  v
+---+        +---+             | +---+
|"B"| next   |"A"| next        | |"C"| next
|   |------> |   |------> null | |   |------> null
+---+        +---+             | +---+
  ^                            |   ^
  |                                |
previous                         temp

ptr = temp;

                                  ptr
                                   |
                                   v
+---+        +---+             | +---+
|"B"| next   |"A"| next        | |"C"| next
|   |------> |   |------> null | |   |------> null
+---+        +---+             | +---+
  ^                            |   ^
  |                                |
previous                         temp

Since ptr != null is true, the loop continues and the same logic is applied :

temp = ptr.next;

                                  ptr
                                   |
                                   v
+---+        +---+             | +---+
|"B"| next   |"A"| next        | |"C"| next
|   |------> |   |------> null | |   |------> null
+---+        +---+          ^  | +---+          ^
  ^                         |  |                |
  |                         |                   |
previous                    +-----------------temp

ptr.next = previous;

 ptr
  |
  v
+---+        +---+        +---+
|"C"| next   |"B"| next   |"A"| next
|   |------> |   |------> |   |------> null
+---+        +---+        +---+          ^
               ^                         |
               |                         |
           previous                     temp

previous = ptr;

 ptr
  |
  v
+---+        +---+        +---+
|"C"| next   |"B"| next   |"A"| next
|   |------> |   |------> |   |------> null
+---+        +---+        +---+         ^
  ^                                     |
  |                                     |
previous                               temp

ptr = temp;

                                       ptr
                                        |
+---+        +---+        +---+         |
|"C"| next   |"B"| next   |"A"| next    v
|   |------> |   |------> |   |------> null
+---+        +---+        +---+         ^
  ^                                     |
  |                                     |
previous                               temp

Now, while (ptr != null) is false. The loop ends and previous, which is the new head is returned.

This method reverse the order of a linked list and returns the head.


问:
What is the reason to initialize or assign an empty string literal to a pointer to char in C, or a pointer to const char in C++?
My question is actually quite simply for those who might know about it, but I ask because I'm not aware of this technique already.

What is the reason for initializing or assigning an empty string literal to a pointer to char in C, or a pointer to const char in C++?

Like f.e.:

```<code>char* p = "";
</code>```

or

```<code>char* p;
p = "";
</code>```

Or, as suggested in the comments, in C++:

```<code>const char* p = "";
</code>```

or

```<code>const char* p;
p = "";
</code>```

I do often see this technique, but don't understand why someone shall assign an empty string literal to a char pointer (or pointer to const char for C++) or where this is coming from.

I have read Initialize a string in C to empty string, but this question is focused on initializing a char array with an empty string.

And I have also read: Initializing a string with the empty string, but this question covers an incorrect approach to assign an empty string to a pointer earlier returned by a malloc() function.

答:
It depends entirely on what follows. For example, the following would be acceptable:

```<code>const char *p = "";

if (f()) {
   p = "Foo";
}
else if (g())
   p = "Bar";
}

strcat(msg, p);
</code>```

That said, this isn't a likely scenario. The value subsequently assigned to p is probably a pointer to dynamically-allocated memory which requires freeing, but "" can't be freed, so you'd end up with

```<code>char *p = "";
int free_it = 0;

if (f()) {
   p = ff();
   free_it = 1;
}
else if (g())
   p = gg();
   free_it = 1;
}

strcat(msg, p);
if (free_it)
   free(p);
</code>```

when you could just as easily to

```<code>char *p = NULL;

if (f()) {
   p = ff();
}
else if (g())
   p = gg();
}

if (p)
   strcat(msg, p);

free(p);
</code>```

The approach taken in the question you linked in the comments leads to an inability to free the values. It would make more sense to have a node allocator and a node destructor.

```<code>int Node_init(Node *node, const char *value) {
    char *value_ = strdup(value);
    if (!value_)
       return 0;

    node->value = value_;
    node->sibling = NULL;
    node->child = NULL;
    return 1;
}

Node *Node_new(const char *value) {
   Node *node = malloc(sizeof(Node));
   if (!node) {
      return NULL;
   }

   if (!Node_init(node, value)) {
      free(node);
      return NULL;
   }

   return node;
}

void Node_destroy(Node *node) {
    free(node->value);
}

void Node_delete(Node *node) {
   Node_destroy(node);
   free(node);
}

int main(void) {
   Node root;
   Node_init(&root, "");
   ...
   Node_destroy(&root);
}
</code>```

Body:
My question is actually quite simply for those who might know about it, but I ask because I'm not aware of this technique already.

What is the reason for initializing or assigning an empty string literal to a pointer to char in C, or a pointer to const char in C++?

Like f.e.:

char* p = "";

or

char* p;
p = "";

Or, as suggested in the comments, in C++:

const char* p = "";

or

const char* p;
p = "";

I do often see this technique, but don't understand why someone shall assign an empty string literal to a char pointer (or pointer to const char for C++) or where this is coming from.

I have read Initialize a string in C to empty string, but this question is focused on initializing a char array with an empty string.

And I have also read: Initializing a string with the empty string, but this question covers an incorrect approach to assign an empty string to a pointer earlier returned by a malloc() function.

Body:
It depends entirely on what follows. For example, the following would be acceptable:

const char *p = "";

if (f()) {
   p = "Foo";
}
else if (g())
   p = "Bar";
}

strcat(msg, p);

That said, this isn't a likely scenario. The value subsequently assigned to p is probably a pointer to dynamically-allocated memory which requires freeing, but "" can't be freed, so you'd end up with

char *p = "";
int free_it = 0;

if (f()) {
   p = ff();
   free_it = 1;
}
else if (g())
   p = gg();
   free_it = 1;
}

strcat(msg, p);
if (free_it)
   free(p);

when you could just as easily to

char *p = NULL;

if (f()) {
   p = ff();
}
else if (g())
   p = gg();
}

if (p)
   strcat(msg, p);

free(p);

The approach taken in the question you linked in the comments leads to an inability to free the values. It would make more sense to have a node allocator and a node destructor.

int Node_init(Node *node, const char *value) {
    char *value_ = strdup(value);
    if (!value_)
       return 0;

    node->value = value_;
    node->sibling = NULL;
    node->child = NULL;
    return 1;
}

Node *Node_new(const char *value) {
   Node *node = malloc(sizeof(Node));
   if (!node) {
      return NULL;
   }

   if (!Node_init(node, value)) {
      free(node);
      return NULL;
   }

   return node;
}

void Node_destroy(Node *node) {
    free(node->value);
}

void Node_delete(Node *node) {
   Node_destroy(node);
   free(node);
}

int main(void) {
   Node root;
   Node_init(&root, "");
   ...
   Node_destroy(&root);
}


问:
Convert String to boolean only if input is "true" or "false"
How can I make sure that the input of a String is either "true" or "false" and then parse it to a boolean?

For example:

```<code>String input = "true"; -> boolean result = true;
String input = "false"; -> boolean result = false;
String input = "foobar"; -> throw new InvalidInputException("true or false is allowed");
</code>```

答:
Try some thing like this : </p>

```<code>String s = input.toLowerCase();
Boolean b ;
if ("true".equals(s) || "false".equals(s)) {
   b= Boolean.parseBoolean(s);
}
else  {
    throw new InvalidInputException("true or false is allowed");
}
</code>```

<p>I hope this helps </p>

Body:
How can I make sure that the input of a String is either "true" or "false" and then parse it to a boolean?

For example:

String input = "true"; -> boolean result = true;
String input = "false"; -> boolean result = false;
String input = "foobar"; -> throw new InvalidInputException("true or false is allowed");

Body:
Try some thing like this :

String s = input.toLowerCase();
Boolean b ;
if ("true".equals(s) || "false".equals(s)) {
   b= Boolean.parseBoolean(s);
}
else  {
    throw new InvalidInputException("true or false is allowed");
}

I hope this helps


问:
How do I use cordova-plugin-admob-free in Ionic 5
I am getting the following error when I try to add AdMob to my Ionic 5 app....

"export 'AdMobFreeOriginal' was not found in '@ionic-native/admob-free'

My code....

```<code>import { AdMobFreeOriginal, AdMobFreeBannerConfig } from '@ionic-native/admob-free';

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
    imports: [
        BrowserModule,
        IonicModule.forRoot(),
        AppRoutingModule,
        HttpClientModule,    ],
  providers: [
    StatusBar,
      SplashScreen,
      AdMobFreeOriginal,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}
</code>```

答:
Import the plugin with /ngx at the end. You are also using an incorrect import. See the quote below.

```<code>@ionic-native/admob-free/ngx
</code>```

You can always lookup the plugin on their repository. The import is stated in the plugin file:

@usage

  * ```typescript

  * import { AdMobFree, AdMobFreeBannerConfig } from '@ionic-native/admob-free/ngx';

https://github.com/ionic-team/ionic-native/blob/master/src/%40ionic-native/plugins/admob-free/index.ts

Body:
I am getting the following error when I try to add AdMob to my Ionic 5 app....

"export 'AdMobFreeOriginal' was not found in '@ionic-native/admob-free'

My code....

import { AdMobFreeOriginal, AdMobFreeBannerConfig } from '@ionic-native/admob-free';

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
    imports: [
        BrowserModule,
        IonicModule.forRoot(),
        AppRoutingModule,
        HttpClientModule,    ],
  providers: [
    StatusBar,
      SplashScreen,
      AdMobFreeOriginal,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

Body:
Import the plugin with /ngx at the end. You are also using an incorrect import. See the quote below.

@ionic-native/admob-free/ngx

You can always lookup the plugin on their repository. The import is stated in the plugin file:

@usage

  * ```typescript

  * import { AdMobFree, AdMobFreeBannerConfig } from '@ionic-native/admob-free/ngx';

https://github.com/ionic-team/ionic-native/blob/master/src/%40ionic-native/plugins/admob-free/index.ts


问:
How i can count the instance of ckeditor exist on webpage in javascript?
How i can count the instance of ckeditor exist on webpage in javascript ? can anyone show me sample code for that ?</p>

答:
Just do it manually,There may be an easy way to do it . It is simple idea.

try it

for example

```<code>var total_ck = new array();

var oEditor1 = FCKeditorAPI.GetInstance('field1');//instance 1

total_ck.push("field1");

var oEditor2 = FCKeditorAPI.GetInstance('field2');//instance 2
total_ck.push("field2");

var oEditor3 = FCKeditorAPI.GetInstance('field3');//instance 3
total_ck.push("field3");

var numberof_fck = total_ck.length;

alert(numberof_fck );
</code>```

Body:
Just do it manually,There may be an easy way to do it . It is simple idea.

try it

for example

var total_ck = new array();

var oEditor1 = FCKeditorAPI.GetInstance('field1');//instance 1

total_ck.push("field1");

var oEditor2 = FCKeditorAPI.GetInstance('field2');//instance 2
total_ck.push("field2");

var oEditor3 = FCKeditorAPI.GetInstance('field3');//instance 3
total_ck.push("field3");

var numberof_fck = total_ck.length;

alert(numberof_fck );


问:
Auth0: Limiting access based on scopes
I'm in the process of setting up authorization for a Web API.
The API will both be receiving post/put requests from a m2m application, and get/post/put requests from a front-end application.

I understand that I can use scopes to limit the access that these applications receive, but I have no idea how to implement it.

I've made the scopes I require, but how do I actually check the scopes, and then grant access to GET/POST etc based on that?

If this is a stupid question, I apologize. I've only been programming for a year.

答:
You should read about or look into Role-based authorization (https://learn.microsoft.com/en-us/aspnet/core/security/authorization/roles?view=aspnetcore-3.1) - Note that URL to the Microsoft Docs are for DotNet Core version 3.1

If configured correctly, you can use annotation on top of your methods that you want to specify a scope:

[Authorize(Roles = "Administrator")]
public class AdministrationController : Controller
{
}
```

<p>or</p>

<pre class="lang-cs prettyprint-override"><code>[Authorize(Roles = "Administrator, PowerUser")]
public class ControlPanelController : Controller
{
    public ActionResult SetTime()
    {
    }

    [Authorize(Roles = "Administrator")]
    public ActionResult ShutDown()
    {
    }
}
</code>```

Then you could create a Role for your M2M application and allow this application only specific methods and the users that use your frontend can have other roles. As you can see in the second example, you can set Authoriziation Roles on the Controller itself and then later on your methods bring the scope down.

Title: Auth0: Limiting access based on scopes

Body:
You should read about or look into Role-based authorization (https://learn.microsoft.com/en-us/aspnet/core/security/authorization/roles?view=aspnetcore-3.1) - Note that URL to the Microsoft Docs are for DotNet Core version 3.1

If configured correctly, you can use annotation on top of your methods that you want to specify a scope:

[Authorize(Roles = "Administrator")]
public class AdministrationController : Controller
{
}

or

[Authorize(Roles = "Administrator, PowerUser")]
public class ControlPanelController : Controller
{
    public ActionResult SetTime()
    {
    }

    [Authorize(Roles = "Administrator")]
    public ActionResult ShutDown()
    {
    }
}

Then you could create a Role for your M2M application and allow this application only specific methods and the users that use your frontend can have other roles. As you can see in the second example, you can set Authoriziation Roles on the Controller itself and then later on your methods bring the scope down.


问:
Column does not allow DBNull.Value and Remove does not help. Why?
I am getting the error:

Column 'Code' does not allow DBNull.Value

Here is my code:

```<code>public async Task UpdateDBWithXML(XmlReader reader, string hashKey, string hash)
        {
            var table = new DataTable();
            table.Columns.Add("Code");
            table.Columns.Add("ShortName");
            table.Columns.Add("Name");
            table.Columns.Add("LegalAddress");
            table.Columns.Add("Status");

            using (var transaction = this.Context.Database.BeginTransaction(IsolationLevel.ReadUncommitted))
            using (var sqlBulk = new SqlBulkCopy((SqlConnection)this.Connection, SqlBulkCopyOptions.Default, transaction.UnderlyingTransaction as SqlTransaction))
            {
                this.Context.Database.ExecuteSqlCommand("DELETE FROM [dbo].[LegalContractors]");

                sqlBulk.DestinationTableName = "LegalContractors";

                string lastElement = null;
                DataRow lastRow = null;
                while (reader.Read())
                {
                    switch (reader.NodeType)
                    {
                        case XmlNodeType.Element:
                            if(reader.Name == "RECORD")
                            {
                                if (table.Rows.Count > 0 && lastRow.IsNull("Code"))
                                {
                                    table.Rows.Remove(lastRow);
                                }
                                if (table.Rows.Count > 10000)
                                {
                                    await sqlBulk.WriteToServerAsync(table);
                                    table.Rows.Clear();
                                }

                                lastRow = table.Rows.Add();
                            }
                            lastElement = reader.Name;
                            break;
                        case XmlNodeType.Text:
                            ProcessList(lastElement, reader.Value, lastRow);
                            break;
                    }
                }

                if (table.Rows.Count > 0 && lastRow.IsNull("Code"))
                {
                    table.Rows.Remove(lastRow);
                }
                if (table.Rows.Count > 0)
                {
                    await sqlBulk.WriteToServerAsync(table);
                    table.Rows.Clear();
                }

                //update hash here

                transaction.Commit();
            }
        }

        private void ProcessList(string lastElement, string value, DataRow row)
        {
            switch (lastElement)
            {
                case "NAME":
                    row["Name"] = value;
                    break;

                case "SHORT_NAME":
                    row["ShortName"] = value;
                    break;

                case "EDRPOU":
                    row["Code"] = value;
                    break;

                case "ADDRESS":
                    row["LegalAddress"] = value;
                    break;

                case "STAN":
                    row["Status"] = value;
                    break;
            }
        }
</code>```

As you can see I am removing the DataRows with the empty 'Code'. Why may the error happen then? Should I use a different API for the deletion?

I tried the approach suggested in this question: use the lastRow["Code"] == DBNull.Value instead of the lastRow.IsNull("Code"). That did not help as well.

Here is the sample XML I am parsing:

```<code><?xml version="1.0" encoding="windows-1251"?>
<DATA FORMAT_VERSION="1.0">
    <RECORD>
        <NAME>МІЖНАРОДНА ГРОМАДСЬКА ОРГАНІЗАЦІЯ МІЖНАРОДНА АКАДЕМІЯ БІОЕНЕРГОТЕХНОЛОГІЙ</NAME>
        <SHORT_NAME>МАБЕТ</SHORT_NAME>
        <EDRPOU>00011601</EDRPOU>
        <ADDRESS>01001, м.Київ, Шевченківський район, ВУЛИЦЯ ПРОРІЗНА, будинок 8, офіс 426</ADDRESS>
        <BOSS>ТКАЧЕНКО ВОЛОДИМИР АНДРІЙОВИЧ</BOSS>
        <KVED>94.12 Діяльність професійних громадських організацій</KVED>
        <STAN>зареєстровано</STAN>
        <FOUNDERS>
            <FOUNDER>Члени організації, розмір внеску до статутного фонду - 0.00 грн.</FOUNDER>
        </FOUNDERS>
    </RECORD>
    <RECORD>
        <NAME>фоо</NAME>
        <SHORT_NAME>фоо короткое имя</SHORT_NAME>
        <EDRPOU></EDRPOU>
        <ADDRESS>фоо адрес</ADDRESS>
        <BOSS>фоо бос</BOSS>
        <KVED>фоо квед</KVED>
        <STAN>фоо состояние</STAN>
        <FOUNDERS>
            <FOUNDER>фоо организатор</FOUNDER>
        </FOUNDERS>
    </RECORD>
</DATA>
</code>```

答:
Your XML  doesn't contain a column called code, neither does ProcessList() create it.  Yet it is in your table definition so it would appear that it is always null.

I suspect your SQL Table structure has set that column Code does not allow nulls and so the SQL update is throwing the error.

You either need to populate the Code column with something, or set it to allow nulls or have a default value in the database.

Body:
I am getting the error:

Column 'Code' does not allow DBNull.Value

Here is my code:

public async Task UpdateDBWithXML(XmlReader reader, string hashKey, string hash)
        {
            var table = new DataTable();
            table.Columns.Add("Code");
            table.Columns.Add("ShortName");
            table.Columns.Add("Name");
            table.Columns.Add("LegalAddress");
            table.Columns.Add("Status");

            using (var transaction = this.Context.Database.BeginTransaction(IsolationLevel.ReadUncommitted))
            using (var sqlBulk = new SqlBulkCopy((SqlConnection)this.Connection, SqlBulkCopyOptions.Default, transaction.UnderlyingTransaction as SqlTransaction))
            {
                this.Context.Database.ExecuteSqlCommand("DELETE FROM [dbo].[LegalContractors]");

                sqlBulk.DestinationTableName = "LegalContractors";

                string lastElement = null;
                DataRow lastRow = null;
                while (reader.Read())
                {
                    switch (reader.NodeType)
                    {
                        case XmlNodeType.Element:
                            if(reader.Name == "RECORD")
                            {
                                if (table.Rows.Count > 0 && lastRow.IsNull("Code"))
                                {
                                    table.Rows.Remove(lastRow);
                                }
                                if (table.Rows.Count > 10000)
                                {
                                    await sqlBulk.WriteToServerAsync(table);
                                    table.Rows.Clear();
                                }

                                lastRow = table.Rows.Add();
                            }
                            lastElement = reader.Name;
                            break;
                        case XmlNodeType.Text:
                            ProcessList(lastElement, reader.Value, lastRow);
                            break;
                    }
                }

                if (table.Rows.Count > 0 && lastRow.IsNull("Code"))
                {
                    table.Rows.Remove(lastRow);
                }
                if (table.Rows.Count > 0)
                {
                    await sqlBulk.WriteToServerAsync(table);
                    table.Rows.Clear();
                }

                //update hash here

                transaction.Commit();
            }
        }

        private void ProcessList(string lastElement, string value, DataRow row)
        {
            switch (lastElement)
            {
                case "NAME":
                    row["Name"] = value;
                    break;

                case "SHORT_NAME":
                    row["ShortName"] = value;
                    break;

                case "EDRPOU":
                    row["Code"] = value;
                    break;

                case "ADDRESS":
                    row["LegalAddress"] = value;
                    break;

                case "STAN":
                    row["Status"] = value;
                    break;
            }
        }

As you can see I am removing the DataRows with the empty 'Code'. Why may the error happen then? Should I use a different API for the deletion?

I tried the approach suggested in this question: use the lastRow["Code"] == DBNull.Value instead of the lastRow.IsNull("Code"). That did not help as well.

Here is the sample XML I am parsing:

<?xml version="1.0" encoding="windows-1251"?>
<DATA FORMAT_VERSION="1.0">
    <RECORD>
        <NAME>МІЖНАРОДНА ГРОМАДСЬКА ОРГАНІЗАЦІЯ МІЖНАРОДНА АКАДЕМІЯ БІОЕНЕРГОТЕХНОЛОГІЙ</NAME>
        <SHORT_NAME>МАБЕТ</SHORT_NAME>
        <EDRPOU>00011601</EDRPOU>
        <ADDRESS>01001, м.Київ, Шевченківський район, ВУЛИЦЯ ПРОРІЗНА, будинок 8, офіс 426</ADDRESS>
        <BOSS>ТКАЧЕНКО ВОЛОДИМИР АНДРІЙОВИЧ</BOSS>
        <KVED>94.12 Діяльність професійних громадських організацій</KVED>
        <STAN>зареєстровано</STAN>
        <FOUNDERS>
            <FOUNDER>Члени організації, розмір внеску до статутного фонду - 0.00 грн.</FOUNDER>
        </FOUNDERS>
    </RECORD>
    <RECORD>
        <NAME>фоо</NAME>
        <SHORT_NAME>фоо короткое имя</SHORT_NAME>
        <EDRPOU></EDRPOU>
        <ADDRESS>фоо адрес</ADDRESS>
        <BOSS>фоо бос</BOSS>
        <KVED>фоо квед</KVED>
        <STAN>фоо состояние</STAN>
        <FOUNDERS>
            <FOUNDER>фоо организатор</FOUNDER>
        </FOUNDERS>
    </RECORD>
</DATA>


问:
How to Compare two files using AWK or GREP
So I have two questions, I have two files where I am trying to sort and filter. In these two files they each have two columns wherein file1 there is IP and Port and in file2 there is domain and IP.

```<code>file1:

Address,Port
1.2.3.4,8080
4.5.6.7,80
6.7.8.9,443

file2:

Domain,IP
google.com,1.2.3.4
google.fe,6.7.8.9
admin.ko,3.2.4.5
</code>```

So the first question: I want to find IPs in file1 that don't match any IP's located in file2.

I have tried using awk, and here is what I used:

```<code>awk -F',' FNR==NR{ a[$2]; next } !($1 in a)' file2 file1
</code>```

So I really don't understand awk really well, so could someone also assist me in understanding each section of that awk command you provide :)

```<code>Desired output:

Address,Port,Status
1.2.3.4,8080,Present
4.5.6.7,80,Not-Present
6.7.8.9,443,Present
</code>```

The next question, I have no idea how to do it so kindly assist.

Second question: so I want to list the same desired Output as the first one but this time I want to add the domain column.

```<code>Desired output:

Address,Port,Domain,Status
1.2.3.4,8080,google.com,Present
4.5.6.7,80,NULL,Not-Present
6.7.8.9,443,google.fe,Present
</code>```

Thank you in advance.

答:
```<code>awk -F,  '
          BEGIN{OFS=","}/*Set output file descriptor*/
          FNR==1{next} /*Skip in case of header*/
          NR==FNR{a[$2]=$1;next}/*Store ips in associative array from file2 */
          {/* Process records in file1*/
           if(a[$1])
                   {$3="present"}
           else
                   {$3="not present"}
          print
          }' file2 file1
</code>```

Body:
So I have two questions, I have two files where I am trying to sort and filter. In these two files they each have two columns wherein file1 there is IP and Port and in file2 there is domain and IP.

file1:

Address,Port
1.2.3.4,8080
4.5.6.7,80
6.7.8.9,443

file2:

Domain,IP
google.com,1.2.3.4
google.fe,6.7.8.9
admin.ko,3.2.4.5

So the first question: I want to find IPs in file1 that don't match any IP's located in file2.

I have tried using awk, and here is what I used:

awk -F',' FNR==NR{ a[$2]; next } !($1 in a)' file2 file1

So I really don't understand awk really well, so could someone also assist me in understanding each section of that awk command you provide :)

Desired output:

Address,Port,Status
1.2.3.4,8080,Present
4.5.6.7,80,Not-Present
6.7.8.9,443,Present

The next question, I have no idea how to do it so kindly assist.

Second question: so I want to list the same desired Output as the first one but this time I want to add the domain column.

Desired output:

Address,Port,Domain,Status
1.2.3.4,8080,google.com,Present
4.5.6.7,80,NULL,Not-Present
6.7.8.9,443,google.fe,Present

Thank you in advance.


问:
Seaborn heatmap, lines not of the same width
I'm plotting an heatmap with Seaborn. If I set lines that divide each cell with "linewidth=value", the lines are printed, but their width is not the same. (e.g. in my plot below the external vertical lines are thinner than the internal ones and the horizontal line between 1 and 2 is thicker than the other two).

Here's a simple code that recreates the issue:

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns;sns.set()

plt.figure(figsize=(10,5))
df = np.random.rand(4,6)
ax = sns.heatmap(df,cmap="Blues",linewidths=1,linecolor='k')
plt.show()
```

And here's the heatmap that I get:

Why are the lines of different width when linewidths is 1 for all of them?

Let's ignore the fact that the first and last row of cells are smaller than the others, I know that that's an issue with the matplotlib version.

答:
I was having the same problem.
Passing rasterized=False as parameter to sns.heatmap() fixed it for me.

Body:
I'm plotting an heatmap with Seaborn. If I set lines that divide each cell with "linewidth=value", the lines are printed, but their width is not the same. (e.g. in my plot below the external vertical lines are thinner than the internal ones and the horizontal line between 1 and 2 is thicker than the other two).

Here's a simple code that recreates the issue:

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns;sns.set()

plt.figure(figsize=(10,5))
df = np.random.rand(4,6)
ax = sns.heatmap(df,cmap="Blues",linewidths=1,linecolor='k')
plt.show()

And here's the heatmap that I get:

Why are the lines of different width when linewidths is 1 for all of them?

Let's ignore the fact that the first and last row of cells are smaller than the others, I know that that's an issue with the matplotlib version.


问:
Null Pointer Exception accessing Dataframe
```<code>val opt2 :Option[DataFrame]= None

val result:Option[DataFrame] =opt2.getOrElse(None)
if (!result.isEmpty) {
result.show()
}
</code>```

If i don't use getOrElse and use get instead , I am getting Null pointer exception.

If i use getOrElse , i m getting type Mismatch in result .How to fix. Also is there is any method like creatingEmpty Dataframe.

答:
Spark provide pre-defined function to declare empty dataframe.

Please note, In below code spark in SparkSession.

```<code>scala> import org.apache.spark.sql.SparkSession

scala> val df = spark.emptyDataFrame
df: org.apache.spark.sql.DataFrame = []

scala> df.show()
++
||
++
++
</code>```

Body:
val opt2 :Option[DataFrame]= None

val result:Option[DataFrame] =opt2.getOrElse(None)
if (!result.isEmpty) {
result.show()
}

If i don't use getOrElse and use get instead , I am getting Null pointer exception.

If i use getOrElse , i m getting type Mismatch in result .How to fix. Also is there is any method like creatingEmpty Dataframe.

Body:
Spark provide pre-defined function to declare empty dataframe.

Please note, In below code spark in SparkSession.

scala> import org.apache.spark.sql.SparkSession

scala> val df = spark.emptyDataFrame
df: org.apache.spark.sql.DataFrame = []

scala> df.show()
++
||
++
++


问:
When should copy-local be set to true and when should it not?
I am wondering if there are any heuristics for when to set copy-local=true for references?

If referenced types are only used internally can I set copy-local to true but if referenced types are exposed as parameters or return values I set copy-local to false and indicate that a specific version of the dependency should be referenced when my library should be used?

Can anyone clarify this for me?

答: It's really about the target environment. If copy local is false, you're saying that the assembly will already exist in the target environment (normally in the GAC). Setting it to true ensures it will appear in the output of your build, so makes it easier to deploy to the target environment.</p>

OwnerDisplayName: Fadeproof

LastEditorDisplayName: Gortok

OwnerDisplayName: Kent Boogaart


问:
System.ArgumentException Column <ColumnName> does not belong to table
I am having a problem when accessing a DataColumn value in datatable with its name the System.ArgumentException Column <ColumnName> does not belong to table occurs for some of the columns. However the column exists in the database but with a different case. I thought DataTable column names are case insensitive. Any 1 got any idea why I am getting this. On a different machine this code is working fine. I don't think it has any thing to do with SQL Coallation but in this case the coallation are same on both SQL servers.

```<code>vpg_awardtype = row["vpg_awardtype"];
vpg_eventcount = row["vpg_eventcount"];
</code>```

If i change it to the following then it's working:

```<code>vpg_awardtype = row["Vpg_AwardType"];
vpg_eventcount = row["Vpg_EventCount"];
</code>```

答:
I've resolved it. Basically when a DataTable contains a simillar column name whose name is only different in Case i.e AwardType and awardType are same column names but only different in spelling case. If such a collision occur inside a DataTable This makes the access to all DataTable columns as case sensitive.

In my case there was some joins applied by a developer to get the data in the datatable. However the number of columns were not filtered and unfortunately in 2 different tables one of the column name was simillar but written with different case. I wasn't able to notice that because the datatable was huge. Finally I found this out the hard way. Hence aliasing one of the column name worked for me.

Body:
I am having a problem when accessing a DataColumn value in datatable with its name the System.ArgumentException Column <ColumnName> does not belong to table occurs for some of the columns. However the column exists in the database but with a different case. I thought DataTable column names are case insensitive. Any 1 got any idea why I am getting this. On a different machine this code is working fine. I don't think it has any thing to do with SQL Coallation but in this case the coallation are same on both SQL servers.

vpg_awardtype = row["vpg_awardtype"];
vpg_eventcount = row["vpg_eventcount"];

If i change it to the following then it's working:

vpg_awardtype = row["Vpg_AwardType"];
vpg_eventcount = row["Vpg_EventCount"];


问:
Axios to generate Nuxt dynamic routes based on query
I have dynamic pages' routes being generated in nuxt.config.js like this:

```<code>  generate:{
    routes: function () {
      return axios.get(apiUrl + '/pages')
        .then((res) => {
          return res.data.map(page => {
            return page.slug
          })
      })
    }
  }
</code>```

This works fine, however, my pages have a name "publish" which can be true or false.

How can I filter them?
Thanks

答:
Ok I think I found it, this seems to work!</p>

```<code>  generate:{
    routes: function () {
      return axios.get(apiUrl + '/pages')
        .then((res) => {
          return res.data.filter(page => {
            return page.publish === true;
          }).map(page => {
            return page.slug
          })
      })
    }
  }
</code>```

Body:
I have dynamic pages' routes being generated in nuxt.config.js like this:

  generate:{
    routes: function () {
      return axios.get(apiUrl + '/pages')
        .then((res) => {
          return res.data.map(page => {
            return page.slug
          })
      })
    }
  }

This works fine, however, my pages have a name "publish" which can be true or false.

How can I filter them?
Thanks

Body:
Ok I think I found it, this seems to work!

  generate:{
    routes: function () {
      return axios.get(apiUrl + '/pages')
        .then((res) => {
          return res.data.filter(page => {
            return page.publish === true;
          }).map(page => {
            return page.slug
          })
      })
    }
  }


问:
Prompt asking for password then redirecting
I'm very new to PHP and JavaScript and I'm stuck. I spent a good 7 hours so far trying to figure this one out but I just do not know what or how to do it. So in my application, when you try to add a new row to my table, I have a html form to get the data. When you enter the data into the form, and press submit, it prompts for a password, and if the correct password is put in, it submits the form. It work just as I wanted it, here is what I have:

```<code><button onclick="password()" type="button">Create New Hero</button>
    <div>
        <a id="discl">*-Required Fields</a>
    </div>
    <script>
        function password(){
            var password = prompt("Please Enter the Admin Password");
            if(password != "shaun"){
                alert("Wrong Password");
            }
            else{
                if(validation()){
                document.getElementById("form_id").submit();
                }
                else{
                    alert("One or more required fields were left empty, or tried to use <script>");
                }
            }
        }
        function validation(){
            var f = document.getElementById("f_name").value;
            var l = document.getElementById("l_name").value;
            var d = document.getElementById("dob").value;
            var a = document.getElementById("alias").value;
            if(f == "" || l == "" || d == "" || f.includes("<script>") || l.includes("<script>") || a.includes("<script>")){
                return false;
            }
            else{
                return true;
            }
        }
    </script>
</code>```

Now I also have an edit and delete on my table. My problem is that with edit and delete, they are in  tags with an href, and they are not buttons. This is how they originally looked when it worked without asking for a password:

```<code>               echo "<a href='./edit.php?id={$row['id']}'>edit</a>";
</code>```

So based on which row of the table it was, where you clicked edit or delete, based on the row's id from the database, it would edit or delete that table. Now my problem is I don't know how to properly set up the function so it asks for the password and redirect to the right url. This is what I have right now:

```<code>           foreach($results as $row){
            echo "<tr>";
            echo "<td>{$row['first_name']}</td>";
            echo "<td>{$row['last_name']}</td>";
            echo "<td>{$row['date_of_birth']}</td>";
            echo "<td>{$row['alias']}</td>";
            echo "<td>{$row['active']}</td>";
            echo "<td>{$row['hero']}</td>";
            echo "<td>";
            echo "<a href='./edit.php?id={$row['id']}'>edit</a>";
            echo " | ";
            echo "<a  href='javascript: password()'>delete</a>";
            echo "</td>";
            echo "</tr>";
        }
        ?>
        <script type="text/javascript">
        function password(){
            var password = prompt("Please Enter the Admin Password");
            if(password != "shaun"){
                alert("Wrong Password");
            }
            else{
                window.location.replace("./delete.php?id=<?php echo $row['id']; ?>");
            }
        }
    </script>
</code>```

The problem with this is that no matter which delete I click on on my table, it always deletes the last one, because the ID it's getting out after the url is the last available ID from my database. I'm not sure if I'm just missing something small, or I'm completely on the wrong path but any help would be appreciated because I'm very lost. Thank you

答:
It is the target request, not the calling page which requires authentication, otherwise anybody could call the ./delete.php?... url and delete a row in the database.

This is usually done by maintaining a session, which remembers a login of the user. The delete.php request can then check whether the user is already logged in / has admin privileges, or demand the password when necessary.

Body:
I'm very new to PHP and JavaScript and I'm stuck. I spent a good 7 hours so far trying to figure this one out but I just do not know what or how to do it. So in my application, when you try to add a new row to my table, I have a html form to get the data. When you enter the data into the form, and press submit, it prompts for a password, and if the correct password is put in, it submits the form. It work just as I wanted it, here is what I have:

<button onclick="password()" type="button">Create New Hero</button>

        *-Required Fields

Now I also have an edit and delete on my table. My problem is that with edit and delete, they are in  tags with an href, and they are not buttons. This is how they originally looked when it worked without asking for a password:

               echo "edit";

So based on which row of the table it was, where you clicked edit or delete, based on the row's id from the database, it would edit or delete that table. Now my problem is I don't know how to properly set up the function so it asks for the password and redirect to the right url. This is what I have right now:

           foreach($results as $row){
            echo "
";
            echo "{$row['first_name']}	";
            echo "{$row['last_name']}	";
            echo "{$row['date_of_birth']}	";
            echo "{$row['alias']}	";
            echo "{$row['active']}	";
            echo "{$row['hero']}	";
            echo "";
            echo "edit";
            echo " | ";
            echo "delete";
            echo "	";
            echo "
";
        }
        ?>

The problem with this is that no matter which delete I click on on my table, it always deletes the last one, because the ID it's getting out after the url is the last available ID from my database. I'm not sure if I'm just missing something small, or I'm completely on the wrong path but any help would be appreciated because I'm very lost. Thank you


问:
How do I alter the position of a column in a PostgreSQL database table?
I've tried the following, but I was unsuccessful:</p>

```<code>ALTER TABLE person ALTER COLUMN dob POSITION 37;
</code>```

答:
There are some workarounds to make it possible:

Recreating the whole table

Create new columns within the current table

Create a view

https://tableplus.com/blog/2018/09/postgresql-is-it-possible-to-alter-column-order-position-in-a-table.html

OwnerDisplayName: Huuuze

Body:
I've tried the following, but I was unsuccessful:

ALTER TABLE person ALTER COLUMN dob POSITION 37;


问:
Why does my Shiny iframe tell me "localhost didn’t send any data" when trying to display a local PDF?

Intention:

I'm trying to build a Shiny app that contains a pdf viewer. I'm trying my best to replicate this example:

displaying a pdf from a local drive in shiny

Problem:

In the reprex below, I download a dummy pdf into the 'www' directory in the same root as 'App.R'.

As far as I can understand, the http protocols innate to Shiny apps require me to set the source for the iframe as "http://localhost/test.pdf", as opposed to "www/test.pdf". But when I run this code, I get an iframe with nothing but this in:

I've also followed the additional advice in the previously mentioned SO thread - running the app using the 'Run App' button in RStudio, instead of Ctrl+return-ing through the code. No success. Anyone know how I can make this work?

Reprex:

require(shiny)
#> Loading required package: shiny

ui = fluidPage(
  htmlOutput("pdfViewer")
)

server = function(input, output, session) {
  ### Libraries
  require(pdftools)

  ### Create 'www' dir (understand that this
  ### is where 'localhost' stuff is kept?)
  suppressWarnings(dir.create("www"))

  ### Make a test pdf file using the w3 dummy pdf
  pdf = "www/test.pdf"
  download.file(url = "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf",
                       destfile = pdf)

  ### Define the http: address for the pdf
  pdfHttp = "http://localhost/test.pdf"

  output$pdfViewer =
    renderText({
      ### Copied this from here: "https://stackoverflow.com/a/21024943/11149547"
      return(paste('', sep = ""))
    })
}

shinyApp(ui = ui, server = server)
```
<h2>Appendix (R version data)</h2>
```> R.version
               _
platform       x86_64-w64-mingw32
arch           x86_64
os             mingw32
system         x86_64, mingw32
status
major          3
minor          6.1
year           2019
month          07
day            05
svn rev        76782
language       R
version.string R version 3.6.1 (2019-07-05)
nickname       Action of the Toes
```

答:
I needed to add a port to the local host address.

I've learnt that http://localhost is synonymous with http://127.0.0.1. I then noticed that when my Shiny App was running in browser, the omnibox listed the address as: 127.0.0.1:5056.

I replaced http://localhost/test.pdf in the above code with http://127.0.0.1:6056/test.pdf, and now the pdf loads.

I imagine this is related to the fact that I'm using my work computer, which part of a local network of some kind.

Edit:

Furthermore, you can explicitly define the port my running options(shiny.port = 6056) before you run runApp(server = server, ui = ui). I needed to do this in the end, because my other Shiny App (not reprex) launched to a different port.

Body:
Intention:

I'm trying to build a Shiny app that contains a pdf viewer. I'm trying my best to replicate this example:

displaying a pdf from a local drive in shiny

Problem:

In the reprex below, I download a dummy pdf into the 'www' directory in the same root as 'App.R'.

As far as I can understand, the http protocols innate to Shiny apps require me to set the source for the iframe as "http://localhost/test.pdf", as opposed to "www/test.pdf". But when I run this code, I get an iframe with nothing but this in:

I've also followed the additional advice in the previously mentioned SO thread - running the app using the 'Run App' button in RStudio, instead of Ctrl+return-ing through the code. No success. Anyone know how I can make this work?

Reprex:

require(shiny)
#> Loading required package: shiny

ui = fluidPage(
  htmlOutput("pdfViewer")
)

server = function(input, output, session) {
  ### Libraries
  require(pdftools)

  ### Create 'www' dir (understand that this
  ### is where 'localhost' stuff is kept?)
  suppressWarnings(dir.create("www"))

  ### Make a test pdf file using the w3 dummy pdf
  pdf = "www/test.pdf"
  download.file(url = "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf",
                       destfile = pdf)

  ### Define the http: address for the pdf
  pdfHttp = "http://localhost/test.pdf"

  output$pdfViewer =
    renderText({
      ### Copied this from here: "https://stackoverflow.com/a/21024943/11149547"
      return(paste('', sep = ""))
    })
}

shinyApp(ui = ui, server = server)

Appendix (R version data)

> R.version
               _
platform       x86_64-w64-mingw32
arch           x86_64
os             mingw32
system         x86_64, mingw32
status
major          3
minor          6.1
year           2019
month          07
day            05
svn rev        76782
language       R
version.string R version 3.6.1 (2019-07-05)
nickname       Action of the Toes


问:
How Can i remove duplicate from a list in Groovy
Hi I have a groovy code for JIRA.
Here I need to sort or remove duplicate value from the list.

Ex :

```<code>["154515 Sawgrass",
 "170985 Mexico APIs for Payments",
 "153026 CitiCards Consumer and Business Account Online (authenticated pgs), No CSI App ID",
 "153890 GC Citibank Online - Singapore IPB v3",
 "144564 Citibank Online (CBOL) US, Zack Dummy CSI #3",
 "171706 Quip",
 "167518 GC Eclipse [Teller]",
 "167518 GC Eclipse [Signature]]",]
</code>```

the above is the result, from where I need a sorting like ... 167518 - with this number there are two values, but I need to store only one 167518, I dont want to store multi value. or else in simple word I need to sort the list in this way that if number is same but with multiple values, I need to store only 1 value with same number.

```<code>// From here Child Issue Details Starts....
def issue = event.issue as Issue
def issueManager = ComponentAccessor.getIssueManager() ;
def customField = ComponentAccessor.getComponent(CustomFieldManager).getCustomFieldObject("customfield_10602")
log.debug("Printing Custom Field : --" + customField)
def impactedAppValues = customField.getValueFromIssue(issue) as String
log.info "Printing Custom Field with Issuee Value : --" + impactedAppValues

String[] elements = impactedAppValues.split("\\s*[;]\\s*");
log.info "Printing elements with Issuee Value : --" + elements

List<String> fixedLenghtList = Arrays.asList(elements);

ArrayList<String> listOfString = new ArrayList<String>(fixedLenghtList);

log.info "Printing listOfString with Issuee Value : --" + listOfString

// From here parent Issue Details Starts....
def cf = ComponentAccessor.customFieldManager.getCustomFieldObjectByName("Parent Link")
def parentValue = issue.getCustomFieldValue(cf)
log.info "Printing parentValue value :-----" + parentValue

def planviewProjectSide =  ComponentAccessor.getComponent(CustomFieldManager).getCustomFieldObject("customfield_10602");
Issue PlanviewIssue = issueManager.getIssueObject("" + parentValue);
def parentCustomField = planviewProjectSide.getValueFromIssue(PlanviewIssue) as String
log.info "Printing parentCustomField value :-----" + parentCustomField

String[] elements1 = parentCustomField.split("\\s*[;]\\s*");
log.info "Printing elements for Parent Issuee Value : --" + elements1

List<String> fixedLenghtList1 = Arrays.asList(elements1);

ArrayList<String> listOfString1 = new ArrayList<String>(fixedLenghtList1);

log.info "Printing listOfString1 For Parent Issuee Value : --" + listOfString1

listOfString1.addAll(listOfString)
log.info "Printing listOfString1 Againnnnnnnnn For Combined Value of 1 & 2--" + listOfString1

listOfString1.unique()
log.info "Printing listOfString1 Unique Values of 1 & 2--" + listOfString1

parentCustomField = listOfString1 as String
log.info "Printing parentCustomField -----" + parentCustomField

here I have gave the code for what I have written till now.
</code>```

Is this possible to to sort like the above? I mean we can remove the duplicates but how to removes the number from a value or String?

答:
You could extract the ID and put it in a SortedMap.
e.g.</p>

```<code>def data =
[ "154515 Sawgrass"
, "171706 Quip"
, "167518 GC Eclipse [Teller]"
, "167518 GC Eclipse [Signature]]" ]

println(
    data.collectEntries(new TreeMap()) {
        [it.findAll(/\d+/).first().toLong(), it]
    }
)
// → [154515:154515 Sawgrass, 167518:167518 GC Eclipse [Signature]], 171706:171706 Quip]
</code>```

Body:
Hi I have a groovy code for JIRA.
Here I need to sort or remove duplicate value from the list.

Ex :

["154515 Sawgrass",
 "170985 Mexico APIs for Payments",
 "153026 CitiCards Consumer and Business Account Online (authenticated pgs), No CSI App ID",
 "153890 GC Citibank Online - Singapore IPB v3",
 "144564 Citibank Online (CBOL) US, Zack Dummy CSI #3",
 "171706 Quip",
 "167518 GC Eclipse [Teller]",
 "167518 GC Eclipse [Signature]]",]

the above is the result, from where I need a sorting like ... 167518 - with this number there are two values, but I need to store only one 167518, I dont want to store multi value. or else in simple word I need to sort the list in this way that if number is same but with multiple values, I need to store only 1 value with same number.

// From here Child Issue Details Starts....
def issue = event.issue as Issue
def issueManager = ComponentAccessor.getIssueManager() ;
def customField = ComponentAccessor.getComponent(CustomFieldManager).getCustomFieldObject("customfield_10602")
log.debug("Printing Custom Field : --" + customField)
def impactedAppValues = customField.getValueFromIssue(issue) as String
log.info "Printing Custom Field with Issuee Value : --" + impactedAppValues

String[] elements = impactedAppValues.split("\\s*[;]\\s*");
log.info "Printing elements with Issuee Value : --" + elements

List<String> fixedLenghtList = Arrays.asList(elements);

ArrayList<String> listOfString = new ArrayList<String>(fixedLenghtList);

log.info "Printing listOfString with Issuee Value : --" + listOfString

// From here parent Issue Details Starts....
def cf = ComponentAccessor.customFieldManager.getCustomFieldObjectByName("Parent Link")
def parentValue = issue.getCustomFieldValue(cf)
log.info "Printing parentValue value :-----" + parentValue

def planviewProjectSide =  ComponentAccessor.getComponent(CustomFieldManager).getCustomFieldObject("customfield_10602");
Issue PlanviewIssue = issueManager.getIssueObject("" + parentValue);
def parentCustomField = planviewProjectSide.getValueFromIssue(PlanviewIssue) as String
log.info "Printing parentCustomField value :-----" + parentCustomField

String[] elements1 = parentCustomField.split("\\s*[;]\\s*");
log.info "Printing elements for Parent Issuee Value : --" + elements1

List<String> fixedLenghtList1 = Arrays.asList(elements1);

ArrayList<String> listOfString1 = new ArrayList<String>(fixedLenghtList1);

log.info "Printing listOfString1 For Parent Issuee Value : --" + listOfString1

listOfString1.addAll(listOfString)
log.info "Printing listOfString1 Againnnnnnnnn For Combined Value of 1 & 2--" + listOfString1

listOfString1.unique()
log.info "Printing listOfString1 Unique Values of 1 & 2--" + listOfString1

parentCustomField = listOfString1 as String
log.info "Printing parentCustomField -----" + parentCustomField

here I have gave the code for what I have written till now.

Is this possible to to sort like the above? I mean we can remove the duplicates but how to removes the number from a value or String?

Body:
You could extract the ID and put it in a SortedMap.
e.g.

def data =
[ "154515 Sawgrass"
, "171706 Quip"
, "167518 GC Eclipse [Teller]"
, "167518 GC Eclipse [Signature]]" ]

println(
    data.collectEntries(new TreeMap()) {
        [it.findAll(/\d+/).first().toLong(), it]
    }
)
// → [154515:154515 Sawgrass, 167518:167518 GC Eclipse [Signature]], 171706:171706 Quip]


问:
e.target.value gives me this error whenever i enter more than one letter react Uncaught TypeError: Cannot read property 'value' of null"
I am trying to update my useState value with the one in  so I am using
setObject(prev => ({...prev, MachineName: e.target.value }));
but whenever i enter more than a letter i get this error "Uncaught TypeError: Cannot read property 'value'
of null"

```<code>const [object, setObject] = useState({
   MachineName: "",
   Building: "",
   IP: ""
});

const actionHandler = () => {
  //setObject({ MachineName: " ", Building: " ", IP: " " });
};
function UpdateValue(e) {
    setObject(prev => ({ ...prev, MachineName: e.target.value }));
    console.log("Test", object.MachineName);
}
return (
  <Modal
    show={true}
    size="lg"
    aria-labelledby="contained-modal-title-vcenter"
    centered
  >
    <Modal.Header closeButton>
    <Modal.Title>New Machine</Modal.Title>
  </Modal.Header>
  <Modal.Body>
    <Form>
      <Row>
        <Col>
          <FloatingLabelInput
            id="1"
            className="FormFields"
            label="Machine Name"
            value={object.MachineName}
            onInput={e => UpdateValue(e)}
          />
        </Col>

      </Row>

    </Form>
  </Modal.Body>

</Modal>
);
</code>```

答:
Lets try to give some default values, and maybe bind the envirement(with arrow function) like this: </p>

```<code>const UpdateValue = e => {
  const { target = {} } = e || {};
  const { value = "" } = target || {};
  setObject(prev => ({ ...prev, MachineName: value }));
  console.log("Test", object.MachineName);
}
</code>```

Body:
I am trying to update my useState value with the one in  so I am using
setObject(prev => ({...prev, MachineName: e.target.value }));
but whenever i enter more than a letter i get this error "Uncaught TypeError: Cannot read property 'value'
of null"

const [object, setObject] = useState({
   MachineName: "",
   Building: "",
   IP: ""
});

const actionHandler = () => {
  //setObject({ MachineName: " ", Building: " ", IP: " " });
};
function UpdateValue(e) {
    setObject(prev => ({ ...prev, MachineName: e.target.value }));
    console.log("Test", object.MachineName);
}
return (
  <Modal
    show={true}
    size="lg"
    aria-labelledby="contained-modal-title-vcenter"
    centered
  >
    <Modal.Header closeButton>
    <Modal.Title>New Machine</Modal.Title>
  </Modal.Header>
  <Modal.Body>
    <Form>
      <Row>
        <Col>
          <FloatingLabelInput
            id="1"
            className="FormFields"
            label="Machine Name"
            value={object.MachineName}
            onInput={e => UpdateValue(e)}
          />
        </Col>

      </Row>

    </Form>
  </Modal.Body>

</Modal>
);

Body:
Lets try to give some default values, and maybe bind the envirement(with arrow function) like this:

const UpdateValue = e => {
  const { target = {} } = e || {};
  const { value = "" } = target || {};
  setObject(prev => ({ ...prev, MachineName: value }));
  console.log("Test", object.MachineName);
}