问:
WPF MouseMove InvalidateVisual OnRender update VERY SLOW
I haven't found anything useful either on Google or Stack Overflow or simply no answers (or maybe I just don't know what to search for) -- the closest question I can get to is this one: The reason behind slow performance in WPF

But I want to get to the bottom of this lag in this simple program, maybe I'm just not doing something right.

I'm rendering about 2000 points with lines between them in the OnRender() of a UI Element, essentially creating a line graph. That's okay, but I want to pan the graph with MouseMove. That works fine, but it is the LAG that is the problem. Whenever dragging with the mouse I'd expect a smooth update, I'd think that redrawing 2000 points with lines between them would be a walk in the park for an i5 CPU. But it is incredibly slow, even at low resolutions on my laptop at home. So I checked the Performance Profiler. The OnRender() function hardly uses any CPU.

It turns out it's the Layout that's changing and using so much CPU.

"Layout" is taking the most time to complete

Now, I've heard the term Visual Tree kicking about , but there is hardly any visuals in this simple project. Just a UI Element on a Main Window. And it's using a drawing context, I'd have thought that the drawing context drew like a bitmap, or is it drawing UI elements with their own events/hit boxes etc? Because all I want is the UIElement to act like an image but also handle mouse events so I can drag the whole thing (or zoom with mousewheel).

So Questions:

If Layout is causing the slowness/lag, how can I prevent this?

I also Notice a lot of garbage collection which makes sense, but I don't want it to happen during Rendering. I'd rather do that while it's idle. but how?

Here is the source:

.cs file

```<code>using System;
using System.Collections.Generic;
using System.Globalization;
using System.Windows;
using System.Windows.Media;

namespace SlowChart
{
    public class SlowChartClass : UIElement
    {
        List<Point> points = new List<Point>();

        double XAxis_Width = 2000;
        double XAxis_LeftMost = 0;

        double YAxis_Height = 300;
        double YAxis_Lowest = -150;

        Point mousePoint;
        double XAxis_LeftMostPan = 0;
        double YAxis_LowestPan = 0;

        public SlowChartClass()
        {
            for (int i = 0; i < 2000; i++)
            {
                double cos = (float)Math.Cos(((double)i / 100) * Math.PI * 2);
                cos *= 100;

                points.Add(new Point(i, cos));
            }

            MouseDown += SlowChartClass_MouseDown;
            MouseUp += SlowChartClass_MouseUp;
            MouseMove += SlowChartClass_MouseMove;
        }

        private void SlowChartClass_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            if (IsMouseCaptured)
            {
                XAxis_LeftMost = XAxis_LeftMostPan - (e.GetPosition(this).X - mousePoint.X);
                YAxis_Lowest = YAxis_LowestPan + (e.GetPosition(this).Y - mousePoint.Y);
                InvalidateVisual();
            }
        }

        private void SlowChartClass_MouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            ReleaseMouseCapture();
        }

        private void SlowChartClass_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            mousePoint = e.GetPosition(this);
            XAxis_LeftMostPan = XAxis_LeftMost;
            YAxis_LowestPan = YAxis_Lowest;
            CaptureMouse();
        }

        double translateYToScreen(double Y)
        {
            double y = RenderSize.Height - (RenderSize.Height * ((Y - YAxis_Lowest) / YAxis_Height));

            return y;
        }

        double translateXToScreen(double X)
        {
            double x = (RenderSize.Width * ((X - XAxis_LeftMost) / XAxis_Width));

            return x;
        }

        protected override void OnRender(DrawingContext drawingContext)
        {
            bool lastPointValid = false;
            Point lastPoint = new Point();
            Rect window = new Rect(RenderSize);
            Pen pen = new Pen(Brushes.Black, 1);

            // fill background
            drawingContext.DrawRectangle(Brushes.White, null, window);

            foreach (Point p in points)
            {
                Point screenPoint = new Point(translateXToScreen(p.X), translateYToScreen(p.Y));

                if (lastPointValid)
                {
                    // draw from last to  this one
                    drawingContext.DrawLine(pen, lastPoint, screenPoint);
                }

                lastPoint = screenPoint;
                lastPointValid = true;
            }

            // draw axis
            drawingContext.DrawText(new FormattedText(XAxis_LeftMost.ToString("0.0") + "," + YAxis_Lowest.ToString("0.0"),CultureInfo.InvariantCulture,FlowDirection.LeftToRight,new Typeface("Arial"),12,Brushes.Black),new Point(0,RenderSize.Height-12));

        }
    }
}
</code>```

.XAML file

```<code><Window x:Class="SlowChart.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:SlowChart"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <local:SlowChartClass/>
    </Grid>
</Window>
</code>```

答:
Don't call InvalidateVisual() for this. It triggers a full relayout of your UI, which is very slow.

The key to good performance in WPF is understanding that it's a retained drawing system. OnRender() should really be named AccumulateDrawingObjects(). It is only used at the end of the layout process, and the objects it is accumulating are actually live objects you can update after it's completed.

The efficient way to do what you are trying to do, is create a DrawingGroup "backingStore" for your chart. The only thing your OnRender() needs to do is add the backingStore to the DrawingContext. Then you can update it anytime you want by using backingStore.Open() and just drawing into it. WPF will automatically update your UI.

You'll find StreamGeometry is the fastest way to draw to a DrawingContext, as it optimizes for non-animated geometry.

You can also get some additional performance by using .Freeze() on your Pen, because it is not animated. Though I doubt you will notice when drawing only 2000 points.

It looks something like this:

```<code>DrawingGroup backingStore = new DrawingGroup();

protected override void OnRender(DrawingContext drawingContext) {
    base.OnRender(drawingContext);

    Render(); // put content into our backingStore
    drawingContext.DrawDrawing(backingStore);
}

// Call render anytime, to update visual
// without triggering layout or OnRender()
public void Render() {
    var drawingContext = backingStore.Open();
    Render(drawingContext);
    drawingContext.Close();
}

private void Render(DrawingContext drawingContext) {
    // move the code from your OnRender() here
}
</code>```

If you'd like to see more example code, take a look here:

https://github.com/jeske/SoundLevelMonitor/blob/master/SoundLevelMonitorWPF/SoundLevelMonitor/AudioLevelsUIElement.cs#L172

However, if the visual is relatively static, and all you want to do is pan and zoom around, there are other options. You can create a Canvas, and instantiate Shapes into it, and then during mouse move you mess with the Canvas transform to pan and zoom.

Body:
I haven't found anything useful either on Google or Stack Overflow or simply no answers (or maybe I just don't know what to search for) -- the closest question I can get to is this one: The reason behind slow performance in WPF

But I want to get to the bottom of this lag in this simple program, maybe I'm just not doing something right.

I'm rendering about 2000 points with lines between them in the OnRender() of a UI Element, essentially creating a line graph. That's okay, but I want to pan the graph with MouseMove. That works fine, but it is the LAG that is the problem. Whenever dragging with the mouse I'd expect a smooth update, I'd think that redrawing 2000 points with lines between them would be a walk in the park for an i5 CPU. But it is incredibly slow, even at low resolutions on my laptop at home. So I checked the Performance Profiler. The OnRender() function hardly uses any CPU.

It turns out it's the Layout that's changing and using so much CPU.

"Layout" is taking the most time to complete

Now, I've heard the term Visual Tree kicking about , but there is hardly any visuals in this simple project. Just a UI Element on a Main Window. And it's using a drawing context, I'd have thought that the drawing context drew like a bitmap, or is it drawing UI elements with their own events/hit boxes etc? Because all I want is the UIElement to act like an image but also handle mouse events so I can drag the whole thing (or zoom with mousewheel).

So Questions:

If Layout is causing the slowness/lag, how can I prevent this?

I also Notice a lot of garbage collection which makes sense, but I don't want it to happen during Rendering. I'd rather do that while it's idle. but how?

Here is the source:

.cs file

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Windows;
using System.Windows.Media;

namespace SlowChart
{
    public class SlowChartClass : UIElement
    {
        List<Point> points = new List<Point>();

        double XAxis_Width = 2000;
        double XAxis_LeftMost = 0;

        double YAxis_Height = 300;
        double YAxis_Lowest = -150;

        Point mousePoint;
        double XAxis_LeftMostPan = 0;
        double YAxis_LowestPan = 0;

        public SlowChartClass()
        {
            for (int i = 0; i < 2000; i++)
            {
                double cos = (float)Math.Cos(((double)i / 100) * Math.PI * 2);
                cos *= 100;

                points.Add(new Point(i, cos));
            }

            MouseDown += SlowChartClass_MouseDown;
            MouseUp += SlowChartClass_MouseUp;
            MouseMove += SlowChartClass_MouseMove;
        }

        private void SlowChartClass_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            if (IsMouseCaptured)
            {
                XAxis_LeftMost = XAxis_LeftMostPan - (e.GetPosition(this).X - mousePoint.X);
                YAxis_Lowest = YAxis_LowestPan + (e.GetPosition(this).Y - mousePoint.Y);
                InvalidateVisual();
            }
        }

        private void SlowChartClass_MouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            ReleaseMouseCapture();
        }

        private void SlowChartClass_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            mousePoint = e.GetPosition(this);
            XAxis_LeftMostPan = XAxis_LeftMost;
            YAxis_LowestPan = YAxis_Lowest;
            CaptureMouse();
        }

        double translateYToScreen(double Y)
        {
            double y = RenderSize.Height - (RenderSize.Height * ((Y - YAxis_Lowest) / YAxis_Height));

            return y;
        }

        double translateXToScreen(double X)
        {
            double x = (RenderSize.Width * ((X - XAxis_LeftMost) / XAxis_Width));

            return x;
        }

        protected override void OnRender(DrawingContext drawingContext)
        {
            bool lastPointValid = false;
            Point lastPoint = new Point();
            Rect window = new Rect(RenderSize);
            Pen pen = new Pen(Brushes.Black, 1);

            // fill background
            drawingContext.DrawRectangle(Brushes.White, null, window);

            foreach (Point p in points)
            {
                Point screenPoint = new Point(translateXToScreen(p.X), translateYToScreen(p.Y));

                if (lastPointValid)
                {
                    // draw from last to  this one
                    drawingContext.DrawLine(pen, lastPoint, screenPoint);
                }

                lastPoint = screenPoint;
                lastPointValid = true;
            }

            // draw axis
            drawingContext.DrawText(new FormattedText(XAxis_LeftMost.ToString("0.0") + "," + YAxis_Lowest.ToString("0.0"),CultureInfo.InvariantCulture,FlowDirection.LeftToRight,new Typeface("Arial"),12,Brushes.Black),new Point(0,RenderSize.Height-12));

        }
    }
}

.XAML file

<Window x:Class="SlowChart.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:SlowChart"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <local:SlowChartClass/>
    </Grid>
</Window>

Body:
Don't call InvalidateVisual() for this. It triggers a full relayout of your UI, which is very slow.

The key to good performance in WPF is understanding that it's a retained drawing system. OnRender() should really be named AccumulateDrawingObjects(). It is only used at the end of the layout process, and the objects it is accumulating are actually live objects you can update after it's completed.

The efficient way to do what you are trying to do, is create a DrawingGroup "backingStore" for your chart. The only thing your OnRender() needs to do is add the backingStore to the DrawingContext. Then you can update it anytime you want by using backingStore.Open() and just drawing into it. WPF will automatically update your UI.

You'll find StreamGeometry is the fastest way to draw to a DrawingContext, as it optimizes for non-animated geometry.

You can also get some additional performance by using .Freeze() on your Pen, because it is not animated. Though I doubt you will notice when drawing only 2000 points.

It looks something like this:

DrawingGroup backingStore = new DrawingGroup();

protected override void OnRender(DrawingContext drawingContext) {
    base.OnRender(drawingContext);

    Render(); // put content into our backingStore
    drawingContext.DrawDrawing(backingStore);
}

// Call render anytime, to update visual
// without triggering layout or OnRender()
public void Render() {
    var drawingContext = backingStore.Open();
    Render(drawingContext);
    drawingContext.Close();
}

private void Render(DrawingContext drawingContext) {
    // move the code from your OnRender() here
}

If you'd like to see more example code, take a look here:

https://github.com/jeske/SoundLevelMonitor/blob/master/SoundLevelMonitorWPF/SoundLevelMonitor/AudioLevelsUIElement.cs#L172

However, if the visual is relatively static, and all you want to do is pan and zoom around, there are other options. You can create a Canvas, and instantiate Shapes into it, and then during mouse move you mess with the Canvas transform to pan and zoom.


来源: stackexchange

问:
Are there any good open source smalltalk implementations?
Do you know any good smalltalk implementations which meet the following criteria:

are open source (and free)

are enterprise ready - I can do commercial apps into it

works on os x

I'm asking this because I heard a lot about smalltalk, and I want to learn it - just for fun. But it seems to be hard to find the right tools and books for this language.

答:
I forgot...fore even more books, check

http://stephane.ducasse.free.fr/FreeBooks.html

and for web development you can check

http://book.seaside.st/

ContentLicense: CC BY-SA 2.5


问:
Why use factory_girl for rails testing?
I am a newbie at rails testing so i want to know the rationale behind using a gem called factory_girl for testing.

Currently i am only using rspecs. My model specs is as follows:

```<code>require 'rails_helper'

RSpec.describe User, type: :model do

  it 'creates user' do
      User.create(email: 'asd@we.com', password: 'asasdasdasd', admin: true, firstname: 'qwe', lastname: 'wer', grade: 5, section: 'w', role: 1)
      expect(User.count).to eq(1)
  end

  it 'should not have password attribute' do

      User.create(email: 'asd@we.com', password: 'asdasdasd', admin: true, firstname: 'qwe', lastname: 'wer', grade: 5, section: 'w', role: 1)
      expect(User.first.attributes).to_not include('password')

  end

  it 'encrypts password' do
      User.create(email: 'asd@we.com', password: 'asdasdasd', admin: true, firstname: 'qwe', lastname: 'wer', grade: 5, section: 'w', role: 1)
      expect(User.first.encrypted_password).to_not eq('asdasdasd')
  end

end
</code>```

In the context of this code, i am expecting a rationale for integrating  factory_girl for testing. Does using factory_girl make this code more concise and clear? What specific problems does factory_girl help solve? I appreciate any insights. Thanks!

答:
The idea behind factories vs. fixtures is that you can create special-purpose models for particular test cases rather than maintaining a stable of them for a variety of purposes.

FactoryGirl and others like it make stamping out arbitrary users pretty easy, like your code could collapse to:

```<code>it 'users can be created' do
  create(:user)
  expect(User.count).to eq(1)
end
</code>```

Then you can customize that to make an admin, or a user with an invalid password, or whatever you might need for any particular case.

I'm a big fan of factories because even if they can make your tests marginally slower they're self-cleaning, that is the method that makes then, when deleted, no longer makes them. Fixtures often end up filled with bizarre artifacts you're not sure are used, and yet removing them breaks tests due to assertions that expect things to be a particular way.

ContentLicense: CC BY-SA 3.0

Title: Why use factory_girl for rails testing?

Body:
I am a newbie at rails testing so i want to know the rationale behind using a gem called factory_girl for testing.

Currently i am only using rspecs. My model specs is as follows:

require 'rails_helper'

RSpec.describe User, type: :model do

  it 'creates user' do
      User.create(email: 'asd@we.com', password: 'asasdasdasd', admin: true, firstname: 'qwe', lastname: 'wer', grade: 5, section: 'w', role: 1)
      expect(User.count).to eq(1)
  end

  it 'should not have password attribute' do

      User.create(email: 'asd@we.com', password: 'asdasdasd', admin: true, firstname: 'qwe', lastname: 'wer', grade: 5, section: 'w', role: 1)
      expect(User.first.attributes).to_not include('password')

  end

  it 'encrypts password' do
      User.create(email: 'asd@we.com', password: 'asdasdasd', admin: true, firstname: 'qwe', lastname: 'wer', grade: 5, section: 'w', role: 1)
      expect(User.first.encrypted_password).to_not eq('asdasdasd')
  end

end

In the context of this code, i am expecting a rationale for integrating  factory_girl for testing. Does using factory_girl make this code more concise and clear? What specific problems does factory_girl help solve? I appreciate any insights. Thanks!

Body:
The idea behind factories vs. fixtures is that you can create special-purpose models for particular test cases rather than maintaining a stable of them for a variety of purposes.

FactoryGirl and others like it make stamping out arbitrary users pretty easy, like your code could collapse to:

it 'users can be created' do
  create(:user)
  expect(User.count).to eq(1)
end

Then you can customize that to make an admin, or a user with an invalid password, or whatever you might need for any particular case.

I'm a big fan of factories because even if they can make your tests marginally slower they're self-cleaning, that is the method that makes then, when deleted, no longer makes them. Fixtures often end up filled with bizarre artifacts you're not sure are used, and yet removing them breaks tests due to assertions that expect things to be a particular way.


问:
Laravel - PDO Prepared Statement - Cannot execute queries while other unbuffered queries are active
I am having trouble running the following prepared statement in Laravel:

```<code>$pdo = DB::connection()->getPdo();
$ps_TempTable_PushCsv = $pdo->prepare(
    "LOAD DATA LOCAL INFILE '123'
    INTO TABLE `123`
    CHARACTER SET utf8mb4
    FIELDS TERMINATED BY ','
    OPTIONALLY ENCLOSED BY '\"'
    LINES TERMINATED BY '\\n'"
);
$ps_TempTable_PushCsv->execute();
$ps_TempTable_PushCsv->closeCursor();
$rowCount = $ps_TempTable_PushCsv->rowCount();
</code>```

I get the following error:

[2017-06-08 03:41:35] local.ERROR: PDOException: SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries are active.  Consider using PDOStatement::fetchAll().  Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute.

This is the entry-point of my controller, so there are definitely no prior queries running.

What do?

Thanks

答:
The only way I could get it working was to replace the prepared statement with an 'exec' call:

```<code>$rowCount = DB::connection()->getpdo()->exec(
            "LOAD DATA LOCAL INFILE '$fileName'
            INTO TABLE $tableName
            CHARACTER SET utf8mb4
            FIELDS TERMINATED BY ','
            OPTIONALLY ENCLOSED BY '\"'
            LINES TERMINATED BY '\\n'"
        );
</code>```

I have no idea why it wouldn't work using a prepared statement in Laravel - it definitely does work with a pure PDO prepared statement.

Body:
I am having trouble running the following prepared statement in Laravel:

$pdo = DB::connection()->getPdo();
$ps_TempTable_PushCsv = $pdo->prepare(
    "LOAD DATA LOCAL INFILE '123'
    INTO TABLE `123`
    CHARACTER SET utf8mb4
    FIELDS TERMINATED BY ','
    OPTIONALLY ENCLOSED BY '\"'
    LINES TERMINATED BY '\\n'"
);
$ps_TempTable_PushCsv->execute();
$ps_TempTable_PushCsv->closeCursor();
$rowCount = $ps_TempTable_PushCsv->rowCount();

I get the following error:

[2017-06-08 03:41:35] local.ERROR: PDOException: SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries are active.  Consider using PDOStatement::fetchAll().  Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute.

This is the entry-point of my controller, so there are definitely no prior queries running.

What do?

Thanks

Body:
The only way I could get it working was to replace the prepared statement with an 'exec' call:

$rowCount = DB::connection()->getpdo()->exec(
            "LOAD DATA LOCAL INFILE '$fileName'
            INTO TABLE $tableName
            CHARACTER SET utf8mb4
            FIELDS TERMINATED BY ','
            OPTIONALLY ENCLOSED BY '\"'
            LINES TERMINATED BY '\\n'"
        );

I have no idea why it wouldn't work using a prepared statement in Laravel - it definitely does work with a pure PDO prepared statement.


问:
How do I remote debug a net46 ASP.NET Core application in Azure?
I am trying to remote debug my net46 ASP.NET Core application in Azure.  It appears the debugger attaches to the process just fine (WebApiNetCore.exe), however the breakpoints I've set are not being hit.

The available processes I have to choose from are here.

I've tried selecting all of these options and they don't seem to work either.

Is it currently possible to remote debug a net46 ASP.NET Core application?

答: I had the same issue with invalid username/password. It turned out that remote debugging was turned off for that web app from Application Settings in Azure portal.</p>


问:
Why can't I remove these divs with jQuery?
I have dynamically created elements within a parent element of .output which are created within my on('click') function.

```<code>$(document).on("click", '#search', function() {
//Loop crime data array from api request above...
for(var i = 0; i < mapData.length; i++) {

  //Fill in crime data
  var fill = '<div class="row resu"><div class="col-xs-2 number"><h5>'+[i+1]+'</h5></div><div class="col-xs-10"><p class="text-primary">Type of crime: <span class="text-strong">'+mapData[i][0]+'</span></p><p class="text-primary">Location specifics: <span class="text-strong">'+mapData[i][1]+'</span></p></div></div>';

  //add to div
  $('.output').append(fill);
}
...
.......
</code>```

But nowhere outside the function am I able to target the new .resu rows for which I can apply .empty() or .remove(). Every time I hit the search button I wish to empty the output container div first.

If you go to my pen and hit the button, you will see some information regarding crime in that postcode's area. If you keep pressing it then multiple duplications of the same information will fill it up. How can I get rid of those with jquery?

My pen:
https://codepen.io/anon/pen/xrwXYy

答:
Here is the update DEMO: https://codepen.io/anon/pen/PjPJaZ

The isuue is, You are adding data to mapData array after each request. You need to reset the mapData array after each request as well.

```<code>function getPolApi(year,month,lat,lng,mapData) {
    $.ajax({
    url : "https://data.police.uk/api/crimes-at-location?date="+year+"-"+month+"&lat="+lat+"&lng="+lng,
    type : "get",
    async: false,
    success : function(data) {
     mapData = [];// Empty the array
      for(var i = 1; i < data.length; i++) {
            mapData.push([
              data[i]['category'],
              data[i]['location']['street']['name'],
            ]);

           heatmapData.push(new google.maps.LatLng(data[i].location.latitude,data[i].location.longitude));
      }
       //Add results into view

          for(var i = 0; i < mapData.length; i++) {
             var fill = '<div class="row resu"><div class="col-xs-2 number"><h5>'+[i+1]+'</h5></div><div class="col-xs-10"><p class="text-primary">Type of crime: <span class="text-strong">'+mapData[i][0]+'</span></p><p class="text-primary">Location specifics: <span class="text-strong">'+mapData[i][1]+'</span></p></div></div>';
            $('.output').append(fill);

          }//endforloop

          //Move the map into view of the heatmaps
          moveMap(lat,lng);
          //Add the heatmaps
          addHeatMap();
      mapData = [];
      // console.log(mapData);
    },
    error: function(dat) {
       console.log('error');
    }
</code>```

Body:
I have dynamically created elements within a parent element of .output which are created within my on('click') function.

$(document).on("click", '#search', function() {
//Loop crime data array from api request above...
for(var i = 0; i < mapData.length; i++) {

  //Fill in crime data
  var fill = '

'+[i+1]+'

Type of crime: '+mapData[i][0]+'

Location specifics: '+mapData[i][1]+'

';

  //add to div
  $('.output').append(fill);
}
...
.......

But nowhere outside the function am I able to target the new .resu rows for which I can apply .empty() or .remove(). Every time I hit the search button I wish to empty the output container div first.

If you go to my pen and hit the button, you will see some information regarding crime in that postcode's area. If you keep pressing it then multiple duplications of the same information will fill it up. How can I get rid of those with jquery?

My pen:
https://codepen.io/anon/pen/xrwXYy

Body:
Here is the update DEMO: https://codepen.io/anon/pen/PjPJaZ

The isuue is, You are adding data to mapData array after each request. You need to reset the mapData array after each request as well.

function getPolApi(year,month,lat,lng,mapData) {
    $.ajax({
    url : "https://data.police.uk/api/crimes-at-location?date="+year+"-"+month+"&lat="+lat+"&lng="+lng,
    type : "get",
    async: false,
    success : function(data) {
     mapData = [];// Empty the array
      for(var i = 1; i < data.length; i++) {
            mapData.push([
              data[i]['category'],
              data[i]['location']['street']['name'],
            ]);

           heatmapData.push(new google.maps.LatLng(data[i].location.latitude,data[i].location.longitude));
      }
       //Add results into view

          for(var i = 0; i < mapData.length; i++) {
             var fill = '<div class="row resu"><div class="col-xs-2 number"><h5>'+[i+1]+'</h5></div><div class="col-xs-10"><p class="text-primary">Type of crime: <span class="text-strong">'+mapData[i][0]+'</span></p><p class="text-primary">Location specifics: <span class="text-strong">'+mapData[i][1]+'</span></p></div></div>';
            $('.output').append(fill);

          }//endforloop

          //Move the map into view of the heatmaps
          moveMap(lat,lng);
          //Add the heatmaps
          addHeatMap();
      mapData = [];
      // console.log(mapData);
    },
    error: function(dat) {
       console.log('error');
    }


问:
Yii2 How to save file with custom file name?
How to save a file using a custom file name? I used gii generator for my website and i have a file input in my form now i want is after saving the file the name is get from report_id which is my primary key. For example, 1_.docx the 1 is my report_id. I have also a doc_name field, Yes i can save my file and get the name in doc_name. For example, sample.docx. But my problem is when i used the report_id and for example save the data the name of the file is .docx only.

This is my controller:

```<code>  public function actionCreate()
{
    $model = new reportDetails();
    if ($model->load(Yii::$app->request->post()))
{
    $project= $model->doc_name;
    $model->upload_file= UploadedFile::getInstance($model,'doc_file');
    $model->upload_file->saveAs('uploads/'.$project.'.'.$model->upload_file->extension);
    $model->doc_file='uploads/'.$project.'.'.$model->upload_file->extension;
    $model->doc_name=$project.'.'.$model->upload_file->extension;
    $model->save();

    Yii::$app->getSession()->setFlash('success','Data saved!');
    return $this->redirect(['view','id'=> $model->report_id]);
    }

    else {

    return $this ->render('create', [
        'model'=>$model,
    ]);
    }

}
</code>```

As you can see, $project=$model->doc_name; this the codes when i save a data, the name of the file will get from the doc_name but if i change it into report_id, when i save it the result is blank or .docx only.

This is my _form:

```<code>  <?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
        <?= Html::button('<i class="fa fa-plus"></i> Add Person', ['value' => Url::to('index.php?r=name/create'), 'class' => 'btn btn-custom-pos btn-success', 'id' => 'officialsfor']) ?>
        </br>
        </br>
  <?php Pjax::begin(['id' => 'for_from']) ?>
      <div class="col-sm-6">
     <?= $form->field($model, 'doc_for')->widget(Select2::classname(), [
           'data' => ArrayHelper::map(Name::find()->asArray()->all(),
            'name_id',
            function($model, $defaultValue){
              return $model['position'].' '.$model['fname'].' '.$model['mname'].' '.$model['lname'];
            }),
            'language' => 'en',
            'options' => ['placeholder' => 'Choose a person ...'],
            'pluginOptions' => [
                'allowClear' => true,
                'width' => 500,
             ],
            ]); ?>
      </div>
      <div class="col-sm-6">
    <?= $form->field($model, 'doc_from')->widget(Select2::classname(), [
           'data' => ArrayHelper::map(Name::find()->asArray()->all(),
           'name_id',
            function($model, $defaultValue){
            return $model['position'].' '.$model['fname'].' '.$model['mname'].' '.$model['lname'];
            }),
            'language' => 'en',
            'options' => ['placeholder' => 'Choose a person ...'],
            'pluginOptions' => [
                'allowClear' => true,
                'width' => 500,
            ],
            ]); ?>
 <?php Pjax::end(); ?>
      </div>
        </br>
        </br></br></br>
      <div class="broder" style=" border-radius: 5px; padding: 12px; ">
      </div>
  <div class="col-sm-6">
      <?= $form->field($model, 'user_id')->textInput(['type' => 'hidden','style'=>'width:500px;','placeholder' => 'Enter a Reference No....','value' =>ucfirst(Yii::$app->user->identity->first_name) . ' ' . ucfirst(Yii::$app->user->identity->middle_name) . ' ' . ucfirst(Yii::$app->user->identity->last_name)]) ?>
       <?= Html::activeLabel($model, 'user_id', ['label'=>ucfirst(Yii::$app->user->identity->first_name) . ' ' . ucfirst(Yii::$app->user->identity->middle_name) . ' ' . ucfirst(Yii::$app->user->identity->last_name),'style' => 'font-size: 21px;','class' => 'color']) ?>
      <br>
      <br>
      <?= $form->field($model, 'reference_no')->textInput(['style'=>'width:500px','placeholder' => 'Enter a Reference No....']) ?>
      <?= $form->field($model, 'subject')->textInput(['maxlength'=>true,'style'=>'width:500px','placeholder' => 'Enter a Subject....']) ?>
    <?= $form->field($model, 'doc_date')->widget(
        DatePicker::className(), [
            'inline' => false,
            'options' => ['placeholder' => 'Choose a Entry Date ...'],
            'clientOptions' => [
            'autoclose' => true,
            'format' => 'yyyy-mm-dd'
              ]
             ]);?>
  </div>
  <div class="col-sm-6" style="padding-top: 14px; ">
         </br>
         </br>
         </br></br>
    <?= $form->field($model, 'drawer_id')->textInput(['maxlength'=>true,'style'=>'width:500px','placeholder' => 'Enter a Drawer ID....', ]) ?>
    <?= $form->field($model, 'doc_name')->textInput(['maxlength'=>true,'style'=>'width:500px','placeholder' => 'Enter a Document Name....']) ?>
      <?= $form->field($model, 'doc_file')-> widget(
        FileInput::classname(),[
      'name' => 'doc_file',
      'options' => ['accept' => '.docx','.doc','.docs'],
      'pluginOptions' => [
          'showPreview' => false,
          'showCaption' => true,
          'showRemove' => true,
          'showUpload' => false
            ]
        ]);
      ?>
  </div>
</div>
</br>
<div class="row">
  <div class="col-sm-12 text-center">
    <div class="form-group">
      <?= Html::submitButton($model->isNewRecord ? '<i class="fa fa-plus"></i> Create' : '<i class="fa fa-pencil"></i> Update', ['class' => $model->isNewRecord ? 'btn btn-success'  : 'btn btn-success','style' => 'padding:10px 60px;']) ?>
    </div>
  </div>
</div>
<?php ActiveForm::end(); ?>
</code>```

答:
as you said report_id is primary key, so you won't get it before save the new record in db.

as per your logic, insertion is happing with new record. so you need to updated your code like below. check it.

```<code>public function actionCreate()
{
    $model = new reportDetails();
    if ($model->load(Yii::$app->request->post()))
    {
        $project= $model->doc_name;
        $model->upload_file = UploadedFile::getInstance($model,'doc_file');
        $model->upload_file->saveAs('uploads/'.$project.'.'.$model->upload_file->extension);
        $model->doc_file='uploads/'.$project.'.'.$model->upload_file->extension;
        $model->doc_name=$project.'.'.$model->upload_file->extension;
        $model->save();

        // after save you will get report_id
        rename('uploads/'.$project.'.'.$model->upload_file->extension, 'uploads/'.$model->report_id.'.'.$model->upload_file->extension);
        $model->doc_file='uploads/'.$model->report_id.'.'.$model->upload_file->extension;
        $model->doc_name=$model->report_id.'.'.$model->upload_file->extension;
        $model->save();

        Yii::$app->getSession()->setFlash('success','Data saved!');
        return $this->redirect(['view','id'=> $model->report_id]);
    }

    else {

        return $this ->render('create', [
            'model'=>$model,
        ]);
    }

}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How to save a file using a custom file name? I used gii generator for my website and i have a file input in my form now i want is after saving the file the name is get from report_id which is my primary key. For example, 1_.docx the 1 is my report_id. I have also a doc_name field, Yes i can save my file and get the name in doc_name. For example, sample.docx. But my problem is when i used the report_id and for example save the data the name of the file is .docx only.

This is my controller:

  public function actionCreate()
{
    $model = new reportDetails();
    if ($model->load(Yii::$app->request->post()))
{
    $project= $model->doc_name;
    $model->upload_file= UploadedFile::getInstance($model,'doc_file');
    $model->upload_file->saveAs('uploads/'.$project.'.'.$model->upload_file->extension);
    $model->doc_file='uploads/'.$project.'.'.$model->upload_file->extension;
    $model->doc_name=$project.'.'.$model->upload_file->extension;
    $model->save();

    Yii::$app->getSession()->setFlash('success','Data saved!');
    return $this->redirect(['view','id'=> $model->report_id]);
    }

    else {

    return $this ->render('create', [
        'model'=>$model,
    ]);
    }

}

As you can see, $project=$model->doc_name; this the codes when i save a data, the name of the file will get from the doc_name but if i change it into report_id, when i save it the result is blank or .docx only.

This is my _form:

  <?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
        <?= Html::button(' Add Person', ['value' => Url::to('index.php?r=name/create'), 'class' => 'btn btn-custom-pos btn-success', 'id' => 'officialsfor']) ?>

  <?php Pjax::begin(['id' => 'for_from']) ?>

     <?= $form->field($model, 'doc_for')->widget(Select2::classname(), [
           'data' => ArrayHelper::map(Name::find()->asArray()->all(),
            'name_id',
            function($model, $defaultValue){
              return $model['position'].' '.$model['fname'].' '.$model['mname'].' '.$model['lname'];
            }),
            'language' => 'en',
            'options' => ['placeholder' => 'Choose a person ...'],
            'pluginOptions' => [
                'allowClear' => true,
                'width' => 500,
             ],
            ]); ?>

    <?= $form->field($model, 'doc_from')->widget(Select2::classname(), [
           'data' => ArrayHelper::map(Name::find()->asArray()->all(),
           'name_id',
            function($model, $defaultValue){
            return $model['position'].' '.$model['fname'].' '.$model['mname'].' '.$model['lname'];
            }),
            'language' => 'en',
            'options' => ['placeholder' => 'Choose a person ...'],
            'pluginOptions' => [
                'allowClear' => true,
                'width' => 500,
            ],
            ]); ?>
 <?php Pjax::end(); ?>

      <?= $form->field($model, 'user_id')->textInput(['type' => 'hidden','style'=>'width:500px;','placeholder' => 'Enter a Reference No....','value' =>ucfirst(Yii::$app->user->identity->first_name) . ' ' . ucfirst(Yii::$app->user->identity->middle_name) . ' ' . ucfirst(Yii::$app->user->identity->last_name)]) ?>
       <?= Html::activeLabel($model, 'user_id', ['label'=>ucfirst(Yii::$app->user->identity->first_name) . ' ' . ucfirst(Yii::$app->user->identity->middle_name) . ' ' . ucfirst(Yii::$app->user->identity->last_name),'style' => 'font-size: 21px;','class' => 'color']) ?>

      <?= $form->field($model, 'reference_no')->textInput(['style'=>'width:500px','placeholder' => 'Enter a Reference No....']) ?>
      <?= $form->field($model, 'subject')->textInput(['maxlength'=>true,'style'=>'width:500px','placeholder' => 'Enter a Subject....']) ?>
    <?= $form->field($model, 'doc_date')->widget(
        DatePicker::className(), [
            'inline' => false,
            'options' => ['placeholder' => 'Choose a Entry Date ...'],
            'clientOptions' => [
            'autoclose' => true,
            'format' => 'yyyy-mm-dd'
              ]
             ]);?>

    <?= $form->field($model, 'drawer_id')->textInput(['maxlength'=>true,'style'=>'width:500px','placeholder' => 'Enter a Drawer ID....', ]) ?>
    <?= $form->field($model, 'doc_name')->textInput(['maxlength'=>true,'style'=>'width:500px','placeholder' => 'Enter a Document Name....']) ?>
      <?= $form->field($model, 'doc_file')-> widget(
        FileInput::classname(),[
      'name' => 'doc_file',
      'options' => ['accept' => '.docx','.doc','.docs'],
      'pluginOptions' => [
          'showPreview' => false,
          'showCaption' => true,
          'showRemove' => true,
          'showUpload' => false
            ]
        ]);
      ?>

      <?= Html::submitButton($model->isNewRecord ? ' Create' : ' Update', ['class' => $model->isNewRecord ? 'btn btn-success'  : 'btn btn-success','style' => 'padding:10px 60px;']) ?>

<?php ActiveForm::end(); ?>

Body:
as you said report_id is primary key, so you won't get it before save the new record in db.

as per your logic, insertion is happing with new record. so you need to updated your code like below. check it.

public function actionCreate()
{
    $model = new reportDetails();
    if ($model->load(Yii::$app->request->post()))
    {
        $project= $model->doc_name;
        $model->upload_file = UploadedFile::getInstance($model,'doc_file');
        $model->upload_file->saveAs('uploads/'.$project.'.'.$model->upload_file->extension);
        $model->doc_file='uploads/'.$project.'.'.$model->upload_file->extension;
        $model->doc_name=$project.'.'.$model->upload_file->extension;
        $model->save();

        // after save you will get report_id
        rename('uploads/'.$project.'.'.$model->upload_file->extension, 'uploads/'.$model->report_id.'.'.$model->upload_file->extension);
        $model->doc_file='uploads/'.$model->report_id.'.'.$model->upload_file->extension;
        $model->doc_name=$model->report_id.'.'.$model->upload_file->extension;
        $model->save();

        Yii::$app->getSession()->setFlash('success','Data saved!');
        return $this->redirect(['view','id'=> $model->report_id]);
    }

    else {

        return $this ->render('create', [
            'model'=>$model,
        ]);
    }

}


问:
How to create a logic hook in SugarCRM/SuiteCRM based on info in 'Campaign' subpanel of Leads?
I have a field in leads module as 'interested_c' which is decimal type and would store numeric values.

Here is the detailview of Campaign subpanel of Leads Module.

One record has Activity Type = Click-thru (iink) and corresponding 'related' which is a URL (tracker).

I want to create a logic hook for leads module, which if possibly, could use both pieces of information as conditions on each occuranc of:

if Activity Type = Click-thru (link) and other 'related' = <urlxyz>,
then the incremental value is add to custom field 'interested_c'.

How such logic hook can be created?

There are some pieces of information which may be helpful:

This 'Campaign' Subpanel is getting most data from module: CampaignLog (which has a relationship with Campaign). [Corresponding MySQL Table: campaign_log]

These variables are defined in vardefs.php of suitecrm>modules>CampaignLog> Vardefs of the fields concerned here

答:
Off the top of my head, and using the related field logic hook examples from modules/Accounts/AccountsJjwg_MapsLogicHook.php:

Create two files:

```<code>custom/modules/Leads/logic_hooks.php
custom/modules/Leads/LeadsLogicHooks.php
</code>```

logic_hooks.php:

```<code><?php
$hook_version = 1;
$hook_array = Array();
$hook_array['before_save'][] = Array(51, 'updateCounter',
'custom/modules/Leads/LeadsLogicHooks.php', 'LeadsLogicHooks', 'updateCounter');
?>
</code>```

LeadsLogicHooks.php:

```<code><?php
if (!defined('sugarEntry') || !sugarEntry) die('Not a valid Entry Point');
class LeadsLogicHooks{
 function updateCounter(&$focus, $event, $arguments){
  require_once('custom/modules/CampaignLog/CampaignLog.php');
  $campaigns = $bean->get_linked_beans('campaign', 'Campaign');
  foreach ($campaigns as $campaign) {
   if ($campaign->activity_type == "Click-thruLink" && !empty($campaign->related_type)) {
          $focus->interested_c += 1;
   } #if
  } #for
 } #function
} #class
</code>```

Body:
Off the top of my head, and using the related field logic hook examples from modules/Accounts/AccountsJjwg_MapsLogicHook.php:

Create two files:

custom/modules/Leads/logic_hooks.php
custom/modules/Leads/LeadsLogicHooks.php

logic_hooks.php:

<?php
$hook_version = 1;
$hook_array = Array();
$hook_array['before_save'][] = Array(51, 'updateCounter',
'custom/modules/Leads/LeadsLogicHooks.php', 'LeadsLogicHooks', 'updateCounter');
?>

LeadsLogicHooks.php:

<?php
if (!defined('sugarEntry') || !sugarEntry) die('Not a valid Entry Point');
class LeadsLogicHooks{
 function updateCounter(&$focus, $event, $arguments){
  require_once('custom/modules/CampaignLog/CampaignLog.php');
  $campaigns = $bean->get_linked_beans('campaign', 'Campaign');
  foreach ($campaigns as $campaign) {
   if ($campaign->activity_type == "Click-thruLink" && !empty($campaign->related_type)) {
          $focus->interested_c += 1;
   } #if
  } #for
 } #function
} #class


答:
You could do

```<code> $('.output').html(fill);
</code>```

instead of

```<code> $('.output').append(fill);
</code>```

In that case there is no need to remove resu

Title: Why can't I remove these divs with jQuery?

Body:
You could do

 $('.output').html(fill);

instead of

 $('.output').append(fill);

In that case there is no need to remove resu


问:
Swift 3 - Reload UICollectionView inside the UITableViewCell
I have a UICollectionView inside a UITableViewCell. You may refer the image at here

I would like to reload the collectionView if any update happen.

I have done some research and found this :

how to reload a collectionview that is inside a tableviewcell

Reloading collection view inside a table view cell happens after all cells in table view have been loaded

UICollectionView not updating inside UITableViewCell

I called the @IBOutlet weak var collectionView: UICollectionView! from UITableViewCell to UITableViewController at cellForRowAt.

Here is the code:

```<code>var refreshNow: Bool = false

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: Storyboard.allCardCell, for: indexPath) as! AllCardTableViewCell

        if refreshNow {
          cell.collectionView.reloadData()
          refreshNow = false
        }

        cell.collectionView.collectionViewLayout.invalidateLayout()
        return cell
    }
</code>```

If the user click Ok on UIAlertAction :

```<code>let alert = UIAlertController(title: "Success", message: "Card successfully added", preferredStyle: .alert)
                let action = UIAlertAction(title: "Ok", style: .default) { (action) in
                    self.refreshNow = true
                    self.tableView.reloadData()
                }
                alert.addAction(action)
                self.present(alert, animated: true, completion: nil)
</code>```

The reason why I put the refreshNow is to prevent the apps from lagging and slow. But still did not update if any changes happen.

The problem is the collectionView did not refresh. But when I debug, it was went through the cell.collectionView.reloadData().

The update/changes only happen when I restart the apps. I want it to be so called real-times update.

Any help is really appreciated and many thanks.

Image credit: How to use StoryBoard quick build a collectionView inside UITableViewCell

答:
Because you reused UITableViewCell so you must alway reload your UICollectionView. If you use refreshNow to reload UICollectionView, at the cell have refreshNow = false, UICollectionView will display like cell that it 's reused => wrong

Udate rep:

See , in picture  uitableviewcell 1 will reuse at index 6. If you not reload content of cell (reload collectionview) it will display like uitableviewcell 1 at index 0

Body:
I have a UICollectionView inside a UITableViewCell. You may refer the image at here

I would like to reload the collectionView if any update happen.

I have done some research and found this :

how to reload a collectionview that is inside a tableviewcell

Reloading collection view inside a table view cell happens after all cells in table view have been loaded

UICollectionView not updating inside UITableViewCell

I called the @IBOutlet weak var collectionView: UICollectionView! from UITableViewCell to UITableViewController at cellForRowAt.

Here is the code:

var refreshNow: Bool = false

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: Storyboard.allCardCell, for: indexPath) as! AllCardTableViewCell

        if refreshNow {
          cell.collectionView.reloadData()
          refreshNow = false
        }

        cell.collectionView.collectionViewLayout.invalidateLayout()
        return cell
    }

If the user click Ok on UIAlertAction :

let alert = UIAlertController(title: "Success", message: "Card successfully added", preferredStyle: .alert)
                let action = UIAlertAction(title: "Ok", style: .default) { (action) in
                    self.refreshNow = true
                    self.tableView.reloadData()
                }
                alert.addAction(action)
                self.present(alert, animated: true, completion: nil)

The reason why I put the refreshNow is to prevent the apps from lagging and slow. But still did not update if any changes happen.

The problem is the collectionView did not refresh. But when I debug, it was went through the cell.collectionView.reloadData().

The update/changes only happen when I restart the apps. I want it to be so called real-times update.

Any help is really appreciated and many thanks.

Image credit: How to use StoryBoard quick build a collectionView inside UITableViewCell


问:
NServiceBus Deserialization Exception After Deployment
I am currently using NServiceBus6.  I am successfully submitting a message from my web api to endpoint which is windows service hosted.  Everything works fine in my development environment on my local machine.  I am using "NewtonsoftSerializer" in all my endpoint configurations.  I have now deployed my solution to a server.  My services are now hosted as Window Services as opposed to a console app.  Service Insight is now reporting an NServiceBusDeserialization Exception:

An error occurred while attempting to extract logical messages from transport message 8221d498-81ca-406e-8ab6-a77701065f1f ---> System.Xml.XmlException: Data at the root level is invalid. Line 1, position 1.

A couple items stick out.  A.  I am not using XmlSerialization. B. I have no serialization issues in development environment.  I would appreciate any help provided thank you.

Message Class:

```<code> public class CreateSearchRequest : ICommand
{
    public SearchRequest Request { get; set; }
}
</code>```

SearchRequest:

```<code> public class SearchRequest : Resource
{
    public string User { get; set; }
    public string SearchName { get; set; }
    public SearchCriteriaSimple Criteria { get; set; }
    public string Status { get; set; }
    public DateTime RequestBegin { get; set; }
    public DateTime RequestEnd { get; set; }
    public int Records { get; set; }
    public string OutputFileName { get; set; }
    public string FtpLocation { get; set; }
    public DateTime CreateDate { get; set; }
}
</code>```

SearchRequestSimple:

```<code> public class SearchCriteriaSimple
{
    public string Name { get; set; }
    public List<Dictionary<string, string>> Criteria { get; set; }
}
</code>```

Resource: Azure DocumentDbResource class

答: I am embarrassed to say.  But I have figured out the issue.  During development in Visual studio I configured the endpoint in the Task AsyncOnStart() method of ProgramService.cs.  It seems once I install the NServiceBus host I must also provide configuration via Endpoint Config.  Once I matched serialization there the issues went away.</p>

Body:
I am currently using NServiceBus6.  I am successfully submitting a message from my web api to endpoint which is windows service hosted.  Everything works fine in my development environment on my local machine.  I am using "NewtonsoftSerializer" in all my endpoint configurations.  I have now deployed my solution to a server.  My services are now hosted as Window Services as opposed to a console app.  Service Insight is now reporting an NServiceBusDeserialization Exception:

An error occurred while attempting to extract logical messages from transport message 8221d498-81ca-406e-8ab6-a77701065f1f ---> System.Xml.XmlException: Data at the root level is invalid. Line 1, position 1.

A couple items stick out.  A.  I am not using XmlSerialization. B. I have no serialization issues in development environment.  I would appreciate any help provided thank you.

Message Class:

 public class CreateSearchRequest : ICommand
{
    public SearchRequest Request { get; set; }
}

SearchRequest:

 public class SearchRequest : Resource
{
    public string User { get; set; }
    public string SearchName { get; set; }
    public SearchCriteriaSimple Criteria { get; set; }
    public string Status { get; set; }
    public DateTime RequestBegin { get; set; }
    public DateTime RequestEnd { get; set; }
    public int Records { get; set; }
    public string OutputFileName { get; set; }
    public string FtpLocation { get; set; }
    public DateTime CreateDate { get; set; }
}

SearchRequestSimple:

 public class SearchCriteriaSimple
{
    public string Name { get; set; }
    public List<Dictionary<string, string>> Criteria { get; set; }
}

Resource: Azure DocumentDbResource class


问:
Using MEF in an editor
Im trying to developing editor like VS editor where i hawe components like FTP, TelNet (where you drag and drop in designer and connect them with each other change properties in PropertyGrid and so on) and then execute. Is good idea to use MEF to scan all dll-s that have interface IComponent and then use reflection to get the original Object from dll-s. example

```<code>[Export(typeof(ICOmponent))]
[MetadataExport("Name", "FTP")]
public class FTP : ICOmponent
{
    public string Server { get; set; }
    public void Start()
    {
        ....ConectTOServer(Server);
    }
}
[Export(typeof(ICOmponent))]
[MetadataExport("Name", "MessageBox")]
public class MessageBox : ICOmponent
{
    public string Message { get; set; }
    public void Start()
    {
        System.Windows.Forms.MessageBox.Show(Message);
    }
}

public interface ICOmponent
{
    void Start();
}
</code>```

Or is another method to get original object from MEF from ICOmponent like from Metadata.. because PropertyGrid nead real object for displaying properties for FTP Server and From MessageBox Message.
Sorry for my bad english.

答:
For MEF to work, any assembly/dll that is dropped on you application must implement Exports. If it does not, you won't be able to Import anything.

To work with assembly/dll that does not have any exports, use reflection to search for types that implement IComponent. And use Activator class to create instances from their type information.

Title: Using MEF in an editor

Body:
Im trying to developing editor like VS editor where i hawe components like FTP, TelNet (where you drag and drop in designer and connect them with each other change properties in PropertyGrid and so on) and then execute. Is good idea to use MEF to scan all dll-s that have interface IComponent and then use reflection to get the original Object from dll-s. example

[Export(typeof(ICOmponent))]
[MetadataExport("Name", "FTP")]
public class FTP : ICOmponent
{
    public string Server { get; set; }
    public void Start()
    {
        ....ConectTOServer(Server);
    }
}
[Export(typeof(ICOmponent))]
[MetadataExport("Name", "MessageBox")]
public class MessageBox : ICOmponent
{
    public string Message { get; set; }
    public void Start()
    {
        System.Windows.Forms.MessageBox.Show(Message);
    }
}

public interface ICOmponent
{
    void Start();
}

Or is another method to get original object from MEF from ICOmponent like from Metadata.. because PropertyGrid nead real object for displaying properties for FTP Server and From MessageBox Message.
Sorry for my bad english.


问:
c# assign values from a for loop to individual variables
I have the value of Cell and Value in a for loop.  For example when i=0, value will be "first value" which I want to assign to A0Text.text. When i=1, , value will be "second value" which I want to assign to A1Text.text.. –

```<code>for (int i = 0; i < BLOCKS.Count; i++)
{
//possible values of Cell are A0, A1, A2 ...
var Cell = currentBLOCKData["cell"];

var Value = currentBLOCKData["value"];

....
</code>```

Then I have fields named with the same name as Cell

```<code>//possible cellName are - A0Text, A1text, A2Text .....
string cellName = Cell + "Text";
</code>```

I want to assign

```<code>A0Text.text = First value in above field - Value
A1Text.text = 2nd value in above field - Value
A2Text.text = 3rd value in above field - Value
</code>```

How can I make the above assigments?

答:
Yes - I figured it out - Searching and assigning as below:</p>

```<code>        txtRef = GameObject.Find(cellName).GetComponent<Text>();

        txtRef.text = Value.ToString();
</code>```

Body:
I have the value of Cell and Value in a for loop.  For example when i=0, value will be "first value" which I want to assign to A0Text.text. When i=1, , value will be "second value" which I want to assign to A1Text.text.. –

for (int i = 0; i < BLOCKS.Count; i++)
{
//possible values of Cell are A0, A1, A2 ...
var Cell = currentBLOCKData["cell"];

var Value = currentBLOCKData["value"];

....

Then I have fields named with the same name as Cell

//possible cellName are - A0Text, A1text, A2Text .....
string cellName = Cell + "Text";

I want to assign

A0Text.text = First value in above field - Value
A1Text.text = 2nd value in above field - Value
A2Text.text = 3rd value in above field - Value

How can I make the above assigments?

Body:
Yes - I figured it out - Searching and assigning as below:

        txtRef = GameObject.Find(cellName).GetComponent<Text>();

        txtRef.text = Value.ToString();


问:
How does the Google "Did you mean?" Algorithm work?
I've been developing an internal website for a portfolio management tool.  There is a lot of text data, company names etc.  I've been really impressed with some search engines ability to very quickly respond to queries with "Did you mean: xxxx".

I need to be able to intelligently take a user query and respond with not only raw search results but also with a "Did you mean?" response when there is a highly likely alternative answer etc

[I'm developing in ASP.NET (VB - don't hold it against me! )]

UPDATE:
OK, how can I mimic this without the millions of 'unpaid users'?

Generate typos for each 'known' or 'correct' term and perform lookups?

Some other more elegant method?

答:
Apart from the above answers, in case you want to implement something by yourself quickly, here is a suggestion -

Algorithm

You can find the implementation and detailed documentation of this algorithm on  GitHub.

Create a Priority Queue with a comparator.

Create a Ternay Search Tree and insert all english words (from Norvig's post) along with their frequencies.

Start traversing the TST and for every word encountered in TST, calculate its Levenshtein Distance(LD) from input_word

If LD ≤ 3 then put it in a Priority Queue.

At Last extract 10 words from the Priority Queue and display.

OwnerDisplayName: Harry

LastEditorDisplayName: Oscar Reyes


问:
pass value to Redirect in mvc5
```<code>    [HttpPost]
    public ActionResult Welcome(FormCollection frm)
    {

        frm["parameter1"] = "Welcome1";
        frm["parameter2"] = "Welcome2";
        frm["parameter3"] = "Welcome3";
        frm["parameter4"] = "Welcome4";
        return Redirect("https://www.example.com");
    }
</code>```

Question :

I want to pass FormCollection Object when redirect to separate domain like "https://www.example.com"

Is this possible or not ?

Thanks in advance

答:
You can pass the id as part of the routeValues parameter of the RedirectToAction() method.

return RedirectToAction("Action", new { id = 20 });

Title: pass value to Redirect in mvc5

Body:
    [HttpPost]
    public ActionResult Welcome(FormCollection frm)
    {

        frm["parameter1"] = "Welcome1";
        frm["parameter2"] = "Welcome2";
        frm["parameter3"] = "Welcome3";
        frm["parameter4"] = "Welcome4";
        return Redirect("https://www.example.com");
    }

Question :

I want to pass FormCollection Object when redirect to separate domain like "https://www.example.com"

Is this possible or not ?

Thanks in advance


问:
I want to get keys names from hash which has same values in ruby
```<code>{"Amar"=>20,"Benton"=>14,"John"=>32,"Sunny"=>28,"Edward"=>19,"Leon"=>12,"Ram"=>19,"David"=>28}
</code>```

the above hash has name and age ,i want to get the names which has same age in ruby

答:
try this.</p>

```<code>hash = {"name1"=>12, "name2"=>13, "name3"=>12}

groups = {}
hash.each do |k, v|
  groups[v] = groups[v] || []
  groups[v].push(k)
end
</code>```

Body:
{"Amar"=>20,"Benton"=>14,"John"=>32,"Sunny"=>28,"Edward"=>19,"Leon"=>12,"Ram"=>19,"David"=>28}

the above hash has name and age ,i want to get the names which has same age in ruby

Body:
try this.

hash = {"name1"=>12, "name2"=>13, "name3"=>12}

groups = {}
hash.each do |k, v|
  groups[v] = groups[v] || []
  groups[v].push(k)
end


问:
How will I know when to create an interface?
I'm at a point in my development learning where I feel like I must learn more about interfaces.

I frequently read about them but it just seems like I cannot grasp them.

I've read examples like: Animal base class, with IAnimal interface for things like 'Walk', 'Run', 'GetLegs', etc - but I've never been working on something and felt like "Hey I should use an interface here!"

What am I missing? Why is it such a hard concept for me to grasp! I am just intimidated by the fact that I might not ever realize a concrete need for one - mostly due to some missing aspect of understanding them! It makes me feel like I'm missing something up top in terms of being a developer! If anyone has had an experience like this and had a breakthrough I would appreciate some tips on how to understand this concept. Thank you.

答:
In my experience the driving force to create interfaces didn't occur until I start doing unit testing with a mocking framework.  It became abundantly clear that using interfaces was going to make mocking much easier (since the framework depended on the methods being virtual).  Once I started I saw the value of abstracting away the interface to my class from the implementation.  Even if I don't create an actual interface, I try now to make my methods virtual (providing an implicit interface that can be overridden).

There are lots of other reasons that I've found to reinforce the good practice of refactoring to interfaces, but the unit testing/mocking thing was what provided the intial "aha moment" of practical experience.

EDIT: To clarify, with unit testing and mocking I always have two implementations -- the real, concrete implementation and an alternate mock implementation used in testing.  Once you have two implementations, the value of the interface becomes obvious -- deal with it in terms of the interface so you can replace the implementation at any time.  In this case I'm replacing it with a mock interface.  I know that I can do this without an actual interface if my class is constructed properly, but using an actual interface reinforces this and makes it cleaner (clearer to the reader).  Without this impetus, I don't think I would have appreciated the value of interfaces since most of my classes only, ever have a single concrete implementation.

LastEditorDisplayName: ALassek

OwnerDisplayName: tvanfosson

LastEditorDisplayName: tvanfosson


问:
Simple jQuery problem
This one should be easy

I've got this HTML

```<code><table class="PageNumbers">
<tr>
    <td colspan="3">text3
    </td>
</tr>
<tr>
    <td colspan="2">text
    </td>
    <td>text2
    </td>
</tr>
<tr>
    <td>moretext
    </td>
    <td>moretext2
    </td>
<td>moretext3
    </td>
</tr>
</table>
</code>```

I need to change the colspan of the first rows first column to one

This is what i've got

```<code>$('.PageNumbers tr:first td:first').attr('colspan') = '1'
</code>```

Doesn't seem to work though

Any ideas?

Thanks

答:
Here's another way:

```<code>$('.PageNumbers')[0].rows[0].cells[0].colSpan = 1;
</code>```

or:

```<code>$('.PageNumbers')[0].rows[0].cells[0].setAttribute('colSpan', 1);
</code>```

Title: Simple jQuery problem

Body:
This one should be easy

I've got this HTML

    text3

    text

    text2

    moretext

    moretext2

moretext3

I need to change the colspan of the first rows first column to one

This is what i've got

$('.PageNumbers tr:first td:first').attr('colspan') = '1'

Doesn't seem to work though

Any ideas?

Thanks

Body:
Here's another way:

$('.PageNumbers')[0].rows[0].cells[0].colSpan = 1;

or:

$('.PageNumbers')[0].rows[0].cells[0].setAttribute('colSpan', 1);


问:
Change python environment 'cmd' is not recognized
7 using anaconda on win10. And then I use conda to create a seperate environment of python3:

conda create --name python3 python=3

However, when I use activate python3

it shows that:

```<code>C:\Users\xxxxx>activate python3
'cmd' is not recognized as an internal or external command,
operable program or batch file.
'cmd' is not recognized as an internal or external command,
operable program or batch file.
</code>```

I have checked all the environment:

```<code>C:\Users\Alex Cui>conda info --envs
# conda environments:
#
python3                  C:\Users\Alex Cui\Anaconda2\envs\python3
root                  *  C:\Users\Alex Cui\Anaconda2
</code>```

Can someone help why it cannot recognize activate cmd?

答: Do not use spaces in paths where anaconda is installed. Reinstall elsewhere and make sure windows does not search for used commands in a path with spaces too.</p>

Body:
7 using anaconda on win10. And then I use conda to create a seperate environment of python3:

conda create --name python3 python=3

However, when I use activate python3

it shows that:

C:\Users\xxxxx>activate python3
'cmd' is not recognized as an internal or external command,
operable program or batch file.
'cmd' is not recognized as an internal or external command,
operable program or batch file.

I have checked all the environment:

C:\Users\Alex Cui>conda info --envs
# conda environments:
#
python3                  C:\Users\Alex Cui\Anaconda2\envs\python3
root                  *  C:\Users\Alex Cui\Anaconda2

Can someone help why it cannot recognize activate cmd?


问:
How to change Custom Spinner Text color android
I am working on a android project where i have to implement a custom spinner in the register form for selecting the Profession,Family name. Spinner functionality is working fine but spinner is a custom spinner and  its not accepting the text color to be changed. Is there any way i can change the color of the text?

Below is my xml code:

```<code><com.infantstudio.CatholicMithrulu.Spinner.SearchableSpinnerProfestion
    android:id="@+id/profestion_spinner"
    android:layout_width="100dp"
    android:layout_height="wrap_content"
    android:entries="@array/profestion"
    app:hintTextCountry="Select"/>
</code>```

答: You said you are using custom spinner. You should also bind the data with custom view or custom list. You should change the text color of custom list.</p>

Body:
I am working on a android project where i have to implement a custom spinner in the register form for selecting the Profession,Family name. Spinner functionality is working fine but spinner is a custom spinner and  its not accepting the text color to be changed. Is there any way i can change the color of the text?

Below is my xml code:

<com.infantstudio.CatholicMithrulu.Spinner.SearchableSpinnerProfestion
    android:id="@+id/profestion_spinner"
    android:layout_width="100dp"
    android:layout_height="wrap_content"
    android:entries="@array/profestion"
    app:hintTextCountry="Select"/>


问:
Xcode error connecting to simulator "Software caused connection abort"
When I try to run my project through the Xcode simulator, it keeps giving me the error "Software caused connection abort".

Tried restarting the simulator & Xcode, and I recently deleted the DerivedData folder as suggested in this post about broken playgrounds so that also didn't help.

答:
It's due to multiple Xcode installed in your system. This is how you make it work:

Quit all running Xcodes

Re-launch Xcode

Go to Xcode > Preferences > Locations

Change to the correct version in Command Line Tools

Clean project and clear Derived data if necessary, then run!


答:
One solution is to create a hash with ages as the key and an array of names as the values:

```<code>names = {"Amar"=>20,
         "Benton"=>14,
         "John"=>32,
         "Sunny"=>28,
         "Edward"=>19,
         "Leon"=>12,
         "Ram"=>19,
         "David"=>28}

ages = {}
names.each do |key, value|
  ages[value] ||= []
  ages[value] << key
end

puts ages
#=> {20=>["Amar"], 14=>["Benton"], 32=>["John"], 28=>["Sunny", "David"], 19=>["Edward", "Ram"], 12=>["Leon"]}
</code>```

Note that if you want to get all the people who are 19 years old, you can just use ages[19].

Title: I want to get keys names from hash which has same values in ruby

Body:
One solution is to create a hash with ages as the key and an array of names as the values:

names = {"Amar"=>20,
         "Benton"=>14,
         "John"=>32,
         "Sunny"=>28,
         "Edward"=>19,
         "Leon"=>12,
         "Ram"=>19,
         "David"=>28}

ages = {}
names.each do |key, value|
  ages[value] ||= []
  ages[value] << key
end

puts ages
#=> {20=>["Amar"], 14=>["Benton"], 32=>["John"], 28=>["Sunny", "David"], 19=>["Edward", "Ram"], 12=>["Leon"]}

Note that if you want to get all the people who are 19 years old, you can just use ages[19].


问:
Python Turtle Graphics and Loops
I am trying to create a loop which prints out 6 parallel lines horizontally.However when I using the code below I only am able to see one line that just moves continuously. Any tips would be appreciated. Here is the code:  </p>

```<code>count = 0;
while(count < 6):
  actor.penup()
  actor.backward(100)
  actor.pendown()
  actor.forward(150)
  count = count + 1
</code>```

答:
There must be other ways but I'm not at all familiar with turtle.
  - @BillBell

Yes, there are, we can make a line shaped cookie cutter and stamp them out:

```<code>import turtle

STAMP_SIZE = 20

actor = turtle.Turtle('square', visible=False)
actor.shapesize(0.5 / STAMP_SIZE, 200 / STAMP_SIZE, 0)
actor.penup()

for y in range(-3, 3):
    actor.sety(10 * y)
    actor.stamp()

turtle.exitonclick()
</code>```

(If the lines don't appear on your system, change the 0.5 above to 1.0)

This approach only uses turtle's .circle() method to draw the parallel lines:

```<code>import tkinter as tk
import turtle

WIDTH = 300

root = tk.Tk()  # extra work up front to make canvas smaller than window
root.title('Python Turtle Graphics')
root.geometry('{}x{}'.format(WIDTH, WIDTH * 2))

canvas = tk.Canvas(root, width=5 * WIDTH / 6, height=WIDTH * 2)
canvas.pack()
screen = turtle.TurtleScreen(canvas)

actor = turtle.RawTurtle(screen, shape='turtle')
actor.penup()
actor.right(45)
actor.goto(-WIDTH / 2, -5 * WIDTH / 6)
actor.pendown()

for y in range(3):
    actor.circle(WIDTH / 2**0.5, steps=4)
    actor.sety(actor.ycor() + WIDTH / 3)

root.mainloop()
</code>```

Title: Python Turtle Graphics and Loops

Body:
I am trying to create a loop which prints out 6 parallel lines horizontally.However when I using the code below I only am able to see one line that just moves continuously. Any tips would be appreciated. Here is the code:

count = 0;
while(count < 6):
  actor.penup()
  actor.backward(100)
  actor.pendown()
  actor.forward(150)
  count = count + 1

Body:
There must be other ways but I'm not at all familiar with turtle.
  - @BillBell

Yes, there are, we can make a line shaped cookie cutter and stamp them out:

import turtle

STAMP_SIZE = 20

actor = turtle.Turtle('square', visible=False)
actor.shapesize(0.5 / STAMP_SIZE, 200 / STAMP_SIZE, 0)
actor.penup()

for y in range(-3, 3):
    actor.sety(10 * y)
    actor.stamp()

turtle.exitonclick()

(If the lines don't appear on your system, change the 0.5 above to 1.0)

This approach only uses turtle's .circle() method to draw the parallel lines:

import tkinter as tk
import turtle

WIDTH = 300

root = tk.Tk()  # extra work up front to make canvas smaller than window
root.title('Python Turtle Graphics')
root.geometry('{}x{}'.format(WIDTH, WIDTH * 2))

canvas = tk.Canvas(root, width=5 * WIDTH / 6, height=WIDTH * 2)
canvas.pack()
screen = turtle.TurtleScreen(canvas)

actor = turtle.RawTurtle(screen, shape='turtle')
actor.penup()
actor.right(45)
actor.goto(-WIDTH / 2, -5 * WIDTH / 6)
actor.pendown()

for y in range(3):
    actor.circle(WIDTH / 2**0.5, steps=4)
    actor.sety(actor.ycor() + WIDTH / 3)

root.mainloop()


问:
router-flux navbar button this.function is not a function
I implemented in my router-flux nav bar a right button like this:

```<code>  static renderRightButton = (props) => {
          return (
              <TouchableOpacity onPress={() => this.getCurrentPosition()} style={{bottom: 4, right: 8}}>
                  <Icon name='ios-locate-outline' style={{color: 'white'}} />
              </TouchableOpacity>
          );
    }
</code>```

But If I click on my button I get this error :this.5.getCurrentPosition is not a function

I declare my function in the constructor with
this.getCurrentPosition = this.getCurrentPosition.bind(this)

答:
Assuming that you are using jsx file the return can take html like format but you can't structure it that way. Your transpiler didn't pass this.getCurrentPosition() expression. Take a look at your minified file and search for that.

This is how you embed expressions in jsx

function formatName(user) {
  return user.firstName + ' ' + user.lastName;
}

const user = {
  firstName: 'test',
  lastName: 'tesjgg'
};

const element = (

    Hello, {formatName(user)}!

);

ReactDOM.render(
  element,
  document.getElementById('root')
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root">
  <!-- This div's content will be managed by React. -->
</div></code>```

Body:
I implemented in my router-flux nav bar a right button like this:

  static renderRightButton = (props) => {
          return (
              <TouchableOpacity onPress={() => this.getCurrentPosition()} style={{bottom: 4, right: 8}}>
                  <Icon name='ios-locate-outline' style={{color: 'white'}} />
              </TouchableOpacity>
          );
    }

But If I click on my button I get this error :this.5.getCurrentPosition is not a function

I declare my function in the constructor with
this.getCurrentPosition = this.getCurrentPosition.bind(this)

Body:
Assuming that you are using jsx file the return can take html like format but you can't structure it that way. Your transpiler didn't pass this.getCurrentPosition() expression. Take a look at your minified file and search for that.

This is how you embed expressions in jsx

function formatName(user) {
  return user.firstName + ' ' + user.lastName;
}

const user = {
  firstName: 'test',
  lastName: 'tesjgg'
};

const element = (
  <h1>
    Hello, {formatName(user)}!
  </h1>
);

ReactDOM.render(
  element,
  document.getElementById('root')
);

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root">
  <!-- This div's content will be managed by React. -->
</div>


问:
C# MVC Query String Encoding and Decoding
I want to encode and decode the url parameters.

calling function in javascript

```<code>var url = '/Demo/Demo?id=58';
$(location).attr('href', url)
</code>```

Current url parameter

www.example.com/Demo/Demo?id=58

code in Demo controller

```<code>public ActionResult Demo(int id)
{
   return view();
}
</code>```

i want the above url to be changed like the bolow line

www.example.com/Demo/Demo?id=Sff5f8ddg

So that the id value will be confidential. what is the best way to encode and decode.

Note: we calling method by anchor tag, ajax and jquery. Encoding and Decoding other than Base64

Is there any cryptography method other than Base64 enoding and decoding like encrypt in javascript and decrypt in C# method

答:
What I am able to understand from your question is that you want to restrict user from being able to know the exact value of the id parameter.

But that's not gonna help because you already have that value on your browser/client side.
so you have id on your client and you want to restrict your client from knowing its value.
An average developer(anyone who write code) can access your value using developer tool of browser.
So no benefit.

Another way is you send your id encrypted from server itself.
For that you can use the solution provided by @Karan Singh.
Or any other option you want to explore for that matter is up to you.

One suggestion try to use an encryption method which can not be done in reverse. This will add overhead in processing as you will have to first encrypt your Id from DB and then match it with the value sent by client.

Thanks.

Body:
I want to encode and decode the url parameters.

calling function in javascript

var url = '/Demo/Demo?id=58';
$(location).attr('href', url)

Current url parameter

www.example.com/Demo/Demo?id=58

code in Demo controller

public ActionResult Demo(int id)
{
   return view();
}

i want the above url to be changed like the bolow line

www.example.com/Demo/Demo?id=Sff5f8ddg

So that the id value will be confidential. what is the best way to encode and decode.

Note: we calling method by anchor tag, ajax and jquery. Encoding and Decoding other than Base64

Is there any cryptography method other than Base64 enoding and decoding like encrypt in javascript and decrypt in C# method


问:
How do you do GIS queries on Heroku using the shared database?
I have a table of geocoded locations with latitude and longitude.  I'd like my database query to return a filtered list of them, ordered by distance from a fixed point.

There are a few options which I've explored:

Postgresql's earthdistance contrib is probably closest to my needs; however, I've found no indication that this is installed on heroku's db server.

PostGIS is the most often prescribed solution for GIS, but heroku does not have it installed, and heroku support confirmed that they have no intention of doing so in the near future.

I'll need a solution which works with Rails3.

If there are no better options, i'll have to implement my own haversine function, which sure seems like reinventing the wheel.  Any better options?

答:
I would now (July 2011) recommend using geocoder

```<code>gem 'geocoder'
</code>```

http://www.rubygeocoder.com/

You could also use geokit-rails3 as I previously mentioned but it isn't complete and isn't maintained.

```<code>gem 'geokit-rails3'
</code>```

http://github.com/jlecour/geokit-rails3

Body:
I would now (July 2011) recommend using geocoder

gem 'geocoder'

http://www.rubygeocoder.com/

You could also use geokit-rails3 as I previously mentioned but it isn't complete and isn't maintained.

gem 'geokit-rails3'

http://github.com/jlecour/geokit-rails3


答:
I'd write a SP for this... For example</p>

```<code>CREATE PROC your_procedure
@param1
@param2
@param3

AS
BEGIN

SELECT * FROM your_table WHERE Col1 = @param1 AND Col2 = @param2 AND Col3 = @param3

END
</code>```

Title: Matching All the Columns Have the Same Value

Body:
I have a data set as follows:

Col1 | COl2  | Col3
--------------------
A    | Jan-1 |   1
-------------------
A    | Jan-2 |   2
-------------------
A    | Jan-3 |   2
-------------------
A    | Jan-4 |   3
-------------------
B    | Jan-1 |   1
-------------------
B    | Jan-2 |   1
-------------------
B    | Jan-3 |   1
-------------------
B    | Jan-4 |   1
-------------------

I want to select all the Col1 entities that have the same Col3 value for entire date range available in Col2.

Would you be able to help me with this. Thanks.

Body:
I'd write a SP for this... For example

CREATE PROC your_procedure
@param1
@param2
@param3

AS
BEGIN

SELECT * FROM your_table WHERE Col1 = @param1 AND Col2 = @param2 AND Col3 = @param3

END


问:
Process categorical features when building decision tree models
I was using H2O to build classification models like GBM, DRF and DL.
The dataset I have contains a few categorical columns, and if I want to use them as features for building models do I need to manually convert them into dummy variables? I read that GBM can dummify the categorical variables internally? </p>

答:
Yes, H2O is one of the few machine learning libraries that does not require the user to pre-process or one-hot-encode (aka "dummy-encode") the categorical variables.  As long as the column type is "factor" (aka "enum") in your data frame, then H2O knows what to do automatically.

In particular, H2O allows direct use of categorical variables in tree-based methods like Random Forest or GBM.  Tree based algorithms have the ability to use the categorical data natively and typically this leads to better performance than one-hot encoding.  In GLM or Deep Learning, H2O will one-hot encode the categoricals automatically under the hood -- either way you don't need to do any pre-processing.  If you want more control, you can control the type of automatic encoding using the categorical_encoding argument.


问:
Passing data from an Activity to a fragment that has no onCreate
Is it possible to pass data from an Activity using Bundle to a Fragment that has no OnCreate</p>

答:
From Activity, you send data with intent as:

```<code>Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);
</code>```

and in Fragment onCreateView method:

```<code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    String strtext = getArguments().getString("edttext");
    return inflater.inflate(R.layout.fragment, container, false);
}
</code>```

Body:
From Activity, you send data with intent as:

Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);

and in Fragment onCreateView method:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    String strtext = getArguments().getString("edttext");
    return inflater.inflate(R.layout.fragment, container, false);
}


问:
Vbscript to search for all files with an extension and save them to a CSV
I am trying to write a script that will search say C:\ and all of its sub folders for a specific extension and save all of theme to a CSV file. I have tried this but to no avail:

```<code>Set objFSO = CreateObject("Scripting.FileSystemObject")
objStartFolder = "C:\"

Set objFolder = objFSO.GetFolder(objStartFolder)
Wscript.Echo objFolder.GetExtensionName("*.txt")

Set colFiles = objFolder.Files

For Each objFile in colFiles
If objFile.Extension = "pfx" Then
    Wscript.Echo objFile.Name
    End If
Next
Wscript.Echo

ShowSubfolders objFSO.GetFolder(objStartFolder)

Sub ShowSubFolders(Folder)
    For Each Subfolder in Folder.SubFolders
        Wscript.Echo Subfolder.Path
        Set objFolder = objFSO.GetFolder(Subfolder.Path)
        Set colFiles = objFolder.Files
        For Each objFile in colFiles
            Wscript.Echo objFile.Name
        Next
        Wscript.Echo
        ShowSubFolders Subfolder
    Next

Set WScript = CreateObject("WScript.Shell")

End Sub
</code>```

I don't think I am going down the right path here. I am not proficient in the least in vb script it just happens to be the only thing I am allowed to use.

答:
Later still but even simpler (and fast :0)):

Open a CMD, CD to the directory in question

DIR /S /A-D /B C:\*.something >> D:\ListOf.Files

Body:
I am trying to write a script that will search say C:\ and all of its sub folders for a specific extension and save all of theme to a CSV file. I have tried this but to no avail:

Set objFSO = CreateObject("Scripting.FileSystemObject")
objStartFolder = "C:\"

Set objFolder = objFSO.GetFolder(objStartFolder)
Wscript.Echo objFolder.GetExtensionName("*.txt")

Set colFiles = objFolder.Files

For Each objFile in colFiles
If objFile.Extension = "pfx" Then
    Wscript.Echo objFile.Name
    End If
Next
Wscript.Echo

ShowSubfolders objFSO.GetFolder(objStartFolder)

Sub ShowSubFolders(Folder)
    For Each Subfolder in Folder.SubFolders
        Wscript.Echo Subfolder.Path
        Set objFolder = objFSO.GetFolder(Subfolder.Path)
        Set colFiles = objFolder.Files
        For Each objFile in colFiles
            Wscript.Echo objFile.Name
        Next
        Wscript.Echo
        ShowSubFolders Subfolder
    Next

Set WScript = CreateObject("WScript.Shell")

End Sub

I don't think I am going down the right path here. I am not proficient in the least in vb script it just happens to be the only thing I am allowed to use.


问:
Use user-defined asset servers in Rails
I'm building an application in Rails where sets of images can be created, i.e. the user uploads a file of image names and specifies a path where those images can be found on the web.

So, for example, the image file contains:

```<code>image1.jpg
image2.jpg
</code>```

and the path is specified as http://www.user1-server.com/.

Another user could load his own file of image names, but specify another server: http://www.user2-server.com/ or even http://my-fancy-server.com.

Is there any way to use the AssetTagHelper functionality of Rails to help me generate the image tags?

So, if I'm in the context of user 1, e.g. /users/1/images/1, and use:

```<code>image_tag("1.jpg")
</code>```

it should deliver http://www.user1-server.com/images/1.jpg, but for /users/2/images/1 it should return http://www.user2-server.com/images/1.jpg or http://my-fancy-server.com/images/1.jpg.

答: I don't think you can change asset host in Rails on the fly like that. Rails is smart enough to not set or override the host passed into an image tag, though. Maybe just write a helper method or something to pass the correct host in?</p>

Title: Use user-defined asset servers in Rails

Body:
I'm building an application in Rails where sets of images can be created, i.e. the user uploads a file of image names and specifies a path where those images can be found on the web.

So, for example, the image file contains:

image1.jpg
image2.jpg

and the path is specified as http://www.user1-server.com/.

Another user could load his own file of image names, but specify another server: http://www.user2-server.com/ or even http://my-fancy-server.com.

Is there any way to use the AssetTagHelper functionality of Rails to help me generate the image tags?

So, if I'm in the context of user 1, e.g. /users/1/images/1, and use:

image_tag("1.jpg")

it should deliver http://www.user1-server.com/images/1.jpg, but for /users/2/images/1 it should return http://www.user2-server.com/images/1.jpg or http://my-fancy-server.com/images/1.jpg.


问:
PHP string convert encoding from utf8 to cp1251 with replace impossible characters via html-mnemonics
I convert string encoding from wide utf8 to limited encoding cp1251. I need to preserve some characters not included into cp1251.

In python 2.x there is a special function, which during encoding conversion replaces impossible characters with html-entities:

```<code># -*- coding: utf-8 -*-

s_in = "Ø 125 mm".decode('utf8')
s_out = s_in.encode('cp1251', 'xmlcharrefreplace')
print s_out # prints Ø 125 mm
</code>```

Live example on ideone

Is there any ready-to-use func/lib in PHP to do the task?

My code is:

```<code><?php
$in = 'Ø 125 mm';
$out = mb_convert_encoding($in, 'cp1251', 'utf8');
echo $out; // prints ? 125 mm
</code>```

Live example on sandbox.onlinephpfunctions

答:
By using iconv() function in PHP you can convert string from one to another encoded scheme. Example:

```<code>$out = iconv("UTF-8", "CP1251//IGNORE", $in);
</code>```

If you append the string //IGNORE, characters that cannot be
  represented in the target charset are silently discarded

For complete description see link:
http://php.net/manual/en/function.iconv.php

Body:
I convert string encoding from wide utf8 to limited encoding cp1251. I need to preserve some characters not included into cp1251.

In python 2.x there is a special function, which during encoding conversion replaces impossible characters with html-entities:

# -*- coding: utf-8 -*-

s_in = "Ø 125 mm".decode('utf8')
s_out = s_in.encode('cp1251', 'xmlcharrefreplace')
print s_out # prints Ø 125 mm

Live example on ideone

Is there any ready-to-use func/lib in PHP to do the task?

My code is:

<?php
$in = 'Ø 125 mm';
$out = mb_convert_encoding($in, 'cp1251', 'utf8');
echo $out; // prints ? 125 mm

Live example on sandbox.onlinephpfunctions

Body:
By using iconv() function in PHP you can convert string from one to another encoded scheme. Example:

$out = iconv("UTF-8", "CP1251//IGNORE", $in);

If you append the string //IGNORE, characters that cannot be
  represented in the target charset are silently discarded

For complete description see link:
http://php.net/manual/en/function.iconv.php


问:
How we can authenticate webview with username and password in xamarin.forms for iOS?
I recently started development using Xamarin. Forms and I am new to C#. I have a URL which I am using for resetting password, this URL is an HTML page and I am loading it in a Webview. If we open this URL in a browser it will ask for authentication i.e Username and Password, but I am not able to open this on iOS.
I have created custom class for Webview in Android and iOS. For Android it's working fine but in iOS it's not.

Code:

```<code>private void WillSendRequestForAuthenticationChallenge
(NSUrlConnection connection, NSUrlAuthenticationChallenge challenge)
</code>```

But I am not sure how to use this. Thanks in advance.

答:
If you are using the newer iOS webkit WkWebView, you can override the function DidReceiveAuthenticationChallenge in your WKNavigationDelegate. Like so:</p>

```<code>public class MyNavigationDelegate : WKNavigationDelegate
{
     public override void DidReceiveAuthenticationChallenge(WKWebView webView, NSUrlAuthenticationChallenge challenge, Action<nsurlsessionauthchallengedisposition, nsurlcredential=""> completionHandler)
     {
         var credential = new NSUrlCredential("username", "password", NSUrlCredentialPersistence.ForSession);
         completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, credential);
     }
}
</code>```

Body:
I recently started development using Xamarin. Forms and I am new to C#. I have a URL which I am using for resetting password, this URL is an HTML page and I am loading it in a Webview. If we open this URL in a browser it will ask for authentication i.e Username and Password, but I am not able to open this on iOS.
I have created custom class for Webview in Android and iOS. For Android it's working fine but in iOS it's not.

Code:

private void WillSendRequestForAuthenticationChallenge
(NSUrlConnection connection, NSUrlAuthenticationChallenge challenge)

But I am not sure how to use this. Thanks in advance.

Body:
If you are using the newer iOS webkit WkWebView, you can override the function DidReceiveAuthenticationChallenge in your WKNavigationDelegate. Like so:

public class MyNavigationDelegate : WKNavigationDelegate
{
     public override void DidReceiveAuthenticationChallenge(WKWebView webView, NSUrlAuthenticationChallenge challenge, Action<nsurlsessionauthchallengedisposition, nsurlcredential=""> completionHandler)
     {
         var credential = new NSUrlCredential("username", "password", NSUrlCredentialPersistence.ForSession);
         completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, credential);
     }
}


问:
Custom Validation in dynamic Form against array of item
I have a Person[] which can be edited dynamically, one at a time, so I have a the following:

```<code><template ngFor let-indx="index" let-persons [ngForOf]="persons">
    <div *ngIf="!person.isEditing">
        <h4>{{person.name}}</h4>
    </div>
    <div *ngIf="person.isEditing">
        <form #addNewGuestForm="ngForm" novalidate>
            <input [(ngModel)]="person.name" #personName="ngModel" required maxlength="50" minlength="2">
        </form>
    </div>
    <button (click)="person.isEditing=!person.isEditing">Edit/Save</button>
</template>
</code>```

Note: the form is wrapped by a *ngIf.

Question: how do I validate the name is unique and doesnt collide with other names in the persons array? I tried doing the following, but I get the classic: Can't bind to 'persons' since it isn't a known property of 'input':

```<code>@Directive({
    selector: '[uniqueValidator][ngModelGroup]',
    providers: [{ provide: NG_VALIDATORS, useExisting: UniqueValidator, multi: true }]
})
export class UniqueValidator implements Validator {
    @Input() persons: Person[];
    validate(control: FormGroup): { [key: string]: any } {
        //validation against other items in persons
    }
}
</code>```

and the html changed into:

```<code><input uniqueValidator [persons]="persons" [(ngModel)]="person.name" #personName="ngModel" required maxlength="50" minlength="2">
</code>```

Note: I have included the UniqueValidator in the @NgModule's declarations section.

答:
Selector was the culprit, changing it to

```<code>selector: '[uniqueValidator][ngModel]'
</code>```

worked !

Body:
I have a Person[] which can be edited dynamically, one at a time, so I have a the following:

<template ngFor let-indx="index" let-persons [ngForOf]="persons">

{{person.name}}

        <form #addNewGuestForm="ngForm" novalidate>
            <input [(ngModel)]="person.name" #personName="ngModel" required maxlength="50" minlength="2">
        </form>

    <button (click)="person.isEditing=!person.isEditing">Edit/Save</button>
</template>

Note: the form is wrapped by a *ngIf.

Question: how do I validate the name is unique and doesnt collide with other names in the persons array? I tried doing the following, but I get the classic: Can't bind to 'persons' since it isn't a known property of 'input':

@Directive({
    selector: '[uniqueValidator][ngModelGroup]',
    providers: [{ provide: NG_VALIDATORS, useExisting: UniqueValidator, multi: true }]
})
export class UniqueValidator implements Validator {
    @Input() persons: Person[];
    validate(control: FormGroup): { [key: string]: any } {
        //validation against other items in persons
    }
}

and the html changed into:

<input uniqueValidator [persons]="persons" [(ngModel)]="person.name" #personName="ngModel" required maxlength="50" minlength="2">

Note: I have included the UniqueValidator in the @NgModule's declarations section.

Body:
Selector was the culprit, changing it to

selector: '[uniqueValidator][ngModel]'

worked !