问:
tableViewCell image to new view
My image is not showing in my new view, it shows the url in my console but not on the simulator or device. I am getting the data from firebase and sending it to a class named User. The data then shows on my tableViewCell and I segue to a new ViewController, however the image view is blank.

//my code for tableViewController

```<code> override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "prefCell", for: indexPath) as! SFPTableViewCell

      let user = userList[indexPath.row]

    cell.name.text = userList[indexPath.row].name
    cell.location.text = userList[indexPath.row].location
    cell.bio.text = userList[indexPath.row].bio

    if let imageURL = user.image {

        cell.imageOne.loadImageUsingCacheWithUrlString(urlString: imageURL)
    }

          return cell
}

   override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if let destination = segue.destination as? SFProfileViewController{
        let cell = sender as! UITableViewCell
        let selectedRow = tableView.indexPath(for: cell)!.row
        destination.nameProfile = userList[selectedRow].name!
        destination.locationProfile = userList[selectedRow].location!
        destination.imageOneUrl = userList[selectedRow].image!

    }
        }
</code>```

//my destination ViewController

```<code>class SFProfileViewController: UIViewController, UITableViewDelegate {

@IBOutlet weak var nameLabelTwo: UILabel!

var user: User?
var userList = [User]()

@IBOutlet weak var imageOne: UIImageView!

var imageURL: String?

var imageOneUrl: String!

var nameProfile : String!

var locationProfile: String!

@IBOutlet weak var nameLabel: UILabel!

@IBOutlet weak var locationLabel: UILabel!

override func viewWillAppear(_ animated: Bool) {
    print(locationProfile)
    print(nameProfile)
    print(imageOneUrl)

    imageOne.image = UIImage(named: imageOneUrl)
    nameLabelTwo.text = String(describing: nameProfile!)
    nameLabel.text = String(describing: nameProfile!)

    locationLabel.text = String(describing: locationProfile!)

}
</code>```

答:
Replace this line  destination.imageOneUrl = userList[selectedRow].image! with

```<code>destination.imageOne = userList[selectedRow].image!
</code>```

OR

Pass the image URL from tableViewCell to new Controller and then load the image from cache as you are doing in tableview delegate.

Title: tableViewCell image to new view

Body:
My image is not showing in my new view, it shows the url in my console but not on the simulator or device. I am getting the data from firebase and sending it to a class named User. The data then shows on my tableViewCell and I segue to a new ViewController, however the image view is blank.

//my code for tableViewController

 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "prefCell", for: indexPath) as! SFPTableViewCell

      let user = userList[indexPath.row]

    cell.name.text = userList[indexPath.row].name
    cell.location.text = userList[indexPath.row].location
    cell.bio.text = userList[indexPath.row].bio

    if let imageURL = user.image {

        cell.imageOne.loadImageUsingCacheWithUrlString(urlString: imageURL)
    }

          return cell
}

   override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if let destination = segue.destination as? SFProfileViewController{
        let cell = sender as! UITableViewCell
        let selectedRow = tableView.indexPath(for: cell)!.row
        destination.nameProfile = userList[selectedRow].name!
        destination.locationProfile = userList[selectedRow].location!
        destination.imageOneUrl = userList[selectedRow].image!

    }
        }

//my destination ViewController

class SFProfileViewController: UIViewController, UITableViewDelegate {

@IBOutlet weak var nameLabelTwo: UILabel!

var user: User?
var userList = [User]()

@IBOutlet weak var imageOne: UIImageView!

var imageURL: String?

var imageOneUrl: String!

var nameProfile : String!

var locationProfile: String!

@IBOutlet weak var nameLabel: UILabel!

@IBOutlet weak var locationLabel: UILabel!

override func viewWillAppear(_ animated: Bool) {
    print(locationProfile)
    print(nameProfile)
    print(imageOneUrl)

    imageOne.image = UIImage(named: imageOneUrl)
    nameLabelTwo.text = String(describing: nameProfile!)
    nameLabel.text = String(describing: nameProfile!)

    locationLabel.text = String(describing: locationProfile!)

}

Body:
Replace this line  destination.imageOneUrl = userList[selectedRow].image! with

destination.imageOne = userList[selectedRow].image!

OR

Pass the image URL from tableViewCell to new Controller and then load the image from cache as you are doing in tableview delegate.


来源: stackexchange

答:
Change below line and pass imageOne Url instead of image

```<code>imageOne.image = UIImage(named: imageOneUrl)
</code>```

To

```<code>imageOne.loadImageUsingCacheWithUrlString(urlString: imageURL)
</code>```

As imageoneurl is url not image name

ContentLicense: CC BY-SA 3.0

Title: tableViewCell image to new view

Body:
Change below line and pass imageOne Url instead of image

imageOne.image = UIImage(named: imageOneUrl)

To

imageOne.loadImageUsingCacheWithUrlString(urlString: imageURL)

As imageoneurl is url not image name


问:
MySql Connector/J 5.1.41 not connecting
I'm using MySQL Connector/J 5.1.41 to connect to a DB, here's the code I'm using to connect:

```<code>package DB;

import java.sql.Connection;
import java.sql.DriverManager;
import javax.swing.JOptionPane;

public class ConexionMYSQL {
    public String db="floreria";
    public String url= "jdbc:mysql:/localhost"+db;
    public String user= "root";//aqui va el usuario del phpmyadmin
    public String pwd="";

public Connection conectar(){
    Connection link = null;
    try {
        Class.forName("org.gjt.mm.mysql.Driver");
        link = DriverManager.getConnection(this.url, this.user, this.pwd);
    } catch (Exception e) {

        JOptionPane.showMessageDialog(null, "ERROR: "+e);
    }
    return link;
  }
}
</code>```

I'm a newbie in Java and mysql connections, when I execute the code, It shows me the following exception:

ERROR:java.lang.ClassNotFoundException:org.gjt.mm.mysql.Driver

I've already checked that the jar file is in the classpath, I've reinstalled and replaced the jar file for MySql connector too, but stays the same. As I said, I'm new in this world, I barely know about JavaFX and mysql connections, so thats all info I think I can provide, here's an image from my classpath, maybe there's the problem:

答:
First :
 Change this line from :  public String url= "jdbc:mysql:/localhost"+db; to  public String url= "jdbc:mysql://localhost/"+db;

Second :
 This is a strange driver name : org.gjt.mm.mysql.Driver

This is the one I know of : com.mysql.jdbc.Driver so you can change line from :
 Class.forName("org.gjt.mm.mysql.Driver");  to this one :Class.forName("com.mysql.jdbc.Driver");

EDIT: Mistake on the driver name, I've corrected it.

Make sure the jar files are in the classpath.

Good luck.

Title: MySql Connector/J 5.1.41 not connecting

Body:
I'm using MySQL Connector/J 5.1.41 to connect to a DB, here's the code I'm using to connect:

package DB;

import java.sql.Connection;
import java.sql.DriverManager;
import javax.swing.JOptionPane;

public class ConexionMYSQL {
    public String db="floreria";
    public String url= "jdbc:mysql:/localhost"+db;
    public String user= "root";//aqui va el usuario del phpmyadmin
    public String pwd="";

public Connection conectar(){
    Connection link = null;
    try {
        Class.forName("org.gjt.mm.mysql.Driver");
        link = DriverManager.getConnection(this.url, this.user, this.pwd);
    } catch (Exception e) {

        JOptionPane.showMessageDialog(null, "ERROR: "+e);
    }
    return link;
  }
}

I'm a newbie in Java and mysql connections, when I execute the code, It shows me the following exception:

ERROR:java.lang.ClassNotFoundException:org.gjt.mm.mysql.Driver

I've already checked that the jar file is in the classpath, I've reinstalled and replaced the jar file for MySql connector too, but stays the same. As I said, I'm new in this world, I barely know about JavaFX and mysql connections, so thats all info I think I can provide, here's an image from my classpath, maybe there's the problem:


问:
Asking multiplication questions and computing the total of answers correct in Java
The code should output a table for Farenheit and Celsius</p>

```<code>public static void main(String[] args) {
    System.out.println("Fahrenheit\tCelsius");
    System.out.println("=======================");
     for(int temp = -45; temp <= 120; temp += 5) //for(int i = 0; i <= 100; i+= 10)
        {
            System.out.printf("%5d       |",          temp);
            double sum = (temp + (9.0/5.0)) * 32;
            System.out.printf("%5d", (int)sum );
            System.out.printl

n();
</code>```

答:
You should do this all in one encompassing while loop.

the while loop pseudo code is like this:

```<code>string answer = "";
While (answer != quit)
{
answer = (ask question to user)
if (answer != quit)
   compute/display response
}
</code>```

Body:
The code should output a table for Farenheit and Celsius

public static void main(String[] args) {
    System.out.println("Fahrenheit\tCelsius");
    System.out.println("=======================");
     for(int temp = -45; temp <= 120; temp += 5) //for(int i = 0; i <= 100; i+= 10)
        {
            System.out.printf("%5d       |",          temp);
            double sum = (temp + (9.0/5.0)) * 32;
            System.out.printf("%5d", (int)sum );
            System.out.printl

n();

Body:
You should do this all in one encompassing while loop.

the while loop pseudo code is like this:

string answer = "";
While (answer != quit)
{
answer = (ask question to user)
if (answer != quit)
   compute/display response
}


问:
Show Image for ToolStripControlHost in drop down menu
I have a ToolStripSplitButton with various elements in dropdown list.
One of them is a Trackbar enclosed in a ToolStripControlHost, called ToolStripTrackbarItem. It's code (I've got it from stackoverflow):

```<code>using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Windows.Forms.Design;

namespace Application
{
    [System.ComponentModel.DesignerCategory("code")]
    [System.Windows.Forms.Design.ToolStripItemDesignerAvailability(ToolStripItemDesignerAvailability.ContextMenuStrip | ToolStripItemDesignerAvailability.MenuStrip)]

    public class ToolStripTrackbarItem : ToolStripControlHost
    {
        public ToolStripTrackbarItem()
            : base(CreateControlInstance())
        {
            this.Size = Control.Size;
        }
        public TrackBar TrackBar
        {
            get { return Control as TrackBar; }
        }
        private static Control CreateControlInstance()
        {
            TrackBar t = new TrackBar();
            t.AutoSize = false;
            return t;
        }
        [DefaultValue(0)]
        public int Value
        {
            get { return TrackBar.Value; }
            set { TrackBar.Value = value; }
        }
        protected override void OnSubscribeControlEvents(Control control)
        {
            base.OnSubscribeControlEvents(control);
            TrackBar trackBar = control as TrackBar;
            trackBar.ValueChanged += new EventHandler(trackBar_ValueChanged);
        }
        protected override void OnUnsubscribeControlEvents(Control control)
        {
            base.OnUnsubscribeControlEvents(control);
            TrackBar trackBar = control as TrackBar;
            trackBar.ValueChanged -= new EventHandler(trackBar_ValueChanged);
        }
        void trackBar_ValueChanged(object sender, EventArgs e)
        {
            if (this.ValueChanged != null)
                ValueChanged(sender, e);
        }
        public event EventHandler ValueChanged;
        protected override Size DefaultSize
        {
            get { return new Size(300, 16); }
        }
    }
</code>```

It works, but I need to show images to the left of the dropdown items:

I'm successful with a simple ToolStripMenuItem by setting the Image property. However, it is ineffective to set Image property of my ToolStripTrackbarItem (that is inherited from ToolStripControlHost, see code above). According to MSDN, Image property is irrelevant to ToolStripControlHost.

What does it mean? Is it not even possible to include an image left to ToolStripControlHost?

If it is possible anyway, how to do that?

答:
You should solve 2 problems here:

ToolStripControlHost doesn't show Image property and also doesn't serialize the image when you save the form.

ToolStripProfessionalRendered doesn't draw image for ToolStripControlHost.

You need to override Image property of ToolStripControlHost and make it browsable and serializable. Also you need to create a custom renderer to draw the image in the correct location and size. Then if you simply set the renderer for ToolStrip using below code, you will get expected result:

```<code>this.toolStrip1.Renderer = new MyCustomRenderer();
</code>```

ToolStripTrackBar

The item enables Image property to show in property grid and let it serialize when saving form.

```<code>using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using System.Windows.Forms.Design;
[ToolStripItemDesignerAvailability(ToolStripItemDesignerAvailability.All)]
public class ToolStripTrackBar : ToolStripControlHost
{
    public TrackBar TrackBar { get { return (TrackBar)Control; } }
    public ToolStripTrackBar() : base(CreateControl()) { }
    private static TrackBar CreateControl()
    {
        var t = new TrackBar()
        { TickStyle = TickStyle.None, AutoSize = false, Height = 28 };
        return t;
    }
    [Browsable(true)]
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
    public override Image Image
    {
        get { return base.Image; }
        set { base.Image = value; }
    }
    /*Expose properties and events which you need.*/
    public int Value
    {
        get { return TrackBar.Value; }
        set { TrackBar.Value = value; }
    }
}
</code>```

MyCustomRenderer

This renderer draws images for ToolStripTrackBar.

```<code>using System.Drawing;
using System.Linq;
using System.Windows.Forms;
public class MyCustomRenderer : ToolStripProfessionalRenderer
{
    protected override void OnRenderImageMargin(ToolStripRenderEventArgs e)
    {
        base.OnRenderImageMargin(e);
        e.ToolStrip.Items.OfType<ToolStripTrackBar>()
         .ToList().ForEach(item =>
         {
             if (item.Image != null)
             {
                 var size = item.GetCurrentParent().ImageScalingSize;
                 var location = item.Bounds.Location;
                 location = new Point(5, location.Y + 1);
                 var imageRectangle = new Rectangle(location, size);
                 e.Graphics.DrawImage(item.Image, imageRectangle,
                     new Rectangle(Point.Empty, item.Image.Size),
                     GraphicsUnit.Pixel);
             }
         });
    }
}
</code>```

Body:
I have a ToolStripSplitButton with various elements in dropdown list.
One of them is a Trackbar enclosed in a ToolStripControlHost, called ToolStripTrackbarItem. It's code (I've got it from stackoverflow):

using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Windows.Forms.Design;

namespace Application
{
    [System.ComponentModel.DesignerCategory("code")]
    [System.Windows.Forms.Design.ToolStripItemDesignerAvailability(ToolStripItemDesignerAvailability.ContextMenuStrip | ToolStripItemDesignerAvailability.MenuStrip)]

    public class ToolStripTrackbarItem : ToolStripControlHost
    {
        public ToolStripTrackbarItem()
            : base(CreateControlInstance())
        {
            this.Size = Control.Size;
        }
        public TrackBar TrackBar
        {
            get { return Control as TrackBar; }
        }
        private static Control CreateControlInstance()
        {
            TrackBar t = new TrackBar();
            t.AutoSize = false;
            return t;
        }
        [DefaultValue(0)]
        public int Value
        {
            get { return TrackBar.Value; }
            set { TrackBar.Value = value; }
        }
        protected override void OnSubscribeControlEvents(Control control)
        {
            base.OnSubscribeControlEvents(control);
            TrackBar trackBar = control as TrackBar;
            trackBar.ValueChanged += new EventHandler(trackBar_ValueChanged);
        }
        protected override void OnUnsubscribeControlEvents(Control control)
        {
            base.OnUnsubscribeControlEvents(control);
            TrackBar trackBar = control as TrackBar;
            trackBar.ValueChanged -= new EventHandler(trackBar_ValueChanged);
        }
        void trackBar_ValueChanged(object sender, EventArgs e)
        {
            if (this.ValueChanged != null)
                ValueChanged(sender, e);
        }
        public event EventHandler ValueChanged;
        protected override Size DefaultSize
        {
            get { return new Size(300, 16); }
        }
    }

It works, but I need to show images to the left of the dropdown items:

I'm successful with a simple ToolStripMenuItem by setting the Image property. However, it is ineffective to set Image property of my ToolStripTrackbarItem (that is inherited from ToolStripControlHost, see code above). According to MSDN, Image property is irrelevant to ToolStripControlHost.

What does it mean? Is it not even possible to include an image left to ToolStripControlHost?

If it is possible anyway, how to do that?

Body:
You should solve 2 problems here:

ToolStripControlHost doesn't show Image property and also doesn't serialize the image when you save the form.

ToolStripProfessionalRendered doesn't draw image for ToolStripControlHost.

You need to override Image property of ToolStripControlHost and make it browsable and serializable. Also you need to create a custom renderer to draw the image in the correct location and size. Then if you simply set the renderer for ToolStrip using below code, you will get expected result:

this.toolStrip1.Renderer = new MyCustomRenderer();

ToolStripTrackBar

The item enables Image property to show in property grid and let it serialize when saving form.

using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using System.Windows.Forms.Design;
[ToolStripItemDesignerAvailability(ToolStripItemDesignerAvailability.All)]
public class ToolStripTrackBar : ToolStripControlHost
{
    public TrackBar TrackBar { get { return (TrackBar)Control; } }
    public ToolStripTrackBar() : base(CreateControl()) { }
    private static TrackBar CreateControl()
    {
        var t = new TrackBar()
        { TickStyle = TickStyle.None, AutoSize = false, Height = 28 };
        return t;
    }
    [Browsable(true)]
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
    public override Image Image
    {
        get { return base.Image; }
        set { base.Image = value; }
    }
    /*Expose properties and events which you need.*/
    public int Value
    {
        get { return TrackBar.Value; }
        set { TrackBar.Value = value; }
    }
}

MyCustomRenderer

This renderer draws images for ToolStripTrackBar.

using System.Drawing;
using System.Linq;
using System.Windows.Forms;
public class MyCustomRenderer : ToolStripProfessionalRenderer
{
    protected override void OnRenderImageMargin(ToolStripRenderEventArgs e)
    {
        base.OnRenderImageMargin(e);
        e.ToolStrip.Items.OfType<ToolStripTrackBar>()
         .ToList().ForEach(item =>
         {
             if (item.Image != null)
             {
                 var size = item.GetCurrentParent().ImageScalingSize;
                 var location = item.Bounds.Location;
                 location = new Point(5, location.Y + 1);
                 var imageRectangle = new Rectangle(location, size);
                 e.Graphics.DrawImage(item.Image, imageRectangle,
                     new Rectangle(Point.Empty, item.Image.Size),
                     GraphicsUnit.Pixel);
             }
         });
    }
}


问:
jQuery datatable table inside table causing mData undefined
In one of my projects I am using datatables. This is one column structure in my table which is causing an error:

```<code><th>
    <table class="table table-bordered table-condesed">
        <thead>
            <tr>
                <th colspan="7" class="text-center">Day Run</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>M</td>
                <td>T</td>
                <td>W</td>
                <td>T</td>
                <td>F</td>
                <td>S</td>
                <td>S</td>
            </tr>
        </tbody>
    </table>
</th>
</code>```

Also this is the respective column:

```<code><td>
    <table class="table table-bordered">
        <tbody>
            <tr>
                <td tabindex="0">N</td>
                <td>N</td>
                <td>N</td>
                <td>N</td>
                <td>N</td>
                <td>N</td>
                <td>Y</td>
            </tr>
        </tbody>
    </table>
</td>
</code>```

I don't know why but this is throwing an error when initialized. This is the error I am facing.

Uncaught TypeError: Cannot read property 'mData' of undefined

I don't see anything wrong here. Any idea why its does not work?

Here is the live demo Demo

答:
This is because you are initializing datatable by using class like:

```<code>$('.table').dataTable({searching: false, paging: false, responsive: true});
</code>```

and the column definition are different for both the table, I think this is the issue.

Do one thing, provide different id to both the table and initiate datatable with those id's

Body:
In one of my projects I am using datatables. This is one column structure in my table which is causing an error:

                Day Run

                M
                T
                W
                T
                F
                S
                S

Also this is the respective column:

                N
                N
                N
                N
                N
                N
                Y

I don't know why but this is throwing an error when initialized. This is the error I am facing.

Uncaught TypeError: Cannot read property 'mData' of undefined

I don't see anything wrong here. Any idea why its does not work?

Here is the live demo Demo

Body:
This is because you are initializing datatable by using class like:

$('.table').dataTable({searching: false, paging: false, responsive: true});

and the column definition are different for both the table, I think this is the issue.

Do one thing, provide different id to both the table and initiate datatable with those id's


问:
LISP: How can I test if two lists have the same elements?
I want to write a function that takes as parameters two lists and checks if every element in the first one is included in the second ( the order of the elements doesn't matter). The function will also be checking if the two list have the same length (the two list can't have duplicate elements) because if not then the function will return nill/false.

For example:
(A B C D E F) and (B E A F D C) have the same elements
(nil) and (nil) have the same elements

(A B C D E F) and (A B C D E F G) don't have the same elements

The problem is that I know only some basic commands and I can use just those ones. These are almost all the commands that I know:

```<code>CAR, CDR, LENGTH, NULL, MEMBER, NOT, AND, OR, NOT, MAPCAR, APPLY, DO, SETQ, LET
</code>```

I wrote the following function up until now, but I don't know how to check for duplicate members and it doesn't work properly for all the lists that I want to check:

```<code>(defun same-elem-p (lst1 lst2)
  (cond ((not (null lst1))
         (cond ((member (car lst1) lst2)
                (same-elem-p (cdr lst1) lst2))
               (t nil)))
        (t t)))
</code>```

I hope I explained the problem well enough.

答:
Two lists contain the same elements iff they are subsets of each other.</p>

```<code>(defun same-elements (l1 l2)
  (and (subsetp l1 l2) (subsetp l2 l1)))
</code>```

Body:
I want to write a function that takes as parameters two lists and checks if every element in the first one is included in the second ( the order of the elements doesn't matter). The function will also be checking if the two list have the same length (the two list can't have duplicate elements) because if not then the function will return nill/false.

For example:
(A B C D E F) and (B E A F D C) have the same elements
(nil) and (nil) have the same elements

(A B C D E F) and (A B C D E F G) don't have the same elements

The problem is that I know only some basic commands and I can use just those ones. These are almost all the commands that I know:

CAR, CDR, LENGTH, NULL, MEMBER, NOT, AND, OR, NOT, MAPCAR, APPLY, DO, SETQ, LET

I wrote the following function up until now, but I don't know how to check for duplicate members and it doesn't work properly for all the lists that I want to check:

(defun same-elem-p (lst1 lst2)
  (cond ((not (null lst1))
         (cond ((member (car lst1) lst2)
                (same-elem-p (cdr lst1) lst2))
               (t nil)))
        (t t)))

I hope I explained the problem well enough.

Body:
Two lists contain the same elements iff they are subsets of each other.

(defun same-elements (l1 l2)
  (and (subsetp l1 l2) (subsetp l2 l1)))


问:
Unless current user is one of the users who belong to a record
Walls have many users through WallAssignments

```<code>has_many :users, :through => :wall_assignments
</code>```

Users have many walls through WallAssignments

```<code>has_many :wall_assignments
has_many :walls, :through => :wall_assignments
</code>```

I want to redirect away from walls#show unless the user belongs to the wall.

So far I have this

```<code>unless @wall.user_id == current_user.id
    redirect_to current_user
end
</code>```

The problem is, this is finding the creator of the wall. I want to allow all users who belong to the wall to view the wall.

答:
```<code>if @wall.users.include?(current_user)
  # redirect to wall view
end
</code>```

Body:
Walls have many users through WallAssignments

has_many :users, :through => :wall_assignments

Users have many walls through WallAssignments

has_many :wall_assignments
has_many :walls, :through => :wall_assignments

I want to redirect away from walls#show unless the user belongs to the wall.

So far I have this

unless @wall.user_id == current_user.id
    redirect_to current_user
end

The problem is, this is finding the creator of the wall. I want to allow all users who belong to the wall to view the wall.


问:
How to fetch HTTP parameters in java transformer in MULE ESB
I am bit new at Mule ESB and Anypoint Studio so I am trying to figure out how to fetch HTTP query parameters in a java transformer class.

I have tried

```<code>String firstname = message.getInboundProperty("fname");
String lastName = message.getInboundProperty("lname");
</code>```

even went with

```<code>Map<String, String> queryParams = message.getInboundProperty("http.query.params");
String firstname = queryParams.get("fname");
String lastname = queryParams.get("lname");
</code>```

but they return null values, I have even tried to use Callable Interface but I think it only possible to use it if it's a JAVA Component.

Do please let me know,

Thanks.

答:
You could also get property as a separate approach below.

public class MyCustomTransformer extends AbstractMessageTransformer {
        @Override
        public Object transformMessage(MuleMessage message, String outputEncoding) throws TransformerException {

```<code>        Map<String, String> queryParams =
        message.getProperty("http.query.params", PropertyScope.INVOCATION);
        String fname=queryParams.get("fname");
        System.out.println("fname: "+fname);
        String lname=queryParams.get("lname");
        System.out.println("lname: "+lname);
        return message;

     }
     }
</code>```

Body:
I am bit new at Mule ESB and Anypoint Studio so I am trying to figure out how to fetch HTTP query parameters in a java transformer class.

I have tried

String firstname = message.getInboundProperty("fname");
String lastName = message.getInboundProperty("lname");

even went with

Map<String, String> queryParams = message.getInboundProperty("http.query.params");
String firstname = queryParams.get("fname");
String lastname = queryParams.get("lname");

but they return null values, I have even tried to use Callable Interface but I think it only possible to use it if it's a JAVA Component.

Do please let me know,

Thanks.

Body:
You could also get property as a separate approach below.

public class MyCustomTransformer extends AbstractMessageTransformer {
        @Override
        public Object transformMessage(MuleMessage message, String outputEncoding) throws TransformerException {

        Map<String, String> queryParams =
        message.getProperty("http.query.params", PropertyScope.INVOCATION);
        String fname=queryParams.get("fname");
        System.out.println("fname: "+fname);
        String lname=queryParams.get("lname");
        System.out.println("lname: "+lname);
        return message;

     }
     }


问:
How do I list the contents of a directory with Dart?
I would like to list all the contents of a directory (on the file system) using Dart. How can I do this?</p>

答:
With this function you can print all the directories and files of a directory.
You just need to pass a specific path.</p>

```<code>Future listDir(String folderPath) async {
  var directory = new Directory(folderPath);
  print(directory);

  var exists = await directory.exists();
  if (exists) {
    print("exits");

    directory
      .list(recursive: true, followLinks: false)
      .listen((FileSystemEntity entity) {
        print(entity.path);
      });
  }
}
</code>```

Body:
With this function you can print all the directories and files of a directory.
You just need to pass a specific path.

Future listDir(String folderPath) async {
  var directory = new Directory(folderPath);
  print(directory);

  var exists = await directory.exists();
  if (exists) {
    print("exits");

    directory
      .list(recursive: true, followLinks: false)
      .listen((FileSystemEntity entity) {
        print(entity.path);
      });
  }
}


问:
getting multiple errors for this code within the for loop and for the variable value;
used the variable value as a size of an array but it will not let me.   </p>

```<code>int main () {
    double a,b,N,increment,value;
    value=0;
    cout<< "enter values for (a,b,N)";
    cin>>a;
    cin>>b;
    cin>>N;
    increment= (b-a)/(N-1);
    for (int i =0;i<=b;i+=increment){
    value = value+i;
    }
    double sivalues[value];
    for (int x=a;i<=b;i+=increment){
        sivalues[a]=si(x);
        cout<<"si("<<x<<") = "<< sivalues[a];
    }
</code>```

答:
The item placed inside the [] when creating an array must be constant.  This does not apply however when you create arrays on the heap.

```<code>int mySize = 50;
int myArray[mySize]; // error: mySize must be const
int* myHeapArray = new int[mySize]; // all good! (just don't forget to free the memory)
</code>```

Body:
used the variable value as a size of an array but it will not let me.

int main () {
    double a,b,N,increment,value;
    value=0;
    cout<< "enter values for (a,b,N)";
    cin>>a;
    cin>>b;
    cin>>N;
    increment= (b-a)/(N-1);
    for (int i =0;i<=b;i+=increment){
    value = value+i;
    }
    double sivalues[value];
    for (int x=a;i<=b;i+=increment){
        sivalues[a]=si(x);
        cout<<"si("<<x<<") = "<< sivalues[a];
    }

Body:
The item placed inside the [] when creating an array must be constant.  This does not apply however when you create arrays on the heap.

int mySize = 50;
int myArray[mySize]; // error: mySize must be const
int* myHeapArray = new int[mySize]; // all good! (just don't forget to free the memory)


问:
Firefox WebExtensions: dyamically decide when contents scripts are run automatically
One option for running a content script is to match one or more URLs to run it automatically. From the web site:

```<code>"content_scripts": [
    {
        "matches": ["*://*.mozilla.org/*"],
        "js": ["borderify.js"]
    }
]
</code>```

Is it possible to update this dynamically? That is, can I add or remove to the macthes array using JavaScript?

My next step would be to save changes in storage, and reload that next time.

My plan is to allow my addon to automatically run for selected URLs, to allow users to edit these URLs.

答:
Use "matches": ["*://*/*"], to match any URL.

And check the document.URL in the content script to see if it matches any among user-defined URLs retrieved by calling browser.storage.local.get. If document.URL doesn't match, do nothing.

Body:
One option for running a content script is to match one or more URLs to run it automatically. From the web site:

"content_scripts": [
    {
        "matches": ["*://*.mozilla.org/*"],
        "js": ["borderify.js"]
    }
]

Is it possible to update this dynamically? That is, can I add or remove to the macthes array using JavaScript?

My next step would be to save changes in storage, and reload that next time.

My plan is to allow my addon to automatically run for selected URLs, to allow users to edit these URLs.


问:
Read office excel 2007 documents from within silverlight
I have a requirement to read in an excel 2007 file (*.xls) from within Silverlight, then extract data from this xls file. My background in web tech tells me this might be impossible to do, but I thought I would ask the question anyways.

The solution that comes to mind is to create a service which can handle this extraction, but this implementation is for a huge user global user base, and we're concerned about not having enough server resources, hence we're investigating client side options.

It will be a corporate intranet, but we the users are familiar with an exact xls file layout, and cannot convert before handing over to the Silverlight component.

So firstly, is this type of thing possible with Silverlight, I know it wasn't a few years ago

If its not possible out of the box, any 3rd party components, commercial or open source?

I've thought about writing a client side WCF app that will service requests from Silverlight in this way send the opened xls file to the WCF service app, process -> send results back. Do you think this is plausible?

If not Silverlight, could flash or a Java Applet handle conversion from xls to xml client side, and communicate this info to the silverlight app?

What about Microsoft Office Online, do you think its possible to get the file in binary format into the silver light app, then send it to open office, and get it back as xml?

Thanks in advance.

答: I'm investigating this, http://www.dotnetcurry.com/ShowArticle.aspx?ID=576</p>

ContentLicense: CC BY-SA 2.5


问:
Comparing 2 arrays for equal elements and deleting the entries from both arrays
Suppose i have 2 numpy arrays which have elements like these:

```<code>arr1 = [[1, 2], [3, 5], [3, 4]]
arr2 = [[2, 3], [3, 4], [6, 6]]
</code>```

I want the resultant array to have arr2 appended or horizontally stacked to
 arr1 containing the elements which are NOT present in both the arrays:

```<code>arr3 = [[1, 2], [3, 5], [2, 3], [6, 6]]
</code>```

As you can see, [3, 4] is not there in the expected resultant array. What is the best numpy and pythonic implementation for this?

答:
I'm a bit late to the party but here is an approach that leverages numpy speed at only moderate algorithmic cost: O(n log n). It turns out that for many sizes of the input arrays runtime is dominated by the cost of type conversions. See benchmarks below:

```<code>from timeit import timeit
import numpy as np

def make_inputs(N, ncol):
    global arr1, arr2, list1, list2, lot1, lot2
    # create making sure there are no duplicates *within* arr1 or arr2
    all_ = np.array(list(set(map(tuple, np.random.randint(0, 2 * N, (N + N//2, ncol))))))
    # create input of various data types
    arr1 = all_[np.random.choice(len(all_), N, False)]
    arr2 = all_[np.random.choice(len(all_), N, False)]
    list1 = arr1.tolist()
    list2 = arr2.tolist()
    lot1 = list(map(tuple, list1))
    lot2 = list(map(tuple, list2))

def np_unique_preserve_order(a, b):
    c = np.r_[a, b]
    cr = c.view(np.dtype("|S" + str(c.shape[-1] * c.dtype.itemsize)))
    uniq, inv, count = np.unique(cr.ravel(), return_inverse=True,
                                 return_counts=True)
    return c[(count==1)[inv], :]

def np_unique(a, b):
    c = np.r_[a, b]
    cr = c.view(np.dtype("|S" + str(c.shape[-1] * c.dtype.itemsize)))
    uniq, count = np.unique(cr.ravel(), return_counts=True)
    return uniq[count==1, None].view(c.dtype)

def np_sort(a, b):
    c = np.r_[a, b]
    cr = np.sort(c.view(np.dtype("|S" + str(c.shape[-1] * c.dtype.itemsize))).ravel())
    m = np.empty(cr.shape, bool)
    m[0] = True
    m[1:] = cr[:-1] != cr[1:]
    m[:-1] &= m[1:]
    return cr[m, None].view(c.dtype)

# check
make_inputs(1000, 2)
assert set(map(tuple, lot1)).symmetric_difference(set(map(tuple, lot2))) == set(map(tuple, np_sort(arr1, arr2)))
assert set(map(tuple, lot1)).symmetric_difference(set(map(tuple, lot2))) == set(map(tuple, np_unique(arr1, arr2)))
assert set(map(tuple, lot1)).symmetric_difference(set(map(tuple, lot2))) == set(map(tuple, np_unique_preserve_order(arr1, arr2)))

for N, ncol in ((10, 2), (10000, 2), (100000, 20)):
    make_inputs(N, ncol)
    results = []
    for inputs in 'lot', 'list', 'arr':
        res = []
        if inputs == 'lot':
            res.append('{:11.5f} ms'.format(timeit(f'list(set({inputs}1).symmetric_difference(set({inputs}2)))',
                 f'from __main__ import {inputs}1, {inputs}2', number=10) * 100))
        else:
            res.append('{:11.5f} ms'.format(timeit(f'list(set(map(tuple, {inputs}1)).symmetric_difference(set(map(tuple, {inputs}2))))',
                 f'from __main__ import {inputs}1, {inputs}2', number=10) * 100))

        res.append('{:11.5f} ms'.format(timeit(f'np_sort({inputs}1, {inputs}2)', f'from __main__ import {inputs}1, {inputs}2, np_sort',
                 number=10) * 100))
        res.append('{:11.5f} ms'.format(timeit(f'np_unique({inputs}1, {inputs}2)', f'from __main__ import {inputs}1, {inputs}2, np_unique',
                 number=10) * 100))
        res.append('{:11.5f} ms'.format(timeit(f'np_unique_preserve_order({inputs}1, {inputs}2)', f'from __main__ import {inputs}1, {inputs}2, np_unique_preserve_order',
                 number=10) * 100))
        results.append(res)
    results = zip(*results)
    appmin = lambda l: l + (min(l),)
    print(f'\nno rows {N}, no colums {ncol}')
    print('input type                           lot           list          array           best')
    print(f'symm_diff                ', *appmin(next(results)))
    print(f'np_sort                  ', *appmin(next(results)))
    print(f'np_unique                ', *appmin(next(results)))
    print(f'np_unique_preserve_order ', *appmin(next(results)))
</code>```

Output:

```<code>no rows 10, no colums 2
input type                           lot           list          array           best
symm_diff                     0.00232 ms     0.00453 ms     0.02034 ms     0.00232 ms
np_sort                       0.03890 ms     0.03269 ms     0.03060 ms     0.03060 ms
np_unique                     0.04209 ms     0.04118 ms     0.04136 ms     0.04118 ms
np_unique_preserve_order      0.05289 ms     0.05253 ms     0.05253 ms     0.05253 ms

no rows 10000, no colums 2
input type                           lot           list          array           best
symm_diff                     3.71800 ms     8.30081 ms    21.92841 ms     3.71800 ms
np_sort                       7.98128 ms     8.09973 ms     2.80091 ms     2.80091 ms
np_unique                     8.49229 ms     8.25701 ms     3.00654 ms     3.00654 ms
np_unique_preserve_order     10.12377 ms     8.67133 ms     3.36172 ms     3.36172 ms

no rows 100000, no colums 20
input type                           lot           list          array           best
symm_diff                    97.83141 ms   211.20736 ms   590.15145 ms    97.83141 ms
np_sort                     317.73268 ms   316.50081 ms    89.97820 ms    89.97820 ms
np_unique                   324.68922 ms   326.89891 ms    98.06377 ms    98.06377 ms
np_unique_preserve_order    339.18597 ms   339.00286 ms   120.94041 ms   120.94041 ms
</code>```

For very small arrays symm_diff is fastest, but for larger ones np_sort has a small edge when all methods are allowed to use the data type they are most comfortable with.

Body:
Suppose i have 2 numpy arrays which have elements like these:

arr1 = [[1, 2], [3, 5], [3, 4]]
arr2 = [[2, 3], [3, 4], [6, 6]]

I want the resultant array to have arr2 appended or horizontally stacked to
 arr1 containing the elements which are NOT present in both the arrays:

arr3 = [[1, 2], [3, 5], [2, 3], [6, 6]]

As you can see, [3, 4] is not there in the expected resultant array. What is the best numpy and pythonic implementation for this?

Body:
I'm a bit late to the party but here is an approach that leverages numpy speed at only moderate algorithmic cost: O(n log n). It turns out that for many sizes of the input arrays runtime is dominated by the cost of type conversions. See benchmarks below:

from timeit import timeit
import numpy as np

def make_inputs(N, ncol):
    global arr1, arr2, list1, list2, lot1, lot2
    # create making sure there are no duplicates *within* arr1 or arr2
    all_ = np.array(list(set(map(tuple, np.random.randint(0, 2 * N, (N + N//2, ncol))))))
    # create input of various data types
    arr1 = all_[np.random.choice(len(all_), N, False)]
    arr2 = all_[np.random.choice(len(all_), N, False)]
    list1 = arr1.tolist()
    list2 = arr2.tolist()
    lot1 = list(map(tuple, list1))
    lot2 = list(map(tuple, list2))

def np_unique_preserve_order(a, b):
    c = np.r_[a, b]
    cr = c.view(np.dtype("|S" + str(c.shape[-1] * c.dtype.itemsize)))
    uniq, inv, count = np.unique(cr.ravel(), return_inverse=True,
                                 return_counts=True)
    return c[(count==1)[inv], :]

def np_unique(a, b):
    c = np.r_[a, b]
    cr = c.view(np.dtype("|S" + str(c.shape[-1] * c.dtype.itemsize)))
    uniq, count = np.unique(cr.ravel(), return_counts=True)
    return uniq[count==1, None].view(c.dtype)

def np_sort(a, b):
    c = np.r_[a, b]
    cr = np.sort(c.view(np.dtype("|S" + str(c.shape[-1] * c.dtype.itemsize))).ravel())
    m = np.empty(cr.shape, bool)
    m[0] = True
    m[1:] = cr[:-1] != cr[1:]
    m[:-1] &= m[1:]
    return cr[m, None].view(c.dtype)

# check
make_inputs(1000, 2)
assert set(map(tuple, lot1)).symmetric_difference(set(map(tuple, lot2))) == set(map(tuple, np_sort(arr1, arr2)))
assert set(map(tuple, lot1)).symmetric_difference(set(map(tuple, lot2))) == set(map(tuple, np_unique(arr1, arr2)))
assert set(map(tuple, lot1)).symmetric_difference(set(map(tuple, lot2))) == set(map(tuple, np_unique_preserve_order(arr1, arr2)))

for N, ncol in ((10, 2), (10000, 2), (100000, 20)):
    make_inputs(N, ncol)
    results = []
    for inputs in 'lot', 'list', 'arr':
        res = []
        if inputs == 'lot':
            res.append('{:11.5f} ms'.format(timeit(f'list(set({inputs}1).symmetric_difference(set({inputs}2)))',
                 f'from __main__ import {inputs}1, {inputs}2', number=10) * 100))
        else:
            res.append('{:11.5f} ms'.format(timeit(f'list(set(map(tuple, {inputs}1)).symmetric_difference(set(map(tuple, {inputs}2))))',
                 f'from __main__ import {inputs}1, {inputs}2', number=10) * 100))

        res.append('{:11.5f} ms'.format(timeit(f'np_sort({inputs}1, {inputs}2)', f'from __main__ import {inputs}1, {inputs}2, np_sort',
                 number=10) * 100))
        res.append('{:11.5f} ms'.format(timeit(f'np_unique({inputs}1, {inputs}2)', f'from __main__ import {inputs}1, {inputs}2, np_unique',
                 number=10) * 100))
        res.append('{:11.5f} ms'.format(timeit(f'np_unique_preserve_order({inputs}1, {inputs}2)', f'from __main__ import {inputs}1, {inputs}2, np_unique_preserve_order',
                 number=10) * 100))
        results.append(res)
    results = zip(*results)
    appmin = lambda l: l + (min(l),)
    print(f'\nno rows {N}, no colums {ncol}')
    print('input type                           lot           list          array           best')
    print(f'symm_diff                ', *appmin(next(results)))
    print(f'np_sort                  ', *appmin(next(results)))
    print(f'np_unique                ', *appmin(next(results)))
    print(f'np_unique_preserve_order ', *appmin(next(results)))

Output:

no rows 10, no colums 2
input type                           lot           list          array           best
symm_diff                     0.00232 ms     0.00453 ms     0.02034 ms     0.00232 ms
np_sort                       0.03890 ms     0.03269 ms     0.03060 ms     0.03060 ms
np_unique                     0.04209 ms     0.04118 ms     0.04136 ms     0.04118 ms
np_unique_preserve_order      0.05289 ms     0.05253 ms     0.05253 ms     0.05253 ms

no rows 10000, no colums 2
input type                           lot           list          array           best
symm_diff                     3.71800 ms     8.30081 ms    21.92841 ms     3.71800 ms
np_sort                       7.98128 ms     8.09973 ms     2.80091 ms     2.80091 ms
np_unique                     8.49229 ms     8.25701 ms     3.00654 ms     3.00654 ms
np_unique_preserve_order     10.12377 ms     8.67133 ms     3.36172 ms     3.36172 ms

no rows 100000, no colums 20
input type                           lot           list          array           best
symm_diff                    97.83141 ms   211.20736 ms   590.15145 ms    97.83141 ms
np_sort                     317.73268 ms   316.50081 ms    89.97820 ms    89.97820 ms
np_unique                   324.68922 ms   326.89891 ms    98.06377 ms    98.06377 ms
np_unique_preserve_order    339.18597 ms   339.00286 ms   120.94041 ms   120.94041 ms

For very small arrays symm_diff is fastest, but for larger ones np_sort has a small edge when all methods are allowed to use the data type they are most comfortable with.


问:
remove extraneous characters from a filename
I have been tasked a little above my head with taking a repository of files and removing excess garbage characters from the filename and saving the renamed file in a different directory folder.

An example of the filenames are:

```
100-expresstoll.pdf
1000-2012-09-29.jpg
10000-2014-01-15_14.03.22.jpg
10001-2014-01-15_19.05.24.jpg
10002-2014-01-15_21.30.23.jpg
10003-2014-01-16_07.33.54.jpg
10004-2014-01-16_13.33.21.jpg
10005-Feb 4, 2014.jpeg
10006-O'Reilly_Media,_Inc..pdf
```

First group of numbers at the beginning are record IDs and are to be retained along with the file's extension. Everything else between the record IDs and the file extension needs to be dropped.

For example, the final name for first three files would be:

```
100.pdf
1000.jpg
10000.jpg
```

I have read Removing characters and Rearranging filenames in addition to other postings, but the complexity of having a variable character length at the front, a variable number of intermediary characters to be removed and variable file extension types have really tossed this beyond my limited PowerShell reach.

答:
Probably the most idiomatic way of solving this is as follows (assumes that all files of interest - and no others - are in the current dir.):

```<code>Get-ChildItem -File | Rename-Item -NewName { ($_.BaseName -split '-')[0] + $_.Extension }
</code>```

Add common parameter -WhatIf to the Rename-Item command to preview the renaming operation.

Note that Rename-Item always renames items in their current location; to (also) move them, use Move-Item.

If a target with the same name already exists, Rename-Item reports a non-terminating error for each such case (without aborting overall processing).

Note that his could also happen if an input filename contains no -, as that would result in attempt to rename a file to itself.

Explanation:

Get-ChildItem -File outputs [System.IO.FileInfo] objects representing the files in the current directory, which are passed through the pipeline (|) to Rename-Item.

Passing a script block ({ ... }) to Rename-Item's -NewName parameter executes the contained code for each input object, where $_ represents the input object at hand.

Note that this virtually undocumented but frequently used technique is called a script-block parameter [value], where a parameter that is designed to take pipeline input can be bound with a script block that processes the input indirectly.

($_.BaseName -split '-')[0] extracts the 1st --separated token from each input filename's base name (filename without extension).

+, because the LHS is a string, performs string concatenation.

$_.Extension extracts the filename extension  from each input filename.

Body:
I have been tasked a little above my head with taking a repository of files and removing excess garbage characters from the filename and saving the renamed file in a different directory folder.

An example of the filenames are:

100-expresstoll.pdf
1000-2012-09-29.jpg
10000-2014-01-15_14.03.22.jpg
10001-2014-01-15_19.05.24.jpg
10002-2014-01-15_21.30.23.jpg
10003-2014-01-16_07.33.54.jpg
10004-2014-01-16_13.33.21.jpg
10005-Feb 4, 2014.jpeg
10006-O'Reilly_Media,_Inc..pdf

First group of numbers at the beginning are record IDs and are to be retained along with the file's extension. Everything else between the record IDs and the file extension needs to be dropped.

For example, the final name for first three files would be:

100.pdf
1000.jpg
10000.jpg

I have read Removing characters and Rearranging filenames in addition to other postings, but the complexity of having a variable character length at the front, a variable number of intermediary characters to be removed and variable file extension types have really tossed this beyond my limited PowerShell reach.

Body:
Probably the most idiomatic way of solving this is as follows (assumes that all files of interest - and no others - are in the current dir.):

Get-ChildItem -File | Rename-Item -NewName { ($_.BaseName -split '-')[0] + $_.Extension }

Add common parameter -WhatIf to the Rename-Item command to preview the renaming operation.

Note that Rename-Item always renames items in their current location; to (also) move them, use Move-Item.

If a target with the same name already exists, Rename-Item reports a non-terminating error for each such case (without aborting overall processing).

Note that his could also happen if an input filename contains no -, as that would result in attempt to rename a file to itself.

Explanation:

Get-ChildItem -File outputs [System.IO.FileInfo] objects representing the files in the current directory, which are passed through the pipeline (|) to Rename-Item.

Passing a script block ({ ... }) to Rename-Item's -NewName parameter executes the contained code for each input object, where $_ represents the input object at hand.

Note that this virtually undocumented but frequently used technique is called a script-block parameter [value], where a parameter that is designed to take pipeline input can be bound with a script block that processes the input indirectly.

($_.BaseName -split '-')[0] extracts the 1st --separated token from each input filename's base name (filename without extension).

+, because the LHS is a string, performs string concatenation.

$_.Extension extracts the filename extension  from each input filename.


问:
Running SonarQube analysis scan - SonarSource build-wrapper
I'm new to running SonarQube scans and I get this error message in the log in Jenkins:

16:17:39 16:17:36.926 ERROR - The only way to get an accurate analysis of your C/C++/Objective-C project is by using the SonarSource build-wrapper. If for any reason, the use of the build-wrapper is not possible on your project, you can bypass it with the help of the "sonar.cfamily.build-wrapper-output.bypass=true" property. By using that property, you'll switch to an "at best" mode that could result in false-positives and false-negatives.

Can someone please advise where I can find and run this SonarSource build-wrapper?

Thanks a lot for your help!

答:
Build wrapper downloads:

Linux: https://sonarcloud.io/static/cpp/build-wrapper-linux-x86.zip

macOS: https://sonarcloud.io/static/cpp/build-wrapper-macosx-x86.zip

Windows: https://sonarcloud.io/static/cpp/build-wrapper-win-x86.zip

Some links covering how to run the build wrapper:

https://docs.sonarqube.org/latest/analysis/languages/cfamily/

https://blog.sonarsource.com/with-great-power-comes-great-configuration/

ContentLicense: CC BY-SA 4.0


问:
Does anyone know how to return a grid into the shell based on a txt file?
Iam trying to make a small interior designing app, I type a txt file and make my program return the grid on shell.
I just need to know how to make a grid where the height and width are both 20.

These are the codes I have so far.. I only know how to make the width but not the height. I also don't know how to get the numbers and letters from my txt file but i made my txt file into a list line by line.

```<code>f = open('Apt_3_4554_Hastings_Coq.txt','r')
bigListA = [ line.strip().split(',') for line in f ]

offset = "   "
width = 20
string1 = offset
for number in range(width):
    if len(str(number)) == 1:
        string1 += " " + str(number) + " "
    else:
        string1 += str(number) + " "
print (string1)
</code>```

答:
A bit of an overkill, but it was fun to make a class around it:

```<code>def decimal_string(number, before=True):
    """
    Convert a number between 0 and 99 to a space padded string.

    Parameters
    ----------
    number: int
        The number to convert to string.
    before: bool
        Whether to place the spaces before or after the nmuber.

    Examples
    --------
    >>> decimal_string(1)
    ' 1'
    >>> decimal_string(1, False)
    '1 '
    >>> decimal_string(10)
    '10'
    >>> decimal_string(10, False)
    '10'
    """
    number = int(number)%100
    if number < 10:
        if before:
            return ' ' + str(number)
        else:
            return str(number) + ' '
    else:
        return str(number)

class Grid(object):
    def __init__(self, doc=None, shape=(10,10)):
        """
        Create new grid object from a given file or with a given shape.

        Parameters
        ----------
        doc: file, None
            The name of the file from where to read the data.
        shape: (int, int), (10, 10)
            The shape to use if no `doc` is provided.
        """
        if doc is not None:
            self.readfile(doc)
        else:
            self.empty_grid(shape)

    def __repr__(self):
        """
        Representation method.
        """
        # first lines
        #    0  1  2  3  4  5  6  7 ...
        #    -  -  -  -  -  -  -  - ...
        number_line = '   '
        traces_line = '   '
        for i in range(len(self.grid)):
            number_line += decimal_string(i) + ' '
            traces_line += ' - '
        lines = ''
        for j in range(len(self.grid[0])):
            line = decimal_string(j, False) + '|'
            for i in range(len(self.grid)):
                line += ' ' + self.grid[i][j] + ' '
            lines += line + '|\n'
        return '\n'.join((number_line, traces_line, lines[:-1], traces_line))

    def readfile(self, doc):
        """
        Read instructions from a file, overwriting current grid.
        """
        with open(doc, 'r') as open_doc:
            lines = open_doc.readlines()
        shape = lines[0].split(' ')[-2:]
        # grabs the first line (line[0]),
        # splits the line into pieces by the ' ' symbol
        # grabs the last two of them ([-2:])
        shape = (int(shape[0]), int(shape[1]))
        # and turns them into numbers (np.array(..., dtype=int))
        self.empty_grid(shape=shape)
        for instruction in lines[1:]:
            self.add_pieces(*self._parse(instruction))

    def empty_grid(self, shape=None):
        """
        Empty grid, changing the shape to the new one, if provided.
        """
        if shape is None:
            # retain current shape
            shape = (len(self.grid), len(self.grid[0]))
        self.grid = [[' ' for i in range(shape[0])]
                          for j in range(shape[1])]

    def _parse(self, instruction):
        """
        Parse string instructions in the shape:
            "C 5 6 13 13"
        where the first element is the charachter,
        the second and third elements are the vertical indexes
        and the fourth and fifth are the horizontal indexes
        """
        pieces = instruction.split(' ')
        char = pieces[0]
        y_start = int(pieces[1])
        y_stop = int(pieces[2])
        x_start = int(pieces[3])
        x_stop = int(pieces[4])
        return char, y_start, y_stop, x_start, x_stop

    def add_pieces(self, char, y_start, y_stop, x_start, x_stop):
        """
        Add a piece to the current grid.

        Parameters
        ----------
        char: str
            The char to place in the grid.
        y_start: int
            Vertical start index.
        y_stop: int
            Vertical stop index.
        x_start: int
            Horizontal start index.
        x_stop: int
            Horizontal stop index.

        Examples
        --------
        >>> b = Grid(shape=(4, 4))
        >>> b
            0  1  2  3
            -  -  -  -
        0 |            |
        1 |            |
        2 |            |
        3 |            |
            -  -  -  -
        >>> b.add_pieces('a', 0, 1, 0, 0)
        >>> b
            0  1  2  3
            -  -  -  -
        0 | a          |
        1 | a          |
        2 |            |
        3 |            |
            -  -  -  -
        >>> b.add_pieces('b', 3, 3, 2, 3)
        >>> b
            0  1  2  3
            -  -  -  -
        0 | a          |
        1 | a          |
        2 |            |
        3 |       b  b |
            -  -  -  -
        """
        assert y_start <= y_stop < len(self.grid[0]),\
               "Vertical index out of bounds."
        assert x_start <= x_stop < len(self.grid),\
               "Horizontal index out of bounds."
        for i in range(x_start, x_stop+1):
            for j in range(y_start, y_stop+1):
                self.grid[i][j] = char
</code>```

You can then have file.txt with:

```<code>    20 20
C 5 6 13 13
C 8 9 13 13
C 5 6 18 18
C 8 9 18 18
C 3 3 15 16
C 11 11 15 16
E 2 3 3 6
S 17 18 2 7
t 14 15 3 6
T 4 10 14 17
</code>```

and make:

```<code>>>> a = Grid('file.txt')
>>> a
    0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19
    -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -
0 |                                                            |
1 |                                                            |
2 |          E  E  E  E                                        |
3 |          E  E  E  E                          C  C          |
4 |                                           T  T  T  T       |
5 |                                        C  T  T  T  T  C    |
6 |                                        C  T  T  T  T  C    |
7 |                                           T  T  T  T       |
8 |                                        C  T  T  T  T  C    |
9 |                                        C  T  T  T  T  C    |
10|                                           T  T  T  T       |
11|                                              C  C          |
12|                                                            |
13|                                                            |
14|          t  t  t  t                                        |
15|          t  t  t  t                                        |
16|                                                            |
17|       S  S  S  S  S  S                                     |
18|       S  S  S  S  S  S                                     |
19|                                                            |
    -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -
</code>```

Body:
Iam trying to make a small interior designing app, I type a txt file and make my program return the grid on shell.
I just need to know how to make a grid where the height and width are both 20.

These are the codes I have so far.. I only know how to make the width but not the height. I also don't know how to get the numbers and letters from my txt file but i made my txt file into a list line by line.

f = open('Apt_3_4554_Hastings_Coq.txt','r')
bigListA = [ line.strip().split(',') for line in f ]

offset = "   "
width = 20
string1 = offset
for number in range(width):
    if len(str(number)) == 1:
        string1 += " " + str(number) + " "
    else:
        string1 += str(number) + " "
print (string1)

Body:
A bit of an overkill, but it was fun to make a class around it:

def decimal_string(number, before=True):
    """
    Convert a number between 0 and 99 to a space padded string.

    Parameters
    ----------
    number: int
        The number to convert to string.
    before: bool
        Whether to place the spaces before or after the nmuber.

    Examples
    --------
    >>> decimal_string(1)
    ' 1'
    >>> decimal_string(1, False)
    '1 '
    >>> decimal_string(10)
    '10'
    >>> decimal_string(10, False)
    '10'
    """
    number = int(number)%100
    if number < 10:
        if before:
            return ' ' + str(number)
        else:
            return str(number) + ' '
    else:
        return str(number)

class Grid(object):
    def __init__(self, doc=None, shape=(10,10)):
        """
        Create new grid object from a given file or with a given shape.

        Parameters
        ----------
        doc: file, None
            The name of the file from where to read the data.
        shape: (int, int), (10, 10)
            The shape to use if no `doc` is provided.
        """
        if doc is not None:
            self.readfile(doc)
        else:
            self.empty_grid(shape)

    def __repr__(self):
        """
        Representation method.
        """
        # first lines
        #    0  1  2  3  4  5  6  7 ...
        #    -  -  -  -  -  -  -  - ...
        number_line = '   '
        traces_line = '   '
        for i in range(len(self.grid)):
            number_line += decimal_string(i) + ' '
            traces_line += ' - '
        lines = ''
        for j in range(len(self.grid[0])):
            line = decimal_string(j, False) + '|'
            for i in range(len(self.grid)):
                line += ' ' + self.grid[i][j] + ' '
            lines += line + '|\n'
        return '\n'.join((number_line, traces_line, lines[:-1], traces_line))

    def readfile(self, doc):
        """
        Read instructions from a file, overwriting current grid.
        """
        with open(doc, 'r') as open_doc:
            lines = open_doc.readlines()
        shape = lines[0].split(' ')[-2:]
        # grabs the first line (line[0]),
        # splits the line into pieces by the ' ' symbol
        # grabs the last two of them ([-2:])
        shape = (int(shape[0]), int(shape[1]))
        # and turns them into numbers (np.array(..., dtype=int))
        self.empty_grid(shape=shape)
        for instruction in lines[1:]:
            self.add_pieces(*self._parse(instruction))

    def empty_grid(self, shape=None):
        """
        Empty grid, changing the shape to the new one, if provided.
        """
        if shape is None:
            # retain current shape
            shape = (len(self.grid), len(self.grid[0]))
        self.grid = [[' ' for i in range(shape[0])]
                          for j in range(shape[1])]

    def _parse(self, instruction):
        """
        Parse string instructions in the shape:
            "C 5 6 13 13"
        where the first element is the charachter,
        the second and third elements are the vertical indexes
        and the fourth and fifth are the horizontal indexes
        """
        pieces = instruction.split(' ')
        char = pieces[0]
        y_start = int(pieces[1])
        y_stop = int(pieces[2])
        x_start = int(pieces[3])
        x_stop = int(pieces[4])
        return char, y_start, y_stop, x_start, x_stop

    def add_pieces(self, char, y_start, y_stop, x_start, x_stop):
        """
        Add a piece to the current grid.

        Parameters
        ----------
        char: str
            The char to place in the grid.
        y_start: int
            Vertical start index.
        y_stop: int
            Vertical stop index.
        x_start: int
            Horizontal start index.
        x_stop: int
            Horizontal stop index.

        Examples
        --------
        >>> b = Grid(shape=(4, 4))
        >>> b
            0  1  2  3
            -  -  -  -
        0 |            |
        1 |            |
        2 |            |
        3 |            |
            -  -  -  -
        >>> b.add_pieces('a', 0, 1, 0, 0)
        >>> b
            0  1  2  3
            -  -  -  -
        0 | a          |
        1 | a          |
        2 |            |
        3 |            |
            -  -  -  -
        >>> b.add_pieces('b', 3, 3, 2, 3)
        >>> b
            0  1  2  3
            -  -  -  -
        0 | a          |
        1 | a          |
        2 |            |
        3 |       b  b |
            -  -  -  -
        """
        assert y_start <= y_stop < len(self.grid[0]),\
               "Vertical index out of bounds."
        assert x_start <= x_stop < len(self.grid),\
               "Horizontal index out of bounds."
        for i in range(x_start, x_stop+1):
            for j in range(y_start, y_stop+1):
                self.grid[i][j] = char

You can then have file.txt with:

    20 20
C 5 6 13 13
C 8 9 13 13
C 5 6 18 18
C 8 9 18 18
C 3 3 15 16
C 11 11 15 16
E 2 3 3 6
S 17 18 2 7
t 14 15 3 6
T 4 10 14 17

and make:

>>> a = Grid('file.txt')
>>> a
    0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19
    -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -
0 |                                                            |
1 |                                                            |
2 |          E  E  E  E                                        |
3 |          E  E  E  E                          C  C          |
4 |                                           T  T  T  T       |
5 |                                        C  T  T  T  T  C    |
6 |                                        C  T  T  T  T  C    |
7 |                                           T  T  T  T       |
8 |                                        C  T  T  T  T  C    |
9 |                                        C  T  T  T  T  C    |
10|                                           T  T  T  T       |
11|                                              C  C          |
12|                                                            |
13|                                                            |
14|          t  t  t  t                                        |
15|          t  t  t  t                                        |
16|                                                            |
17|       S  S  S  S  S  S                                     |
18|       S  S  S  S  S  S                                     |
19|                                                            |
    -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -


问:
How to use fscanf to reads any character into a string until a tab is reached?
How to use fscanf to reads any character into a string until a tab is reached?

My data file have only 1 row:

```<code>123'\t'(Tab)345'\t'Le Duc Huy'\t'567
</code>```

and i use fscanf like this:

```<code>fscanf(fin,"%d %d %d %[^\t]%s %d",&m,&n,&k,s,&q);
</code>```

it return q with wrong value. Anybody can tell me what made it failed?

答: Eliminate the space before %[. It's eating your tab. Also, as others have said, this code is unsafe and probably unreliable on input that's not formatted exactly as you expect. It would be better to use fgets and then parse it yourself with strtol and a few for loops.

Body:
How to use fscanf to reads any character into a string until a tab is reached?

My data file have only 1 row:

123'\t'(Tab)345'\t'Le Duc Huy'\t'567

and i use fscanf like this:

fscanf(fin,"%d %d %d %[^\t]%s %d",&m,&n,&k,s,&q);

it return q with wrong value. Anybody can tell me what made it failed?


问:
How do I switch rows and columns in a 2D array?
I am working on a code that will create a visual Sierpinski triangle to 3D print, and in order for it to work I have to use a Pascal triangle algorithm that will create an array so I can use to tell my algorithm that will create my triangles where not to put triangles.

Anyway the problem is, that my code that arranges the triangles creates the triangles by column instead of by row like the Pascal algorithm does so I am just trying to do a quick fix by having a subroutine that rearranges the Pascal array. I am just stumped on how to do it since I am not sure how to avoid index out of range errors.

This is the code that creates the array for Pascal's triangle.

TL:DR I am trying to make an rearrange an array where rows are the columns and columns are the rows

```<code>def pascal(n):
    """Prints out n rows of Pascal's triangle."""
    row = [1]
    global array
    array = [[0 for x in range(int(n))] for y in range(int(n))]
    array[0]=row
    k = [0]
    for x in range(int(max(n,0)-1)):
       row=[l+r for l,r in zip(row+k,k+row)]
       array[x+1]=row
    return 1
</code>```

This is the output of printing the array. I just want the rows to be columns and columns to be rows

[[1],
 [1, 1],
 [1, 2, 1],
 [1, 3, 3, 1],
 [1, 4, 6, 4, 1],
 [1, 5, 10, 10, 5, 1],
 [1, 6, 15, 20, 15, 6, 1],
 [1, 7, 21, 35, 35, 21, 7, 1]]
```

<p>Here is the full code if you are curious about the project, but it requires <code>rhinoscriptsyntax</code> to make the model.</p>

```import rhinoscriptsyntax as rhino
import math

obj = rhino.GetObject("Select object to transform", preselect=True)
scale = 3
n=math.pow(3,scale)
def pascal(n):
   """Prints out n rows of Pascal's triangle."""
   row = [1]
   global array
   array = [[0 for x in range(int(n))] for y in range(int(n))]
   array[0]=row
   k = [0]
   for x in range(int(max(n,0)-1)):
      row=[l+r for l,r in zip(row+k,k+row)]
      array[x+1]=row
   return 1
pascal(math.pow(2,scale))
print array
def remakePascal():
    pass
my_horizontalVector = [[1,0,0,6],
           [0,1,0,0],
           [0,0,1,0],
           [0,0,0,1]]

my_tsfm = [[1,0,0,0],  #identity
           [0,1,0,0],
           [0,0,1,0],
           [0,0,0,1]]

def makeTriangle(scale,obj):
    w=1/scale
    h=1/scale
    tsfm= [[w,0,0,0],   #scale about origin
            [0,h,0,0],
            [0,0,1,0],
            [0,0,0,1]]
    output= rhino.XformMultiply(my_tsfm,tsfm)
    new_obj=rhino.TransformObject(obj,output,copy=True)
    return new_obj
def placeObj(i):
    my_moveUpVector = [[1,0,0,(3/scale)*i],
           [0,1,0,(4/scale)*i],
           [0,0,1,0],
           [0,0,0,1]]
    vector = rhino.XformMultiply(my_tsfm,my_moveUpVector)
    return vector
n=0
for i in range(int(math.pow(2,scale))):
    if(i>0):
       hPlace=rhino.XformMultiply(my_tsfm,my_horizontalVector)
       obj = rhino.TransformObject(obj,hPlace)
    factor = int(math.pow(2,scale))-n
    for j in range(factor):
        if():
            pass
        else:
            Vertobj=makeTriangle(scale,obj)
            tsfm = rhino.TransformObject(Vertobj,placeObj(j),copy=True)
    n=n+1
```

答:
For transposing square arrays, the simple solution is

```<code>transposed_array = zip(*array)
</code>```

This approach is not suitable for triangular data as zip does not insert padding when the rows are of unequal length. itertools.izip_longest does, however:

```<code>import itertools
transposed_array = itertools.izip_longest(*array)
</code>```

By default izip_longest pads with None, so you get results like:

```<code>[(1, 1, 1, 1, 1),
 (None, 1, 2, 3, 4),
 (None, None, 1, 3, 6),
 (None, None, None, 1, 4),
 (None, None, None, None, 1)]
</code>```

If you wish, you can remove the None entries with a list comprehension:

```<code>no_nones = [[item for item in row if item is not None] for row in transposed_array]
</code>```

which leaves you with:

```<code>[[1, 1, 1, 1, 1],
 [1, 2, 3, 4],
 [1, 3, 6],
 [1, 4],
 [1]]
</code>```

If you prefer to pad with 0s (or anything else), specify that as the fillvalue keyword argument to itertools.izip_longest; e.g.

```<code>list(itertools.izip_longest(*array, fillvalue=0))
</code>```

returns

```<code>[(1, 1, 1, 1, 1),
 (0, 1, 2, 3, 4),
 (0, 0, 1, 3, 6),
 (0, 0, 0, 1, 4),
 (0, 0, 0, 0, 1)]
</code>```

I'm assuming here that a list of tuples works for your purposes. If you need the inside to mutable, you can get that with a list comprehension, e.g.:

```<code>list_of_lists = [list(row) for row in transposed_array]
</code>```

Body:
I am working on a code that will create a visual Sierpinski triangle to 3D print, and in order for it to work I have to use a Pascal triangle algorithm that will create an array so I can use to tell my algorithm that will create my triangles where not to put triangles.

Anyway the problem is, that my code that arranges the triangles creates the triangles by column instead of by row like the Pascal algorithm does so I am just trying to do a quick fix by having a subroutine that rearranges the Pascal array. I am just stumped on how to do it since I am not sure how to avoid index out of range errors.

This is the code that creates the array for Pascal's triangle.

TL:DR I am trying to make an rearrange an array where rows are the columns and columns are the rows

def pascal(n):
    """Prints out n rows of Pascal's triangle."""
    row = [1]
    global array
    array = [[0 for x in range(int(n))] for y in range(int(n))]
    array[0]=row
    k = [0]
    for x in range(int(max(n,0)-1)):
       row=[l+r for l,r in zip(row+k,k+row)]
       array[x+1]=row
    return 1

This is the output of printing the array. I just want the rows to be columns and columns to be rows

[[1],
 [1, 1],
 [1, 2, 1],
 [1, 3, 3, 1],
 [1, 4, 6, 4, 1],
 [1, 5, 10, 10, 5, 1],
 [1, 6, 15, 20, 15, 6, 1],
 [1, 7, 21, 35, 35, 21, 7, 1]]

Here is the full code if you are curious about the project, but it requires rhinoscriptsyntax to make the model.

import rhinoscriptsyntax as rhino
import math

obj = rhino.GetObject("Select object to transform", preselect=True)
scale = 3
n=math.pow(3,scale)
def pascal(n):
   """Prints out n rows of Pascal's triangle."""
   row = [1]
   global array
   array = [[0 for x in range(int(n))] for y in range(int(n))]
   array[0]=row
   k = [0]
   for x in range(int(max(n,0)-1)):
      row=[l+r for l,r in zip(row+k,k+row)]
      array[x+1]=row
   return 1
pascal(math.pow(2,scale))
print array
def remakePascal():
    pass
my_horizontalVector = [[1,0,0,6],
           [0,1,0,0],
           [0,0,1,0],
           [0,0,0,1]]

my_tsfm = [[1,0,0,0],  #identity
           [0,1,0,0],
           [0,0,1,0],
           [0,0,0,1]]

def makeTriangle(scale,obj):
    w=1/scale
    h=1/scale
    tsfm= [[w,0,0,0],   #scale about origin
            [0,h,0,0],
            [0,0,1,0],
            [0,0,0,1]]
    output= rhino.XformMultiply(my_tsfm,tsfm)
    new_obj=rhino.TransformObject(obj,output,copy=True)
    return new_obj
def placeObj(i):
    my_moveUpVector = [[1,0,0,(3/scale)*i],
           [0,1,0,(4/scale)*i],
           [0,0,1,0],
           [0,0,0,1]]
    vector = rhino.XformMultiply(my_tsfm,my_moveUpVector)
    return vector
n=0
for i in range(int(math.pow(2,scale))):
    if(i>0):
       hPlace=rhino.XformMultiply(my_tsfm,my_horizontalVector)
       obj = rhino.TransformObject(obj,hPlace)
    factor = int(math.pow(2,scale))-n
    for j in range(factor):
        if():
            pass
        else:
            Vertobj=makeTriangle(scale,obj)
            tsfm = rhino.TransformObject(Vertobj,placeObj(j),copy=True)
    n=n+1

Body:
For transposing square arrays, the simple solution is

transposed_array = zip(*array)

This approach is not suitable for triangular data as zip does not insert padding when the rows are of unequal length. itertools.izip_longest does, however:

import itertools
transposed_array = itertools.izip_longest(*array)

By default izip_longest pads with None, so you get results like:

[(1, 1, 1, 1, 1),
 (None, 1, 2, 3, 4),
 (None, None, 1, 3, 6),
 (None, None, None, 1, 4),
 (None, None, None, None, 1)]

If you wish, you can remove the None entries with a list comprehension:

no_nones = [[item for item in row if item is not None] for row in transposed_array]

which leaves you with:

[[1, 1, 1, 1, 1],
 [1, 2, 3, 4],
 [1, 3, 6],
 [1, 4],
 [1]]

If you prefer to pad with 0s (or anything else), specify that as the fillvalue keyword argument to itertools.izip_longest; e.g.

list(itertools.izip_longest(*array, fillvalue=0))

returns

[(1, 1, 1, 1, 1),
 (0, 1, 2, 3, 4),
 (0, 0, 1, 3, 6),
 (0, 0, 0, 1, 4),
 (0, 0, 0, 0, 1)]

I'm assuming here that a list of tuples works for your purposes. If you need the inside to mutable, you can get that with a list comprehension, e.g.:

list_of_lists = [list(row) for row in transposed_array]


答:
Another approach without regular expression. In both following examples is used  risk mitigation parameter -WhatIf for debugging purposes.

Rename files:

```<code>Get-ChildItem -File | ForEach-Object {
    $oldFile = $_.FullName
    $newName = $_.BaseName.Split('-')[0] + $_.Extension
    if ($_.Name -ne $newName) {
        Rename-Item -Path $oldFile -NewName $newName -WhatIf
    }
}
</code>```

Rename and move files:

```<code>$newDest = 'D:\test'                       ### change to fit your circumstances
Get-ChildItem -File | ForEach-Object {
    $oldFile = $_.FullName
    $newName = $_.BaseName.Split('-')[0] + $_.Extension
    $newFile = Join-Path -Path $newDest -ChildPath $newName
    if ( -not ( Test-Path -Path $newFile ) ) {
        Move-Item -Path $oldFile -Destination $newFile -WhatIf
    }
}
</code>```

Title: remove extraneous characters from a filename

Body:
Another approach without regular expression. In both following examples is used  risk mitigation parameter -WhatIf for debugging purposes.

Rename files:

Get-ChildItem -File | ForEach-Object {
    $oldFile = $_.FullName
    $newName = $_.BaseName.Split('-')[0] + $_.Extension
    if ($_.Name -ne $newName) {
        Rename-Item -Path $oldFile -NewName $newName -WhatIf
    }
}

Rename and move files:

$newDest = 'D:\test'                       ### change to fit your circumstances
Get-ChildItem -File | ForEach-Object {
    $oldFile = $_.FullName
    $newName = $_.BaseName.Split('-')[0] + $_.Extension
    $newFile = Join-Path -Path $newDest -ChildPath $newName
    if ( -not ( Test-Path -Path $newFile ) ) {
        Move-Item -Path $oldFile -Destination $newFile -WhatIf
    }
}


问:
How to get click event from markerclustererplus
I implented markerclustererplus in my jquery script like this:

```<code>$('#map_canvas').gmap({'streetViewControl':false,'mapTypeId': 'terrain'}).bind('init', function(evt, map) {
    var mcOptions = {gridSize: 30, maxZoom: 15, ignoreHidden:true};
    $('#map_canvas').gmap('set', 'MarkerClusterer', new MarkerClusterer(map, $('#map_canvas').gmap('get', 'markers'),mcOptions));
});
});
</code>```

Everything is fine so far. The question is: How do i catch the click event, if user clicks on a cluster?

答:
Using MarkerClustererPlus, just attach the event listener to the google maps addListener method:

```<code>var markerCluster = new MarkerClusterer(map, markers, {options});

google.maps.event.addListener(markerCluster, "click", function (c) {
    console.log('Cluster Object:' + c)
});
</code>```

Body:
I implented markerclustererplus in my jquery script like this:

$('#map_canvas').gmap({'streetViewControl':false,'mapTypeId': 'terrain'}).bind('init', function(evt, map) {
    var mcOptions = {gridSize: 30, maxZoom: 15, ignoreHidden:true};
    $('#map_canvas').gmap('set', 'MarkerClusterer', new MarkerClusterer(map, $('#map_canvas').gmap('get', 'markers'),mcOptions));
});
});

Everything is fine so far. The question is: How do i catch the click event, if user clicks on a cluster?

Body:
Using MarkerClustererPlus, just attach the event listener to the google maps addListener method:

var markerCluster = new MarkerClusterer(map, markers, {options});

google.maps.event.addListener(markerCluster, "click", function (c) {
    console.log('Cluster Object:' + c)
});


问:
Eclipse doesn't provide quick fix option for Python as it does for Java
I would like to see quick fixes option in Eclipse for Python. Is there any way to configure it?

For example: In Java, if I don't provide a package name for InputStream, then Eclipse recommends few package options (as shown in below image).

But the same is not happening for PyDev Editor. For suppose, if I don't enter SimpleProducer library, then eclipse doesn't provide any recommendations to fix it (as shown in below image).

Any thoughts?

答:
The Quick Fix / Content Assistants feature of PyDev is activated with the key combination Ctrl + 1.

There are also some other good to know key combinations listed at http://www.pydev.org/manual_adv_keybindings.html


问:
Why does Python mimetype guess XSL when passed an XML file?
When passed a file with a mimetype application/xml, the Python std lib mimetypes.guess_extension method guesses an .xsl extension. This is actually hard-coded in.

Why does it do that?

答: Apparently there are a host of these, and the Python mimetypes module shouldn't generally be relied upon for these kinds of operations. See the bug I filed in the Python bug tracker (and from there, the "superissue").</p>


问:
Why is my new schema not showing in the table properites pane?
I am using SQL Server 2008 Express and Sql Server Management Studio 2008.

I am trying to associate a database table with a new schema.

I have created a new Schema by navigating to Security->Schemas in object explorer. I right clicked on the folder and created a new schema called 'People' and set the owner as db_owner. This new Schema now appears in object explorer.

I would now like to associate a table with this schema. I open the table in design view and click on the drop down list in the table Properties pane which contains the available schemas but my newly created schema is not visible.

I have tried refreshing everything throughout object explorer. Closing design view and reopening etc. but still it isn't there.

Am I doing something wrong?

Can anyone point me in the right direction please?

答:
Sorted... in the most ridiculous way.

Apparently refreshing object browser at every hierarchical level is not sufficient.

I had to CLOSE sql management studio, then re-open it. The list of schemas had then managed to refresh and would allow me to associate my new custom schema with the table.

IMO this is rubbish.


问:
Calculating MSE: why are these two ways giving different results?
I am having some doubt regarding the calculation of MSE in R.

I have tried two different ways and I am getting two different results. Wanted to know which one is the correct way of finding mse.

First:

```<code>model1 <- lm(data=d, x ~ y)
rmse_model1 <- mean((d - predict(model1))^2)
</code>```

Second:

```<code>mean(model1$residuals^2)
</code>```

答:
In principle, they should give you the same result. But in the first option, you should use d$x. If you just use d, recycling rule in R will repeat predict(model1) twice (as d has two columns) and the computation will also involve d$y.

Note that it is recommended to include na.rm = TRUE to mean, and newdata = d to predict in the first option. This makes your code robust to missing values in your data. On the other hand you don't need worry about NA in the second option, as lm automatically drops NA cases. You may have a look at this thread for potential effect of this feature: Aligning Data frame with missing values.

Body:
I am having some doubt regarding the calculation of MSE in R.

I have tried two different ways and I am getting two different results. Wanted to know which one is the correct way of finding mse.

First:

model1 <- lm(data=d, x ~ y)
rmse_model1 <- mean((d - predict(model1))^2)

Second:

mean(model1$residuals^2)


问:
"Google Play services are updating" message in SupportMapFragment when in release mode
I have this strange issue with GoogleMaps.

When I'm in debug mode everything works fine, but when I'm in release mode the onMapReady callback is never called and the map display the "Google Play services are updating" message.

Another strange thing is that if I run an activity at the application start with a map it works, even in other activities.

This is my code in the fragment

```<code>@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    FrameLayout fr = (FrameLayout) inflater.inflate(R.layout.my_fragment, null);
    //views code

    SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    return fr;
}
</code>```

答:
Try adding this line to the proguard rules file

```<code>-keep class com.google. ** {*; }
</code>```

Hope it helps

Body:
I have this strange issue with GoogleMaps.

When I'm in debug mode everything works fine, but when I'm in release mode the onMapReady callback is never called and the map display the "Google Play services are updating" message.

Another strange thing is that if I run an activity at the application start with a map it works, even in other activities.

This is my code in the fragment

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    FrameLayout fr = (FrameLayout) inflater.inflate(R.layout.my_fragment, null);
    //views code

    SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    return fr;
}

Body:
Try adding this line to the proguard rules file

-keep class com.google. ** {*; }

Hope it helps


问:
CPropertyPage dialogue OnOk should not close the dialogue if there is an error
I have a class which inherits from CPropertyPage class. I have a OnOk() method and a OnKillActive() method.
Whenever I press Ok on the dialogue. OnKillActive() gets called but OnOk() is never called.
The problem is depending on a condition I do not want to close the dialogue on pressing Ok. But the dialogue is closing on pressing Ok.

How do I prevent the dialogue from closing when I press Ok?

Code:

```<code>In MyClass.h:
    class MyClass : public CPropertyPage {
    }

In MyClass.cpp:
    void MyClass::OnOK(){
        if (condition true) {
            return; // This should prevent the dialogue from closing but still      the dialogue closes
        }
        return CPropertyPage::OnOk();
    }

    BOOL MyClass::OnKillActive() {
        if (condition true) {
            CDialog::DoModal();
            return FALSE; // This should prevent the dialogue from closing but   still the dialogue closes
        }
        return CPropertyPage::OnKillActive();
    }
</code>```

答:
Actually in the OnClickedOk() function of the PropertySheet class, there was an EndDialog(IDOK). This is why it was closing everytime when Ok was pressed.

I just gave a condition check before EndDialog() and it worked.
Thanks for your reply.

Body:
I have a class which inherits from CPropertyPage class. I have a OnOk() method and a OnKillActive() method.
Whenever I press Ok on the dialogue. OnKillActive() gets called but OnOk() is never called.
The problem is depending on a condition I do not want to close the dialogue on pressing Ok. But the dialogue is closing on pressing Ok.

How do I prevent the dialogue from closing when I press Ok?

Code:

In MyClass.h:
    class MyClass : public CPropertyPage {
    }

In MyClass.cpp:
    void MyClass::OnOK(){
        if (condition true) {
            return; // This should prevent the dialogue from closing but still      the dialogue closes
        }
        return CPropertyPage::OnOk();
    }

    BOOL MyClass::OnKillActive() {
        if (condition true) {
            CDialog::DoModal();
            return FALSE; // This should prevent the dialogue from closing but   still the dialogue closes
        }
        return CPropertyPage::OnKillActive();
    }


问:
Analog to SQL 'JOIN' for Javascript objects?
What's a pragmatic analog to SQL 'JOIN' for tables represented as arrays of Javascript objects?   Javascript Array.join and D3.js 'd3.merge` are not the same concept.

E.g. SELECT * FROM authors LEFT JOIN books ON authors.id = books.author_id?

First table:

```<code>var authors =
[  { id: 1, name: 'adam'},
   { id: 2, name: 'bob'},
   { id: 3, name: 'charlie'}, ...
]
</code>```

Second table:

```<code>var books =
[  { author_id: 1, title: 'Coloring for beginners'},
   { author_id: 1, title: 'Advanced coloring'},
   { author_id: 2, title: '50 Hikes in New England'},
   { author_id: 2, title: '50 Hikes in Illinois'},
   { author_id: 3, title: 'String Theory for Dummies'}, ...
]
</code>```

The tables are loaded from CSV using D3.js d3.csv(), so have D3.js already, open to other libs but generally prefer coding directly if not too far out of the way.

I see Native way to merge objects in Javascript which uses RethinkDB, which seems over the top for this, but this is the idea.

答:
I was looking for something like this as well, and solved it using a bit of functional programming. I've taken the liberty of adding a couple of objects to your initial arrays in order to deal with the "NULL" cases.

```<code>var books = [
    {author_id: 1, title: 'Coloring for beginners'},
    {author_id: 1, title: 'Advanced coloring'},
    {author_id: 2, title: '50 Hikes in New England'},
    {author_id: 2, title: '50 Hikes in Illinois'},
    {author_id: 3, title: 'String Theory for Dummies'},
    {author_id: 5, title: 'Map-Reduce for Fun and Profit'}
];
var authors = [
    {id: 1, name: 'adam'},
    {id: 2, name: 'bob'},
    {id: 3, name: 'charlie'},
    {id: 4, name: 'diane'}
];
</code>```

So now you have a book without an author and an author without a book. My solution looks like this:

```<code>var joined = books.map(function(e) {
    return Object.assign({}, e, authors.reduce(function(acc, val) {
        if (val.id == e.author_id) {
            return val
        } else {
            return acc
        }
    }, {}))
});
</code>```

The map method goes through every element of books using e and returns an array whose elements are the merged object of e, with its corresponding object in the authors array. Object.assign({},a,b) takes care the merge without modifying the original objects.

The corresponding object to each e in books is found by applying a reduce method on the authors array. Starting out with the initial value of an empty object {} (this is the second argument of reduce - it also could have been a null author such as {id:'', name ''}) the reduce method goes through the elements of authors using val and returns the object that ends up in acc. When a match is found between the books author_id and the author's id the entire matched author object ends up in acc and eventually gets returned by authors.reduce(...).

n.b. - Using reduce isn't that efficient because there is no way to break out of reduce loop once the match is found, it will continue to the end of the array

Body:
What's a pragmatic analog to SQL 'JOIN' for tables represented as arrays of Javascript objects?   Javascript Array.join and D3.js 'd3.merge` are not the same concept.

E.g. SELECT * FROM authors LEFT JOIN books ON authors.id = books.author_id?

First table:

var authors =
[  { id: 1, name: 'adam'},
   { id: 2, name: 'bob'},
   { id: 3, name: 'charlie'}, ...
]

Second table:

var books =
[  { author_id: 1, title: 'Coloring for beginners'},
   { author_id: 1, title: 'Advanced coloring'},
   { author_id: 2, title: '50 Hikes in New England'},
   { author_id: 2, title: '50 Hikes in Illinois'},
   { author_id: 3, title: 'String Theory for Dummies'}, ...
]

The tables are loaded from CSV using D3.js d3.csv(), so have D3.js already, open to other libs but generally prefer coding directly if not too far out of the way.

I see Native way to merge objects in Javascript which uses RethinkDB, which seems over the top for this, but this is the idea.

Body:
I was looking for something like this as well, and solved it using a bit of functional programming. I've taken the liberty of adding a couple of objects to your initial arrays in order to deal with the "NULL" cases.

var books = [
    {author_id: 1, title: 'Coloring for beginners'},
    {author_id: 1, title: 'Advanced coloring'},
    {author_id: 2, title: '50 Hikes in New England'},
    {author_id: 2, title: '50 Hikes in Illinois'},
    {author_id: 3, title: 'String Theory for Dummies'},
    {author_id: 5, title: 'Map-Reduce for Fun and Profit'}
];
var authors = [
    {id: 1, name: 'adam'},
    {id: 2, name: 'bob'},
    {id: 3, name: 'charlie'},
    {id: 4, name: 'diane'}
];

So now you have a book without an author and an author without a book. My solution looks like this:

var joined = books.map(function(e) {
    return Object.assign({}, e, authors.reduce(function(acc, val) {
        if (val.id == e.author_id) {
            return val
        } else {
            return acc
        }
    }, {}))
});

The map method goes through every element of books using e and returns an array whose elements are the merged object of e, with its corresponding object in the authors array. Object.assign({},a,b) takes care the merge without modifying the original objects.

The corresponding object to each e in books is found by applying a reduce method on the authors array. Starting out with the initial value of an empty object {} (this is the second argument of reduce - it also could have been a null author such as {id:'', name ''}) the reduce method goes through the elements of authors using val and returns the object that ends up in acc. When a match is found between the books author_id and the author's id the entire matched author object ends up in acc and eventually gets returned by authors.reduce(...).

n.b. - Using reduce isn't that efficient because there is no way to break out of reduce loop once the match is found, it will continue to the end of the array


问:
How to fire an input or change event to trigger AngularJS from external Javascript?
I am doing a school project, working on a website that uses forms to send user data to Mailchimp. The site uses Angularjs to control its inputs (I have no access to this code, nor any knowledge about Angularjs).

What I am trying to accomplish

I want my script to insert whatever text is saved in the 'personalitet' span into the input by name 'form[5606]' and accept it as as filled out, without any interaction from the user.

But Angularjs is refusing to see the input at filled out without the user interacting with the field, what can I do?

How do I trigger the input or change event without having access to the Angularjs script or the HTML markup with external JavaScript?

My Script

```<code>var personalitet = document.getElementById("personalitet").innerHTML;
document.getElementsByName("form[5606]")[0].value = personalitet;
</code>```

The site can be accessed here: site

I have tried using, without luck:

```<code>input.trigger('input');
input.trigger('change');
</code>```

答:
Finally managed to make it work and all that was needed was a .change to tell Angularjs that the input value had changed. As such, the final scrip was:

```<code>var personalitet = document.getElementById("personalitet").innerHTML;
document.getElementsByName("form[5607]")[0].value = personalitet;
$( "input[name='form[5607]']" ).change();
</code>```

Body:
I am doing a school project, working on a website that uses forms to send user data to Mailchimp. The site uses Angularjs to control its inputs (I have no access to this code, nor any knowledge about Angularjs).

What I am trying to accomplish

I want my script to insert whatever text is saved in the 'personalitet' span into the input by name 'form[5606]' and accept it as as filled out, without any interaction from the user.

But Angularjs is refusing to see the input at filled out without the user interacting with the field, what can I do?

How do I trigger the input or change event without having access to the Angularjs script or the HTML markup with external JavaScript?

My Script

var personalitet = document.getElementById("personalitet").innerHTML;
document.getElementsByName("form[5606]")[0].value = personalitet;

The site can be accessed here: site

I have tried using, without luck:

input.trigger('input');
input.trigger('change');

Body:
Finally managed to make it work and all that was needed was a .change to tell Angularjs that the input value had changed. As such, the final scrip was:

var personalitet = document.getElementById("personalitet").innerHTML;
document.getElementsByName("form[5607]")[0].value = personalitet;
$( "input[name='form[5607]']" ).change();