问:
Draggable Boxview crash error Xamarin
The problem lays with the draggable view, in the first part of the code local:draggableview, the program crashes at the Xaml part of the code, but I can't figure out what the problem is. I've removed the draggableview and tried putting out breakpoints in the non xaml part of the code but I can't find out what is casuing a problem.

```<code><ContentPage>
    <ContentPage.Padding>
        <OnPlatform x:TypeArguments="Thickness">
            <On Platform="iOS, Android" Value="0,40,0,0" />
        </OnPlatform>
    </ContentPage.Padding>
    <Grid BackgroundColor="White" ColumnSpacing="10" RowSpacing="10">
        <Label Text="Red" FontSize="Medium" HorizontalOptions="Center" />
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>

        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>

        <BoxView Color="Black" Grid.Column="1" Grid.RowSpan="1"/>
        <BoxView Color="Gray" Grid.Column="2" Grid.RowSpan="1"/>
        <Label Text="9" Font ="60" Grid.Row="1" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" TextColor="Black" />
        <Label Text="8" Font ="60" Grid.Row="2" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" TextColor="Black" />
        <Label Text="7" Font ="60" Grid.Row="3" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" TextColor="Black" />
        <Label Text="6" Font ="60" Grid.Row="4" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" TextColor="Black" />
        <Label Text="5" Font ="60" Grid.Row="5" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" TextColor="Black" />
        <Label Text="4" Font ="60" Grid.Row="6" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" TextColor="Black" />
        <Label Text="3" Font ="60" Grid.Row="7" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" TextColor="Black" />
        <Label Text="2" Font ="60" Grid.Row="8" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" TextColor="Black" />
        <Label Text="1" Font ="60" Grid.Row="9" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" TextColor="Black" />
        <Label Text="0" Font ="60" Grid.Row="10" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" TextColor="Black" />

        <local:DraggableView x:Name="dragView" DragMode="LongPress" DragDirection="All" >
            <local:DraggableView.Content>
                <BoxView x:Name="image" ItemSelected="Handle_ItemSelected" />
            </local:DraggableView.Content>
        </local:DraggableView>
    </Grid>

</ContentPage>
</code>```

Helpers

```<code>public enum DragDirectionType
{
    All,
    Vertical,
    Horizontal
}
public enum DragMode
{
    Touch,
    LongPress
}
</code>```

DraggableView

```<code> public partial class DraggableView : ContentView
    {
        public event EventHandler DragStart = delegate { };
        public event EventHandler DragEnd = delegate { };

        public static readonly BindableProperty DragDirectionProperty = BindableProperty.Create(
            propertyName: "DragDirection",
            returnType: typeof(DragDirectionType),
            declaringType: typeof(DraggableView),
            defaultValue: DragDirectionType.All,
            defaultBindingMode: BindingMode.TwoWay);

        public DragDirectionType DragDirection
        {
            get { return (DragDirectionType)GetValue(DragDirectionProperty); }
            set { SetValue(DragDirectionProperty, value); }
        }

        public static readonly BindableProperty DragModeProperty = BindableProperty.Create(
           propertyName: "DragMode",
           returnType: typeof(DragMode),
           declaringType: typeof(DraggableView),
           defaultValue: DragMode.LongPress,
           defaultBindingMode: BindingMode.TwoWay);

        public DragMode DragMode
        {
            get { return (DragMode)GetValue(DragModeProperty); }
            set { SetValue(DragModeProperty, value); }
        }

        public static readonly BindableProperty IsDraggingProperty = BindableProperty.Create(
          propertyName: "IsDragging",
          returnType: typeof(bool),
          declaringType: typeof(DraggableView),
          defaultValue: false,
          defaultBindingMode: BindingMode.TwoWay);

        public bool IsDragging
        {
            get { return (bool)GetValue(IsDraggingProperty); }
            set { SetValue(IsDraggingProperty, value); }
        }

        public void DragStarted()
        {
            DragStart(this, default(EventArgs));
            IsDragging = true;
        }

        public void DragEnded()
        {
            IsDragging = false;
            DragEnd(this, default(EventArgs));
        }

    }
}
</code>```

This is the android part of the code

```<code>[assembly: ExportRenderer(typeof(DraggableView), typeof(DraggableViewRenderer))]

namespace BabakusXamarin.Droid
{
    public class DraggableViewRenderer : VisualElementRenderer<Xamarin.Forms.View>
    {
        float originalX;
        float originalY;
        float dX;
        float dY;
        bool firstTime = true;
        bool touchedDown = false;

        protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.View> e)
        {
            base.OnElementChanged(e);

            if (e.OldElement != null)
            {
                LongClick -= HandleLongClick;
            }
        }

        private void HandleLongClick(object sender, LongClickEventArgs e)
        {
            var dragView = Element as DraggableView;
            if (firstTime)
            {
                originalX = GetX();
                originalY = GetY();
                firstTime = false;
            }
            dragView.DragStarted();
            touchedDown = true;
        }

        protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            var dragView = Element as DraggableView;
            base.OnElementPropertyChanged(sender, e);

        }
        protected override void OnVisibilityChanged(AView.View changedView, [GeneratedEnum] ViewStates visibility)
        {
            base.OnVisibilityChanged(changedView, visibility);
            if (visibility == ViewStates.Visible)
            {

            }
        }
        public override bool OnTouchEvent(MotionEvent e)
        {
            float x = e.RawX;
            float y = e.RawY;
            var dragView = Element as DraggableView;
            switch (e.Action)
            {
                case MotionEventActions.Down:
                    if (dragView.DragMode == DragMode.Touch)
                    {
                        if (!touchedDown)
                        {
                            if (firstTime)
                            {
                                originalX = GetX();
                                originalY = GetY();
                                firstTime = false;
                            }
                            dragView.DragStarted();
                        }

                        touchedDown = true;
                    }
                    dX = x - this.GetX();
                    dY = y - this.GetY();
                    break;
                case MotionEventActions.Move:
                    if (touchedDown)
                    {
                        if (dragView.DragDirection == DragDirectionType.All || dragView.DragDirection == DragDirectionType.Horizontal)
                        {
                            SetX(x - dX);
                        }

                        if (dragView.DragDirection == DragDirectionType.All || dragView.DragDirection == DragDirectionType.Vertical)
                        {
                            SetY(y - dY);
                        }

                    }
                    break;
                case MotionEventActions.Up:
                    touchedDown = false;
                    dragView.DragEnded();
                    break;
                case MotionEventActions.Cancel:
                    touchedDown = false;
                    break;
            }
            return base.OnTouchEvent(e);
        }

        public override bool OnInterceptTouchEvent(MotionEvent e)
        {

            BringToFront();
            return true;
        }

    }

}
</code>```

答:
The problem lays with the draggable view, in the first part of the code local:draggableview, the program crashes at the Xaml part of the code, but I can't figure out what the problem is.

The problem is: there is no ItemSelected in BoxView. By removing ItemSelected="ItemSelected", your xaml codes will work.

For details of BoxView, please refer to BoxView.

Title: Draggable Boxview crash error Xamarin

Body:
The problem lays with the draggable view, in the first part of the code local:draggableview, the program crashes at the Xaml part of the code, but I can't figure out what the problem is. I've removed the draggableview and tried putting out breakpoints in the non xaml part of the code but I can't find out what is casuing a problem.

<ContentPage>
    <ContentPage.Padding>
        <OnPlatform x:TypeArguments="Thickness">
            <On Platform="iOS, Android" Value="0,40,0,0" />
        </OnPlatform>
    </ContentPage.Padding>
    <Grid BackgroundColor="White" ColumnSpacing="10" RowSpacing="10">

        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>

        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>

        <BoxView Color="Black" Grid.Column="1" Grid.RowSpan="1"/>
        <BoxView Color="Gray" Grid.Column="2" Grid.RowSpan="1"/>

        <local:DraggableView x:Name="dragView" DragMode="LongPress" DragDirection="All" >
            <local:DraggableView.Content>
                <BoxView x:Name="image" ItemSelected="Handle_ItemSelected" />
            </local:DraggableView.Content>
        </local:DraggableView>
    </Grid>

</ContentPage>

Helpers

public enum DragDirectionType
{
    All,
    Vertical,
    Horizontal
}
public enum DragMode
{
    Touch,
    LongPress
}

DraggableView

 public partial class DraggableView : ContentView
    {
        public event EventHandler DragStart = delegate { };
        public event EventHandler DragEnd = delegate { };

        public static readonly BindableProperty DragDirectionProperty = BindableProperty.Create(
            propertyName: "DragDirection",
            returnType: typeof(DragDirectionType),
            declaringType: typeof(DraggableView),
            defaultValue: DragDirectionType.All,
            defaultBindingMode: BindingMode.TwoWay);

        public DragDirectionType DragDirection
        {
            get { return (DragDirectionType)GetValue(DragDirectionProperty); }
            set { SetValue(DragDirectionProperty, value); }
        }

        public static readonly BindableProperty DragModeProperty = BindableProperty.Create(
           propertyName: "DragMode",
           returnType: typeof(DragMode),
           declaringType: typeof(DraggableView),
           defaultValue: DragMode.LongPress,
           defaultBindingMode: BindingMode.TwoWay);

        public DragMode DragMode
        {
            get { return (DragMode)GetValue(DragModeProperty); }
            set { SetValue(DragModeProperty, value); }
        }

        public static readonly BindableProperty IsDraggingProperty = BindableProperty.Create(
          propertyName: "IsDragging",
          returnType: typeof(bool),
          declaringType: typeof(DraggableView),
          defaultValue: false,
          defaultBindingMode: BindingMode.TwoWay);

        public bool IsDragging
        {
            get { return (bool)GetValue(IsDraggingProperty); }
            set { SetValue(IsDraggingProperty, value); }
        }

        public void DragStarted()
        {
            DragStart(this, default(EventArgs));
            IsDragging = true;
        }

        public void DragEnded()
        {
            IsDragging = false;
            DragEnd(this, default(EventArgs));
        }

    }
}

This is the android part of the code

[assembly: ExportRenderer(typeof(DraggableView), typeof(DraggableViewRenderer))]

namespace BabakusXamarin.Droid
{
    public class DraggableViewRenderer : VisualElementRenderer<Xamarin.Forms.View>
    {
        float originalX;
        float originalY;
        float dX;
        float dY;
        bool firstTime = true;
        bool touchedDown = false;

        protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.View> e)
        {
            base.OnElementChanged(e);

            if (e.OldElement != null)
            {
                LongClick -= HandleLongClick;
            }
        }

        private void HandleLongClick(object sender, LongClickEventArgs e)
        {
            var dragView = Element as DraggableView;
            if (firstTime)
            {
                originalX = GetX();
                originalY = GetY();
                firstTime = false;
            }
            dragView.DragStarted();
            touchedDown = true;
        }

        protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            var dragView = Element as DraggableView;
            base.OnElementPropertyChanged(sender, e);

        }
        protected override void OnVisibilityChanged(AView.View changedView, [GeneratedEnum] ViewStates visibility)
        {
            base.OnVisibilityChanged(changedView, visibility);
            if (visibility == ViewStates.Visible)
            {

            }
        }
        public override bool OnTouchEvent(MotionEvent e)
        {
            float x = e.RawX;
            float y = e.RawY;
            var dragView = Element as DraggableView;
            switch (e.Action)
            {
                case MotionEventActions.Down:
                    if (dragView.DragMode == DragMode.Touch)
                    {
                        if (!touchedDown)
                        {
                            if (firstTime)
                            {
                                originalX = GetX();
                                originalY = GetY();
                                firstTime = false;
                            }
                            dragView.DragStarted();
                        }

                        touchedDown = true;
                    }
                    dX = x - this.GetX();
                    dY = y - this.GetY();
                    break;
                case MotionEventActions.Move:
                    if (touchedDown)
                    {
                        if (dragView.DragDirection == DragDirectionType.All || dragView.DragDirection == DragDirectionType.Horizontal)
                        {
                            SetX(x - dX);
                        }

                        if (dragView.DragDirection == DragDirectionType.All || dragView.DragDirection == DragDirectionType.Vertical)
                        {
                            SetY(y - dY);
                        }

                    }
                    break;
                case MotionEventActions.Up:
                    touchedDown = false;
                    dragView.DragEnded();
                    break;
                case MotionEventActions.Cancel:
                    touchedDown = false;
                    break;
            }
            return base.OnTouchEvent(e);
        }

        public override bool OnInterceptTouchEvent(MotionEvent e)
        {

            BringToFront();
            return true;
        }

    }

}


来源: stackexchange

问:
Custom design listview position error
custom design Listview Blog image

i want to create something like shown in the above image, where latest blog show up and other follow the alternate layout.

i have created the odd even follow loop, but its not working, when scrolling the listview it loads from first position,

```<code>@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if (inflater == null)
        inflater = (LayoutInflater) activity
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    int layoutResource = 0; // determined by view type
    int viewType = getItemViewType(position);
    switch (viewType) {
        case 0:
            layoutResource = R.layout.news_row;
            break;

        case 0:
            layoutResource = R.layout.news_row_even;
            break;

        case 1:
            layoutResource = R.layout.news_row_odd;
    }
    if (convertView == null)
        convertView = inflater.inflate(layoutResource, null);

    TextView txtNewsTitle = (TextView) convertView.findViewById(R.id.news_title);
    txtNewsTitle.startAnimation(AnimationUtils.loadAnimation(this.activity, R.anim.fade_in));
    txtNewsTitle.setTypeface(Utils.getTypeFace(Utils.Fonts.ROBOTO));

    TextView txtMessage = (TextView) convertView.findViewById(R.id.message);
    txtMessage.setTypeface(Utils.getTypeFace(Utils.Fonts.ROBOTO));
    txtMessage.startAnimation(AnimationUtils.loadAnimation(this.activity, R.anim.fade_in));

    TextView txtAgo = (TextView) convertView.findViewById(R.id.ago);
    txtAgo.setTypeface(Utils.getTypeFace(Utils.Fonts.ROBOTO));
    txtAgo.startAnimation(AnimationUtils.loadAnimation(this.activity, R.anim.fade_in));

    int MAX_WIDTH = Utils.getScreenWidth() / 2;
    int MAX_HEIGHT = MAX_WIDTH;

    final PNewsData news = (PNewsData) getItem(position);
    int n = 0;

    Log.e("position", String.valueOf(position));

    txtNewsTitle.setText(news.title);
    txtMessage.setText(news.description.substring(0, Math.min(news.description.length(), 120)) + "...");
    txtAgo.setText(news.added);

    if (news.images.get(0).path != null) {
        p.load(Config.APP_IMAGES_URL + news.images.get(0).path)
                .transform(new BitmapTransform(MAX_WIDTH, MAX_HEIGHT))
                .into(imgNewsPhoto);
    }

    return convertView;
}
</code>```

答:
At first RECTIFY case NO.

```<code>          case 0:

            layoutResource = R.layout.news_row;
            break;

        case 1:

            layoutResource = R.layout.news_row_even;
            break;

        case 2:
            layoutResource = R.layout.news_row_odd;
</code>```

ContentLicense: CC BY-SA 3.0

Title: Custom design listview position error

Body:
custom design Listview Blog image

i want to create something like shown in the above image, where latest blog show up and other follow the alternate layout.

i have created the odd even follow loop, but its not working, when scrolling the listview it loads from first position,

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if (inflater == null)
        inflater = (LayoutInflater) activity
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    int layoutResource = 0; // determined by view type
    int viewType = getItemViewType(position);
    switch (viewType) {
        case 0:
            layoutResource = R.layout.news_row;
            break;

        case 0:
            layoutResource = R.layout.news_row_even;
            break;

        case 1:
            layoutResource = R.layout.news_row_odd;
    }
    if (convertView == null)
        convertView = inflater.inflate(layoutResource, null);

    TextView txtNewsTitle = (TextView) convertView.findViewById(R.id.news_title);
    txtNewsTitle.startAnimation(AnimationUtils.loadAnimation(this.activity, R.anim.fade_in));
    txtNewsTitle.setTypeface(Utils.getTypeFace(Utils.Fonts.ROBOTO));

    TextView txtMessage = (TextView) convertView.findViewById(R.id.message);
    txtMessage.setTypeface(Utils.getTypeFace(Utils.Fonts.ROBOTO));
    txtMessage.startAnimation(AnimationUtils.loadAnimation(this.activity, R.anim.fade_in));

    TextView txtAgo = (TextView) convertView.findViewById(R.id.ago);
    txtAgo.setTypeface(Utils.getTypeFace(Utils.Fonts.ROBOTO));
    txtAgo.startAnimation(AnimationUtils.loadAnimation(this.activity, R.anim.fade_in));

    int MAX_WIDTH = Utils.getScreenWidth() / 2;
    int MAX_HEIGHT = MAX_WIDTH;

    final PNewsData news = (PNewsData) getItem(position);
    int n = 0;

    Log.e("position", String.valueOf(position));

    txtNewsTitle.setText(news.title);
    txtMessage.setText(news.description.substring(0, Math.min(news.description.length(), 120)) + "...");
    txtAgo.setText(news.added);

    if (news.images.get(0).path != null) {
        p.load(Config.APP_IMAGES_URL + news.images.get(0).path)
                .transform(new BitmapTransform(MAX_WIDTH, MAX_HEIGHT))
                .into(imgNewsPhoto);
    }

    return convertView;
}

Body:
At first RECTIFY case NO.

          case 0:

            layoutResource = R.layout.news_row;
            break;

        case 1:

            layoutResource = R.layout.news_row_even;
            break;

        case 2:
            layoutResource = R.layout.news_row_odd;


问:
How can I improve the performance of the JbossFuse (v6.3) DSL route code?
APPLICATION INFO:

Code below: reads from IBM MQ queue and then posts the message to a REST service

(note: reading from the MQ queue is fast and not an issue - rather, it is the post operation performance I am having trouble improving)...

PROBLEM:

Unable to output/post more than 44-47 messages per second...

QUESTION:

How can I improve the performance of the JbossFuse (v6.3) DSL route code below?...   (What techniques are available that would make it faster?)

```<code>package aaa.bbb.ccc;

import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.cdi.ContextName;

@ContextName("rest-dsl")
public class Netty4HttpSlowRoutes extends RouteBuilder {

    public Netty4HttpSlowRoutes() {
    }

    private final org.apache.camel.Processor proc1 = new Processor1();

    @Override
    public void configure() throws Exception {

    org.apache.log4j.MDC.put("app.name", "netty4HttpSlow");

    System.getProperties().list(System.out);
    errorHandler(defaultErrorHandler().maximumRedeliveries(3).log("***FAILED_MESSAGE***"));

    from("wmq:queue:mylocalqueue")
        .log("inMessage=" + (null==body()?"":body().toString()))
        .to("seda:node1?concurrentConsumers=20");

    from("seda:node1")
        .streamCaching()
        .threads(20)
        .setHeader(Exchange.HTTP_METHOD, constant(org.apache.camel.component.http4.HttpMethods.POST))
        .setHeader(Exchange.CONTENT_TYPE, constant("application/json"))
        .toD("netty4-http:http://localhost:7001/MyService/myServiceThing?textline\\=true");
    }
}
</code>```

答:
Just a couple of thoughts. First things first: did you measure the slowness? How much time do you spend in Camel VS how much time you spend sending the HTTP request?

If the REST service is slow there's nothing you can do in Camel. Depending on what the service does, you could try reducing the number of threads.

Try to disable streamCaching since it looks like you're not using it.

Then use a to instead of toD to invoke the service, I see that the URL is always the same. In the docs of ToD I read

By default the Simple language is used to compute the endpoint.

There may be a little overhead while parsing the URI string each time you invoke the route.

Body:
APPLICATION INFO:

Code below: reads from IBM MQ queue and then posts the message to a REST service

(note: reading from the MQ queue is fast and not an issue - rather, it is the post operation performance I am having trouble improving)...

PROBLEM:

Unable to output/post more than 44-47 messages per second...

QUESTION:

How can I improve the performance of the JbossFuse (v6.3) DSL route code below?...   (What techniques are available that would make it faster?)

package aaa.bbb.ccc;

import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.cdi.ContextName;

@ContextName("rest-dsl")
public class Netty4HttpSlowRoutes extends RouteBuilder {

    public Netty4HttpSlowRoutes() {
    }

    private final org.apache.camel.Processor proc1 = new Processor1();

    @Override
    public void configure() throws Exception {

    org.apache.log4j.MDC.put("app.name", "netty4HttpSlow");

    System.getProperties().list(System.out);
    errorHandler(defaultErrorHandler().maximumRedeliveries(3).log("***FAILED_MESSAGE***"));

    from("wmq:queue:mylocalqueue")
        .log("inMessage=" + (null==body()?"":body().toString()))
        .to("seda:node1?concurrentConsumers=20");

    from("seda:node1")
        .streamCaching()
        .threads(20)
        .setHeader(Exchange.HTTP_METHOD, constant(org.apache.camel.component.http4.HttpMethods.POST))
        .setHeader(Exchange.CONTENT_TYPE, constant("application/json"))
        .toD("netty4-http:http://localhost:7001/MyService/myServiceThing?textline\\=true");
    }
}


问:
Spring security guest user
I have a custom UserDetails implementation that has a shopping cart property.

```<code>class MyUserDetails implement UserDetails {
    private Cart cart;
    // getters & setters + other properties....
}
</code>```

I want anonymous users to be a instance of MyUserDetails too, so far I have gotten it working otherwise, but all anonymousUsers have the same shopping cart!

```<code>@Override
protected void configure(HttpSecurity http) throws Exception {
    MyUserDetails anonymousUser = new MyUserDetails();
    anonymousUser.setUsername("anonymousUser");
    http.anonymous().principal(anonymousUser);
    ...
}
</code>```

How would I be able to return a new instance of MyUserDetails for anonymous users for each session?

答:
I am pretty sure I managed to get it working by creating a custom AnonymousAuthenticationFilter like this:

```<code>public class MyAnonymousAuthenticationFilter extends AnonymousAuthenticationFilter {
    private static final String USER_SESSION_KEY = "user";
    private final String key;

    public MyAnonymousAuthenticationFilter(String key) {
        super(key);
        this.key = key;
    }

    @Override
    protected Authentication createAuthentication(HttpServletRequest req) {
        HttpSession httpSession = req.getSession();
        MyUserDetails user = Optional.ofNullable((MyUserDetails) httpSession.getAttribute(USER_SESSION_KEY))
                .orElseGet(() -> {
                    MyUserDetails anon = new MyUserDetails();
                    anon.setUsername("anonymousUser");
                    httpSession.setAttribute(USER_SESSION_KEY, anon);
                    return anon;
                });
        return new AnonymousAuthenticationToken(key, user, AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"));
    }
}
</code>```

and then use it with http.anonymous().authenticationFilter(new MyAnonymousAuthenticationFilter(UUID.randomUUID().toString()));

If there is something wrong with this approach, or if you know a better way, please let me know!

Title: Spring security guest user

Body:
I have a custom UserDetails implementation that has a shopping cart property.

class MyUserDetails implement UserDetails {
    private Cart cart;
    // getters & setters + other properties....
}

I want anonymous users to be a instance of MyUserDetails too, so far I have gotten it working otherwise, but all anonymousUsers have the same shopping cart!

@Override
protected void configure(HttpSecurity http) throws Exception {
    MyUserDetails anonymousUser = new MyUserDetails();
    anonymousUser.setUsername("anonymousUser");
    http.anonymous().principal(anonymousUser);
    ...
}

How would I be able to return a new instance of MyUserDetails for anonymous users for each session?

Body:
I am pretty sure I managed to get it working by creating a custom AnonymousAuthenticationFilter like this:

public class MyAnonymousAuthenticationFilter extends AnonymousAuthenticationFilter {
    private static final String USER_SESSION_KEY = "user";
    private final String key;

    public MyAnonymousAuthenticationFilter(String key) {
        super(key);
        this.key = key;
    }

    @Override
    protected Authentication createAuthentication(HttpServletRequest req) {
        HttpSession httpSession = req.getSession();
        MyUserDetails user = Optional.ofNullable((MyUserDetails) httpSession.getAttribute(USER_SESSION_KEY))
                .orElseGet(() -> {
                    MyUserDetails anon = new MyUserDetails();
                    anon.setUsername("anonymousUser");
                    httpSession.setAttribute(USER_SESSION_KEY, anon);
                    return anon;
                });
        return new AnonymousAuthenticationToken(key, user, AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"));
    }
}

and then use it with http.anonymous().authenticationFilter(new MyAnonymousAuthenticationFilter(UUID.randomUUID().toString()));

If there is something wrong with this approach, or if you know a better way, please let me know!


问:
Android Twitter open source client
Where can I get the code of a Twitter client for Android? Possibly a recent one using the latest SDK. Thanks</p>

答:
By Using code we can directly get the twitter log in page</p>

```<code>Intent i = new Intent();
                i.setAction(Intent.ACTION_VIEW);
                i.setData(Uri.parse("http://mobile.twitter.com"));
                startActivity(i);
</code>```

ContentLicense: CC BY-SA 2.5

Title: Android Twitter open source client

Body:
By Using code we can directly get the twitter log in page

Intent i = new Intent();
                i.setAction(Intent.ACTION_VIEW);
                i.setData(Uri.parse("http://mobile.twitter.com"));
                startActivity(i);


问:
How to connect spark application to secure HBase with Kerberos
I`m trying to connect a Spark application to HBase with Kerberos enabled. Spark version is 1.5.0, CDH 5.5.2 and it's executed in yarn cluster mode.

When HbaseContext is initialized, it throws this error:

ERROR ipc.AbstractRpcClient: SASL authentication failed. The most likely cause is missing or invalid credentials. Consider 'kinit'.
  javax.security.sasl.SaslException: GSS initiate failed [Caused by GSSException: No valid credentials provided (Mechanism level: Failed to find any Kerberos tgt)]

I have tried to do the authentication in the code, adding:

```<code>UserGroupInformation.setConfiguration(config)
UserGroupInformation.loginUserFromKeytab(principalName, keytabFilename)
</code>```

I distribute the keytab file with --files option in spark-submit.
Now, the error is:

java.io.IOException: Login failure for usercomp@COMPANY.CORP from keytab krb5.usercomp.keytab: javax.security.auth.login.LoginException: Unable to obtain password from user
  ...

Caused by: javax.security.auth.login.LoginException: Unable to obtain password from user
  at com.sun.security.auth.module.Krb5LoginModule.promptForPass(Krb5LoginModule.java:856)

Is this the way to connect to Kerberized HBase from a Spark app?

答:
you can use loginUserFromKeytabAndReturnUGI, and uig.doAs

or you could put you hbase classpath to SPARK_DIST_CLASSPATH.

Body:
I`m trying to connect a Spark application to HBase with Kerberos enabled. Spark version is 1.5.0, CDH 5.5.2 and it's executed in yarn cluster mode.

When HbaseContext is initialized, it throws this error:

ERROR ipc.AbstractRpcClient: SASL authentication failed. The most likely cause is missing or invalid credentials. Consider 'kinit'.
  javax.security.sasl.SaslException: GSS initiate failed [Caused by GSSException: No valid credentials provided (Mechanism level: Failed to find any Kerberos tgt)]

I have tried to do the authentication in the code, adding:

UserGroupInformation.setConfiguration(config)
UserGroupInformation.loginUserFromKeytab(principalName, keytabFilename)

I distribute the keytab file with --files option in spark-submit.
Now, the error is:

java.io.IOException: Login failure for usercomp@COMPANY.CORP from keytab krb5.usercomp.keytab: javax.security.auth.login.LoginException: Unable to obtain password from user
  ...

Caused by: javax.security.auth.login.LoginException: Unable to obtain password from user
  at com.sun.security.auth.module.Krb5LoginModule.promptForPass(Krb5LoginModule.java:856)

Is this the way to connect to Kerberized HBase from a Spark app?


问:
how prevent the parent click event on change a checkbox
I have a checkbox inside a parent container which has a click event, whenever I try to click the checkbox parent click works first and following by the change event, I am using e.stopPropagation(); on both the parent and child events, but still, it's not working

```<code>// make the .parent react
 function grandParent(){
    alert('Grand Parent: You hit me, my child or my grand child, now deal with me!');
}

// make the .parent react
$('.parent').on('click', function(e){
    e.stopPropagation()
    alert('Parent : Don\'t you dare hitting me or my child, again!');
});

// make the child cry, when we hit him.
$('.child').on('click', function(e){
e.stopPropagation();
 alert('Child : waaaaaa waaaa waa huh huh waaa waaaa!');
});

$('.hello').on('change', function(e){
e.stopPropagation();
 alert('checkbox clicked');
});
</code>```

Fiddle example

答:
This happens because e.stopPropagation(); is on change event and .child has click event. You can do this like in @rikpg example, but if you need change event, you should just add new one click event to checkbox that only has stopPropagation

http://jsfiddle.net/wppv2152/2/

Body:
I have a checkbox inside a parent container which has a click event, whenever I try to click the checkbox parent click works first and following by the change event, I am using e.stopPropagation(); on both the parent and child events, but still, it's not working

// make the .parent react
 function grandParent(){
    alert('Grand Parent: You hit me, my child or my grand child, now deal with me!');
}

// make the .parent react
$('.parent').on('click', function(e){
    e.stopPropagation()
    alert('Parent : Don\'t you dare hitting me or my child, again!');
});

// make the child cry, when we hit him.
$('.child').on('click', function(e){
e.stopPropagation();
 alert('Child : waaaaaa waaaa waa huh huh waaa waaaa!');
});

$('.hello').on('change', function(e){
e.stopPropagation();
 alert('checkbox clicked');
});

Fiddle example


问:
Pattern Matching for CSV processing
I have a csv file with three columns and I want to get the third column into an Iterator. I want to filter out the headers by using the trytoDouble method in combination of the Pattern Matching.

```<code>def trytoDouble(s: String): Option[Double] = {
  try {
    Some(s.toDouble)
  } catch {
    case e: Exception => None
  }
}

val asdf = Source.fromFile("my.csv").getLines().map(_.split(",").map(_.trim).map(utils.trytoDouble(_))).map{
  _ match {
    case Array(a, b, Some(c: Double)) => c
  }
}
</code>```

results in

An exception or error caused a run to abort: [Lscala.Option;@2b4a2ec7 (of class [Lscala.Option;)
  scala.MatchError: [Lscala.Option;@2b4a2ec7 (of class [Lscala.Option;)

what did I do wrong?

答:
Try This:
    val asdf = Array("1,2,3","1,b,c").map(_.split(",").map(_.trim).map(trytoDouble(_))).map{
      _(2) match {
        case x:Option[Double] => x
      }
    }

Title: Pattern Matching for CSV processing

Body:
I have a csv file with three columns and I want to get the third column into an Iterator. I want to filter out the headers by using the trytoDouble method in combination of the Pattern Matching.

def trytoDouble(s: String): Option[Double] = {
  try {
    Some(s.toDouble)
  } catch {
    case e: Exception => None
  }
}

val asdf = Source.fromFile("my.csv").getLines().map(_.split(",").map(_.trim).map(utils.trytoDouble(_))).map{
  _ match {
    case Array(a, b, Some(c: Double)) => c
  }
}

results in

An exception or error caused a run to abort: [Lscala.Option;@2b4a2ec7 (of class [Lscala.Option;)
  scala.MatchError: [Lscala.Option;@2b4a2ec7 (of class [Lscala.Option;)

what did I do wrong?


问:
How can I prevent text/element selection with cursor drag
I made a paging control and I noticed that while clicking on the buttons it is very easy to accidentally select the individual images and text. Is it possible to prevent this?

To clarify selecting I mean highlighting with the mouse. (Try dragging your mouse from one side of the screen to the other.)

If you try to highlight the text/controls in this grid it can't be selected. How is that done?
Link

答:
If you need to block text selection for a certain element using JavaScript, then the simplest method for me was to assign userSelect style like this:</p>

```<code>var myElement = document.createElement('div');
myElement.style.userSelect = 'none';
</code>```

Body:
If you need to block text selection for a certain element using JavaScript, then the simplest method for me was to assign userSelect style like this:

var myElement = document.createElement('div');
myElement.style.userSelect = 'none';


问:
CSS :FirstChild in same section with 2 class not working
Color is not applied as per CSS on the 3rd row, using first child(div.multiple-alerts .normal:first-child span).

https://jsfiddle.net/Lh6cpzeb/

div.multiple-alerts .high:first-child span{ color: yellow; }

div.multiple-alerts .normal:first-child span{ color: yellow; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="multiple-alerts">
  <div class="cls high"><span>high</span></div>
  <div class="cls high"><span>high</span></div>
  <div class="cls normal"><span>normal</span></div>
  <div class="cls normal"><span>normal</span></div>
</div></code>```

答:
:nth-child(i) selector will solve the problem

```<code>div.multiple-alerts .cls:nth-child(3) span{ color: yellow; }
</code>```

Body:
Color is not applied as per CSS on the 3rd row, using first child(div.multiple-alerts .normal:first-child span).

https://jsfiddle.net/Lh6cpzeb/

div.multiple-alerts .high:first-child span{ color: yellow; }

div.multiple-alerts .normal:first-child span{ color: yellow; }

high

high

normal

normal

Body:
:nth-child(i) selector will solve the problem

div.multiple-alerts .cls:nth-child(3) span{ color: yellow; }


问:
OpenCart 1.5.x.x ajax random value
I have dynamic block with show and hide products from table on random sort. But when the cash page is active, this part of page stom showing products and show only first product from query ... i do not understand how can i make it work with this effect and show 10 product on random soring ...
the query

```<code>$sql = "SELECT * FROM " . DB_PREFIX . "product";
$sql .= " WHERE sp_id = ".$id." AND show=1";
$sql .= " ORDER BY shop_id  asc";
$query = $this->db->query($sql);
</code>```

return $query->row;

and part with ajax :

```<code> <div id="content" class="group">
   <div id="backItem">
     <div id="footerItemContent">
     </div>
     <div id="footerItemDivider">-</div>
       <div id="footerItemCustomer">...</div>
       </div>
     </div>
   </div>
</div>
</code>```

and my function

```<code>    $(document).ready(function() {
var products = function() {

    for ( var i = 0; i < complex.length; i++ ) {
        var name = complex[i]['pr_name'];
        var desc = complex[i]['pr_text'];
    }

var i = 0;
var fnchange = function() {
    $('#footerItemContent').animate({'opacity': 0}, 2000, function () {
        $(this).text(desc);
    }).animate({'opacity': 1}, 2500);
    $('#footerItemCustomer').animate({'opacity': 0}, 2000, function () {
        $(this).text(name);
    }).animate({'opacity': 1}, 2500);
    if( ++i < json.length ){
        setTimeout(fnchange, 10000);
    } else {
        i = 0;
        setTimeout(fnchange, 10000);
    }
};
setTimeout(fnchange, 1);
};
setTimeout(feedbacks,1);
</code>```

答:
the name and desc should be an array

```<code>var names = new Array();
var desc = new Array();
for ( var i = 0; i < complex.length; i++ ) {
    names[i] = complex[i]['pr_name'];
    desc[i] = complex[i]['pr_text'];
}
</code>```

and this

```<code>$(this).text(name[i]);
$(this).text(desc[i]);
</code>```

I assume your json.length is the complex.length as the same thing

Title: OpenCart 1.5.x.x ajax random value

Body:
I have dynamic block with show and hide products from table on random sort. But when the cash page is active, this part of page stom showing products and show only first product from query ... i do not understand how can i make it work with this effect and show 10 product on random soring ...
the query

$sql = "SELECT * FROM " . DB_PREFIX . "product";
$sql .= " WHERE sp_id = ".$id." AND show=1";
$sql .= " ORDER BY shop_id  asc";
$query = $this->db->query($sql);

return $query->row;

and part with ajax :

-

...

and my function

    $(document).ready(function() {
var products = function() {

    for ( var i = 0; i < complex.length; i++ ) {
        var name = complex[i]['pr_name'];
        var desc = complex[i]['pr_text'];
    }

var i = 0;
var fnchange = function() {
    $('#footerItemContent').animate({'opacity': 0}, 2000, function () {
        $(this).text(desc);
    }).animate({'opacity': 1}, 2500);
    $('#footerItemCustomer').animate({'opacity': 0}, 2000, function () {
        $(this).text(name);
    }).animate({'opacity': 1}, 2500);
    if( ++i < json.length ){
        setTimeout(fnchange, 10000);
    } else {
        i = 0;
        setTimeout(fnchange, 10000);
    }
};
setTimeout(fnchange, 1);
};
setTimeout(feedbacks,1);

Body:
the name and desc should be an array

var names = new Array();
var desc = new Array();
for ( var i = 0; i < complex.length; i++ ) {
    names[i] = complex[i]['pr_name'];
    desc[i] = complex[i]['pr_text'];
}

and this

$(this).text(name[i]);
$(this).text(desc[i]);

I assume your json.length is the complex.length as the same thing


问:
How to compare stored date and time with SimpleDateFormat and display notification?
In my application I want to display the notification based on the time that user have already set and I am storing the Date and Time into local database.

I am getting the Date and Time from Local database and comparing with SimpleDateFormat and parsing with  Date like this

```<code>SimpleDateFormat yourDateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm");
Date date = null;
     try {
          String date_time = "17-11-2017 15:10";
          date = yourDateFormat.parse(date_time);

     } catch (ParseException e) {
          Log.e(TAG, "Parsing date time failed", e);
     }
     Calendar calendar = Calendar.getInstance();
     calendar.setTime(date);

     Calendar current = Calendar.getInstance();
     if (calendar.compareTo(current) <= 0) {

        Toast.makeText(getApplicationContext(), "Invalid Date/Time", Toast.LENGTH_LONG).show();
     } else {
          AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
          Intent myIntent = new Intent(RemainderActivity.this, NotificationReceiver.class);
          PendingIntent displayIntent = PendingIntent.getBroadcast(getBaseContext(), 0, myIntent, 0);
          alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), displayIntent);

    }
</code>```

Some devices it is working fine like above 7.0 android version but below 7.0 versions it is showing java.lang.NullPointerException like this

```<code> Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.Date java.text.SimpleDateFormat.parse(java.lang.String)' on a null object reference
</code>```

and the error is showing here date = yourDateFormat.parse(date_time);.

Please help me out.

Thanks in Advance.

答:
To get the date which user has selected u can use this,</p>

```<code>private void getSelectedDate() {
        String myFormat = "dd/MM/yyyy";
        SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
        String new_date = sdf.format(cal.getTime());
        System.out.println("DATE SELECTED IS ::    " + new_date);
        your_textview.setText(new_date);
    }
</code>```

Body:
In my application I want to display the notification based on the time that user have already set and I am storing the Date and Time into local database.

I am getting the Date and Time from Local database and comparing with SimpleDateFormat and parsing with  Date like this

SimpleDateFormat yourDateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm");
Date date = null;
     try {
          String date_time = "17-11-2017 15:10";
          date = yourDateFormat.parse(date_time);

     } catch (ParseException e) {
          Log.e(TAG, "Parsing date time failed", e);
     }
     Calendar calendar = Calendar.getInstance();
     calendar.setTime(date);

     Calendar current = Calendar.getInstance();
     if (calendar.compareTo(current) <= 0) {

        Toast.makeText(getApplicationContext(), "Invalid Date/Time", Toast.LENGTH_LONG).show();
     } else {
          AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
          Intent myIntent = new Intent(RemainderActivity.this, NotificationReceiver.class);
          PendingIntent displayIntent = PendingIntent.getBroadcast(getBaseContext(), 0, myIntent, 0);
          alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), displayIntent);

    }

Some devices it is working fine like above 7.0 android version but below 7.0 versions it is showing java.lang.NullPointerException like this

 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.Date java.text.SimpleDateFormat.parse(java.lang.String)' on a null object reference

and the error is showing here date = yourDateFormat.parse(date_time);.

Please help me out.

Thanks in Advance.

Body:
To get the date which user has selected u can use this,

private void getSelectedDate() {
        String myFormat = "dd/MM/yyyy";
        SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
        String new_date = sdf.format(cal.getTime());
        System.out.println("DATE SELECTED IS ::    " + new_date);
        your_textview.setText(new_date);
    }


问:
Image Name Not Save In Database in CodeIgniter 3
Hi friends in my code image upload in my folder but it's not saved in database am not knowledge about CI so help me for this

view code for upload image,

```<code><form role="form" method="post" enctype="multipart/form-data">

   <fieldset class="form-group">
       <input type="hidden" name="txt_hidden" value="" class="form-control">
   </fieldset>

   <fieldset class="form-group">
        <label class="control-label" for="formGroupExampleInput">Add Main Caregory</label>
        <input type="text" value="<?php echo set_value('p_name'); ?>" placeholder="Main Category" name="p_name" class="form-control">
   </fieldset>

   <fieldset class="form-group">
         <label class="control-label"  for="formGroupExampleInput2">Order</label>
         <input type="text" name="order_id" placeholder="Order Id" value="<?php echo set_value('order_id'); ?>" class="form-control" id="formGroupExampleInput2">
   </fieldset>

   <fieldset class="form-group">
         <label class="control-label"  for="formGroupExampleInput2">Status ( 0 active , 1 inactive)</label>
         <input type="text" name="status" placeholder="Status" value="<?php echo set_value('status'); ?>" class="form-control" id="formGroupExampleInput2">
   </fieldset>

   <fieldset class="form-group">
          <label class="control-label"  for="formGroupExampleInput2">Image</label>
          <input type="file" name="image" placeholder="Category Image" value="<?php echo set_value('image'); ?>" class="form-control" id="formGroupExampleInput2">
   </fieldset>

   <div class="form-group">
          <button type="submit" class="btn btn-primary">Add Category</button>
   </div>
</form>
</code>```

in My controller

use this for add category with an image

```<code>function add_main_category()
{

 $this->form_validation->set_rules('p_name', 'Main Category', 'required|is_unique[main_category.p_name]');
 $this->form_validation->set_rules('order_id', 'Order Id');
 $this->form_validation->set_rules('status', 'Status');
 $this->form_validation->set_rules('image', 'Category Image', 'callback_cat_image_upload');

      if ($this->form_validation->run() == FALSE)
      {
           $this->load->view('master/add_main_category');
      }
      else
      {
           $p_name = strtolower($this->input->post('p_name'));
           $order_id = strtolower($this->input->post('order_id'));
           $status = strtolower($this->input->post('status'));
           $image = strtolower($this->input->post('image'));
           $data = array(
                        'p_name' => $p_name,
                        'order_id' => $order_id,
                        'status' => $status,
                        'image' => $image
                  );
           $insert = $this->m->CategoryAdd($data);
           if($insert){
                 $this->session->set_flashdata('success_msg','Category Created Successfully!!');
            }
            else{
                 $this->session->set_flashdata('error_msg', 'Failed to delete Category');
            }
            redirect('admin/main_cat');

       }
}
</code>```

and for image upload use this in controller

```<code>function cat_image_upload(){
  if($_FILES['image']['size'] != 0){
    $upload_dir = './uploads/';
    if (!is_dir($upload_dir)) {
         mkdir($upload_dir);
    }
    $config['upload_path']   = $upload_dir;
    $config['allowed_types'] = 'gif|jpg|png|jpeg';
    $config['file_name']     = 'userimage_'.substr(md5(rand()),0,7);
    $config['overwrite']     = false;
    $config['max_size']  = '5120';

    $this->load->library('upload', $config);
    if (!$this->upload->do_upload('image')){
        $this->form_validation->set_message('cat_image_upload', $this->upload->display_errors());
        return false;
    }
    else{
        $this->upload_data['file'] =  $this->upload->data();
        return true;
    }
}
else{
    $this->form_validation->set_message('cat_image_upload', "No file selected");
    return false;
}
</code>```

}

table main_category in column image

everything is working only no image name save in database!

help me with this.

Thanks in advance!

答:
You can't store the image in the way you used as:

```<code>$image = strtolower($this->input->post('image'));
</code>```

Get the image file name once it is uploaded. Here is your modified code:

```<code> if (!$this->upload->do_upload('image')){
    $this->form_validation->set_message('cat_image_upload', $this->upload->display_errors());
    return false;
}
else{
    $this->upload_data['file'] =  $this->upload->data();
    $data = array('upload_data' => $this->upload->data());
    $doc_file_name = $data['upload_data']['file_name']; // Use this file name to store in database
    return true;
}
</code>```

Body:
Hi friends in my code image upload in my folder but it's not saved in database am not knowledge about CI so help me for this

view code for upload image,

<form role="form" method="post" enctype="multipart/form-data">

   <fieldset class="form-group">
       <input type="hidden" name="txt_hidden" value="" class="form-control">
   </fieldset>

   <fieldset class="form-group">
        Add Main Caregory
        <input type="text" value="<?php echo set_value('p_name'); ?>" placeholder="Main Category" name="p_name" class="form-control">
   </fieldset>

   <fieldset class="form-group">
         Order
         <input type="text" name="order_id" placeholder="Order Id" value="<?php echo set_value('order_id'); ?>" class="form-control" id="formGroupExampleInput2">
   </fieldset>

   <fieldset class="form-group">
         Status ( 0 active , 1 inactive)
         <input type="text" name="status" placeholder="Status" value="<?php echo set_value('status'); ?>" class="form-control" id="formGroupExampleInput2">
   </fieldset>

   <fieldset class="form-group">
          Image
          <input type="file" name="image" placeholder="Category Image" value="<?php echo set_value('image'); ?>" class="form-control" id="formGroupExampleInput2">
   </fieldset>

          <button type="submit" class="btn btn-primary">Add Category</button>

</form>

in My controller

use this for add category with an image

function add_main_category()
{

 $this->form_validation->set_rules('p_name', 'Main Category', 'required|is_unique[main_category.p_name]');
 $this->form_validation->set_rules('order_id', 'Order Id');
 $this->form_validation->set_rules('status', 'Status');
 $this->form_validation->set_rules('image', 'Category Image', 'callback_cat_image_upload');

      if ($this->form_validation->run() == FALSE)
      {
           $this->load->view('master/add_main_category');
      }
      else
      {
           $p_name = strtolower($this->input->post('p_name'));
           $order_id = strtolower($this->input->post('order_id'));
           $status = strtolower($this->input->post('status'));
           $image = strtolower($this->input->post('image'));
           $data = array(
                        'p_name' => $p_name,
                        'order_id' => $order_id,
                        'status' => $status,
                        'image' => $image
                  );
           $insert = $this->m->CategoryAdd($data);
           if($insert){
                 $this->session->set_flashdata('success_msg','Category Created Successfully!!');
            }
            else{
                 $this->session->set_flashdata('error_msg', 'Failed to delete Category');
            }
            redirect('admin/main_cat');

       }
}

and for image upload use this in controller

function cat_image_upload(){
  if($_FILES['image']['size'] != 0){
    $upload_dir = './uploads/';
    if (!is_dir($upload_dir)) {
         mkdir($upload_dir);
    }
    $config['upload_path']   = $upload_dir;
    $config['allowed_types'] = 'gif|jpg|png|jpeg';
    $config['file_name']     = 'userimage_'.substr(md5(rand()),0,7);
    $config['overwrite']     = false;
    $config['max_size']  = '5120';

    $this->load->library('upload', $config);
    if (!$this->upload->do_upload('image')){
        $this->form_validation->set_message('cat_image_upload', $this->upload->display_errors());
        return false;
    }
    else{
        $this->upload_data['file'] =  $this->upload->data();
        return true;
    }
}
else{
    $this->form_validation->set_message('cat_image_upload', "No file selected");
    return false;
}

}

table main_category in column image

everything is working only no image name save in database!

help me with this.

Thanks in advance!

Body:
You can't store the image in the way you used as:

$image = strtolower($this->input->post('image'));

Get the image file name once it is uploaded. Here is your modified code:

 if (!$this->upload->do_upload('image')){
    $this->form_validation->set_message('cat_image_upload', $this->upload->display_errors());
    return false;
}
else{
    $this->upload_data['file'] =  $this->upload->data();
    $data = array('upload_data' => $this->upload->data());
    $doc_file_name = $data['upload_data']['file_name']; // Use this file name to store in database
    return true;
}


问:
can not find element to click on it for below angular code in protracror
Can anyone suggest me how to get an element and how to click on it by using below code

    <button #btn type="button" class="refereFrnd"  (click)="refereFrndMenu.toggle($event)"></button>

```

<p>I have tried with below code but getting error</p>

<pre class="lang-js prettyprint-override"><code>let footer = element(by.css('div[class="ui-g"]'));
footer.element(by.tagName('i')).click();
</code>```

Error: Failed: unknown error: Element  is not clickable at point (1079, 52). Other element would receive the click:
...

      (Session info: chrome=62.0.3202.94)

      (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.15063 x86_64)

答:
You get an error Other element would receive the click:
...

It means that element that you want to select is hidden behind the .modal-content. Probably some modal window appears on the page, so your element is not visible.

Moreover you need to remember that, by default Protractor (as Selenium) try to click at the centre of the selected element. So even if the part of element is visible on page, there might be a case that the centre of this button is overlaid.

Body:
Can anyone suggest me how to get an element and how to click on it by using below code

    <button #btn type="button" class="refereFrnd"  (click)="refereFrndMenu.toggle($event)"></button>

I have tried with below code but getting error

let footer = element(by.css('div[class="ui-g"]'));
footer.element(by.tagName('i')).click();

Error: Failed: unknown error: Element  is not clickable at point (1079, 52). Other element would receive the click:
...

      (Session info: chrome=62.0.3202.94)

      (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.15063 x86_64)

Body:
You get an error Other element would receive the click: <div _ngcontent-c5="" class="modal-content">...</div>

It means that element that you want to select is hidden behind the .modal-content. Probably some modal window appears on the page, so your element is not visible.

Moreover you need to remember that, by default Protractor (as Selenium) try to click at the centre of the selected element. So even if the part of element is visible on page, there might be a case that the centre of this button is overlaid.


问:
AWS auto-scaling group AMI
I have four EC2(API server) instances running on AWS with ELB and I would like to apply auto-scaling group. From my understanding, I first should create an AMI of one of four EC2 instances that I am running and it auto scales from the AMI that I have created based on configuration. At this point, should I re-create the AMI whenever pushing new codes so that it scales up from a latest version of it?</p>

答:
You have the basics down.

When you use Auto Scaling Groups (ASG), your EC2 instances should be stateless. This means that you do not keep data on the instances, but store your data someplace else such as RDS or S3. When ASG launches a new instance, your EC2 instance should have a script (such as in EC2 Userdata) to download or copy any required data for a new instance.

When you already have a good EC2 instance configuration and setup, create an AMI from one of the EC2 instances as your new AMI for the ASG.

When you modify your instance with permanent information (e.g. new Windows or Linux patches, software or application updates, etc.) then you create a new AMI to replace the previous AMI.

Auto Scaling Groups

Title: AWS auto-scaling group AMI


问:
Get remote client ip address NodeJS, ExpressJs
I am trying to get client's ip address with Express js, code is as follows:

```<code>var ip;
if (req.headers['x-forwarded-for']) {
    ip = req.headers['x-forwarded-for'].split(",")[0];
} else if (req.connection && req.connection.remoteAddress) {
    ip = req.connection.remoteAddress;
} else {
    ip = req.ip;
}
ip = (ip.length < 15 ? ip : (ip.substr(0, 7) === '::ffff:' ? ip.substr(7) : undefined));

console.log('ip address',ip);
</code>```

But every time I am getting localhost ip address not Public ip address,
so how can I get public ip address instead of localhost ip address?
can anyone help me please ?

Thanks in advance.

答:
Check the last IP of the x-forwarded-for header.

For example, on aws :

the last IP address in the list is the IP address of the client
  http://docs.aws.amazon.com/elasticloadbalancing/latest/classic/x-forwarded-headers.html#x-forwarded-for

Body:
I am trying to get client's ip address with Express js, code is as follows:

var ip;
if (req.headers['x-forwarded-for']) {
    ip = req.headers['x-forwarded-for'].split(",")[0];
} else if (req.connection && req.connection.remoteAddress) {
    ip = req.connection.remoteAddress;
} else {
    ip = req.ip;
}
ip = (ip.length < 15 ? ip : (ip.substr(0, 7) === '::ffff:' ? ip.substr(7) : undefined));

console.log('ip address',ip);

But every time I am getting localhost ip address not Public ip address,
so how can I get public ip address instead of localhost ip address?
can anyone help me please ?

Thanks in advance.


问:
What are global states? How do they affect testability and how to avoid them?
List down the various global states like global variable, singleton object etc.,

I read that they affect the testability of code. Can you explain alternatives to global states that help in improving the testability of the code?

答:
There are no various global states. Either something is global state or it isn't. The Singleton anti-pattern just removes various initialization headaches, but it's just the same as a global variable.

How to avoid global state? Make some local state and pass a reference or pointer to it around. In the vast, vast majority of occurrences, global state is needless. There are some instances of necessary global state, like the heap, but they're very rare and if you need to ask, then you almost certainly don't know enough to know when it's correct.


问:
what happened when using the same variable in two layer loops in python?
I test the following code:

```<code>for i in range(3):
    for i in range(3,5):
        print "inner i: %d"%(i)
    print "outer i: %d"%(i)
</code>```

and the output is:

```<code>inner i: 3
inner i: 4
outer i: 4
inner i: 3
inner i: 4
outer i: 4
inner i: 3
inner i: 4
outer i: 4
</code>```

I don't understand why in the outer loop the i is 4 but the outer loop still runs for 3 times. It seems that the  the variable i in the print "outer i: %d"%(i) line is the i in the inner loop , but when goes to the for i in range(3) it uses the i in the outer loop.

Anyone can explain this? It's a little confusing to me now.

答:
Notice how the output is always

```<code>inner i: 3
inner i: 4
outer i: 4
</code>```

for every outer loop.

The program takes the final value of i in each iteration.

ie. when the outer loop starts execution, i is either 0, 1 or 2 but the value of i is modified in the inner for loop, which is getting printed.

Update:

```<code>for i in range(3):
    for i in range(3,5):
        print (id(i))
    print (id(i))
</code>```

Output

```<code>1372154016
1372154032
1372154032
1372154016
1372154032
1372154032
1372154016
1372154032
1372154032
</code>```

Body:
I test the following code:

for i in range(3):
    for i in range(3,5):
        print "inner i: %d"%(i)
    print "outer i: %d"%(i)

and the output is:

inner i: 3
inner i: 4
outer i: 4
inner i: 3
inner i: 4
outer i: 4
inner i: 3
inner i: 4
outer i: 4

I don't understand why in the outer loop the i is 4 but the outer loop still runs for 3 times. It seems that the  the variable i in the print "outer i: %d"%(i) line is the i in the inner loop , but when goes to the for i in range(3) it uses the i in the outer loop.

Anyone can explain this? It's a little confusing to me now.

Body:
Notice how the output is always

inner i: 3
inner i: 4
outer i: 4

for every outer loop.

The program takes the final value of i in each iteration.

ie. when the outer loop starts execution, i is either 0, 1 or 2 but the value of i is modified in the inner for loop, which is getting printed.

Update:

for i in range(3):
    for i in range(3,5):
        print (id(i))
    print (id(i))

Output

1372154016
1372154032
1372154032
1372154016
1372154032
1372154032
1372154016
1372154032
1372154032


问:
MVC Details page not showing any data
I am pretty new to MVC and I am building a small contacts app. I have created the database and the Index page displays the data for the DB fine. The Issue I have is my details page. It will display the titles but wont show any data.

Here is my Model:

```<code>namespace BCM.Models
{
    using System;
    using System.Collections.Generic;

    public partial class Contact
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string Surname { get; set; }
        public string CompanyName { get; set; }
        public string Address { get; set; }
        public string Address2 { get; set; }
        public string Address3 { get; set; }
        public string City { get; set; }
        public string County { get; set; }
        public string Country { get; set; }
        public string PostCode { get; set; }
        public string Telephone { get; set; }
        public string Telephone1 { get; set; }
        public string Telephone2 { get; set; }
        public string Telephone3 { get; set; }
        public string Telephone4 { get; set; }
        public string Email { get; set; }
        public string Email2 { get; set; }
        public string Website { get; set; }
        public string Notes { get; set; }
    }
}
</code>```

Here is my controller:

```<code>public ActionResult Details()
    {
        return View();
    }
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Details(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Contact contact = db.Contacts.Find(id);
        if (contact == null)
        {
            return HttpNotFound();
        }

        return View(contact);
    }
</code>```

And here is a section of my View:

```<code>@model BCM.Models.Contact

@{
    ViewBag.Title = "Details";
}

<h2>Details</h2>

<div>
    <h4>Contact</h4>
    <hr />
    <dl class="dl-horizontal">
        <dt>
            @Html.DisplayNameFor(model => model.FirstName)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.FirstName)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.Surname)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.Surname)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.CompanyName)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.CompanyName)
        </dd>
</code>```

This is what my details page shows:
enter image description here

Thanks in advance

答: Managed to work out what I was missing. It was to do with my @Html.ActionLink not passing through the Id</p>

Title: MVC Details page not showing any data

Body:
I am pretty new to MVC and I am building a small contacts app. I have created the database and the Index page displays the data for the DB fine. The Issue I have is my details page. It will display the titles but wont show any data.

Here is my Model:

namespace BCM.Models
{
    using System;
    using System.Collections.Generic;

    public partial class Contact
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string Surname { get; set; }
        public string CompanyName { get; set; }
        public string Address { get; set; }
        public string Address2 { get; set; }
        public string Address3 { get; set; }
        public string City { get; set; }
        public string County { get; set; }
        public string Country { get; set; }
        public string PostCode { get; set; }
        public string Telephone { get; set; }
        public string Telephone1 { get; set; }
        public string Telephone2 { get; set; }
        public string Telephone3 { get; set; }
        public string Telephone4 { get; set; }
        public string Email { get; set; }
        public string Email2 { get; set; }
        public string Website { get; set; }
        public string Notes { get; set; }
    }
}

Here is my controller:

public ActionResult Details()
    {
        return View();
    }
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Details(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Contact contact = db.Contacts.Find(id);
        if (contact == null)
        {
            return HttpNotFound();
        }

        return View(contact);
    }

And here is a section of my View:

@model BCM.Models.Contact

@{
    ViewBag.Title = "Details";
}

Details

Contact

            @Html.DisplayNameFor(model => model.FirstName)

            @Html.DisplayFor(model => model.FirstName)

            @Html.DisplayNameFor(model => model.Surname)

            @Html.DisplayFor(model => model.Surname)

            @Html.DisplayNameFor(model => model.CompanyName)

            @Html.DisplayFor(model => model.CompanyName)

This is what my details page shows:
enter image description here

Thanks in advance


问:
Difference between compile time ,load time and execution time?
What is the difference between Compile time, Load time and Execution time?

Can someone explain me these three terms in a very simple language?

It would be easier to understand if you can provide some examples as well.

Context:

Classically, the binding of instructions and data to memory addresses can be done at any step along the way:

Compile time. The compiler translates symbolic addresses to absolute addresses. If you know at compile time where the process will reside in memory, then absolute code can be generated (Static).

Load time. The compiler translates symbolic addresses to relative (relocatable) addresses. The loader translates these to absolute addresses. If it is not known at compile time where the process will reside in memory, then the compiler must generate relocatable code (Static).

Execution time. If the process can be moved during its execution from one memory segment to another, then binding must be delayed until run time. The absolute addresses are generated by hardware. Most general-purpose OSs use this method (Dynamic).

答:
The source code must be compiled into machine code in order to become and executable program. This compilation process is referred to as compile time. A compiled program can be opened and run by a user. When an application is running, it is called runtime.

Binding means association of program instruction  data to the physical memory location.

Compile time binding means association of instruction data to physical memory and it is done by compiler.

Similarly load time binding is done by loader and run time binding is done by CPU.

ContentLicense: CC BY-SA 4.0


问:
how to store images and display the images when the name of the image is entered in electron app?
I'm trying to make a desktop application wherein I have few images stored inside app, whenever I type some text, the text should be scanned and the corresponding image should be displayed in realtime in electron

Please help me out.

答:
From what I understand this can be done in 3 ways depending on what your trying to do.

If you're trying to do some sort of image search depending on the name of the file this can be quite simple.

Example:
Directory images/ contains an image called rose.png and the user types rose. All you would need to do is get a list of files in the directory using fs and loop through all the files and check if the file name contains the word rose.

If your looking for a solution in which the user describes the image for example you have a directory full of car images and the user types 4 door blue car I say you have 2 options.

1: Give tags/meta data to the images and scan the users input for matching tags e.g. if one of the images has the tags 4 door and blue then the user input of 4 door blue car would match this image. One disadvantage of this method is the user needs to be very specific to the tags which images are given.

2: Use some machine learning and NLP (natural language processing) algorithms. NLP for picking out critical data from the users input and a machine larning algorithm to scan the images for that data. You could use a library like TensorFlow for this. There is an unofficial node version of the library but from my knowledge there is no documentation for it, you will need to use the generic python docs.


问:
What is the difference between func() => {} and func = () => {} in class?
I'm learning to use Class syntax now to create React components now and notice I now have to declare methods like this:

```<code>class Foo extends React.Component {
    ...
    bar = () => {
        this.setState({ ... })
    }
}
</code>```

instead of like this:

```<code>class Foo extends React.Component {
    ...
    bar() {
        this.setState({ ... })  // won't work
    }
}
</code>```

or I can't use this.setState().

Can anybody explain what's the difference between creating methods like this and how they are related to the function prototype?

答:
The first is relying on class fields, which aren't yet part of the language although they're a Stage 3 proposal and likely to be adopted soon. That code is setting a property on the instance (as though it were in the constructor) which is an arrow function (and thus closes over this). It's equivalent to this:

```<code>class Foo extends React.component {
    constructor() {
        this.bar = () => {
            this.setState({ ... })
        };
    }
}
</code>```

The second is method syntax, which creates a property on the prototype object that gets used as the prototype of new instances, and which is a "normal" function in terms of this (e.g., what this is inside it depends on how it's called).

The difference between them in terms of this handling is significant: It means that if you use bar as a prop, with the first example you don't have to worry about this management (but you're creating a new function for every instance); with the method syntax, you do have to worry about this management (which also can end up creating a new function, depending on how you handle it).

Body:
I'm learning to use Class syntax now to create React components now and notice I now have to declare methods like this:

class Foo extends React.Component {
    ...
    bar = () => {
        this.setState({ ... })
    }
}

instead of like this:

class Foo extends React.Component {
    ...
    bar() {
        this.setState({ ... })  // won't work
    }
}

or I can't use this.setState().

Can anybody explain what's the difference between creating methods like this and how they are related to the function prototype?

Body:
The first is relying on class fields, which aren't yet part of the language although they're a Stage 3 proposal and likely to be adopted soon. That code is setting a property on the instance (as though it were in the constructor) which is an arrow function (and thus closes over this). It's equivalent to this:

class Foo extends React.component {
    constructor() {
        this.bar = () => {
            this.setState({ ... })
        };
    }
}

The second is method syntax, which creates a property on the prototype object that gets used as the prototype of new instances, and which is a "normal" function in terms of this (e.g., what this is inside it depends on how it's called).

The difference between them in terms of this handling is significant: It means that if you use bar as a prop, with the first example you don't have to worry about this management (but you're creating a new function for every instance); with the method syntax, you do have to worry about this management (which also can end up creating a new function, depending on how you handle it).


问:
Did NSDate change it's description output?
When I log an NSDate to the console like this:

```<code>NSDate *date = [NSDate date];
NSLog(@"date: %@", date);
</code>```

it logs the output:

date: Fri Nov 17 09:35:27 2017

I was expecting the output to be more like this:

date: 2017-11-17 09:35:27 +0000

For a long time [NSDate description] returned the date as a string in the GMT time zone no matter what the time zone of the machine was set to. Now the output changes when you change the time zone of the machine (although it doesn't print the time zone that it's using).

Have I gone crazy? Is the output different that it was before? Setting the deployment target to an earlier OS makes no difference to the output. If it's different, when did it change? Is it documented?

Edit: CFDate still gives the old description:

```<code>CFAbsoluteTime      absTime;
CFDateRef           aCFDate;
absTime = CFAbsoluteTimeGetCurrent();
aCFDate = CFDateCreate(kCFAllocatorDefault, absTime);
CFStringRef dateDescription = CFCopyDescription(aCFDate);
NSString *description = (__bridge NSString *)dateDescription;
NSLog(@"%@", description);
</code>```

2017-11-17 10:50:19 +0000

Another Edit (Xcode Version 9.2):

Objective-C has different output depending on how the date is logged:

```<code>NSDate *date = [NSDate date];
NSLog(@"date: %@", date);
NSLog(@"date: %@", date.description);
NSLog(@"date: %@", date.debugDescription);
</code>```

date: Tue Jan 23 10:19:29 2018

  date: 2018-01-23 10:19:29 +0000

  date: 2018-01-23 10:19:29 +0000

I had thought that logging an object directly was the same as logging its description.

Swift has the old behaviour:

```<code>let now = Date()
print("\(now)")
print("\(now.description)")
print("\(now.debugDescription)")
</code>```

2018-01-23 10:19:00 +0000

  2018-01-23 10:19:00 +0000

  2018-01-23 10:19:00 +0000

答:
Set Date formatter like below

NSTimeZone *timeZone = [NSTimeZone defaultTimeZone];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:timeZone];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];```

Body:
When I log an NSDate to the console like this:

NSDate *date = [NSDate date];
NSLog(@"date: %@", date);

it logs the output:

date: Fri Nov 17 09:35:27 2017

I was expecting the output to be more like this:

date: 2017-11-17 09:35:27 +0000

For a long time [NSDate description] returned the date as a string in the GMT time zone no matter what the time zone of the machine was set to. Now the output changes when you change the time zone of the machine (although it doesn't print the time zone that it's using).

Have I gone crazy? Is the output different that it was before? Setting the deployment target to an earlier OS makes no difference to the output. If it's different, when did it change? Is it documented?

Edit: CFDate still gives the old description:

CFAbsoluteTime      absTime;
CFDateRef           aCFDate;
absTime = CFAbsoluteTimeGetCurrent();
aCFDate = CFDateCreate(kCFAllocatorDefault, absTime);
CFStringRef dateDescription = CFCopyDescription(aCFDate);
NSString *description = (__bridge NSString *)dateDescription;
NSLog(@"%@", description);

2017-11-17 10:50:19 +0000

Another Edit (Xcode Version 9.2):

Objective-C has different output depending on how the date is logged:

NSDate *date = [NSDate date];
NSLog(@"date: %@", date);
NSLog(@"date: %@", date.description);
NSLog(@"date: %@", date.debugDescription);

date: Tue Jan 23 10:19:29 2018

  date: 2018-01-23 10:19:29 +0000

  date: 2018-01-23 10:19:29 +0000

I had thought that logging an object directly was the same as logging its description.

Swift has the old behaviour:

let now = Date()
print("\(now)")
print("\(now.description)")
print("\(now.debugDescription)")

2018-01-23 10:19:00 +0000

  2018-01-23 10:19:00 +0000

  2018-01-23 10:19:00 +0000


问:
When using the new JSONDecoder protocol in Swift 4 i'm getting the 'the data couldn’t be read because it isn’t in the correct format.' error
Kinda New to swift and haven't seen a solution for this error using swift 4.

When using the JSONDecoder function I've been getting an error saying that 'the data couldn’t be read because it isn’t in the correct format.' I've run my JSON through a validator and it's saying everything is ok there so I'm just not understanding why this error is happening

my code for decoding is as follows:

```<code>import UIKit

class inputscreen: UIViewController {
// the JSONData.php is where the data is being converted into JSON using PhP
    final let url = URL(string: "JSONData.php")

    override func viewDidLoad() {
        super.viewDidLoad()
        downloadJson()

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
func downloadJson() {
    guard let downloadURL = url else {return }
    URLSession.shared.dataTask(with: downloadURL) {data, urlResponse, error in

            guard let data = data, error == nil, urlResponse != nil else {
               print("something went wrong")
               return

            }
           // print(data)
            print("downloaded")
            do {
                // this is where the error is happening, everything else is getting through my checks.
                let decoder = JSONDecoder()
                let variables = try decoder.decode(Variables.self, from:data)
                print(variables.variables[0].TblStaffID)
                print("success")

            } catch {
               print(error.localizedDescription)

          }
        }.resume()
    }
}
</code>```

in the JSON I've converted it to UTF8 so I don't think that's where the error is coming from

I have the struct for this in a different file which looks like this:

```<code>    import Foundation
    import UIKit

class Variables: Codable{

let variables: [Variable]
init(variables: [Variable]){
    self.variables = variables
}

}

struct Variable: Codable {
    let TblStaffID: Int
    let User_code: String
    let Title: String
    let PreName: String
    let Surname: String
  init(TblStaffID: Int, User_code: String, Title: String, PreName: String, Surname: String){

        self.TblStaffID = TblStaffID
        self.User_code = User_code
        self.Title =  Title
        self.PreName = PreName
        self.Surname = Surname
    }
}
</code>```

any and all help on this matter would be appreciated!

答: Make sure that you convert the date format into TimeIntervals or String</p>

Body:
Kinda New to swift and haven't seen a solution for this error using swift 4.

When using the JSONDecoder function I've been getting an error saying that 'the data couldn’t be read because it isn’t in the correct format.' I've run my JSON through a validator and it's saying everything is ok there so I'm just not understanding why this error is happening

my code for decoding is as follows:

import UIKit

class inputscreen: UIViewController {
// the JSONData.php is where the data is being converted into JSON using PhP
    final let url = URL(string: "JSONData.php")

    override func viewDidLoad() {
        super.viewDidLoad()
        downloadJson()

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
func downloadJson() {
    guard let downloadURL = url else {return }
    URLSession.shared.dataTask(with: downloadURL) {data, urlResponse, error in

            guard let data = data, error == nil, urlResponse != nil else {
               print("something went wrong")
               return

            }
           // print(data)
            print("downloaded")
            do {
                // this is where the error is happening, everything else is getting through my checks.
                let decoder = JSONDecoder()
                let variables = try decoder.decode(Variables.self, from:data)
                print(variables.variables[0].TblStaffID)
                print("success")

            } catch {
               print(error.localizedDescription)

          }
        }.resume()
    }
}

in the JSON I've converted it to UTF8 so I don't think that's where the error is coming from

I have the struct for this in a different file which looks like this:

    import Foundation
    import UIKit

class Variables: Codable{

let variables: [Variable]
init(variables: [Variable]){
    self.variables = variables
}

}

struct Variable: Codable {
    let TblStaffID: Int
    let User_code: String
    let Title: String
    let PreName: String
    let Surname: String
  init(TblStaffID: Int, User_code: String, Title: String, PreName: String, Surname: String){

        self.TblStaffID = TblStaffID
        self.User_code = User_code
        self.Title =  Title
        self.PreName = PreName
        self.Surname = Surname
    }
}

any and all help on this matter would be appreciated!


问:
Vaadin 8 convert String to Float
i have 3 TextFiled, one which save String to database, and 2 which should save FLoat to database.
When i run my application, i have this error:

```<code>Property type 'java.lang.Float' doesn't match the field type 'java.lang.String'. Binding should be configured manually using converter.
</code>```

This is my code:

```<code>@SpringComponent
@UIScope
public class FuelEditor extends VerticalLayout{
private final FuelReposiotry fuelRepository;

private Fuel fuel;
/* Fields to edit properties in Customer entity */
TextField date = new TextField("Data");
TextField price = new TextField("Cena");
TextField amount = new TextField("Kwota tankowania");

/* Action buttons */
Button save = new Button("Save", FontAwesome.SAVE);
Button cancel = new Button("Cancel");
Button delete = new Button("Delete", FontAwesome.TRASH_O);
CssLayout actions = new CssLayout(save, cancel, delete);

Binder<Fuel> binder = new Binder<>(Fuel.class);

@Autowired
public FuelEditor(FuelReposiotry fuelReposiotry) {
    this.fuelRepository = fuelReposiotry;

    addComponents(date, price, amount, actions);
    // bind using naming convention
    binder.bindInstanceFields(this);

    // Configure and style components
    setSpacing(true);
    actions.setStyleName(ValoTheme.LAYOUT_COMPONENT_GROUP);
    save.setStyleName(ValoTheme.BUTTON_PRIMARY);
    save.setClickShortcut(ShortcutAction.KeyCode.ENTER);

    // wire action buttons to save, delete and reset
    save.addClickListener(e -> fuelReposiotry.save(fuel));
    delete.addClickListener(e -> fuelReposiotry.delete(fuel));
    cancel.addClickListener(e -> editFuel(fuel));
    setVisible(false);
}
</code>```

How can I convert String to Float? I trying with import com.vaadin.data.util.converter.StringToIntegerConverter;, but in vaadin 8 I cant to use converter.

答:
You should be able to use a StringToFloatConverter, but you have to bind those fields manually:

```<code>@SpringComponent
@UIScope
public class FuelEditor extends VerticalLayout{

TextField date = new TextField("Data");
TextField price = new TextField("Cena");
TextField amount = new TextField("Kwota tankowania");

Binder<Fuel> binder = new Binder<>(Fuel.class);

@Autowired
public FuelEditor(FuelReposiotry fuelReposiotry) {

    // Bind float fields manually
    binder.forField(price)
            .withConverter(new StringToFloatConverter("Value must be a float"))
            .bind(Fuel::getPrice, Fuel::setPrice);
    binder.forField(amount)
            .withConverter(new StringToFloatConverter("Value must be a float"))
            .bind(Fuel::getAmount, Fuel::setAmount);
    // bind the last using naming convention
    binder.bindInstanceFields(this);
}
</code>```

Title: Vaadin 8 convert String to Float

Body:
i have 3 TextFiled, one which save String to database, and 2 which should save FLoat to database.
When i run my application, i have this error:

Property type 'java.lang.Float' doesn't match the field type 'java.lang.String'. Binding should be configured manually using converter.

This is my code:

@SpringComponent
@UIScope
public class FuelEditor extends VerticalLayout{
private final FuelReposiotry fuelRepository;

private Fuel fuel;
/* Fields to edit properties in Customer entity */
TextField date = new TextField("Data");
TextField price = new TextField("Cena");
TextField amount = new TextField("Kwota tankowania");

/* Action buttons */
Button save = new Button("Save", FontAwesome.SAVE);
Button cancel = new Button("Cancel");
Button delete = new Button("Delete", FontAwesome.TRASH_O);
CssLayout actions = new CssLayout(save, cancel, delete);

Binder<Fuel> binder = new Binder<>(Fuel.class);

@Autowired
public FuelEditor(FuelReposiotry fuelReposiotry) {
    this.fuelRepository = fuelReposiotry;

    addComponents(date, price, amount, actions);
    // bind using naming convention
    binder.bindInstanceFields(this);

    // Configure and style components
    setSpacing(true);
    actions.setStyleName(ValoTheme.LAYOUT_COMPONENT_GROUP);
    save.setStyleName(ValoTheme.BUTTON_PRIMARY);
    save.setClickShortcut(ShortcutAction.KeyCode.ENTER);

    // wire action buttons to save, delete and reset
    save.addClickListener(e -> fuelReposiotry.save(fuel));
    delete.addClickListener(e -> fuelReposiotry.delete(fuel));
    cancel.addClickListener(e -> editFuel(fuel));
    setVisible(false);
}

How can I convert String to Float? I trying with import com.vaadin.data.util.converter.StringToIntegerConverter;, but in vaadin 8 I cant to use converter.

Body:
You should be able to use a StringToFloatConverter, but you have to bind those fields manually:

@SpringComponent
@UIScope
public class FuelEditor extends VerticalLayout{

TextField date = new TextField("Data");
TextField price = new TextField("Cena");
TextField amount = new TextField("Kwota tankowania");

Binder<Fuel> binder = new Binder<>(Fuel.class);

@Autowired
public FuelEditor(FuelReposiotry fuelReposiotry) {

    // Bind float fields manually
    binder.forField(price)
            .withConverter(new StringToFloatConverter("Value must be a float"))
            .bind(Fuel::getPrice, Fuel::setPrice);
    binder.forField(amount)
            .withConverter(new StringToFloatConverter("Value must be a float"))
            .bind(Fuel::getAmount, Fuel::setAmount);
    // bind the last using naming convention
    binder.bindInstanceFields(this);
}