问:
Obtain List of Roles in EF Core 3.1
I would like to obtain a list of all identity roles in EF core without the use of UserManager/RoleManager. I am using EF Core 3.1

Currently in my startup:

```<code>services.AddIdentity<ApplicationUser, ApplicationRole>()
                .AddRoles<ApplicationRole>()
                .AddRoleManager<RoleManager<ApplicationRole>>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders(); //2FA
</code>```

Then in my Context:

```<code>public partial class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string>
    {
        public ApplicationDbContext()
        {

        }

        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {

        }
        //....
    }
</code>```

My ApplicationUser and ApplicationRole are defined as the following:

```<code>public class ApplicationUser : IdentityUser
    {
        public virtual UserProfile UserProfile { get; set; }
    }

public class ApplicationRole : IdentityRole<String>
    {
        public int Hierarchy { get; set; }

        public ApplicationRole() : base()
        {

        }

        public ApplicationRole(string roleName) : base(roleName)
        {

        }
    }
</code>```

Then I simply try calling in any controller I would like to access (_context is the ApplicationDBContext):

```<code>var list = _context.Roles.ToArray();
</code>```

In which I get the error:

```<code>Microsoft.Data.SqlClient.SqlException: 'Invalid column name 'ApplicationUserId'.'
</code>```

The ultimate goals is to add an ICollection of ApplicationRole to the ApplicationUser context since EF Core does not seem to support it. I am even unable to do a LINQ2Query join from UserRoles to Role.

Any help is appreciated as I've spent many hours on this.

答:
Alright I finally figured it out, in case anyone is wondering. It is not able to properly map the roles because the ApplicationDBContext is inheriting the wrong configuration of IdentityDbContext model. For this you must create your own class that inherits IdentityUserRole and implement the proper IdentityDBContext.

```<code>public partial class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string, IdentityUserClaim<string>, ApplicationUserRole, IdentityUserLogin<string>, IdentityRoleClaim<string>, IdentityUserToken<string>>
</code>```

Where ApplicationUser, ApplicationRole and ApplicationUserRole are your custom classes.

```<code>public class ApplicationUserRole : IdentityUserRole<string>
{
    public ApplicationUserRole() : base()
    {

    }

    public virtual ApplicationUser User { get; set; }

    public virtual ApplicationRole Role { get; set; }
}
</code>```

For some reason EF was trying to generate additional columns of "UserId1" and "RoleId1", to avoid this I simply instructed the model to take the inheritance of IdentityUserRole, make sure your Id properties match the TKey type.

Then I was able to properly evaluate the roles. Then to get the mapping I added the following to ApplicationUser and ApplicationRole classes:

```<code>public virtual ICollection<ApplicationUserRole> UserRoles { get; set; }
</code>```

Now to map the new entities I added the following to the modelBuilder:

```<code>        modelBuilder.Entity<ApplicationUserRole>(entity =>
        {
            entity.HasOne(e => e.Role)
            .WithMany(e => e.UserRoles)
            .HasForeignKey(e => e.RoleId);

            entity.HasOne(e => e.User)
            .WithMany(e => e.UserRoles)
            .HasForeignKey(e => e.UserId);
        });
</code>```

Simple as that, don't include any configuration whatsoever to ApplicationUser or ApplicationRole as IdentityDBContext will handle that properly.

Now you can chain include/join to get the actual ApplicationRole class instead of IdentityRole<TKey>

eg:

```<code>var list = _context.Users.Include(u => u.UserRoles).ThenInclude(ur => ur.Role).ToList();
</code>```

To Summarize:

Specify the proper instance of IdentityDBContext

Create the junction table entity of ApplicationUserRole

Setup virtual properties to map ApplicationUser and ApplicationRole

Setup virtual properties to map RoleId and UserId matching TKey

Create entity mapping with the modelbuilder but leave the ApplicationUser/ApplicationRole entities alone

Title: Obtain List of Roles in EF Core 3.1

Body:
I would like to obtain a list of all identity roles in EF core without the use of UserManager/RoleManager. I am using EF Core 3.1

Currently in my startup:

services.AddIdentity<ApplicationUser, ApplicationRole>()
                .AddRoles<ApplicationRole>()
                .AddRoleManager<RoleManager<ApplicationRole>>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders(); //2FA

Then in my Context:

public partial class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string>
    {
        public ApplicationDbContext()
        {

        }

        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {

        }
        //....
    }

My ApplicationUser and ApplicationRole are defined as the following:

public class ApplicationUser : IdentityUser
    {
        public virtual UserProfile UserProfile { get; set; }
    }

public class ApplicationRole : IdentityRole<String>
    {
        public int Hierarchy { get; set; }

        public ApplicationRole() : base()
        {

        }

        public ApplicationRole(string roleName) : base(roleName)
        {

        }
    }

Then I simply try calling in any controller I would like to access (_context is the ApplicationDBContext):

var list = _context.Roles.ToArray();

In which I get the error:

Microsoft.Data.SqlClient.SqlException: 'Invalid column name 'ApplicationUserId'.'

The ultimate goals is to add an ICollection of ApplicationRole to the ApplicationUser context since EF Core does not seem to support it. I am even unable to do a LINQ2Query join from UserRoles to Role.

Any help is appreciated as I've spent many hours on this.

Body:
Alright I finally figured it out, in case anyone is wondering. It is not able to properly map the roles because the ApplicationDBContext is inheriting the wrong configuration of IdentityDbContext model. For this you must create your own class that inherits IdentityUserRole and implement the proper IdentityDBContext.

public partial class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string, IdentityUserClaim<string>, ApplicationUserRole, IdentityUserLogin<string>, IdentityRoleClaim<string>, IdentityUserToken<string>>

Where ApplicationUser, ApplicationRole and ApplicationUserRole are your custom classes.

public class ApplicationUserRole : IdentityUserRole<string>
{
    public ApplicationUserRole() : base()
    {

    }

    public virtual ApplicationUser User { get; set; }

    public virtual ApplicationRole Role { get; set; }
}

For some reason EF was trying to generate additional columns of "UserId1" and "RoleId1", to avoid this I simply instructed the model to take the inheritance of IdentityUserRole, make sure your Id properties match the TKey type.

Then I was able to properly evaluate the roles. Then to get the mapping I added the following to ApplicationUser and ApplicationRole classes:

public virtual ICollection<ApplicationUserRole> UserRoles { get; set; }

Now to map the new entities I added the following to the modelBuilder:

        modelBuilder.Entity<ApplicationUserRole>(entity =>
        {
            entity.HasOne(e => e.Role)
            .WithMany(e => e.UserRoles)
            .HasForeignKey(e => e.RoleId);

            entity.HasOne(e => e.User)
            .WithMany(e => e.UserRoles)
            .HasForeignKey(e => e.UserId);
        });

Simple as that, don't include any configuration whatsoever to ApplicationUser or ApplicationRole as IdentityDBContext will handle that properly.

Now you can chain include/join to get the actual ApplicationRole class instead of IdentityRole<TKey>

eg:

var list = _context.Users.Include(u => u.UserRoles).ThenInclude(ur => ur.Role).ToList();

To Summarize:

Specify the proper instance of IdentityDBContext

Create the junction table entity of ApplicationUserRole

Setup virtual properties to map ApplicationUser and ApplicationRole

Setup virtual properties to map RoleId and UserId matching TKey

Create entity mapping with the modelbuilder but leave the ApplicationUser/ApplicationRole entities alone


来源: stackexchange

问:
No module named 'socks'
```<code>import requests, socket, socks
ModuleNotFoundError: No module named 'socks'
</code>```

I have tried pip install socks, and followed instructions of other stackoverflow posts but none of them worked. I'm working on pycharm right now and I have also installed socks and socket on there, in fact, it does show I have installed it. And yes, I do have it on the right interpreter.

How can I solve this?

OS: Latest version of Ubuntu

答:
I think you mean to install PySocks so do pip install PySocks
pypi docs for PySocks
pip install socks installs something different pypi docs for socks

ContentLicense: CC BY-SA 4.0

Title: No module named 'socks'

Body:
import requests, socket, socks
ModuleNotFoundError: No module named 'socks'

I have tried pip install socks, and followed instructions of other stackoverflow posts but none of them worked. I'm working on pycharm right now and I have also installed socks and socket on there, in fact, it does show I have installed it. And yes, I do have it on the right interpreter.

How can I solve this?

OS: Latest version of Ubuntu


问:
Should codes be written before super.initState(); or after in Flutter?
Should the code that is being written to initState() function be written before super.initState(); or after?

Which one is proper:

```<code>  @override
    // code here
    super.initState();
  }
</code>```

or

```<code>  @override
    super.initState();
    // code here
  }
</code>```

答:
abstract class State :</p>

```<code>  /// If you override this, make sure your method starts with a call to
  /// super.initState().
  @protected
  @mustCallSuper
  void initState() {
    assert(_debugLifecycleState == _StateLifecycle.created);
  }
</code>```

Body:
Should the code that is being written to initState() function be written before super.initState(); or after?

Which one is proper:

  @override
    // code here
    super.initState();
  }

or

  @override
    super.initState();
    // code here
  }

Body:
abstract class State :

  /// If you override this, make sure your method starts with a call to
  /// super.initState().
  @protected
  @mustCallSuper
  void initState() {
    assert(_debugLifecycleState == _StateLifecycle.created);
  }


问:
flatten list column within dataframe in R
I have a data frame with two columns containing lists.

```<code>test <- data.frame(var_1 = c("ONE", "TWO"))

test$var_2 <- c(list(data.frame(Date = c("Date 1", "Date 2")), list(data.frame(Date = c("Date 3", "Date 4", "Date 5")))))
test$var_3 <- c(list(data.frame(Name = c("Name 1", "Name 2")), list(data.frame(Date = c("Name 3", "Name 4", "Name 5")))))
</code>```

I'd like to loop over the lists to create a flattened data frame, repeating var_1 for the length of the list of each row

Desired Output

```<code>data.frame(var_1 = c("ONE", "ONE", "TWO", "TWO", "TWO"),
           Date = c("Date 1", "Date 2", "Date 3", "Date 4", "Date 5"),
           Name = c("Name 1", "Name 2", "Name 3", "Name 4", "Name 5"))

  var_1   Date   Name
1   ONE Date 1 Name 1
2   ONE Date 2 Name 2
3   TWO Date 3 Name 3
4   TWO Date 4 Name 4
5   TWO Date 5 Name 5
</code>```

I tried applying some of the proposed solutions like using unnest from this post Flatten list column in data frame with ID column but this didn't quite give me my desired result.

答:
An option using data.table:

```<code>setDT(test)[, c(.(var_1=var_1), do.call(cbind.data.frame, list(var_2, var_3))), var_1][,
    (1L) := NULL][]
</code>```

output:

```<code>   var_1   Date   Name
1:   ONE Date 1 Name 1
2:   ONE Date 2 Name 2
3:   TWO Date 3 Name 3
4:   TWO Date 4 Name 4
5:   TWO Date 5 Name 5
</code>```

data:

```<code>test <- data.frame(var_1 = c("ONE", "TWO"))

test$var_2 <- c(list(data.frame(Date = c("Date 1", "Date 2")), list(data.frame(Date = c("Date 3", "Date 4", "Date 5")))))
test$var_3 <- c(list(data.frame(Name = c("Name 1", "Name 2")), list(data.frame(Name = c("Name 3", "Name 4", "Name 5")))))
</code>```

Body:
I have a data frame with two columns containing lists.

test <- data.frame(var_1 = c("ONE", "TWO"))

test$var_2 <- c(list(data.frame(Date = c("Date 1", "Date 2")), list(data.frame(Date = c("Date 3", "Date 4", "Date 5")))))
test$var_3 <- c(list(data.frame(Name = c("Name 1", "Name 2")), list(data.frame(Date = c("Name 3", "Name 4", "Name 5")))))

I'd like to loop over the lists to create a flattened data frame, repeating var_1 for the length of the list of each row

Desired Output

data.frame(var_1 = c("ONE", "ONE", "TWO", "TWO", "TWO"),
           Date = c("Date 1", "Date 2", "Date 3", "Date 4", "Date 5"),
           Name = c("Name 1", "Name 2", "Name 3", "Name 4", "Name 5"))

  var_1   Date   Name
1   ONE Date 1 Name 1
2   ONE Date 2 Name 2
3   TWO Date 3 Name 3
4   TWO Date 4 Name 4
5   TWO Date 5 Name 5

I tried applying some of the proposed solutions like using unnest from this post Flatten list column in data frame with ID column but this didn't quite give me my desired result.

Body:
An option using data.table:

setDT(test)[, c(.(var_1=var_1), do.call(cbind.data.frame, list(var_2, var_3))), var_1][,
    (1L) := NULL][]

output:

   var_1   Date   Name
1:   ONE Date 1 Name 1
2:   ONE Date 2 Name 2
3:   TWO Date 3 Name 3
4:   TWO Date 4 Name 4
5:   TWO Date 5 Name 5

data:

test <- data.frame(var_1 = c("ONE", "TWO"))

test$var_2 <- c(list(data.frame(Date = c("Date 1", "Date 2")), list(data.frame(Date = c("Date 3", "Date 4", "Date 5")))))
test$var_3 <- c(list(data.frame(Name = c("Name 1", "Name 2")), list(data.frame(Name = c("Name 3", "Name 4", "Name 5")))))


问:
Are you able to retrieve data stored in UserDefaults across different View Controllers/.swift files?
I created a string value and stored it in a UserDefault on one view controller like so:

letSwimmerOneName = "John"

UserDefaults.standard.set(String(swimmerOneName), forKey: "twoFreelayNameOne

And I'm trying to retrieve that data on a different view controller like so:

var swimmerOneName = UserDefaults.standard.string(forKey: "twoFreelayNameOne")

I'm not getting any errors or crashes, it just simply doesn't work. So I was wondering if UserDefaults transfer across the entire project or stay put in the view controller they are created in.

答: You are able to retrieve data stored in UserDefaults across different view controllers. My issue was created on where I had placed the UserDefaults and in the way that I declared my variables that were to be assigned this UserDefault value. TLDR: Sloppy formatting.</p>


问:
C# Write each array element to different textbox on form
Hi all hoping for some direction. I have a text file that I am reading into a C# Form as a simple string array. I want to take each element and put them into their own text box on the form. I know I can do it as

```<code>textBox1.Text = myArray[0];
textBox2.Text = myArray[1];
</code>```

and so forth but I was hoping for some sort of for or foreach statement to iterate through the array and textboxes.

For reference the form has 50 boxes on it and the array will always have 50 elements.

Thanks in advance!

Update, I appreciate both comments it got me pointed in the right direction. I was really struggling to think through it. What I ended up coming up with is:

```<code>   //Read Data
        string[] lines = File.ReadAllLines(Globals.savePath);

        //Write Data To Form
        for (int i = 1; i <= 20; i++)
        {
            TextBox textBox = (TextBox)groupBox1.Controls["textBox" + i];
            textBox.Text = lines[i-1];
        }
        for (int i = 21; i <= 40; i++)
        {
            TextBox textBox = (TextBox)groupBox2.Controls["textBox" + i];
            textBox.Text = lines[i - 1];
        }
        for (int i = 41; i <= 60; i++)
        {
            TextBox textBox = (TextBox)groupBox3.Controls["textBox" + i];
            textBox.Text = lines[i - 1];
        }
        for (int i = 61; i <= 80; i++)
        {
            TextBox textBox = (TextBox)groupBox4.Controls["textBox" + i];
            textBox.Text = lines[i - 1];
        }
</code>```

I am sure there is a cleaner way to do this. But this worked for me and was much better then doing the whole

```<code>textbox1.Text = myArray[0]
</code>```

Plus it had the added benefit of translating over when to the next part where I was editing text boxes and than writing back to the text file.

```<code>           string[] lines = new string [81];
        for (int i = 1; i <= 20; i++)
        {
            TextBox textBox = (TextBox)groupBox1.Controls["textBox" + i];
            lines[i - 1] = textBox.Text;
        }
        for (int i = 21; i <= 40; i++)
        {
            TextBox textBox = (TextBox)groupBox2.Controls["textBox" + i];
            lines[i - 1] = textBox.Text;
        }
        for (int i = 41; i <= 60; i++)
        {
            TextBox textBox = (TextBox)groupBox3.Controls["textBox" + i];
            lines[i - 1] = textBox.Text;
        }
        for (int i = 61; i <= 80; i++)
        {
            TextBox textBox = (TextBox)groupBox4.Controls["textBox" + i];
            lines[i - 1] = textBox.Text;
        }
        lines[81] = "End";
        File.Delete(Globals.savePath);
        File.WriteAllLines(Globals.savePath, lines);
</code>```

Once again Thank You to those that commented!

答:
This is my first attempt at an answer, so fingers crossed this is helpful. I would store the textboxes in a list, then when you loop through your array, just do something like the following:

```<code>var maxItems = myArray.Length;
for(int loop = 0; loop < maxItems; loop++)
{
     textBoxItemList[loop].Text = myArray[loop];
}
</code>```

This could be tweaked to determine the loop size using the smallest array size, so you didn't go out of bounds.  The maxItems is there just as an example of where you would set this up.
Hope that helps.

Body:
Hi all hoping for some direction. I have a text file that I am reading into a C# Form as a simple string array. I want to take each element and put them into their own text box on the form. I know I can do it as

textBox1.Text = myArray[0];
textBox2.Text = myArray[1];

and so forth but I was hoping for some sort of for or foreach statement to iterate through the array and textboxes.

For reference the form has 50 boxes on it and the array will always have 50 elements.

Thanks in advance!

Update, I appreciate both comments it got me pointed in the right direction. I was really struggling to think through it. What I ended up coming up with is:

   //Read Data
        string[] lines = File.ReadAllLines(Globals.savePath);

        //Write Data To Form
        for (int i = 1; i <= 20; i++)
        {
            TextBox textBox = (TextBox)groupBox1.Controls["textBox" + i];
            textBox.Text = lines[i-1];
        }
        for (int i = 21; i <= 40; i++)
        {
            TextBox textBox = (TextBox)groupBox2.Controls["textBox" + i];
            textBox.Text = lines[i - 1];
        }
        for (int i = 41; i <= 60; i++)
        {
            TextBox textBox = (TextBox)groupBox3.Controls["textBox" + i];
            textBox.Text = lines[i - 1];
        }
        for (int i = 61; i <= 80; i++)
        {
            TextBox textBox = (TextBox)groupBox4.Controls["textBox" + i];
            textBox.Text = lines[i - 1];
        }

I am sure there is a cleaner way to do this. But this worked for me and was much better then doing the whole

textbox1.Text = myArray[0]

Plus it had the added benefit of translating over when to the next part where I was editing text boxes and than writing back to the text file.

           string[] lines = new string [81];
        for (int i = 1; i <= 20; i++)
        {
            TextBox textBox = (TextBox)groupBox1.Controls["textBox" + i];
            lines[i - 1] = textBox.Text;
        }
        for (int i = 21; i <= 40; i++)
        {
            TextBox textBox = (TextBox)groupBox2.Controls["textBox" + i];
            lines[i - 1] = textBox.Text;
        }
        for (int i = 41; i <= 60; i++)
        {
            TextBox textBox = (TextBox)groupBox3.Controls["textBox" + i];
            lines[i - 1] = textBox.Text;
        }
        for (int i = 61; i <= 80; i++)
        {
            TextBox textBox = (TextBox)groupBox4.Controls["textBox" + i];
            lines[i - 1] = textBox.Text;
        }
        lines[81] = "End";
        File.Delete(Globals.savePath);
        File.WriteAllLines(Globals.savePath, lines);

Once again Thank You to those that commented!

Body:
This is my first attempt at an answer, so fingers crossed this is helpful. I would store the textboxes in a list, then when you loop through your array, just do something like the following:

var maxItems = myArray.Length;
for(int loop = 0; loop < maxItems; loop++)
{
     textBoxItemList[loop].Text = myArray[loop];
}

This could be tweaked to determine the loop size using the smallest array size, so you didn't go out of bounds.  The maxItems is there just as an example of where you would set this up.
Hope that helps.


问:
Custom xib inside another xib not being sized properly
To get started, here is the hierarchy of my views:

```<code>- Table view
-- Table view cell (loaded from custom xib)
--- Collection view
---- Collection view cell (loaded from custom xib)
----- Custom view (loaded from custom xib)
</code>```

What I'm having trouble with is that last view, the custom view, that I'm loading into the collection view cell as a custom xib. For some reason, it isn't being sized properly:

As you can see, the view has a giant white space above it, instead of filling out the cell properly. Funnily enough, if I scroll down the table view a bit, and then scroll back up, it displays at it should:

Here is part of my collection view code:

```<code>// I use this to size the collection view cells to be of 16:9 ratio, nothing crazy
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    // Get the width of the screen
    let width = UIScreen.main.bounds.width

    let imageWidth = width
    let imageHeight = imageWidth / (16 / 9)

    self.postMediaHeight = imageHeight

    return CGSize(width: imageWidth, height: imageHeight)
}

// Here I initialize the cell
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PostMediaCollectionViewCell", for: indexPath as IndexPath) as? PostMediaCollectionViewCell else {
        fatalError("The dequeued cell is not an instance of PostMediaCollectionViewCell.")
    }

    let media = post.images[indexPath.row]

    cell.initialize()

    return cell
}
</code>```

Here is my collection view cell class, PostMediaCollectionViewCell. Nothing out of the ordinary:

```<code>class PostMediaCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var container: UIView!
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var moreView: UIView!
    @IBOutlet weak var moreViewLabel: UILabel!
    @IBOutlet weak var myCustomView: MyCustomView!

    override func awakeFromNib() {
        super.awakeFromNib()
    }

    func initialize() {
        //
    }
}
</code>```

And lastly, here is my class for MyCustomView:

```<code>class MyCustomView: UIView {
    @IBOutlet var rootView: UIView!
    @IBOutlet weak var videoView: VideoView!

    override init(frame: CGRect) {
        super.init(frame: frame)
        initialize()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        initialize()
    }

    func initialize() {
        Bundle.main.loadNibNamed("MyCustomView", owner: self, options: nil)
        addSubview(rootView)
        rootView.frame = self.bounds
        rootView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
    }
}
</code>```

I've made sure that I have my constraints set right in my xibs, so auto layout should be working, but it's clearly not:

PostMediaCollectionViewCell xib:
https://i.stack.imgur.com/GQLpj.png

MyCustomView xib:
https://i.stack.imgur.com/jpSi0.png

So what am I doing wrong here?

答:
So I found a solution to this, but I don't know why it works and whether or not it's the best way of solving it, so I'm looking for input.

If I modify my PostMediaCollectionViewCell class to include layoutIfNeeded() in the initialization function, it works:

```<code>class PostMediaCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var container: UIView!
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var moreView: UIView!
    @IBOutlet weak var moreViewLabel: UILabel!
    @IBOutlet weak var myCustomView: MyCustomView!

    override func awakeFromNib() {
        super.awakeFromNib()
    }

    func initialize() {
        layoutIfNeeded()
    }
}
</code>```

But I don't understand why. Can someone explain?

Body:
To get started, here is the hierarchy of my views:

- Table view
-- Table view cell (loaded from custom xib)
--- Collection view
---- Collection view cell (loaded from custom xib)
----- Custom view (loaded from custom xib)

What I'm having trouble with is that last view, the custom view, that I'm loading into the collection view cell as a custom xib. For some reason, it isn't being sized properly:

As you can see, the view has a giant white space above it, instead of filling out the cell properly. Funnily enough, if I scroll down the table view a bit, and then scroll back up, it displays at it should:

Here is part of my collection view code:

// I use this to size the collection view cells to be of 16:9 ratio, nothing crazy
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    // Get the width of the screen
    let width = UIScreen.main.bounds.width

    let imageWidth = width
    let imageHeight = imageWidth / (16 / 9)

    self.postMediaHeight = imageHeight

    return CGSize(width: imageWidth, height: imageHeight)
}

// Here I initialize the cell
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PostMediaCollectionViewCell", for: indexPath as IndexPath) as? PostMediaCollectionViewCell else {
        fatalError("The dequeued cell is not an instance of PostMediaCollectionViewCell.")
    }

    let media = post.images[indexPath.row]

    cell.initialize()

    return cell
}

Here is my collection view cell class, PostMediaCollectionViewCell. Nothing out of the ordinary:

class PostMediaCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var container: UIView!
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var moreView: UIView!
    @IBOutlet weak var moreViewLabel: UILabel!
    @IBOutlet weak var myCustomView: MyCustomView!

    override func awakeFromNib() {
        super.awakeFromNib()
    }

    func initialize() {
        //
    }
}

And lastly, here is my class for MyCustomView:

class MyCustomView: UIView {
    @IBOutlet var rootView: UIView!
    @IBOutlet weak var videoView: VideoView!

    override init(frame: CGRect) {
        super.init(frame: frame)
        initialize()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        initialize()
    }

    func initialize() {
        Bundle.main.loadNibNamed("MyCustomView", owner: self, options: nil)
        addSubview(rootView)
        rootView.frame = self.bounds
        rootView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
    }
}

I've made sure that I have my constraints set right in my xibs, so auto layout should be working, but it's clearly not:

PostMediaCollectionViewCell xib:
https://i.stack.imgur.com/GQLpj.png

MyCustomView xib:
https://i.stack.imgur.com/jpSi0.png

So what am I doing wrong here?

Body:
So I found a solution to this, but I don't know why it works and whether or not it's the best way of solving it, so I'm looking for input.

If I modify my PostMediaCollectionViewCell class to include layoutIfNeeded() in the initialization function, it works:

class PostMediaCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var container: UIView!
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var moreView: UIView!
    @IBOutlet weak var moreViewLabel: UILabel!
    @IBOutlet weak var myCustomView: MyCustomView!

    override func awakeFromNib() {
        super.awakeFromNib()
    }

    func initialize() {
        layoutIfNeeded()
    }
}

But I don't understand why. Can someone explain?


答:
pip install pysocks

should fix it for you.

Pysocks website

Title: No module named 'socks'


问:
How to pass params with arrow function in ReactJS hooks
I am new to ReactJS, I am confused how to pass params with arrow functions, I tried to use .bind() to bind the value so i can use it in the function but it didn't work, and passing it like a normal function didn't work as well.

My Code

```<code>const getCheckById = (checkID) =>{
    console.log(checkID)
}

<div className=''>
    {
        // allChecks is an array of objects
        allChecks.map((el,index) => {
        return <div key ={index}>
                <span onClick={getCheckById(el.checkID)}>+</span>
            </div>
        })
    }
</div>
</code>```

答:
const getCheckById = (checkID) =>{
    console.log(checkID)
}

    {
        // allChecks is an array of objects
        allChecks.map((el,index) => {
        return

                 getCheckById(el.checkID)}>+

        })
    }

```

Body:
I am new to ReactJS, I am confused how to pass params with arrow functions, I tried to use .bind() to bind the value so i can use it in the function but it didn't work, and passing it like a normal function didn't work as well.

My Code

const getCheckById = (checkID) =>{
    console.log(checkID)
}

    {
        // allChecks is an array of objects
        allChecks.map((el,index) => {
        return

                +

        })
    }

Body:
const getCheckById = (checkID) =>{
    console.log(checkID)
}

<div className=''>
    {
        // allChecks is an array of objects
        allChecks.map((el,index) => {
        return <div key ={index}>
                <span onClick={() => getCheckById(el.checkID)}>+</span>
            </div>
        })
    }
</div>


问:
Disable submit button on form submit
I wrote this code to disable submit buttons on my website after the click:

```<code>$('input[type=submit]').click(function(){
    $(this).attr('disabled', 'disabled');
});
</code>```

Unfortunately, it doesn't send the form. How can I fix this?

EDIT
I'd like to bind the submit, not the form :)

答:
Want to submit value of button as well and prevent double form submit?

If you are using button of type submit and want to submit value of button as well, which will not happen if the button is disabled, you can set a form data attribute and test afterwards.

```<code>// Add class disableonsubmit to your form
    $(document).ready(function () {
        $('form.disableonsubmit').submit(function(e) {
            if ($(this).data('submitted') === true) {
                // Form is already submitted
                console.log('Form is already submitted, waiting response.');
                // Stop form from submitting again
                e.preventDefault();
            } else {
                // Set the data-submitted attribute to true for record
                $(this).data('submitted', true);
            }
        });
    });
</code>```

ContentLicense: CC BY-SA 3.0

Title: Disable submit button on form submit

Body:
I wrote this code to disable submit buttons on my website after the click:

$('input[type=submit]').click(function(){
    $(this).attr('disabled', 'disabled');
});

Unfortunately, it doesn't send the form. How can I fix this?

EDIT
I'd like to bind the submit, not the form :)

Body:
Want to submit value of button as well and prevent double form submit?

If you are using button of type submit and want to submit value of button as well, which will not happen if the button is disabled, you can set a form data attribute and test afterwards.

// Add class disableonsubmit to your form
    $(document).ready(function () {
        $('form.disableonsubmit').submit(function(e) {
            if ($(this).data('submitted') === true) {
                // Form is already submitted
                console.log('Form is already submitted, waiting response.');
                // Stop form from submitting again
                e.preventDefault();
            } else {
                // Set the data-submitted attribute to true for record
                $(this).data('submitted', true);
            }
        });
    });


问:
AttributeError: 'numpy.ndarray' object has no attribute 'insert'
Code:

```<code>import numpy as np

coordinates = np.array([])

for x in range(1, 9):
  for y in range(1, 9):
    coordinates = coordinates.insert(coordinates, (x,y))
</code>```

Despite having read many tutorials and Stack Overflow responses, everything I try is not working. Can somebody help?

答:
It isn't clear what you want to produce, but if you want a list of 'coordinate' tuples, here's one way:

```<code>In [310]: alist = []
     ...: for x in range(1,4):
     ...:     for y in range(1,4):
     ...:         alist.append((x,y))
     ...:
In [311]: alist
Out[311]: [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
</code>```

or as a list comprehension:

```<code>In [312]: [(x,y) for x in range(1,4) for y in range(1,4)]
Out[312]: [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
</code>```

Repeated calls to numpy functions like np.insert and np.append is discouraged, since they create a whole new array each time.  List append is much better - if you have to work repeatedly like this.

With numpy use something like meshgrid to generate the 'coordinates'

```<code>In [319]: np.meshgrid(range(1,4),range(1,4))
Out[319]:
[array([[1, 2, 3],
        [1, 2, 3],
        [1, 2, 3]]), array([[1, 1, 1],
        [2, 2, 2],
        [3, 3, 3]])]
In [320]: np.reshape(_,(-1,2))      # rearrange into (n,2) array
Out[320]:
array([[1, 2],
       [3, 1],
       [2, 3],
       [1, 2],
       [3, 1],
       [1, 1],
       [2, 2],
       [2, 3],
       [3, 3]])
</code>```

Body:
Code:

import numpy as np

coordinates = np.array([])

for x in range(1, 9):
  for y in range(1, 9):
    coordinates = coordinates.insert(coordinates, (x,y))

Despite having read many tutorials and Stack Overflow responses, everything I try is not working. Can somebody help?

Body:
It isn't clear what you want to produce, but if you want a list of 'coordinate' tuples, here's one way:

In [310]: alist = []
     ...: for x in range(1,4):
     ...:     for y in range(1,4):
     ...:         alist.append((x,y))
     ...:
In [311]: alist
Out[311]: [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]

or as a list comprehension:

In [312]: [(x,y) for x in range(1,4) for y in range(1,4)]
Out[312]: [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]

Repeated calls to numpy functions like np.insert and np.append is discouraged, since they create a whole new array each time.  List append is much better - if you have to work repeatedly like this.

With numpy use something like meshgrid to generate the 'coordinates'

In [319]: np.meshgrid(range(1,4),range(1,4))
Out[319]:
[array([[1, 2, 3],
        [1, 2, 3],
        [1, 2, 3]]), array([[1, 1, 1],
        [2, 2, 2],
        [3, 3, 3]])]
In [320]: np.reshape(_,(-1,2))      # rearrange into (n,2) array
Out[320]:
array([[1, 2],
       [3, 1],
       [2, 3],
       [1, 2],
       [3, 1],
       [1, 1],
       [2, 2],
       [2, 3],
       [3, 3]])


问:
I can not find a suitable ARIMA, can anyone help me?
I am doing a time series analysis but I can not find a suitable univariate Arima model for one particular series (it remains to show autocorrelation of the residuals or not all the parameters show significance).

I have tried to differentiate it in the order of 2 also.

I was wondering if anyone could help me?

Here is the file:
https://drive.google.com/open?id=1lHJx-sR32ZQW-3FVnu45jHiVtneSF44Y

Thank you very much!

答:
I agree with MrFlick's comment, this seems more of a statistics question than about coding. That aside, here are some pointers that may help to get you started.

Let's take a look at the raw time series data.

library(forecast)
autoplot(ts) + theme_minimal()
```

<p><img src="https://i.stack.imgur.com/xVgv8.png" alt="enter image description here"></p></li>
<li><p>Being aware of <code>forecast::auto.arima</code>s limitations in the presence of outliers, level shifts and other "abnormalities", <code>auto.arima</code> suggests a model of the form SARIMA(0,0,1)(1,0,0)<sub>12</sub>. </p>

<p><strong>Note that this is different from an ARIMA(0,0,1) model that you mention in the comments!</strong> We can see the difference, by writing down the equations for the SARIMA(0,0,1)(1,0,0)<sub>12</sub> model</p>

<p><img src="https://i.stack.imgur.com/F5Cmu.png" alt="enter image description here"></p>

<p>and an ARIMA(0,0,1) model</p>

<p><img src="https://i.stack.imgur.com/0qaFo.png" alt="enter image description here"></p>

<p>The fit results are</p>

<pre class="lang-r prettyprint-override"><code>fit <- auto.arima(ts)
fit
#Series: ts
#ARIMA(0,0,1)(1,0,0)[12] with non-zero mean
#
#Coefficients:
#         ma1    sar1     mean
#      0.3644  0.2302  15.8426
#s.e.  0.1321  0.1298   0.4803
#
#sigma^2 estimated as 5.671:  log likelihood=-149.78
#AIC=307.55   AICc=308.21   BIC=316.31
</code>```

We take a look at the residuals along with their ACF and PACF

gg1 <- autoplot(fit$residuals) + theme_minimal()
gg2 <- ggAcf(fit$residuals) + theme_minimal()
gg3 <- ggPacf(fit$residuals) + theme_minimal()
library(ggpubr)
ggarrange(gg1, ggarrange(gg2, gg3, ncol = 2), nrow = 2)
```</li>
</ol>

<p><img src="https://i.stack.imgur.com/2JO6C.png" alt="enter image description here"></p>

<h2>Conclusion</h2>

<p>The distribution of the residuals look "ok": the residuals themselves look more-or-less stationary, and there is little (partial) auto-correlation at the first 9 lags. The spikes at lag 10 in the ACF and PACF may be indicative of other processes and would need further investigation. </p>

<p>Overall, an ARIMA(0,0,1)(1,0,0)<sub>12</sub> model seems to give a decent fit to the data.  </p>

<p>PS. Since you mention differencing in your main post: Be aware of the effects of (over)differencing.</p>

<hr>

<h2>Sample data</h2>

<pre class="lang-r prettyprint-override"><code>ts <- structure(c(15.6518870777097, 15.3322867608582, 17.6151603498542,
16.9445877027104, 14.7031828275352, 16.0412944212825, 16.861729056851,
13.452283131823, 13.2855709987104, 16.0124941065535, 16.5882352941176,
13.8099874808736, 16.9928053525937, 13.3337023302153, 15.4694135718804,
14.9111123979385, 16.1105207226355, 16.5585054080629, 13.5606661379857,
15.1856487275761, 20.4671985306778, 16.863711001642, 14.8349514563107,
16.0655394440664, 18.9172303262434, 18.9811320754717, 20.2998379254457,
15.8995316648271, 13.8971057363262, 18.3333810765132, 19.1311805257776,
16.7306443040217, 14.6418822305992, 20.1152852315643, 14.9894158704731,
13.5667766218388, 16.5179451090781, 12.3646258503401, 11.1907676167162,
16.7851016907621, 15.8961621664931, 18.853901818893, 18.216933524391,
16.4258603642395, 12.0362991336538, 14.6222482941739, 13.5002635740643,
11.3637532794897, 11.6990571483548, 17.3600605143722, 11.5196876016922,
17.7933147413488, 18.2443257676903, 16.983016983017, 22.6372784948589,
20.0215707422296, 12.2457223648902, 13.0610780897725, 13.7779017857143,
14.115336856392, 13.2063002533319, 15.7881424524484, 12.9566768310224,
16.7059081202431, 19.0690998564691, 18.4743742550656), .Dim = c(66L,
1L), .Dimnames = list(NULL, "serie"), .Tsp = c(2013.5, 2018.91666666667,
12), class = "ts")
</code>```

Body:
I agree with MrFlick's comment, this seems more of a statistics question than about coding. That aside, here are some pointers that may help to get you started.

Let's take a look at the raw time series data.

library(forecast)
autoplot(ts) + theme_minimal()

Being aware of forecast::auto.arimas limitations in the presence of outliers, level shifts and other "abnormalities", auto.arima suggests a model of the form SARIMA(0,0,1)(1,0,0)12.

Note that this is different from an ARIMA(0,0,1) model that you mention in the comments! We can see the difference, by writing down the equations for the SARIMA(0,0,1)(1,0,0)12 model

and an ARIMA(0,0,1) model

The fit results are

fit <- auto.arima(ts)
fit
#Series: ts
#ARIMA(0,0,1)(1,0,0)[12] with non-zero mean
#
#Coefficients:
#         ma1    sar1     mean
#      0.3644  0.2302  15.8426
#s.e.  0.1321  0.1298   0.4803
#
#sigma^2 estimated as 5.671:  log likelihood=-149.78
#AIC=307.55   AICc=308.21   BIC=316.31

We take a look at the residuals along with their ACF and PACF

gg1 <- autoplot(fit$residuals) + theme_minimal()
gg2 <- ggAcf(fit$residuals) + theme_minimal()
gg3 <- ggPacf(fit$residuals) + theme_minimal()
library(ggpubr)
ggarrange(gg1, ggarrange(gg2, gg3, ncol = 2), nrow = 2)

Conclusion

The distribution of the residuals look "ok": the residuals themselves look more-or-less stationary, and there is little (partial) auto-correlation at the first 9 lags. The spikes at lag 10 in the ACF and PACF may be indicative of other processes and would need further investigation.

Overall, an ARIMA(0,0,1)(1,0,0)12 model seems to give a decent fit to the data.

PS. Since you mention differencing in your main post: Be aware of the effects of (over)differencing.

Sample data

ts <- structure(c(15.6518870777097, 15.3322867608582, 17.6151603498542,
16.9445877027104, 14.7031828275352, 16.0412944212825, 16.861729056851,
13.452283131823, 13.2855709987104, 16.0124941065535, 16.5882352941176,
13.8099874808736, 16.9928053525937, 13.3337023302153, 15.4694135718804,
14.9111123979385, 16.1105207226355, 16.5585054080629, 13.5606661379857,
15.1856487275761, 20.4671985306778, 16.863711001642, 14.8349514563107,
16.0655394440664, 18.9172303262434, 18.9811320754717, 20.2998379254457,
15.8995316648271, 13.8971057363262, 18.3333810765132, 19.1311805257776,
16.7306443040217, 14.6418822305992, 20.1152852315643, 14.9894158704731,
13.5667766218388, 16.5179451090781, 12.3646258503401, 11.1907676167162,
16.7851016907621, 15.8961621664931, 18.853901818893, 18.216933524391,
16.4258603642395, 12.0362991336538, 14.6222482941739, 13.5002635740643,
11.3637532794897, 11.6990571483548, 17.3600605143722, 11.5196876016922,
17.7933147413488, 18.2443257676903, 16.983016983017, 22.6372784948589,
20.0215707422296, 12.2457223648902, 13.0610780897725, 13.7779017857143,
14.115336856392, 13.2063002533319, 15.7881424524484, 12.9566768310224,
16.7059081202431, 19.0690998564691, 18.4743742550656), .Dim = c(66L,
1L), .Dimnames = list(NULL, "serie"), .Tsp = c(2013.5, 2018.91666666667,
12), class = "ts")


问:
Is there a way to send response from server even if no callback is provided from client side?

Issue clarification

When we use .emit() or .send() and we also want to confirm message reception (so called acknowledgements) we simply write something like this:

```<code>socket.emit('someEvent', payload, callback);
</code>```

What this question is all about is a callback part. That's the great stuff as it allows to generally send back some data as a response with no extra events emitted. All that server needs to do is to handle the request in a proper way:

```<code>socket.on('someEvent', (payload, callback) => {
   doSomeStuff();
   callback(someData);
);
</code>```

That works just fine when we deal with a success case. But what shall we do in these cases:

1) Callback was not sent from the client side / callback's not a function and there's a need to respond from the server side with something like 'Error: no callback is provided. Usage: ...'

Example:

Client side - socket.emit('someEvent'); or socket.emit('someEvent', 1);

Server side - socket.on('someEvent', callback => callback());

or

2) While handling the request something went wrong (e.g. an unsuccessful validation result) and we need to report this in a way like: 'No payload is provided or it is invalid'

Example:

Server side -

```<code>socket.emit('someEvent', payload, callback => {
   checkPayload();
   callback(someData);
});
</code>```

Client side - socket.on('someEvent', invalidPayload, callback);

Question: is there a mechanism to create custom callback from responder's side?

My workings and workarounds

1) As for the missing callback or that one which is not a function I've concluded that I can only validate it and then invoke it only in case of its validity. So the server side is undergoing some changes:

socket.emit('someEvent', callback => callback instanceof Function && callback()); //check callback correctness

Pros: there won't be an internal error if a callback is not a function as expected.

Cons: in case of invalid callback a client won't be noticed about it.

2) As for the case when we need to send some error back I've only found a workaround to return a specific, agreed in advance, falsy value like null so that it means that no data can be returned.

```<code>socket.emit('someEvent', payload, callback => {
   checkPayload();
   callback(someData || null); //send falsy, error-like value instead
});
</code>```

Pros: a client will be noticed about some error by getting null.

Cons: from server side there's no simple middleware function that validates the input data and returns error before the main logic is being executed.

I've thought about middlewares for reaching the needed functionality, but there's no, so to say, 'event level middlewares' yet, only on the whole namespace and socket levels. Shall I try to filter events by their names on the socket level to attach the needed functionality and send error in a way like next(new Error(...));? In this case there can be a work with error event listening, I guess.

socket.io / socket.io-client versions used: 2.3.0

答:
1) Callback was not sent from the client side / callback's not a function and there's a need to respond from the server side with something like 'Error: no callback is provided. Usage: ...'

The client and server have to agree how to do this.  If the client doesn't provide a callback, then the server argument will be undefined so you can detect that from the server.

So, the proper way to do it is this:

```<code>// client
socket.emit('someMsg', someData, function(response) {
    console.log(`Got ${response} from server`);
});

// server
io.on('connection', socket => {
    socket.on('someMsg', (data, fn) => {
        console.log(`Got data ${data} from client, sending response`);
        // if client wants a response, send the response
        if (fn) {
            fn("got your data");
        }
    });
});
</code>```

So, if the client does not pass the callback, then fn on the server side will be undefined.  So, you are correct to test for that before calling it.

2) As for the case when we need to send some error back I've only found a workaround to return a specific, agreed in advance, falsy value like null so that it means that no data can be returned.

Yes, you have to agree in advance how to send an error back.  The cleanest way to send an error back would probably be to wrap your response in an object and use a .error property on that object.

```<code>// client
socket.emit('someMsg', someData, function(response) {
    if (response.error) {
        console.log(`Got error ${response.error} from server`);
    } else {
        console.log(`Got data ${response.data} from server`);
    }
});

// server
io.on('connection', socket => {
    socket.on('someMsg', (data, fn) => {
        console.log(`Got data ${data} from client, sending response`);
        // if client wants a response, send the response
        if (fn) {
            // no error here
            fn({error: null, data: "Got your message"});
        }
    });
});
</code>```

What you're seeing here is that socket.io is not really a request/response type protocol and socket.io has tried to shoehorn in a bit of a response around which you have to build your own structure.

Or, you can send an error object if there's an error:

```<code>// server
io.on('connection', socket => {
    socket.on('someMsg', (data, fn) => {
        console.log(`Got data ${data} from client, sending response`);
        // if client wants a response, send the response
        if (fn) {
            // send an error here
            fn({error: new Error("xxx Error")});
        }
    });
});
</code>```

From server side there's no simple middleware function that validates the input data and returns error before the main logic is being executed.

I don't really understand what you're trying to use middleware for or to validate?  the only place this data is present is on your message handler so any server-side validation you want to do on what the client sent needs to be there.  You can certainly do that validation before you've send a response.

Shall I try to filter events by their names on the socket level to attach the needed functionality and send error in a way like next(new Error(...));? In this case there can be a work with error event listening, I guess.

Socket.io doesn't work like Express and I don't really see why you'd try to make it work that way.  There is no next() involved in receiving a socket.io message so I'm not sure what you're trying to do there.  There is an option for middleware when the socket.io connection is first made, but not for subsequent messages sent over that connection.

Is there a way to send response from server even if no callback is provided from client side?

If the client does not provide a callback, then the only way to send a response back to the client would be to send another message.  But, the whole point of sending a response is if you have a cooperating client that is listening and expecting a response so the client may as well use the callback if they want the response.  If the client doesn't want the response and won't code anything to receive it, there's nothing you can do about that.

Body:
Issue clarification

When we use .emit() or .send() and we also want to confirm message reception (so called acknowledgements) we simply write something like this:

socket.emit('someEvent', payload, callback);

What this question is all about is a callback part. That's the great stuff as it allows to generally send back some data as a response with no extra events emitted. All that server needs to do is to handle the request in a proper way:

socket.on('someEvent', (payload, callback) => {
   doSomeStuff();
   callback(someData);
);

That works just fine when we deal with a success case. But what shall we do in these cases:

1) Callback was not sent from the client side / callback's not a function and there's a need to respond from the server side with something like 'Error: no callback is provided. Usage: ...'

Example:

Client side - socket.emit('someEvent'); or socket.emit('someEvent', 1);

Server side - socket.on('someEvent', callback => callback());

or

2) While handling the request something went wrong (e.g. an unsuccessful validation result) and we need to report this in a way like: 'No payload is provided or it is invalid'

Example:

Server side -

socket.emit('someEvent', payload, callback => {
   checkPayload();
   callback(someData);
});

Client side - socket.on('someEvent', invalidPayload, callback);

Question: is there a mechanism to create custom callback from responder's side?

My workings and workarounds

1) As for the missing callback or that one which is not a function I've concluded that I can only validate it and then invoke it only in case of its validity. So the server side is undergoing some changes:

socket.emit('someEvent', callback => callback instanceof Function && callback()); //check callback correctness

Pros: there won't be an internal error if a callback is not a function as expected.

Cons: in case of invalid callback a client won't be noticed about it.

2) As for the case when we need to send some error back I've only found a workaround to return a specific, agreed in advance, falsy value like null so that it means that no data can be returned.

socket.emit('someEvent', payload, callback => {
   checkPayload();
   callback(someData || null); //send falsy, error-like value instead
});

Pros: a client will be noticed about some error by getting null.

Cons: from server side there's no simple middleware function that validates the input data and returns error before the main logic is being executed.

I've thought about middlewares for reaching the needed functionality, but there's no, so to say, 'event level middlewares' yet, only on the whole namespace and socket levels. Shall I try to filter events by their names on the socket level to attach the needed functionality and send error in a way like next(new Error(...));? In this case there can be a work with error event listening, I guess.

socket.io / socket.io-client versions used: 2.3.0

Body:
1) Callback was not sent from the client side / callback's not a function and there's a need to respond from the server side with something like 'Error: no callback is provided. Usage: ...'

The client and server have to agree how to do this.  If the client doesn't provide a callback, then the server argument will be undefined so you can detect that from the server.

So, the proper way to do it is this:

// client
socket.emit('someMsg', someData, function(response) {
    console.log(`Got ${response} from server`);
});

// server
io.on('connection', socket => {
    socket.on('someMsg', (data, fn) => {
        console.log(`Got data ${data} from client, sending response`);
        // if client wants a response, send the response
        if (fn) {
            fn("got your data");
        }
    });
});

So, if the client does not pass the callback, then fn on the server side will be undefined.  So, you are correct to test for that before calling it.

2) As for the case when we need to send some error back I've only found a workaround to return a specific, agreed in advance, falsy value like null so that it means that no data can be returned.

Yes, you have to agree in advance how to send an error back.  The cleanest way to send an error back would probably be to wrap your response in an object and use a .error property on that object.

// client
socket.emit('someMsg', someData, function(response) {
    if (response.error) {
        console.log(`Got error ${response.error} from server`);
    } else {
        console.log(`Got data ${response.data} from server`);
    }
});

// server
io.on('connection', socket => {
    socket.on('someMsg', (data, fn) => {
        console.log(`Got data ${data} from client, sending response`);
        // if client wants a response, send the response
        if (fn) {
            // no error here
            fn({error: null, data: "Got your message"});
        }
    });
});

What you're seeing here is that socket.io is not really a request/response type protocol and socket.io has tried to shoehorn in a bit of a response around which you have to build your own structure.

Or, you can send an error object if there's an error:

// server
io.on('connection', socket => {
    socket.on('someMsg', (data, fn) => {
        console.log(`Got data ${data} from client, sending response`);
        // if client wants a response, send the response
        if (fn) {
            // send an error here
            fn({error: new Error("xxx Error")});
        }
    });
});

From server side there's no simple middleware function that validates the input data and returns error before the main logic is being executed.

I don't really understand what you're trying to use middleware for or to validate?  the only place this data is present is on your message handler so any server-side validation you want to do on what the client sent needs to be there.  You can certainly do that validation before you've send a response.

Shall I try to filter events by their names on the socket level to attach the needed functionality and send error in a way like next(new Error(...));? In this case there can be a work with error event listening, I guess.

Socket.io doesn't work like Express and I don't really see why you'd try to make it work that way.  There is no next() involved in receiving a socket.io message so I'm not sure what you're trying to do there.  There is an option for middleware when the socket.io connection is first made, but not for subsequent messages sent over that connection.

Is there a way to send response from server even if no callback is provided from client side?

If the client does not provide a callback, then the only way to send a response back to the client would be to send another message.  But, the whole point of sending a response is if you have a cooperating client that is listening and expecting a response so the client may as well use the callback if they want the response.  If the client doesn't want the response and won't code anything to receive it, there's nothing you can do about that.


问:
How can I share my stylesheets between different solutions in ASP.NET MVC 3?
I have three solutions; all share one thing in common which is the stylesheets. I would like to have only one version of the stylesheets.

I thought to put this and maybe other things like common scripts in one project and then have all three solutions reference this same project.

But how can I link in the stylesheets to my layout pages. Currently I use:

```<code><link href="@Url.Content("~/Content/Stylesheets/Package3.css")"
      rel="stylesheet" type="text/css" />
</code>```

Any advice would be appreciated.

答:
You might be able to do this with your source control?  But the better solution might ultimately be to make a 4th project of your static shared files (ex. css, javascript, images) and deploy them to a URL that you will only use to serve this content.

So you can reference in your project like:

```<code><link href="http://mydomain.com/content/stylesheets/package3.css" rel=stylesheet" type="text/css" />
</code>```

Where mydomain.com is actually your 4th project that only hosts the static content.

Body:
I have three solutions; all share one thing in common which is the stylesheets. I would like to have only one version of the stylesheets.

I thought to put this and maybe other things like common scripts in one project and then have all three solutions reference this same project.

But how can I link in the stylesheets to my layout pages. Currently I use:

<link href="@Url.Content("~/Content/Stylesheets/Package3.css")"
      rel="stylesheet" type="text/css" />

Any advice would be appreciated.

Body:
You might be able to do this with your source control?  But the better solution might ultimately be to make a 4th project of your static shared files (ex. css, javascript, images) and deploy them to a URL that you will only use to serve this content.

So you can reference in your project like:

<link href="http://mydomain.com/content/stylesheets/package3.css" rel=stylesheet" type="text/css" />

Where mydomain.com is actually your 4th project that only hosts the static content.


问:
Paste multiple column values with column name with empty values
```<code>dt <- data.table(v1 = c("", "17-Sep-2019"),
                   v2 = c("", "17-Sep-2019"))
  cols <- paste0("v",1:2)
  dt[, do.call(paste, Map(function(x, y) paste(x, y, sep = ':'),
                                    lubridate::dmy(.SD),
                                    toupper(gsub(".*(\\(.*\\)).*","\\1", names(.SD))))),
     .SDcols = cols]
</code>```

I want the code to return c(NA, "2019-09-17:V1 2019-09-17:V2")

答:
Maybe something like:</p>

```<code>dt <- data.table(v1 = c("", "17-Sep-2019"), v2 = c("", "17-Sep-2019"))
cols <- paste0("v",1:2)
dt[, fifelse(v1!="",
    do.call(paste, Map(function(x, v) paste0(as.Date(x, "%d-%b-%Y"), ":", toupper(v)), .SD, cols)),
    NA_character_), .SDcols=cols]
</code>```

Body:
dt <- data.table(v1 = c("", "17-Sep-2019"),
                   v2 = c("", "17-Sep-2019"))
  cols <- paste0("v",1:2)
  dt[, do.call(paste, Map(function(x, y) paste(x, y, sep = ':'),
                                    lubridate::dmy(.SD),
                                    toupper(gsub(".*(\\(.*\\)).*","\\1", names(.SD))))),
     .SDcols = cols]

I want the code to return c(NA, "2019-09-17:V1 2019-09-17:V2")

Body:
Maybe something like:

dt <- data.table(v1 = c("", "17-Sep-2019"), v2 = c("", "17-Sep-2019"))
cols <- paste0("v",1:2)
dt[, fifelse(v1!="",
    do.call(paste, Map(function(x, v) paste0(as.Date(x, "%d-%b-%Y"), ":", toupper(v)), .SD, cols)),
    NA_character_), .SDcols=cols]


问:
Videos in subfolders of static not working
I found this snippet of code:

```<code>from flask import Flask
import flask
from os import listdir
import os.path
import pathlib
import ntpath

app = Flask(__name__)
@app.route('/', defaults={'req_path': ''})
@app.route('/<path:req_path>')
def dir_listing(req_path):
    BASE_DIR = 'D:/Users/xxx/projects/project1/static'

    # Joining the base and the requested path
    abs_path = os.path.join(BASE_DIR, req_path)

    # Return 404 if path doesn't exist
    if not os.path.exists(abs_path):
        return flask.abort(404)

    # Check if path is a file and serve
    if os.path.isfile(abs_path):
        return flask.send_file(abs_path)

    # Show directory contents
    files = os.listdir(abs_path)
    for i, f in enumerate(files):
        files[i] = os.path.join(req_path, f).replace('\\', '/')
    return flask.render_template('files.html', files=files)

if __name__ == '__main__':
    app.run(host='10.13.0.33', port=80)
</code>```

along with the corresponding index.html:

```<code><ul>
    {% for file in files %}
        <li><a href="{{ file }}">{{ file }}</a></li>
    {% endfor %}
</ul>
</code>```

It works as expected until you get to the SecondFolder!

the rendered html looks OK:

```<code><ul>
    <li><a href="FirstFolder/SecondFolder/file3.mp4">FirstFolder/SecondFolder/file3.mp4</a></li>
    <li><a href="FirstFolder/SecondFolder/ThirdFolder">FirstFolder/SecondFolder/ThirdFolder</a></li>
</ul>
</code>```

BUT, when I hover on a link, I get this (note the first folder is duplicated!):
http://10.13.0.33/FirstFolder/FirstFolder/SecondFolder/ThirdFolder

Original Post:
I am trying to display links to videos in nested folders.  There are many files in each folder (as much as 30) so I don't want to download or play all of them at once.  The idea is for the user to see the one they want to view and click the play button.

This is currently being developed/tested on Windows 10 in PyCharm.

The top-level (home) page and next folder deep act as expected.  When I select the next depth folder, the video is labeled "Invalid Source"

Is there a limit to the depth?

Here is my code:

```<code>from flask import Flask
from os import listdir
import os.path
import pathlib
import ntpath

def remove_top_folder(path):
    path_to_file = pathlib.Path(path)
    path_to_file = path_to_file.relative_to(*path_to_file.parts[:1])
    return str(path_to_file).replace('\\', '/')

def get_folders(folder):
    if folder is not None and os.path.isdir(folder):
        folders = []
        for f in listdir(folder):
            path_to_folder = os.path.join(folder, f).replace('\\', '/')
            if os.path.isdir(path_to_folder) and not f.startswith('.'):
                folders.append(remove_top_folder(path_to_folder))
        return folders
    return None

def get_videos(folder):
    if folder is not None and os.path.isdir(folder):
        videos = []
        for f in listdir(folder):
            path_to_video = os.path.join(folder, f).replace('\\', '/')
            if os.path.isfile(os.path.join(folder, f)) and not f.startswith('.') and f.endswith('.mp4'):
                videos.append(path_to_video)
        return videos
    return None

def get_stuff(folder):
    folders = get_folders(folder)
    videos = get_videos(folder)
    if folder == 'static\\' or folder == 'static/':
        rtn = ''
    else:
        rtn = '<H1>{}</H1>'.format(remove_top_folder(folder))
    if videos is not None:
        for file_name in videos:
            file_name = file_name
            rtn += '''
            <div class="container">
                <video width="320" controls preload="metadata">
                  <source src="{0}" type="video/mp4">
                </video>
            <div class="top">{1}</div>
            </div>
            '''.format(file_name, ntpath.basename(file_name))

    for folder in folders:
        rtn += '''
        <div class="container">
          <a href="{0}">{1}
        </div>
        '''.format(folder, ntpath.basename(folder))
    return rtn

app = Flask(__name__)
@app.route('/', defaults={'u_path': ''})
@app.route('/<path:u_path>')
def catch_all(u_path):
    if u_path is None:
        folder = 'static//'
    elif u_path.endswith('mp4'):
        rtn = '''
        <div class="container">
            <video width="320" controls preload="metadata">
              <source src="{0}" type="video/mp4">
            </video>
        <div class="top">{1}</div>
        </div>
        '''.format(u_path, remove_top_folder(u_path))
        return rtn
    else:
        folder = os.path.join('static', u_path).replace('\\', '/')
    stuff = get_stuff(folder)
    html = '''
        <!doctype html>
        <html>
            <body>
                <h1>{0}</h1>
            </body>
        </html>
    '''.format(stuff)
    return html

if __name__ == '__main__':
    app.run(host='10.13.0.33', port=80)
</code>```

and I have my folders looking something like this:

```<code>static
  file_1.mp4
  First_Folder
    file_2.mp4
    Second_folder
      file_3.mp4
</code>```

When I visit the web page, I get this:

When I click the FirstFolder link, I get this:

When I click the SecondFolder link, I get this:

答:
I got it working:

app.py:

```<code>import flask
import ntpath
import os
import socket

host_name = socket.gethostname()
if host_name == 'hostname1':
    static_folder = '/some/path/to/videos'
    ip_address = '192.xxx.xxx.xxx'
    port = 80
elif host_name == "hostname2":
    static_folder = '/another/path/to/videos'
    ip_address = '10.xxx.xxx.xxx'
    port = 8000
else:
    raise Exception('hostname is not defined!')

def remove_static_folder(path):
    path_to_file = path.replace(static_folder, '/')
    return path_to_file

def get_folders(folder):
    if folder is not None and os.path.isdir(folder):
        folders = []
        for f in os.listdir(folder):
            path_to_folder = os.path.join(folder, f).replace('\\', '/')
            if os.path.isdir(path_to_folder) and not f.startswith('.'):
                folders.append([remove_static_folder(path_to_folder), ntpath.basename(path_to_folder)])
        return folders
    return []

def get_videos(folder):
    if os.path.isdir(folder):
        print("is dir")
    if folder is not None and os.path.isdir(folder):
        videos = []
        for f in os.listdir(folder):
            if os.path.isfile(os.path.join(folder, f)) and not f.startswith('.') and f.endswith('.mp4'):
                path_to_video = os.path.join(folder, f).replace('\\', '/')
                videos.append([remove_static_folder(path_to_video), ntpath.basename(f)])
        return videos
    return []

app = flask.Flask(__name__, static_folder=static_folder,
                  static_url_path= os.path.join(os.path.sep, os.path.basename(os.path.normpath(static_folder))))

@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def catch_all(path):
    if path is None or path == "":
        folder = static_folder
    else:
        folder = os.path.join(static_folder, path).replace('\\', '/')
    videos = get_videos(folder)
    folders = get_folders(folder)
    folder = remove_static_folder(folder)
    if folder.startswith(".") or folder.startswith('/'):
        folder = folder[1:]
    return flask.render_template("index.html", folder=folder, videos=videos, folders=folders)

if __name__ == '__main__':
    if ip_address is None:
        print("hostname cannot be determined")
        exit(-1)
    app.run(host=ip_address, port=port)
</code>```

index.html:

```<code><!DOCTYPE html>
<html>

<head>
    <title>{{ folder }}</title>
</head>

<body>
    <div>
        <h1>{{ folder}} </h1>
        <ul>
            {% for video in videos %}
                <div class="container">
                    <video width="640" controls preload="metadata">
                      <source src="{{ url_for('static', filename=video[0]) }}" type="video/mp4">
                    </video>
                    <div class="top">{{ video[1] }}</div>
                </div>
            {% endfor %}
        </ul>
        <ul>
            {% for folder in folders %}
                <a href="{{ folder[0] }}">{{ folder[1] }} <br>
            {% endfor %}
        </ul>
    </div>
</body>

</html>
</code>```

Body:
I found this snippet of code:

from flask import Flask
import flask
from os import listdir
import os.path
import pathlib
import ntpath

app = Flask(__name__)
@app.route('/', defaults={'req_path': ''})
@app.route('/<path:req_path>')
def dir_listing(req_path):
    BASE_DIR = 'D:/Users/xxx/projects/project1/static'

    # Joining the base and the requested path
    abs_path = os.path.join(BASE_DIR, req_path)

    # Return 404 if path doesn't exist
    if not os.path.exists(abs_path):
        return flask.abort(404)

    # Check if path is a file and serve
    if os.path.isfile(abs_path):
        return flask.send_file(abs_path)

    # Show directory contents
    files = os.listdir(abs_path)
    for i, f in enumerate(files):
        files[i] = os.path.join(req_path, f).replace('\\', '/')
    return flask.render_template('files.html', files=files)

if __name__ == '__main__':
    app.run(host='10.13.0.33', port=80)

along with the corresponding index.html:

    {% for file in files %}

{{ file }}

    {% endfor %}

It works as expected until you get to the SecondFolder!

the rendered html looks OK:

FirstFolder/SecondFolder/file3.mp4

FirstFolder/SecondFolder/ThirdFolder

BUT, when I hover on a link, I get this (note the first folder is duplicated!):
http://10.13.0.33/FirstFolder/FirstFolder/SecondFolder/ThirdFolder

Original Post:
I am trying to display links to videos in nested folders.  There are many files in each folder (as much as 30) so I don't want to download or play all of them at once.  The idea is for the user to see the one they want to view and click the play button.

This is currently being developed/tested on Windows 10 in PyCharm.

The top-level (home) page and next folder deep act as expected.  When I select the next depth folder, the video is labeled "Invalid Source"

Is there a limit to the depth?

Here is my code:

from flask import Flask
from os import listdir
import os.path
import pathlib
import ntpath

def remove_top_folder(path):
    path_to_file = pathlib.Path(path)
    path_to_file = path_to_file.relative_to(*path_to_file.parts[:1])
    return str(path_to_file).replace('\\', '/')

def get_folders(folder):
    if folder is not None and os.path.isdir(folder):
        folders = []
        for f in listdir(folder):
            path_to_folder = os.path.join(folder, f).replace('\\', '/')
            if os.path.isdir(path_to_folder) and not f.startswith('.'):
                folders.append(remove_top_folder(path_to_folder))
        return folders
    return None

def get_videos(folder):
    if folder is not None and os.path.isdir(folder):
        videos = []
        for f in listdir(folder):
            path_to_video = os.path.join(folder, f).replace('\\', '/')
            if os.path.isfile(os.path.join(folder, f)) and not f.startswith('.') and f.endswith('.mp4'):
                videos.append(path_to_video)
        return videos
    return None

def get_stuff(folder):
    folders = get_folders(folder)
    videos = get_videos(folder)
    if folder == 'static\\' or folder == 'static/':
        rtn = ''
    else:
        rtn = '
{}
'.format(remove_top_folder(folder))
    if videos is not None:
        for file_name in videos:
            file_name = file_name
            rtn += '''

                <video width="320" controls preload="metadata">
                  <source src="{0}" type="video/mp4">
                </video>

{1}

            '''.format(file_name, ntpath.basename(file_name))

    for folder in folders:
        rtn += '''

          {1}

        '''.format(folder, ntpath.basename(folder))
    return rtn

app = Flask(__name__)
@app.route('/', defaults={'u_path': ''})
@app.route('/<path:u_path>')
def catch_all(u_path):
    if u_path is None:
        folder = 'static//'
    elif u_path.endswith('mp4'):
        rtn = '''

            <video width="320" controls preload="metadata">
              <source src="{0}" type="video/mp4">
            </video>

{1}

        '''.format(u_path, remove_top_folder(u_path))
        return rtn
    else:
        folder = os.path.join('static', u_path).replace('\\', '/')
    stuff = get_stuff(folder)
    html = '''
        <!doctype html>

{0}

    '''.format(stuff)
    return html

if __name__ == '__main__':
    app.run(host='10.13.0.33', port=80)

and I have my folders looking something like this:

static
  file_1.mp4
  First_Folder
    file_2.mp4
    Second_folder
      file_3.mp4

When I visit the web page, I get this:

When I click the FirstFolder link, I get this:

When I click the SecondFolder link, I get this:

Body:
I got it working:

app.py:

import flask
import ntpath
import os
import socket

host_name = socket.gethostname()
if host_name == 'hostname1':
    static_folder = '/some/path/to/videos'
    ip_address = '192.xxx.xxx.xxx'
    port = 80
elif host_name == "hostname2":
    static_folder = '/another/path/to/videos'
    ip_address = '10.xxx.xxx.xxx'
    port = 8000
else:
    raise Exception('hostname is not defined!')

def remove_static_folder(path):
    path_to_file = path.replace(static_folder, '/')
    return path_to_file

def get_folders(folder):
    if folder is not None and os.path.isdir(folder):
        folders = []
        for f in os.listdir(folder):
            path_to_folder = os.path.join(folder, f).replace('\\', '/')
            if os.path.isdir(path_to_folder) and not f.startswith('.'):
                folders.append([remove_static_folder(path_to_folder), ntpath.basename(path_to_folder)])
        return folders
    return []

def get_videos(folder):
    if os.path.isdir(folder):
        print("is dir")
    if folder is not None and os.path.isdir(folder):
        videos = []
        for f in os.listdir(folder):
            if os.path.isfile(os.path.join(folder, f)) and not f.startswith('.') and f.endswith('.mp4'):
                path_to_video = os.path.join(folder, f).replace('\\', '/')
                videos.append([remove_static_folder(path_to_video), ntpath.basename(f)])
        return videos
    return []

app = flask.Flask(__name__, static_folder=static_folder,
                  static_url_path= os.path.join(os.path.sep, os.path.basename(os.path.normpath(static_folder))))

@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def catch_all(path):
    if path is None or path == "":
        folder = static_folder
    else:
        folder = os.path.join(static_folder, path).replace('\\', '/')
    videos = get_videos(folder)
    folders = get_folders(folder)
    folder = remove_static_folder(folder)
    if folder.startswith(".") or folder.startswith('/'):
        folder = folder[1:]
    return flask.render_template("index.html", folder=folder, videos=videos, folders=folders)

if __name__ == '__main__':
    if ip_address is None:
        print("hostname cannot be determined")
        exit(-1)
    app.run(host=ip_address, port=port)

index.html:

<!DOCTYPE html>
<html>

<head>
    <title>{{ folder }}</title>
</head>

<body>
    <div>
        <h1>{{ folder}} </h1>
        <ul>
            {% for video in videos %}
                <div class="container">
                    <video width="640" controls preload="metadata">
                      <source src="{{ url_for('static', filename=video[0]) }}" type="video/mp4">
                    </video>
                    <div class="top">{{ video[1] }}</div>
                </div>
            {% endfor %}
        </ul>
        <ul>
            {% for folder in folders %}
                <a href="{{ folder[0] }}">{{ folder[1] }} <br>
            {% endfor %}
        </ul>
    </div>
</body>

</html>


问:
Generate a random integer array with repeating values in J
I want to generate a random array with repeating values. Something like this:

```<code>4 11 6 3 5 4 16 11 26 5 4
</code>```

I know that the statement 12 ? 50 will generate a random integer array with 12 unique values in the range 0 to 49. How would I allow repeating values?

Also can J create random floating point arrays?

答:
Whether the Roll (?) will give repeating values depends on the ratio of its arguments. If the repeatability requirement is optional, then just use Roll. If it is mandatory then first use the Roll to get unique values, and then dispense that values to get the length required.

J Vocabulary for Roll says how to get a random floating-point number:

```<code>   ? 0      NB. as a scalar
0.331228
   ] r=. 5 ?@$ 0  NB. as an array of shape x (which is 5 here)
0.331228 0.905526 0.71756 0.637666 0.486918
</code>```

Then it may be scaled to the range desired, say, the open interval (3,26), via arithmetic operators:

```<code>   ] s=. 3 + (26-3) * r
10.6182 23.8271 19.5039 17.6663 14.1991
</code>```

or via Polynomial (p.):

```<code>   ] s=. (3 , 26-3) p. r
10.6182 23.8271 19.5039 17.6663 14.1991
</code>```

And then it may be dispensed to the final length (say, 8):

```<code>   (8 ?@$ 5) { s
10.6182 14.1991 17.6663 10.6182 17.6663 17.6663 23.8271 19.5039
</code>```

Body:
I want to generate a random array with repeating values. Something like this:

4 11 6 3 5 4 16 11 26 5 4

I know that the statement 12 ? 50 will generate a random integer array with 12 unique values in the range 0 to 49. How would I allow repeating values?

Also can J create random floating point arrays?

Body:
Whether the Roll (?) will give repeating values depends on the ratio of its arguments. If the repeatability requirement is optional, then just use Roll. If it is mandatory then first use the Roll to get unique values, and then dispense that values to get the length required.

J Vocabulary for Roll says how to get a random floating-point number:

   ? 0      NB. as a scalar
0.331228
   ] r=. 5 ?@$ 0  NB. as an array of shape x (which is 5 here)
0.331228 0.905526 0.71756 0.637666 0.486918

Then it may be scaled to the range desired, say, the open interval (3,26), via arithmetic operators:

   ] s=. 3 + (26-3) * r
10.6182 23.8271 19.5039 17.6663 14.1991

or via Polynomial (p.):

   ] s=. (3 , 26-3) p. r
10.6182 23.8271 19.5039 17.6663 14.1991

And then it may be dispensed to the final length (say, 8):

   (8 ?@$ 5) { s
10.6182 14.1991 17.6663 10.6182 17.6663 17.6663 23.8271 19.5039


问:
Wordpress - Display only pages with specific template in search results
I want to display in my WP search results ONLY pages with specific template beceuse I trying to build product catalog without any plugins. Pure WP code. Some pages are my products, and they have product.php template file. This is my search.php:

```<code><?php
    if ( have_posts() ) :
        while ( have_posts() ) :
            the_post();
            get_template_part( 'template-parts/post/content', 'excerpt' );
        endwhile;
        the_posts_pagination();
    else :
        ?>
        <p><?php _e( 'No results.' ); ?></p>
        <?php
            get_search_form();
    endif;
?>
</code>```

And the question is, how to display only my product pages without any other pages?

答:
Try this out!
This function will interrupt the search query and add some condition fo the query to returns specific pages.

```<code>//Filter the search for only posts and parts
function SearchFilter($query)
{
    // Now filter the posts
    if ($query->is_main_query() & $query->is_search && $search_template) {
        $query->set('post_type', 'page');
        $query->set('meta_key' => '_wp_page_template',);
        $query->set('meta_value' => 'product.php');
    }
   // Returning the query after it has been modified
    return $query;
}

add_action('pre_get_posts', 'SearchFilter');
</code>```

Explaining the code:

The "post_type" will limit this filter for page post type only.

The condition Will limit this filter to only work on the search queries and not every time the posts query is called.

```<code> $query->is_search && $search_template
</code>```

These parameters will filter the returned posts by the meta_key "_wp_page_template" which contains the page template, so we only return the pages with the page template "product.php".

```<code>        $query->set('meta_key' => '_wp_page_template',);
        $query->set('meta_value' => 'product.php');
</code>```

Body:
I want to display in my WP search results ONLY pages with specific template beceuse I trying to build product catalog without any plugins. Pure WP code. Some pages are my products, and they have product.php template file. This is my search.php:

<?php
    if ( have_posts() ) :
        while ( have_posts() ) :
            the_post();
            get_template_part( 'template-parts/post/content', 'excerpt' );
        endwhile;
        the_posts_pagination();
    else :
        ?>

<?php _e( 'No results.' ); ?>

        <?php
            get_search_form();
    endif;
?>

And the question is, how to display only my product pages without any other pages?

Body:
Try this out!
This function will interrupt the search query and add some condition fo the query to returns specific pages.

//Filter the search for only posts and parts
function SearchFilter($query)
{
    // Now filter the posts
    if ($query->is_main_query() & $query->is_search && $search_template) {
        $query->set('post_type', 'page');
        $query->set('meta_key' => '_wp_page_template',);
        $query->set('meta_value' => 'product.php');
    }
   // Returning the query after it has been modified
    return $query;
}

add_action('pre_get_posts', 'SearchFilter');

Explaining the code:

The "post_type" will limit this filter for page post type only.

The condition Will limit this filter to only work on the search queries and not every time the posts query is called.

 $query->is_search && $search_template

These parameters will filter the returned posts by the meta_key "_wp_page_template" which contains the page template, so we only return the pages with the page template "product.php".

        $query->set('meta_key' => '_wp_page_template',);
        $query->set('meta_value' => 'product.php');


问:
jQuery slideTo with combined attributes
I am trying to target a specific div holding links that would navigate the user throughout the page.

The code I have is:

```<code>$(document).on('click', 'a[href^="#"]', function(e) { // [id='faqNav']?
    // target element id
    var id = $(this).attr('href');

    // target element
    var $id = $(id);
    if ($id.length === 0) {
        return;
    }

    // prevent standard hash navigation (avoid blinking in IE)
    e.preventDefault();

    // top position relative to the document
    var pos = $id.offset().top;

    // animated top scrolling
    $('body, html').animate({scrollTop: pos});
});
</code>```

The a[href^="#"] is affecting an accordion I have on the page so I am trying to figure out a way to select the links in the div I have. The links are in a list, I thought I'd give the list an id hoping that the code would only affect the hrefs inside there alone. I tried a[href^="#"][id='faqNav'] but it affected all hrefs on the page.

Not sure how to target this alone. Here's an example of the list I'm trying to target:

```<code><ul id="faqNav">
<li href="#link1">A</li>
<li href="#link2">B</li>
<li href="#link3">C</li>
</ul>
</code>```

答:
 Lists items don't accept a href attribute which can be used for ,<base>, <area> or <link>.
The best alternative to use in this case is to add custom data attribute. Like data-link in this example

Solution 1 : following your HTML code

$("#faqNav li").on('click',function(e) {
    // target element id
    var id = $(this).data('link');
    console.log(id);

    // target element
    var $id = $(id);
    if ($id.length === 0) {
        return;
    }

    // prevent standard hash navigation (avoid blinking in IE)
    e.preventDefault();

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="faqNav">
<li data-link="#link1">A</li>
<li data-link="#link2">B</li>
<li data-link="#link3">C</li>
</ul></code>```

Solution 2: Regular Usage with links

$("#faqNav a").on('click',function(e) {
    // target element id
    var id = $(this).attr('href');
    console.log(id);

    // target element
    var $id = $(id);
    if ($id.length === 0) {
        return;
    }

    // prevent standard hash navigation (avoid blinking in IE)
    e.preventDefault();

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="faqNav">
<li>A</li>
<li>B</li>
<li>C</li>
</ul></code>```

Solution 3 : Data attribute alongside Hash

$("#faqNav a").on('click',function(e) {
    // target element id
    var id = $(this).data('link');
    console.log(id);

    // target element
    var $id = $(id);
    if ($id.length === 0) {
        return;
    }

    // prevent standard hash navigation (avoid blinking in IE)
    e.preventDefault();

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="faqNav">
<li>A</li>
<li>B</li>
<li>C</li>
</ul></code>```

It depends on your design requirements, your document Anchors (ids) and your navigation needs. With valid Ids, you can use this to control your page loading too like in yourpage.html#link1 . So priority goes to a valid HTML, then we can customize and prevent defaults...

Title: jQuery slideTo with combined attributes

Body:
I am trying to target a specific div holding links that would navigate the user throughout the page.

The code I have is:

$(document).on('click', 'a[href^="#"]', function(e) { // [id='faqNav']?
    // target element id
    var id = $(this).attr('href');

    // target element
    var $id = $(id);
    if ($id.length === 0) {
        return;
    }

    // prevent standard hash navigation (avoid blinking in IE)
    e.preventDefault();

    // top position relative to the document
    var pos = $id.offset().top;

    // animated top scrolling
    $('body, html').animate({scrollTop: pos});
});

The a[href^="#"] is affecting an accordion I have on the page so I am trying to figure out a way to select the links in the div I have. The links are in a list, I thought I'd give the list an id hoping that the code would only affect the hrefs inside there alone. I tried a[href^="#"][id='faqNav'] but it affected all hrefs on the page.

Not sure how to target this alone. Here's an example of the list I'm trying to target:

A

B

C

Body:
<li> Lists items don't accept a href attribute which can be used for <a>,<base>, <area> or <link>.
The best alternative to use in this case is to add custom data attribute. Like data-link in this example

Solution 1 : following your HTML code

$("#faqNav li").on('click',function(e) {
    // target element id
    var id = $(this).data('link');
    console.log(id);

    // target element
    var $id = $(id);
    if ($id.length === 0) {
        return;
    }

    // prevent standard hash navigation (avoid blinking in IE)
    e.preventDefault();

});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="faqNav">
<li data-link="#link1">A</li>
<li data-link="#link2">B</li>
<li data-link="#link3">C</li>
</ul>

Solution 2: Regular Usage with links

$("#faqNav a").on('click',function(e) {
    // target element id
    var id = $(this).attr('href');
    console.log(id);

    // target element
    var $id = $(id);
    if ($id.length === 0) {
        return;
    }

    // prevent standard hash navigation (avoid blinking in IE)
    e.preventDefault();

});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="faqNav">
<li><a href="#link1">A</a></li>
<li><a href="#link2">B</a></li>
<li><a href="#link3">C</a></li>
</ul>

Solution 3 : Data attribute alongside Hash

$("#faqNav a").on('click',function(e) {
    // target element id
    var id = $(this).data('link');
    console.log(id);

    // target element
    var $id = $(id);
    if ($id.length === 0) {
        return;
    }

    // prevent standard hash navigation (avoid blinking in IE)
    e.preventDefault();

});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="faqNav">
<li><a href="#" data-link="#link1">A</a></li>
<li><a href="#" data-link="#link2">B</a></li>
<li><a href="#" data-link="#link3">C</a></li>
</ul>

It depends on your design requirements, your document Anchors (ids) and your navigation needs. With valid Ids, you can use this to control your page loading too like in yourpage.html#link1 . So priority goes to a valid HTML, then we can customize and prevent defaults...


问:
Consolidate different alternative names of countries, under the official name
I'm searching for a list or python packages, to help me unify under one name different names of countries.

For example:

```<code>USA, SUA, United States, Unites States of America
Germany, Federal Republic of Germany, Deutschland, Duitsland
</code>```

I want to consolidate them under the official name, and allocate them iso standard.

答:
This package, country_converter, can do it: https://github.com/konstantinstadler/country_converter

As shown in their documentation,

```<code>import country_converter as coco
some_names = ['United Rep. of Tanzania', 'DE', 'Cape Verde', '788', 'Burma', 'COG',
              'Iran (Islamic Republic of)', 'Korea, Republic of',
              "Dem. People's Rep. of Korea"]
standard_names = coco.convert(names=some_names, to='name_short')
print(standard_names)
</code>```

Should give

```<code> ['Tanzania', 'Germany', 'Cabo Verde', 'Tunisia', 'Myanmar', 'Congo Republic', 'Iran', 'South Korea', 'North Korea']
</code>```

You can also specify the format you want the country names to be printed, by changing the to='name_short' to to='ISO2'

Body:
I'm searching for a list or python packages, to help me unify under one name different names of countries.

For example:

USA, SUA, United States, Unites States of America
Germany, Federal Republic of Germany, Deutschland, Duitsland

I want to consolidate them under the official name, and allocate them iso standard.

Body:
This package, country_converter, can do it: https://github.com/konstantinstadler/country_converter

As shown in their documentation,

import country_converter as coco
some_names = ['United Rep. of Tanzania', 'DE', 'Cape Verde', '788', 'Burma', 'COG',
              'Iran (Islamic Republic of)', 'Korea, Republic of',
              "Dem. People's Rep. of Korea"]
standard_names = coco.convert(names=some_names, to='name_short')
print(standard_names)

Should give

 ['Tanzania', 'Germany', 'Cabo Verde', 'Tunisia', 'Myanmar', 'Congo Republic', 'Iran', 'South Korea', 'North Korea']

You can also specify the format you want the country names to be printed, by changing the to='name_short' to to='ISO2'


问:
Where should I store common targets for team builds?
I am trying to set up a common.targets file with some common msbuild targets I want to use in my team builds and therefore import into my TFSBuild.proj files. I am wondering what is the best way to achieve this? Do I need to store common.targets right next to each TFSBuild.proj file and therefore having duplicates of the targets file for each team build or is there another way? I would rather not put the targets file on each of the build machines.</p>

答: The goal of a common .targets file is to reduce duplication of your scripts.  If you have multiple copies of this file under source control, what happens when you need to change them (to update a .exe path maybe)?  Personally, I prefer a separate location for common files that any/all other build scripts can reference.  The only downside to this is you will likely be hard-coding the path to this file.</p>

OwnerDisplayName: Fadeproof

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Rich B

OwnerDisplayName: Pedro


问:
How likely are two blocks of data likely to produce the same CRC64 value?
I have an caching application that uses a CRC64 value to ensure data integrity.
I'm thinking about putting an extra field, a timestamp to be passed around with the data
between the various cache servers and compared to see if data has changed.

However, this requires protocol changes.  While that's not a huge deal,  I already have
a CRC64 that could be used as an indicator that something has changed.

Does anyone know the stats around two blocks of data producing the same CRC64? If not, how could I compute it or estimate it's likelyhood?

答:
The probability of any two given blocks colliding is 1/264, or 1 in about 1.8 × 1019.

However, the probability rapidly becomes more likely if you are interested in the rate of collision out of any two blocks from a population of size N.

For more information, see Birthday Problem on Wikipedia, which has formulas and approximations.


问:
Google API - Gmail. Downloading attachments
When calling this method please help by advising what values to pass through such as GmailService? Im guessing userID is the Gmail account and the messageID( i want to download all of them) .

How can i change this to download all the attachments in the inbox.

Thank you in advance and I hope someone can help me.

Method im using is below.

```<code>public static void GetAttachments(GmailService service, String userId, String messageId, String outputDir)
{
  try
  {
    Message message = service.Users.Messages.Get(userId, messageId).Execute();
    IList<MessagePart> parts = message.Payload.Parts;
    foreach (MessagePart part in parts)
    {
      if (!String.IsNullOrEmpty(part.Filename))
      {
        String attId = part.Body.AttachmentId;
        MessagePartBody attachPart = service.Users.Messages.Attachments.Get(userId, messageId, attId).Execute();

        // Converting from RFC 4648 base64 to base64url encoding
        // see http://en.wikipedia.org/wiki/Base64#Implementations_and_history
        String attachData = attachPart.Data.Replace('-', '+');
        attachData = attachData.Replace('_', '/');

        byte[] data = Convert.FromBase64String(attachData);
        File.WriteAllBytes(Path.Combine(outputDir, part.Filename), data);
       }
     }
   }
   catch (Exception e)
   {
     Console.WriteLine("An error occurred: " + e.Message);
   }
 }
</code>```

答:
I know, it's could be an off-topic, but using PostMan in case when programmer use Google API is little but contraproductive :) APIs also have attachments.Get Method, and you will not need to call HTTP request and allow non OAuth 2.0 authentication especially when you're using multi-phase authentication.

Here is example:
https://developers.google.com/gmail/api/v1/reference/users/messages/attachments/get

Body:
When calling this method please help by advising what values to pass through such as GmailService? Im guessing userID is the Gmail account and the messageID( i want to download all of them) .

How can i change this to download all the attachments in the inbox.

Thank you in advance and I hope someone can help me.

Method im using is below.

public static void GetAttachments(GmailService service, String userId, String messageId, String outputDir)
{
  try
  {
    Message message = service.Users.Messages.Get(userId, messageId).Execute();
    IList<MessagePart> parts = message.Payload.Parts;
    foreach (MessagePart part in parts)
    {
      if (!String.IsNullOrEmpty(part.Filename))
      {
        String attId = part.Body.AttachmentId;
        MessagePartBody attachPart = service.Users.Messages.Attachments.Get(userId, messageId, attId).Execute();

        // Converting from RFC 4648 base64 to base64url encoding
        // see http://en.wikipedia.org/wiki/Base64#Implementations_and_history
        String attachData = attachPart.Data.Replace('-', '+');
        attachData = attachData.Replace('_', '/');

        byte[] data = Convert.FromBase64String(attachData);
        File.WriteAllBytes(Path.Combine(outputDir, part.Filename), data);
       }
     }
   }
   catch (Exception e)
   {
     Console.WriteLine("An error occurred: " + e.Message);
   }
 }


问:
How to install package from github repo in Yarn
When I use npm install fancyapps/fancybox#v2.6.1 --save, so fancybox package at v2.6.1 tag will be installed. This behavior is described in docs

I want to ask, how to do this with yarn?

Is this command the right alternative? In yarn docs isn't anything about this format.

```<code>yarn add fancyapps/fancybox#v2.6.1
</code>```

答:
I use this short format for github repositories:

yarn add github_user/repository_name#commit_hash

Body:
When I use npm install fancyapps/fancybox#v2.6.1 --save, so fancybox package at v2.6.1 tag will be installed. This behavior is described in docs

I want to ask, how to do this with yarn?

Is this command the right alternative? In yarn docs isn't anything about this format.

yarn add fancyapps/fancybox#v2.6.1