问:
Facebook auth AuthenticationManager.GetExternalLoginInfoAsync() suddenly returns NULL
```<code>public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
        {

            var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
            if (loginInfo == null) { return RedirectToAction("Login"); }
            // Sign in the user with this external login provider if the user already has a login
            var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false);
</code>```

So in my ExternalLoginCallback method AuthenticationManager.GetExternalLoginInfoAsync() used to work just fine, then suddenly a few days ago it no longer does anything and returns NULL, causing the entire "Register with Facebook" process to be skipped, redirecting the user to the Login page.

I had a separate ASP.NET MVC5 project that I made just to play around witth the Facebook Graph API and when I went back to it (I left it 2 weeks ago and the register/login with Facebook worked just fine on this project) it had the same problem, it returned null ! redirecting the user to the login page.

Is it possible there is something with my Facebook App ? or their API ? I have failed the app review 3 times (had some problems further down the code), put it back to development mode to try to work it out and now its not even hitting the previous problem, it stops at the AuthenticationManager.GetExternalLoginInfoAsync() and I cannot understand whats going on since I did not have this problem last week.

Here is the ExternalLogin method:

```<code>public ActionResult ExternalLogin(string provider, string returnUrl)
        {

            ControllerContext.HttpContext.Session.RemoveAll();

            return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }));
        }
</code>```

I've added ControllerContext.HttpContext.Session.RemoveAll(); to a suggestion I've found here on stackoverflow but it doesn't seem to do anything.

答:
There was a change on Facebook's side which caused Facebook logins for web and mobile apps using Azure App Service Authentication / Authorization to stop working.

There is now a hotfix which was rolled out to most sites.

https://social.msdn.microsoft.com/Forums/azure/en-US/397f6952-57bf-4c28-b383-6bba08d28f9a/facebook-login-failures-with-app-service-authentication-authorization?forum=windowsazurewebsitespreview

Body:
public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
        {

            var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
            if (loginInfo == null) { return RedirectToAction("Login"); }
            // Sign in the user with this external login provider if the user already has a login
            var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false);

So in my ExternalLoginCallback method AuthenticationManager.GetExternalLoginInfoAsync() used to work just fine, then suddenly a few days ago it no longer does anything and returns NULL, causing the entire "Register with Facebook" process to be skipped, redirecting the user to the Login page.

I had a separate ASP.NET MVC5 project that I made just to play around witth the Facebook Graph API and when I went back to it (I left it 2 weeks ago and the register/login with Facebook worked just fine on this project) it had the same problem, it returned null ! redirecting the user to the login page.

Is it possible there is something with my Facebook App ? or their API ? I have failed the app review 3 times (had some problems further down the code), put it back to development mode to try to work it out and now its not even hitting the previous problem, it stops at the AuthenticationManager.GetExternalLoginInfoAsync() and I cannot understand whats going on since I did not have this problem last week.

Here is the ExternalLogin method:

public ActionResult ExternalLogin(string provider, string returnUrl)
        {

            ControllerContext.HttpContext.Session.RemoveAll();

            return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }));
        }

I've added ControllerContext.HttpContext.Session.RemoveAll(); to a suggestion I've found here on stackoverflow but it doesn't seem to do anything.


来源: stackexchange

问:
Working with JPG into Firemonkey
i have a compressed image i am trying to receive it and show it on android plat-from , in vcl i have been doing something like  following

```<code>procedure TForm1.CreateJpg(Data: string);
var
  JpegStream: TMemoryStream;
  JpegImage: TJPEGImage;
  Bitmap: TBitmap;
  tmpPos, tmpLen: integer;
  pp: string;
begin

  try
    tmpPos := Pos('B]>', Data);
    pp := Copy(Data, 5, tmpPos - 5);
    tmpLen := StrToInt(pp);
    Data := Copy(Data, tmpPos + 3, tmpLen);
    Bitmap := TBitmap.Create;

    try
      JpegImage := TJPEGImage.Create;

      try
        JpegStream := TMemoryStream.Create;

        try
          TIdDecoderMIME.DecodeStream(Data, JpegStream);
          JpegStream.Position := 0;
          JpegImage.LoadFromStream(JpegStream);
        finally
          JpegStream.Free;
        end;

        with Bitmap do
        begin
          Canvas.Lock;

          try
            Width := JpegImage.Width;
            Height := JpegImage.Height;
            Canvas.StretchDraw(rect(0, 0, 200, 160), JpegImage);
          finally
            Canvas.Unlock;
          end;
        end;
      finally
        JpegImage.Free;
      end;

      img.Assign(Bitmap);
    finally
      Bitmap.Free;
    end;
  except
    on E: Exception do
      //
  end;
end;
</code>```

but i cannot do the same into android because there is no declaration of TJPEGIMAGE library i am not sure if i can do something as alternative of JPEG on Fire-monkey i am confused about what i have to do

答:
The VCL uses TGraphic-derived classes to handle individual image types.  However, there is no equivalent of TGraphic in FireMonkey.  It has only a single TBitmap class that supports multiple image types.  Different FMX platforms support a different subset of image types (see Supported Image Formats for the complete list).  Fortunately, JPG is one of only two image types that are supported on all FMX platforms (PNG is the other).

The FMX equivalent of your VCL code would look something like this:

```<code>procedure TForm1.CreateJpg(Data: string);
var
  JpegStream: TMemoryStream;
  Jpeg, Bitmap: TBitmap;
  tmpPos, tmpLen: integer;
  pp: string;
begin
  try
    tmpPos := Pos('B]>', Data);
    pp := Copy(Data, 5, tmpPos - 5);
    tmpLen := StrToInt(pp);
    Data := Copy(Data, tmpPos + 3, tmpLen);

    Bitmap := TBitmap.Create;
    try
      Jpeg := TBitmap.Create;
      try
        JpegStream := TMemoryStream.Create;
        try
          TIdDecoderMIME.DecodeStream(Data, JpegStream);
          JpegStream.Position := 0;
          Jpeg.LoadFromStream(JpegStream);
        finally
          JpegStream.Free;
        end;

        with Bitmap do
        begin
          SetSize(Jpeg.Width, Jpeg.Height);

          if Canvas.BeginScene then
          try
            Canvas.DrawBitmap(Jpeg,
                {$IF RTLVersion >= 31} // 10.1 Berlin or higher
                Jpeg.BoundsF,
                {$ELSE}
                TRectF.Create(0, 0, Jpeg.Width, Jpeg.Height),
                {$IFEND}
                TRectF.Create(0, 0, 200, 160), 1.0);
          finally
            Canvas.EndScene;
          end;
        end;
      finally
        Jpeg.Free;
      end;

      img.Bitmap.Assign(Bitmap);
    finally
      Bitmap.Free;
    end;
  except
    on E: Exception do
      //
  end;
end;
</code>```

ContentLicense: CC BY-SA 3.0

Title: Working with JPG into Firemonkey

Body:
i have a compressed image i am trying to receive it and show it on android plat-from , in vcl i have been doing something like  following

procedure TForm1.CreateJpg(Data: string);
var
  JpegStream: TMemoryStream;
  JpegImage: TJPEGImage;
  Bitmap: TBitmap;
  tmpPos, tmpLen: integer;
  pp: string;
begin

  try
    tmpPos := Pos('B]>', Data);
    pp := Copy(Data, 5, tmpPos - 5);
    tmpLen := StrToInt(pp);
    Data := Copy(Data, tmpPos + 3, tmpLen);
    Bitmap := TBitmap.Create;

    try
      JpegImage := TJPEGImage.Create;

      try
        JpegStream := TMemoryStream.Create;

        try
          TIdDecoderMIME.DecodeStream(Data, JpegStream);
          JpegStream.Position := 0;
          JpegImage.LoadFromStream(JpegStream);
        finally
          JpegStream.Free;
        end;

        with Bitmap do
        begin
          Canvas.Lock;

          try
            Width := JpegImage.Width;
            Height := JpegImage.Height;
            Canvas.StretchDraw(rect(0, 0, 200, 160), JpegImage);
          finally
            Canvas.Unlock;
          end;
        end;
      finally
        JpegImage.Free;
      end;

      img.Assign(Bitmap);
    finally
      Bitmap.Free;
    end;
  except
    on E: Exception do
      //
  end;
end;

but i cannot do the same into android because there is no declaration of TJPEGIMAGE library i am not sure if i can do something as alternative of JPEG on Fire-monkey i am confused about what i have to do

Body:
The VCL uses TGraphic-derived classes to handle individual image types.  However, there is no equivalent of TGraphic in FireMonkey.  It has only a single TBitmap class that supports multiple image types.  Different FMX platforms support a different subset of image types (see Supported Image Formats for the complete list).  Fortunately, JPG is one of only two image types that are supported on all FMX platforms (PNG is the other).

The FMX equivalent of your VCL code would look something like this:

procedure TForm1.CreateJpg(Data: string);
var
  JpegStream: TMemoryStream;
  Jpeg, Bitmap: TBitmap;
  tmpPos, tmpLen: integer;
  pp: string;
begin
  try
    tmpPos := Pos('B]>', Data);
    pp := Copy(Data, 5, tmpPos - 5);
    tmpLen := StrToInt(pp);
    Data := Copy(Data, tmpPos + 3, tmpLen);

    Bitmap := TBitmap.Create;
    try
      Jpeg := TBitmap.Create;
      try
        JpegStream := TMemoryStream.Create;
        try
          TIdDecoderMIME.DecodeStream(Data, JpegStream);
          JpegStream.Position := 0;
          Jpeg.LoadFromStream(JpegStream);
        finally
          JpegStream.Free;
        end;

        with Bitmap do
        begin
          SetSize(Jpeg.Width, Jpeg.Height);

          if Canvas.BeginScene then
          try
            Canvas.DrawBitmap(Jpeg,
                {$IF RTLVersion >= 31} // 10.1 Berlin or higher
                Jpeg.BoundsF,
                {$ELSE}
                TRectF.Create(0, 0, Jpeg.Width, Jpeg.Height),
                {$IFEND}
                TRectF.Create(0, 0, 200, 160), 1.0);
          finally
            Canvas.EndScene;
          end;
        end;
      finally
        Jpeg.Free;
      end;

      img.Bitmap.Assign(Bitmap);
    finally
      Bitmap.Free;
    end;
  except
    on E: Exception do
      //
  end;
end;


问:
Dynamic PIVOT two columns prefix
Database: Microsoft SQL Server 2012

I have one table that contains the computers and the software installed.
Now, one computer can have 30+ software installed but there are probably 100+ different software on the infrastructure.

This is a representation of the table

```<code>Computer  | Software
--------------------
PC123     | Office
PC123     | Firefox
PC456     | Office
PC456     | Firefox
PC456     | CAD
PC789     | Firefox
PC789     | Outlook
...
</code>```

I'm looking for a result that would look like this

```<code>Computer  | Software 1 | Software 2 | Software 3
------------------------------------------------
PC123     | Firefox    | Office     | NULL
PC456     | CAD        | Firefox    | Office
PC789     | Firefox    | Outlook    | NULL
...
</code>```

I've been looking into dynamic PIVOT but I'm still new with SQL.

Thank you for the help

答:
There are countless examples of dynamic pivots here, however, I understand sometimes we all need a little jump-start.

Example

```<code>Declare @SQL varchar(max) = Stuff((Select Distinct ',' + QuoteName(concat('Software ',Row_Number() over (Partition By Computer Order By Software))) From Yourtable  Order by 1 For XML Path('')),1,1,'')
Select  @SQL = '
Select [Computer],' + @SQL + '
From (
       Select Computer
             ,Software
             ,Col      = concat(''Software '',Row_Number() over (Partition By Computer Order By Software))
       From YourTable
     ) A
Pivot (max([software]) For [Col] in (' + @SQL + ') ) p'
Exec(@SQL);
</code>```

Returns

```<code>Computer    Software 1  Software 2  Software 3
PC123       Firefox     Office      NULL
PC456       CAD         Firefox     Office
PC789       Firefox     Outlook     NULL
</code>```

If it helps, the generated SQL looks like this:

```<code>Select [Computer],[Software 1],[Software 2],[Software 3]
From (
       Select Computer
             ,Software
             ,Col      = concat('Software ',Row_Number() over (Partition By Computer Order By Software))
       From YourTable
     ) A
Pivot (max([software]) For [Col] in ([Software 1],[Software 2],[Software 3]) ) p
</code>```

Title: Dynamic PIVOT two columns prefix

Body:
Database: Microsoft SQL Server 2012

I have one table that contains the computers and the software installed.
Now, one computer can have 30+ software installed but there are probably 100+ different software on the infrastructure.

This is a representation of the table

Computer  | Software
--------------------
PC123     | Office
PC123     | Firefox
PC456     | Office
PC456     | Firefox
PC456     | CAD
PC789     | Firefox
PC789     | Outlook
...

I'm looking for a result that would look like this

Computer  | Software 1 | Software 2 | Software 3
------------------------------------------------
PC123     | Firefox    | Office     | NULL
PC456     | CAD        | Firefox    | Office
PC789     | Firefox    | Outlook    | NULL
...

I've been looking into dynamic PIVOT but I'm still new with SQL.

Thank you for the help

Body:
There are countless examples of dynamic pivots here, however, I understand sometimes we all need a little jump-start.

Example

Declare @SQL varchar(max) = Stuff((Select Distinct ',' + QuoteName(concat('Software ',Row_Number() over (Partition By Computer Order By Software))) From Yourtable  Order by 1 For XML Path('')),1,1,'')
Select  @SQL = '
Select [Computer],' + @SQL + '
From (
       Select Computer
             ,Software
             ,Col      = concat(''Software '',Row_Number() over (Partition By Computer Order By Software))
       From YourTable
     ) A
Pivot (max([software]) For [Col] in (' + @SQL + ') ) p'
Exec(@SQL);

Returns

Computer    Software 1  Software 2  Software 3
PC123       Firefox     Office      NULL
PC456       CAD         Firefox     Office
PC789       Firefox     Outlook     NULL

If it helps, the generated SQL looks like this:

Select [Computer],[Software 1],[Software 2],[Software 3]
From (
       Select Computer
             ,Software
             ,Col      = concat('Software ',Row_Number() over (Partition By Computer Order By Software))
       From YourTable
     ) A
Pivot (max([software]) For [Col] in ([Software 1],[Software 2],[Software 3]) ) p


问:
Unable to send mails with SMTP in GCE instances
While migrating from AWS EC2 instances to Google Compute Engine instances we got problems with sending emails via SMTP (Sendgrid).

I read a lot about it and read that the ports (587, 462, 25) of SMTP are blocked... And to read this article.
https://cloud.google.com/compute/docs/tutorials/sending-mail/#sending_mail_through_corporate_mail_servers

Questions:

For my understanding we should open a Cloud Launcher of SendGrid?

If (1) = yes, then I see it (the cloud launcher) does not support C# and our code today of sending emails is based on C#. So that we will have to change the code to one of those: Node.js, Python, Ruby, Go & PHP?

Is there any way to unblock this outbound connections on port 587 (or 462, 25)? Without Cloud Launcher.

Thanks in advance

答:
1) Yes, if you want to use it through google. If not I recommend directly going to one of the smtp providers such as sendgrid, spakpost, mandrill... to get and account and use their smtp service to send mail.

2) You can use C# by simply not using the Cloud Launcher and purchasing an account directly from the vendor and usning their SMTP service.

3) No, port 2525 is free to send outbound emails to smtp providers through GCP so I highly recommend using that since it can be used for sendgrid as well.


问:
NFS doesn't sync files if characters are modified in a file
I'm having a strange problem with my vagrant setup: changing characters in a file and saving it doesn't reflect the change in the vm. But if I add/remove some characters or add in a few blank links, everything works fine.

I have already checked if I have opcache enabled on my PHP5.5 and "php -i | grep opcache" get any result ... so I imagine it's no.

Already tested too another vagrant (1.7.2) version, same result.

My configuration is :

Windows 7 Pro

Vagrant 1.6.3 with plugin WinNFSd

VirtualBox 4.3.12

Centos6.5 Box

PHP 5.5.19

Apache 2.4.10

PhpStorm 8 (but problem is same with SublimeText 3 and Notepad++)

Here is a video of a test from me for show you the problem :
https://www.dropbox.com/s/k70fiwfw6mopjs7/2015-03-24%2020-47-07.mp4?dl=0

Two weeks I work on this problem, it will make me crazy ...
I already tried Rsync and Samba or default vagrant synch folder but it doesn't meet my needs.

I really appreciate your help guys!

答:
The problem on sublime was atomic_save setting being true. Not sure if there is an equivalent setting for PHPStorm/Notepad++

https://github.com/mitchellh/vagrant/issues/3888


问:
Change css classes for specified id only
I try to override some basic classes of complex control (dxList) DevExtreme, and it's work fine.

```<code>.dx-loadpanel-content {
    transform: translate(0px, 0px) !important;
    margin: auto !important;
    left: 0px !important;
    top: 0px !important;
    position: absolute !important;
}

.dx-scrollview-loadpanel {
    transform: translate(0px, 0px) !important;
    margin: auto !important;
    left: 50% !important;
    top: 50% !important;
    position: absolute !important;
}
</code>```

but it's not good idea for me, because this classes are already used on different html pages.

I want override this classes only for specified dxList by some id.
Like this:

```<code>#activitiesList .dx-loadpanel-content {
    transform: translate(0px, 0px) !important;
    margin: auto !important;
    left: 0px !important;
    top: 0px !important;
    position: absolute !important;
}

#activitiesList .dx-scrollview-loadpanel {
    transform: translate(0px, 0px) !important;
    margin: auto !important;
    left: 50% !important;
    top: 50% !important;
    position: absolute !important;
}
</code>```

but it takes no effect. whats wrong?

答:
If the ID and class belong to the same element, you need to remove the space between the two in the CSS.

If there is a space, the CSS will find all elements matching the first part of the selector, then look INSIDE those elements for elements matching the second part of the selector.

If there is no space, the CSS will find all elements that have the first part of the selector AND the second part of the selector (eg. matching ID and Class).

Take a look at the code below. Hope this helps.

/* Target all elements with the Class of 'c' that are inside elements with the ID of 'i' */
#i .c {
  background: red;
}

/*Target all elements with the ID of 'i' AND the Class of 'c'*/

#i.c {
  background: yellow;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id='i'>
  <div class='c'>
    ID and Class on different divs. Space in CSS.
  </div>
  <div class='b'>
    This is not targeted because class b was not selected in CSS
  </div>
</div>

<div id='i' class='c'>
  ID and Class on the same div. No space in CSS.
</div></code>```

Body:
I try to override some basic classes of complex control (dxList) DevExtreme, and it's work fine.

.dx-loadpanel-content {
    transform: translate(0px, 0px) !important;
    margin: auto !important;
    left: 0px !important;
    top: 0px !important;
    position: absolute !important;
}

.dx-scrollview-loadpanel {
    transform: translate(0px, 0px) !important;
    margin: auto !important;
    left: 50% !important;
    top: 50% !important;
    position: absolute !important;
}

but it's not good idea for me, because this classes are already used on different html pages.

I want override this classes only for specified dxList by some id.
Like this:

#activitiesList .dx-loadpanel-content {
    transform: translate(0px, 0px) !important;
    margin: auto !important;
    left: 0px !important;
    top: 0px !important;
    position: absolute !important;
}

#activitiesList .dx-scrollview-loadpanel {
    transform: translate(0px, 0px) !important;
    margin: auto !important;
    left: 50% !important;
    top: 50% !important;
    position: absolute !important;
}

but it takes no effect. whats wrong?

Body:
If the ID and class belong to the same element, you need to remove the space between the two in the CSS.

If there is a space, the CSS will find all elements matching the first part of the selector, then look INSIDE those elements for elements matching the second part of the selector.

If there is no space, the CSS will find all elements that have the first part of the selector AND the second part of the selector (eg. matching ID and Class).

Take a look at the code below. Hope this helps.

/* Target all elements with the Class of 'c' that are inside elements with the ID of 'i' */
#i .c {
  background: red;
}

/*Target all elements with the ID of 'i' AND the Class of 'c'*/

#i.c {
  background: yellow;
}

<div id='i'>
  <div class='c'>
    ID and Class on different divs. Space in CSS.
  </div>
  <div class='b'>
    This is not targeted because class b was not selected in CSS
  </div>
</div>

<div id='i' class='c'>
  ID and Class on the same div. No space in CSS.
</div>


问:
Function templates: extern template vs explicit specialisation
Consider the following function template declaration:

```<code>template <typename T, typename = std::enable_if_t<std::is_same_v<T, int>>>
void foo(T i);
</code>```

There is only one possible valid instantiation of this template, namely with T = int. I'd like to put this definition in an implementation file. I can think of two possible ways of doing so. (If you're wondering why on earth I'd do this rather than just saying void foo(int i), it's because the template version prevents implicit conversions at the call site.)

Approach 1:

I can use an extern template declaration to tell other TUs that foo<int>() is instantiated elsewhere:

```<code>// In foo.hpp
template <typename T, typename = std::enable_if_t<std::is_same_v<T, int>>>
void foo(T i);

extern template void foo(int);

// In foo.cpp
template <typename T, typename>
void foo(T i) { ... } // full template definition

template void foo(int); // explicit instantiation with T = int
</code>```

Approach 2:

I can provide an explicit specialisation for the int case:

```<code>// In foo.hpp
template <typename T, typename = std::enable_if_t<std::is_same_v<T, int>>>
void foo(T i);

template <> void foo(int i); // explicit specialisation declaration (*)

// In foo.cpp
template <>
void foo(int i) { ... } // explicit specialisation definition
</code>```

Questions:

Are both of these approaches legal, or am I unintentionally relying on UB?

If both are legal, is there a good reason to prefer one approach over the other, other than the fact that approach 2 is very slightly less typing? Both GCC and Clang work equally well with either approach.

For approach 2, is the explicit specialisation declaration at (*) actually required? Again, both GCC and Clang are perfectly happy if it's omitted, but doing so makes me uncomfortable about the fact that a call to foo(3) in another TU is an implicit instantiation of a template with no definition visible, and no promise that such a definition exists elsewhere.

答:
There is a third approach.  In approach 3 you specify the function you want to have and the you add a template overload and mark that as delete.  That looks like

```<code>void foo(int i)
{
    // stuff
}

template <typename T>
void foo(T t) = delete;
</code>```

Since the template version will match all types exactly it will be preferred in all cases except int since a non template exact match is preferred to a template one.  So you will only be able to call foo with an int and all other types will give you an error that they are trying to call the deleted function void foo(T t).

Live Example

Body:
Consider the following function template declaration:

template <typename T, typename = std::enable_if_t<std::is_same_v<T, int>>>
void foo(T i);

There is only one possible valid instantiation of this template, namely with T = int. I'd like to put this definition in an implementation file. I can think of two possible ways of doing so. (If you're wondering why on earth I'd do this rather than just saying void foo(int i), it's because the template version prevents implicit conversions at the call site.)

Approach 1:

I can use an extern template declaration to tell other TUs that foo<int>() is instantiated elsewhere:

// In foo.hpp
template <typename T, typename = std::enable_if_t<std::is_same_v<T, int>>>
void foo(T i);

extern template void foo(int);

// In foo.cpp
template <typename T, typename>
void foo(T i) { ... } // full template definition

template void foo(int); // explicit instantiation with T = int

Approach 2:

I can provide an explicit specialisation for the int case:

// In foo.hpp
template <typename T, typename = std::enable_if_t<std::is_same_v<T, int>>>
void foo(T i);

template <> void foo(int i); // explicit specialisation declaration (*)

// In foo.cpp
template <>
void foo(int i) { ... } // explicit specialisation definition

Questions:

Are both of these approaches legal, or am I unintentionally relying on UB?

If both are legal, is there a good reason to prefer one approach over the other, other than the fact that approach 2 is very slightly less typing? Both GCC and Clang work equally well with either approach.

For approach 2, is the explicit specialisation declaration at (*) actually required? Again, both GCC and Clang are perfectly happy if it's omitted, but doing so makes me uncomfortable about the fact that a call to foo(3) in another TU is an implicit instantiation of a template with no definition visible, and no promise that such a definition exists elsewhere.

Body:
There is a third approach.  In approach 3 you specify the function you want to have and the you add a template overload and mark that as delete.  That looks like

void foo(int i)
{
    // stuff
}

template <typename T>
void foo(T t) = delete;

Since the template version will match all types exactly it will be preferred in all cases except int since a non template exact match is preferred to a template one.  So you will only be able to call foo with an int and all other types will give you an error that they are trying to call the deleted function void foo(T t).

Live Example


问:
Resolution Depdendent FontSize for Xamarin.Forms
So I am developing a Xamarin.Forms application for Tablets, and now I need it to also run on phones - Great, Xamarin.Forms should handle all that (or so I thought).

I ran the application on my phone but it didnt scale down the Font (or any sizes for that matter, but I'll start with font)

I created an extension method like so:

```<code>[ContentProperty("FontSize")]
public class FontExtension : IMarkupExtension
{
    public string FontSize { get; set; }

    public object ProvideValue(IServiceProvider serviceProvider)
    {
        double fontSize;

        if (FontSize == null)
            throw new Exception("No Font Size provided");

        if (!double.TryParse(FontSize, out fontSize))
            throw new Exception("Font Size Provided is not a double");

        return App.Scaling * fontSize;
    }
}
</code>```

and I use this in my application like FontSize={ns:Font 18} and this will downscale my application based on the App.Scaling property. This property is just set to 0.8 if it is a Phone.

I also found two links that provided a way in Xamarin.Android but I am doing a Xamarin.Forms application so didnt apply. (link1,link2)

Is it possible to scale the font down based on the devices Resolution rather than Idiom?

答:
Xamarin Forms provides some named sizes - small, medium, large etc. that may give you what you want. These will end up as different sizes depending on your platform.

https://developer.xamarin.com/guides/xamarin-forms/user-interface/text/fonts/#Font_Size

Body:
So I am developing a Xamarin.Forms application for Tablets, and now I need it to also run on phones - Great, Xamarin.Forms should handle all that (or so I thought).

I ran the application on my phone but it didnt scale down the Font (or any sizes for that matter, but I'll start with font)

I created an extension method like so:

[ContentProperty("FontSize")]
public class FontExtension : IMarkupExtension
{
    public string FontSize { get; set; }

    public object ProvideValue(IServiceProvider serviceProvider)
    {
        double fontSize;

        if (FontSize == null)
            throw new Exception("No Font Size provided");

        if (!double.TryParse(FontSize, out fontSize))
            throw new Exception("Font Size Provided is not a double");

        return App.Scaling * fontSize;
    }
}

and I use this in my application like FontSize={ns:Font 18} and this will downscale my application based on the App.Scaling property. This property is just set to 0.8 if it is a Phone.

I also found two links that provided a way in Xamarin.Android but I am doing a Xamarin.Forms application so didnt apply. (link1,link2)

Is it possible to scale the font down based on the devices Resolution rather than Idiom?


问:
How to Mock a newly created object?
Very simplified version of code:

```<code>interface IFactory
{
    ITreasure Get(SomeData data);
}

class Factory : IFactory
{
    ITreasure Get(SomeData data)
    {
         // Create instance of ITreasure in very long chain of methods basing on "data"
         // Can produce one of: BlueTreasure, RedTreasure or GreenTreasure
         return treasure;
    }
}
</code>```

And here it is, the class with smell that I can not modify at all.

```<code>class CantModify
{
    public CantModify {}

    public TestMe(SomeData data)
    {
        ITreasure treasure = new Factory().Get(data);

        if(treasure is BlueTreasure) ...
        else if(treasure is RedTreasure) ...
        else if(treasure is GreenTreasure) ...
    }
}
</code>```

I would like to test all code paths of TestMe() but I don't want to prepare data to obtain specific type of ITreasure.
Is there any way to make new Factory() return Mocked instance of Factory that will return different type of ITreasure in each test?

答:
You need to add dependency on IFactory in the Cantmodify class. And then you can Mock Get Method to return whatever you want.
The class should look :</p>

```<code>public class CantModify
{
    private readonly IFactory _factory;

    public CantModify(IFactory factory)
    {
        _factory = factory;
    }

     public TestMe(SomeData data)
    {
        ITreasure treasure = _factory.Get(data);

        if (treasure is BlueTreasure) ...

    else if (treasure is RedTreasure) ...

    else if (treasure is GreenTreasure) ...

}
</code>```

Title: How to Mock a newly created object?

Body:
Very simplified version of code:

interface IFactory
{
    ITreasure Get(SomeData data);
}

class Factory : IFactory
{
    ITreasure Get(SomeData data)
    {
         // Create instance of ITreasure in very long chain of methods basing on "data"
         // Can produce one of: BlueTreasure, RedTreasure or GreenTreasure
         return treasure;
    }
}

And here it is, the class with smell that I can not modify at all.

class CantModify
{
    public CantModify {}

    public TestMe(SomeData data)
    {
        ITreasure treasure = new Factory().Get(data);

        if(treasure is BlueTreasure) ...
        else if(treasure is RedTreasure) ...
        else if(treasure is GreenTreasure) ...
    }
}

I would like to test all code paths of TestMe() but I don't want to prepare data to obtain specific type of ITreasure.
Is there any way to make new Factory() return Mocked instance of Factory that will return different type of ITreasure in each test?

Body:
You need to add dependency on IFactory in the Cantmodify class. And then you can Mock Get Method to return whatever you want.
The class should look :

public class CantModify
{
    private readonly IFactory _factory;

    public CantModify(IFactory factory)
    {
        _factory = factory;
    }

     public TestMe(SomeData data)
    {
        ITreasure treasure = _factory.Get(data);

        if (treasure is BlueTreasure) ...

    else if (treasure is RedTreasure) ...

    else if (treasure is GreenTreasure) ...

}


问:
Only one row echoed
I have following code. I  only get one one row echoed the first one.

What do ido wrong?

```<code><?php
include("/connectdb.php");
$link2=Connection();
$rt = mysql_query("SELECT motion FROM tempLog WHERE Id='13007423' AND DATE(`timeStamp`) = CURDATE() ORDER BY timeStamp DESC LIMIT 2", $link2);
$result = mysql_fetch_row($rt);
if($result)
echo $result[0];
echo $result[1];
?>
</code>```

Thanks for help!

答:
mysql_fetch_row() returns only one line of your query. So you only have an array with your 'mention' variable.

Use this to print all your lines :

```<code>$rt = mysql_query("SELECT motion FROM tempLog WHERE Id='13007423' AND DATE(`timeStamp`) = CURDATE() ORDER BY timeStamp DESC LIMIT 2", $link2);
while ($result =  mysql_fetch_row($rt)) {
    echo $result[0];
}
</code>```

And please, use mysqli_ . mysql_ is deprecated since php5.5 and removed in php7.0

Title: Only one row echoed

Body:
I have following code. I  only get one one row echoed the first one.

What do ido wrong?

<?php
include("/connectdb.php");
$link2=Connection();
$rt = mysql_query("SELECT motion FROM tempLog WHERE Id='13007423' AND DATE(`timeStamp`) = CURDATE() ORDER BY timeStamp DESC LIMIT 2", $link2);
$result = mysql_fetch_row($rt);
if($result)
echo $result[0];
echo $result[1];
?>

Thanks for help!

Body:
mysql_fetch_row() returns only one line of your query. So you only have an array with your 'mention' variable.

Use this to print all your lines :

$rt = mysql_query("SELECT motion FROM tempLog WHERE Id='13007423' AND DATE(`timeStamp`) = CURDATE() ORDER BY timeStamp DESC LIMIT 2", $link2);
while ($result =  mysql_fetch_row($rt)) {
    echo $result[0];
}

And please, use mysqli_ . mysql_ is deprecated since php5.5 and removed in php7.0


问:
Filtering Server Response RestKit + CoreData
Im using RestKit+CoreData. And i always get response code 200 from server. And I don't need all responses to save into core data, Is there any way to filter response ?</p>

答:
Yes. You can use the addFetchRequestBlock to give a fetch request with predicate, by which you can avoid saving unwanted objects from responses.

Reference :
http://cocoadocs.org/docsets/RestKit/0.24.0/Classes/RKManagedObjectRequestOperation.html


问:
Regex not accepting numbers
I can't figure out why this regex pattern isn't accepting numbers? It used to but then I added [()#'/- part and it stopped.</p>

```<code>^[()#'/-0-9A-Za-z ]+$
</code>```

Title: Regex not accepting numbers

Body:
I can't figure out why this regex pattern isn't accepting numbers? It used to but then I added [()#'/- part and it stopped.

^[()#'/-0-9A-Za-z ]+$

Body:
Take "-" out before "0"

^[()#'/0-9A-Za-z ]+$


问:
XPath to select all elements between two headings?
```<code><h2>Headline 1</h2>
<p>some text</p>
<p>some more text</p>
<ul>
<li>list item 1</li>
<li>list item 2</li>
</ul>
<p>more text</p>
<h2>Headline 2</h2>
</code>```

I have the above in a webpage and I want to be able to target all elements following the first h2 that contains the text 'Headline 1' up to but NOT including the element h2 that contains the text 'Headline 2'.

I can target the elements like this:

```<code>//*[count(preceding-sibling::hr)=1]
</code>```

but this is not specific to the text contained and so if the page ever changed then the xpath could be pointing to something totally different.

What I would like in sudo code terms is this:

give me all the elements between the header 'Headline 1' and the
  header 'Headline 2' including 'Headline 1'

Is this at all possible?

答:
What if try something like </p>

```<code>//*[text()="Headline 1"]/following-sibling::*
</code>```

Body:
Headline 1

some text

some more text

list item 1

list item 2

more text

Headline 2

I have the above in a webpage and I want to be able to target all elements following the first h2 that contains the text 'Headline 1' up to but NOT including the element h2 that contains the text 'Headline 2'.

I can target the elements like this:

//*[count(preceding-sibling::hr)=1]

but this is not specific to the text contained and so if the page ever changed then the xpath could be pointing to something totally different.

What I would like in sudo code terms is this:

give me all the elements between the header 'Headline 1' and the
  header 'Headline 2' including 'Headline 1'

Is this at all possible?

Body:
What if try something like

//*[text()="Headline 1"]/following-sibling::*


问:
What is the highest Ruby version supported by Rails v4.1.16?
In other words, can I run Rails 4.1.16 on Ruby 2.4? If not, can I run it on Ruby 2.3?</p>

答:
Based on the CI settings for 4-1-stable, I'd say stick with Ruby 2.3. 2.4.0 isn't on that list, as things stand.

That's not to say that 4.1.16 won't run on Ruby 2.4 - I can't really speak to that - but there's always a possibility that you hit subtle issues, depending on the features you use and the gems that you include. Ruby 2.4 has the Fixnum and Bignum unification, as well as unicode changes - which potentially could have an impact.

FWIW, we have a sizeable, battle-tested application on the 4.1.x branch that works just fine on Ruby 2.3.3.


问:
Unable to locate the element using css selector[JAVA]
Website: http://www.javatpoint.com/

Steps : First click on JAVA=>Scroll down and click on Java String => Substring

I'm trying to locate the webelement using cssSelector, but not able to locate the element whereas I'm able to locate the same using xpath.

```<code>driver.findElement(By.xpath("//div/a[text()='Substring']"));
</code>```

css Selectors I've tried :

```<code>driver.findElement(By.cssSelector("div>a[text='Substring']"));
driver.findElement(By.cssSelector("div>a:contains('Substring')"));
</code>```

答:
As others have said, you cannot locate an element by contained text using CSS selectors. To do that, you'll have to use an XPath.

But... there is an alternative CSS selector that will work here, a[href='substring']. This matches based on the href attribute of the A tag which, at least according to the posted HTML, is unique on the page and should work.

Body:
Website: http://www.javatpoint.com/

Steps : First click on JAVA=>Scroll down and click on Java String => Substring

I'm trying to locate the webelement using cssSelector, but not able to locate the element whereas I'm able to locate the same using xpath.

driver.findElement(By.xpath("//div/a[text()='Substring']"));

css Selectors I've tried :

driver.findElement(By.cssSelector("div>a[text='Substring']"));
driver.findElement(By.cssSelector("div>a:contains('Substring')"));


问:
Error while using md-input-container
I have created a Angular 2 material app as per link https://github.com/angular/material2/blob/master/GETTING_STARTED.md.

I am able to use <md-card>, <md-toolbar>, <md-input> etc. But when I use <md-input-container>, it is throwing error as

```<code>zone.js:388 Unhandled Promise rejection: Template parse errors:
'md-input-container' is not a known element:
</code>```

Here are the detail from packages.json,

```<code>"dependencies": {
    "@angular/common": "~2.1.0",
    "@angular/compiler": "~2.1.0",
    "@angular/core": "~2.1.0",
    "@angular/forms": "~2.1.0",
    "@angular/http": "~2.1.0",
    "@angular/material": "^2.0.0-alpha.11-3",
    "@angular/platform-browser": "~2.1.0",
    "@angular/platform-browser-dynamic": "~2.1.0",
    "@angular/router": "~3.1.0",
    "core-js": "^2.4.1",
    "hammerjs": "^2.0.8",
    "ng2-file-upload": "^1.1.4-2",
    "rxjs": "5.0.0-beta.12",
    "ts-helpers": "^1.1.1",
    "zone.js": "^0.6.23"
  },
</code>```

How I can fix this?

https://github.com/angular/material2/tree/master/src/lib/input says that md-input is deprecated and use md-input-container.

答:
This worked for me.

app.module.ts

import { MaterialModule } from '@angular/material';
...
@NgModule({
imports: [
MaterialModule
]
})
```

<p>app.component.html</p>

<pre class="lang-html prettyprint-override"><code><md-input-container>
<input mdInput placeholder="Favorite food" value="Sushi">
</md-input-container>
</code>```

The key thing here is to make sure that you add this in the head of your index.html.

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
```

Title: Error while using md-input-container

Body:
I have created a Angular 2 material app as per link https://github.com/angular/material2/blob/master/GETTING_STARTED.md.

I am able to use <md-card>, <md-toolbar>, <md-input> etc. But when I use <md-input-container>, it is throwing error as

zone.js:388 Unhandled Promise rejection: Template parse errors:
'md-input-container' is not a known element:

Here are the detail from packages.json,

"dependencies": {
    "@angular/common": "~2.1.0",
    "@angular/compiler": "~2.1.0",
    "@angular/core": "~2.1.0",
    "@angular/forms": "~2.1.0",
    "@angular/http": "~2.1.0",
    "@angular/material": "^2.0.0-alpha.11-3",
    "@angular/platform-browser": "~2.1.0",
    "@angular/platform-browser-dynamic": "~2.1.0",
    "@angular/router": "~3.1.0",
    "core-js": "^2.4.1",
    "hammerjs": "^2.0.8",
    "ng2-file-upload": "^1.1.4-2",
    "rxjs": "5.0.0-beta.12",
    "ts-helpers": "^1.1.1",
    "zone.js": "^0.6.23"
  },

How I can fix this?

https://github.com/angular/material2/tree/master/src/lib/input says that md-input is deprecated and use md-input-container.

Body:
This worked for me.

app.module.ts

import { MaterialModule } from '@angular/material';
...
@NgModule({
imports: [
MaterialModule
]
})

app.component.html

<md-input-container>
<input mdInput placeholder="Favorite food" value="Sushi">
</md-input-container>

The key thing here is to make sure that you add this in the head of your index.html.

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">


问:
How to prevent airflow from backfilling dag runs?
Say you have an airflow DAG that doesn't make sense to backfill, meaning that, after it's run once, running it subsequent times quickly would be completely pointless.

For example, if you're loading data from some source that is only updated hourly into your database, backfilling, which occurs in rapid succession, would just be importing the same data again and again.

This is especially annoying when you instantiate a new hourly task, and it runs N amount of times for each hour it missed, doing redundant work, before it starts running on the interval you specified.

The only solution I can think of is something that they specifically advised against in FAQ of the docs

We recommend against using dynamic values as start_date, especially datetime.now() as it can be quite confusing.

Is there any way to disable backfilling for a DAG, or should I do the above?

答:
Upgrade to airflow version 1.8 and use catchup_by_default=False in the airflow.cfg or apply catchup=False to each of your dags.

https://github.com/apache/incubator-airflow/blob/master/UPDATING.md#catchup_by_default

ContentLicense: CC BY-SA 4.0


问:
C# How to wrap date string in single quote inside the string's double quotes
I am trying to wrap my DateTime's date format in single quotes

e.g. DateTime.Now().ToString("yyyy-MM-dd") output will be like "2017-03-30"

My question, Is there anyway of producing the result like "'2017-03-30'" (i-e single quotes within the double quotes)?

答:
Use string.Format, or on C#6+ string interpolation:

```<code>// String format
string.Format("'{0}'", DateTime.Now.ToString("yyyy-MM-dd"));

// Interpolation
$"'{DateTime.Now.ToString("yyyy-MM-dd")}'";
</code>```

Result:

'2017-03-30'

Body:
Use string.Format, or on C#6+ string interpolation:

// String format
string.Format("'{0}'", DateTime.Now.ToString("yyyy-MM-dd"));

// Interpolation
$"'{DateTime.Now.ToString("yyyy-MM-dd")}'";

Result:

'2017-03-30'


问:
Query xml using sql server
i am new to xml queries. i have one xml like

```<code><fields>
<fields name = "a" active ="1" mandat ="true"/>
<fields name = "a" active ="1"/>
</fields>
</code>```

Now i need to find all the field names that manadt is true. How can i query xml using sql server. please help

答:
Your question is not quite clear, especially the tags (sql, xml, c#-4.0), but from you question's text I take, that you need to query the XML's content within SQL-Server.

You can try it like this

```<code>DECLARE @xml XML=
N'<fields>
  <fields name="a" active="1" mandat="true" />
  <fields name="a" active="1" />
</fields>';

SELECT fld.value(N'@name',N'nvarchar(max)') AS Field_Name
      ,fld.value(N'@active',N'bit') AS Field_Active
      ,fld.value(N'@mandat',N'bit') AS Field_Mandant
FROM @xml.nodes(N'/fields/fields') AS A(fld)
</code>```

The result

```<code>Field_Name  Field_Active    Field_Mandant
a           1               1
a           1               NULL
</code>```

UPDATE

If you want to read the value of @name of the fields-node, where @mandat is "true", do it like this:

```<code>DECLARE @xml XML=
N'<fields>
  <fields name="a" active="1" mandat="true" />
  <fields name="a" active="1" />
</fields>';

SELECT @xml.value(N'(/fields/fields[@mandat="true"]/@name)[1]',N'nvarchar(max)') AS Mandant_Name
</code>```

UPDATE 2: More than one <fields> with @mandat="true"

Just try my first solution with a predicate in .nodes():

```<code>DECLARE @xml XML=
N'<fields>
  <fields name="a" active="1" mandat="true" />
  <fields name="b" active="2" />
  <fields name="c" active="3" mandat="false" />
  <fields name="d" active="4" mandat="true" />
</fields>';

SELECT fld.value(N'@name',N'nvarchar(max)') AS Field_Name
      ,fld.value(N'@active',N'bit') AS Field_Active
      ,fld.value(N'@mandat',N'bit') AS Field_Mandant
FROM @xml.nodes(N'/fields/fields[@mandat="true"]') AS A(fld)
</code>```

This will return only the first and the last <fields> node

Title: Query xml using sql server

Body:
i am new to xml queries. i have one xml like

<fields>
<fields name = "a" active ="1" mandat ="true"/>
<fields name = "a" active ="1"/>
</fields>

Now i need to find all the field names that manadt is true. How can i query xml using sql server. please help

Body:
Your question is not quite clear, especially the tags (sql, xml, c#-4.0), but from you question's text I take, that you need to query the XML's content within SQL-Server.

You can try it like this

DECLARE @xml XML=
N'<fields>
  <fields name="a" active="1" mandat="true" />
  <fields name="a" active="1" />
</fields>';

SELECT fld.value(N'@name',N'nvarchar(max)') AS Field_Name
      ,fld.value(N'@active',N'bit') AS Field_Active
      ,fld.value(N'@mandat',N'bit') AS Field_Mandant
FROM @xml.nodes(N'/fields/fields') AS A(fld)

The result

Field_Name  Field_Active    Field_Mandant
a           1               1
a           1               NULL

UPDATE

If you want to read the value of @name of the fields-node, where @mandat is "true", do it like this:

DECLARE @xml XML=
N'<fields>
  <fields name="a" active="1" mandat="true" />
  <fields name="a" active="1" />
</fields>';

SELECT @xml.value(N'(/fields/fields[@mandat="true"]/@name)[1]',N'nvarchar(max)') AS Mandant_Name

UPDATE 2: More than one <fields> with @mandat="true"

Just try my first solution with a predicate in .nodes():

DECLARE @xml XML=
N'<fields>
  <fields name="a" active="1" mandat="true" />
  <fields name="b" active="2" />
  <fields name="c" active="3" mandat="false" />
  <fields name="d" active="4" mandat="true" />
</fields>';

SELECT fld.value(N'@name',N'nvarchar(max)') AS Field_Name
      ,fld.value(N'@active',N'bit') AS Field_Active
      ,fld.value(N'@mandat',N'bit') AS Field_Mandant
FROM @xml.nodes(N'/fields/fields[@mandat="true"]') AS A(fld)

This will return only the first and the last <fields> node


问:
Chef Ruby object and collections
I've dipped my toe in chef and am having a few difficulties with what should be simple concepts.

I'm obtains data from a node by running a search; my plan is to iterate over the results and create an object of type X setting its variables as I go.

I'd like to store these objects in a collection so that I can access them later in the recipe to carry out other tasks and so on.

My GoogleFu has so far come up short and I'm worried that I'm tackling this in the wrong way.  My search is fine and returning the values, my separate class is also fine but the storing of these objects into a collection and then persisting that is proving more difficult.  Many posts frown against using arrays for my purpose(if it's possible) and I've not found anything similar to an ArrayList or Map.  Additionally, if I use a ruby collection, does it need to be maintained inside a ruby block?

Thanks for any help / advice.

答:
You got to be more specific in where you are actually facing the issue but as far as I have understood why not
just define a ruby class and initialize all the variables you are supposed to get. In the recipe instantiate the object and keep settings its properties from the result. There should be no issue in this approach.

But more importantly what is your use-case here, because you could just define an array attribute and then keep syncing the result in that attribute .  As in ruby Objects are referenced , thus any change you make to resource attributes which takes that object, changes are persistent to in that object.

Title: Chef Ruby object and collections


问:
trigger state of parent component
I have a modal wrapper and within it it has react-modal which is an npm module.

In the render method it open base on the this.props.isOpen

```<code><ReactModal
    contentLabel="modal-big"
    className="modal-big"
    isOpen={this.props.isOpen}
    shouldCloseOnOverlayClick={true}
>
    {this.content()}
</ReactModal>
</code>```

and within this.content I have button that should close the modal. But how to change the state of the parent? I can't call this.props.isOpen = false;

答:
Call a parent function that is passed down to the child as a prop and set the state in it</p>

```<code>class Parent extends React.Component {
     constructor() {
         super();
         this.state = {
            open: false
         }
     }
     closeModal = () => {
          this.setState({open: false});

     }
     render() {
        return (
          <ModalComp closeModal={this.closeModal} open={this.state.open}/>
        )
     }
}

class ModalComp extends React.Component {
   content = () => {
       return (
          <button type="text" onClick={()=> this.props.closeModal()}> close</button>
       )
   }
   render() {
      // .... Modal content here
   }

}
</code>```

Title: trigger state of parent component

Body:
I have a modal wrapper and within it it has react-modal which is an npm module.

In the render method it open base on the this.props.isOpen

<ReactModal
    contentLabel="modal-big"
    className="modal-big"
    isOpen={this.props.isOpen}
    shouldCloseOnOverlayClick={true}
>
    {this.content()}
</ReactModal>

and within this.content I have button that should close the modal. But how to change the state of the parent? I can't call this.props.isOpen = false;

Body:
Call a parent function that is passed down to the child as a prop and set the state in it

class Parent extends React.Component {
     constructor() {
         super();
         this.state = {
            open: false
         }
     }
     closeModal = () => {
          this.setState({open: false});

     }
     render() {
        return (
          <ModalComp closeModal={this.closeModal} open={this.state.open}/>
        )
     }
}

class ModalComp extends React.Component {
   content = () => {
       return (
          <button type="text" onClick={()=> this.props.closeModal()}> close</button>
       )
   }
   render() {
      // .... Modal content here
   }

}


答:
The issue with using del element["type"], del element["properties"] and del element["geometry"] is that it only removes those items from properties dict of that element. Not the element itself.

For your 2nd item, when you're iterating over a list like in for element in data["features"]:, it's not good to modify a list or object while iterating over it (which is what's happening with data["features"].remove(element)). Also, list.remove() removes an item with that value. So element gets used in a value context, not as that element.

It's better to create a new list and then assign that. What you could do is:

```<code>new_features = []
for element in data["features"]:
    if '%' not in element["properties"]["name"]:    # note the 'not'
        new_features.append(element)                # new_features has the one's you want
# and then re-assign features to the list with the elements you want
data["features"] = new_features
</code>```

Title: Python Remove element from json if value exists

Body:
I have a rather large geojson file which is converted from some National Weather Service data. I've trimmed it down to this sample here:

{
  "properties": {
    "name": "day1otlk"
  },
  "type": "FeatureCollection",
  "features": [
    {
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [
              -122.71424459627099,
              40.229695635383166
            ],
            [
              -122.62484780364827,
              40.53410620541074
            ],
            [
              -122.71424459627099,
              40.229695635383166
            ]
          ]
        ]
      },
      "properties": {
        "Name": "General Thunder",
        "stroke-opacity": 1,
        "stroke-width": 4,
        "name": "General Thunder",
        "fill": "#c0e8c0",
        "fill-opacity": 0.75,
        "stroke": "#ffffff",
        "timeSpan": {
          "end": "2017-03-30T12:00:00Z",
          "begin": "2017-03-29T20:00:00Z"
        }
      },
      "type": "Feature"
    },
    {
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [
              -108.65861565996833,
              32.91391108773154
            ],
            [
              -108.63932601964923,
              32.95521185698698
            ],
            [
              -108.65861565996833,
              32.91391108773154
            ]
          ]
        ]
      },
      "properties": {
        "Name": "General Thunder",
        "stroke-opacity": 1,
        "stroke-width": 4,
        "name": "General Thunder",
        "fill": "#c0e8c0",
        "fill-opacity": 0.75,
        "stroke": "#ffffff",
        "timeSpan": {
          "end": "2017-03-30T12:00:00Z",
          "begin": "2017-03-29T20:00:00Z"
        }
      },
      "type": "Feature"
    },
    {
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [
              -92.67280213157608,
              38.47870651780003
            ],
            [
              -92.62448390998837,
              38.45534960370862
            ],
            [
              -92.59475154780039,
              38.493327413824595
            ],
            [
              -92.64308574626148,
              38.51669676139087
            ],
            [
              -92.67280213157608,
              38.47870651780003
            ]
          ]
        ]
      },
      "properties": {
        "Name": "10 %",
        "stroke-opacity": 1,
        "stroke-width": 4,
        "name": "10 %",
        "fill": "#8b4726",
        "fill-opacity": 0.89,
        "stroke": "#ffffff",
        "timeSpan": {
          "end": "2017-03-30T12:00:00Z",
          "begin": "2017-03-29T20:00:00Z"
        }
      },
      "type": "Feature"
    },
    {
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [
              -92.67280213157608,
              38.47870651780003
            ],
            [
              -92.62448390998837,
              38.45534960370862
            ],
            [
              -92.59475154780039,
              38.493327413824595
            ],
            [
              -92.64308574626148,
              38.51669676139087
            ],
            [
              -92.67280213157608,
              38.47870651780003
            ]
          ]
        ]
      },
      "properties": {
        "Name": "10 %",
        "stroke-opacity": 1,
        "stroke-width": 4,
        "name": "20 %",
        "fill": "#8b4726",
        "fill-opacity": 0.89,
        "stroke": "#ffffff",
        "timeSpan": {
          "end": "2017-03-30T12:00:00Z",
          "begin": "2017-03-29T20:00:00Z"
        }
      },
      "type": "Feature"
    },
    {
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [
              -97.09845994557838,
              38.43843745045377
            ],
            [
              -97.07114801649661,
              38.47751978088534
            ],
            [
              -97.09845994557838,
              38.43843745045377
            ]
          ]
        ]
      },
      "properties": {
        "Name": "5 %",
        "stroke-opacity": 1,
        "stroke-width": 4,
        "name": "5 %",
        "fill": "#b47f00",
        "fill-opacity": 0.89,
        "stroke": "#ffffff",
        "timeSpan": {
          "end": "2017-03-30T12:00:00Z",
          "begin": "2017-03-29T20:00:00Z"
        }
      },
      "type": "Feature"
    }
  ]
}

I'm looking to remove the elements where name has a % in it. I don't want those coordinates or anything included.

Here's my code:

import json

with open('test.geojson') as data_file:
    data = json.load(data_file)

for element in data["features"]:
    if '%' in element["properties"]["name"]:
        del element["type"]
        del element["properties"] # Deletes the properties
        del element["geometry"] # Deletes the  coords

with open('test_output.geojson', 'w') as data_file:
    data = json.dump(data, data_file)

This works well enough to remove the element's sub keys, but I'm left with output that looks like:

{}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}

I've also tried to use

for element in data["features"]:
        if '%' in element["properties"]["name"]:
                    data["features"].remove(element)

but that seems to delete only the last element in the sample group, which is the 5 % group. It should be removing the 10 %, 20 % and the 5 % groups.

Is there a way to remove the element from data["features"] if name has a % in it all together so I'm left with clean json output? In this sample data, the only data["features"] I should have left are the General Thunder and no empty brackets.

Body:
The issue with using del element["type"], del element["properties"] and del element["geometry"] is that it only removes those items from properties dict of that element. Not the element itself.

For your 2nd item, when you're iterating over a list like in for element in data["features"]:, it's not good to modify a list or object while iterating over it (which is what's happening with data["features"].remove(element)). Also, list.remove() removes an item with that value. So element gets used in a value context, not as that element.

It's better to create a new list and then assign that. What you could do is:

new_features = []
for element in data["features"]:
    if '%' not in element["properties"]["name"]:    # note the 'not'
        new_features.append(element)                # new_features has the one's you want
# and then re-assign features to the list with the elements you want
data["features"] = new_features


问:
how to trigger function onchange on already selected option
I have a  dropdown which i would like to trigger a function when something is selected.

```<code><select id="myselect">
   <option>1</option>
   <option>2</option>
   <option>3</option>
</select>

$(document).on("change", "#myselect", function(event) {
alert("you selected something");
});
</code>```

The problem I have is that the function is not triggered if i choose option that has already been selected. I do understand that this is because nothing has been changed but is there a way around this?

I have tried

```<code>  <select id="myselect" onmousedown="this.value='';" >
</code>```

this was ok for the few options, but when i had many options when i needed to scroll down to select it would jump up and select the wrong option.
Any help much appreciated.

答:
Try</p>

```<code> <select id="myselect" onclick="alert('Something selected')">
   <option>1</option>
   <option>2</option>
   <option>3</option>
</select>
</code>```

Body:
I have a  dropdown which i would like to trigger a function when something is selected.

<select id="myselect">
   <option>1</option>
   <option>2</option>
   <option>3</option>
</select>

$(document).on("change", "#myselect", function(event) {
alert("you selected something");
});

The problem I have is that the function is not triggered if i choose option that has already been selected. I do understand that this is because nothing has been changed but is there a way around this?

I have tried

  <select id="myselect" onmousedown="this.value='';" >

this was ok for the few options, but when i had many options when i needed to scroll down to select it would jump up and select the wrong option.
Any help much appreciated.

Body:
Try

 <select id="myselect" onclick="alert('Something selected')">
   <option>1</option>
   <option>2</option>
   <option>3</option>
</select>


答: You need to do self join and get differences using DATEDIFF function and get average.</p>

ContentLicense: CC BY-SA 2.5

Title: MySQL: Average interval between records

Body:
Assume this table:

id    date
----------------
1     2010-12-12
2     2010-12-13
3     2010-12-18
4     2010-12-22
5     2010-12-23

How do I find the average intervals between these dates, using MySQL queries only?

For instance, the calculation on this table will be

  (
    ( 2010-12-13 - 2010-12-12 )
  + ( 2010-12-18 - 2010-12-13 )
  + ( 2010-12-22 - 2010-12-18 )
  + ( 2010-12-23 - 2010-12-22 )
  ) / 4
----------------------------------
= ( 1 DAY + 5 DAY + 4 DAY + 1 DAY ) / 4
= 2.75 DAY


问:
Why Chrome console panel Ctrl-[ shortcut doesn't work for me?
Switching between console panels should be possible with Ctrl+[ or ] as per devtools help:

But it does nothing for me. The same goes for Ctrl+Alt+[.

Is it because I'm using french keyboard?

Is it possible to use these shortcuts with a french keyboard?

答:
It could be because you have an extension that is overriding the shortcuts.

Open chrome://extensions/

Scroll to the bottom, click 'Keyboard shortcuts"

Ensure that no shortcuts replicate Chrome defaults. If they do, click the X to remove them.


问:
QueryString converted to URL-Encode using NameValueCollection
I am passing an encrypted URL string:

Default.aspx?S3tLlnIKKzE%3d

I want to pass that URL string back into the ASPX page in a variable.

```<code>protected string qs = string.Empty;

NameValueCollection qscollstring = HttpContext.Current.Request.QueryString;
qs = qscollstring[0];
</code>```

Which return :  S3tLlnIKKzE=

The value in qscollstring[0] is correct: S3tLlnIKKzE%3d

I understand the problem is URL-Encoding, but I cannot find a way to keep the string as is.

It seems that assigning the value from qscollstring[0] is: S3tLlnIKKzE%3d

to string changes the value : S3tLlnIKKzE=

I need to to stay: S3tLlnIKKzE%3d

答:
Like me if you are searching for the reverse .. use

```<code>qs =HttpUtility.UrlDecode("S3tLlnIKKzE%3d");
</code>```

to get back S3tLlnIKKzE=

Body:
I am passing an encrypted URL string:

Default.aspx?S3tLlnIKKzE%3d

I want to pass that URL string back into the ASPX page in a variable.

protected string qs = string.Empty;

NameValueCollection qscollstring = HttpContext.Current.Request.QueryString;
qs = qscollstring[0];

Which return :  S3tLlnIKKzE=

The value in qscollstring[0] is correct: S3tLlnIKKzE%3d

I understand the problem is URL-Encoding, but I cannot find a way to keep the string as is.

It seems that assigning the value from qscollstring[0] is: S3tLlnIKKzE%3d

to string changes the value : S3tLlnIKKzE=

I need to to stay: S3tLlnIKKzE%3d

Body:
Like me if you are searching for the reverse .. use

qs =HttpUtility.UrlDecode("S3tLlnIKKzE%3d");

to get back S3tLlnIKKzE=


问:
CSS: How can I select all ul tags contained within ol tags
My HTML looks like

```<code><ol class='enlarge'>
<li>Larger
<ul>
<li>Normal
</li>
</ul>
</li>
</ol>
</code>```

Where you see Larger I want the font size to be larger. And where you see Normal, I want the font size to be normal.

I've tried

```<code>  ol.enlarge {
    font-size: 130%;
  }
  ul.enlarge {
    font-size: 70%;
  }
</code>```

And

```<code>  ol {
    font-size: 130%;
  }
  ul > ol {
    font-size: 70%;
  }
</code>```

And

```<code>  ol {
    font-size: 130%;
  }
  ol > ul {
    font-size: 70%;
  }
</code>```

All are setting the font size bigger for everything in my

Thanks!

-Tom

答:
Another idea is to use ol > li > ul {...} instead of ol > ul {...}. Anyway, this depends on the markup that you are planning to use. Just keep in mind that > means direct child and this is the reason why ol > ul didn't work.

ol {
  font-size: 130%;
}

ol > li > ul {
  font-size: 70%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ol>
  <li>Larger
    <ul>
      <li>Normal
      </li>
    </ul>
  </li>
</ol></code>```

Body:
My HTML looks like

Larger

Normal

Where you see Larger I want the font size to be larger. And where you see Normal, I want the font size to be normal.

I've tried

  ol.enlarge {
    font-size: 130%;
  }
  ul.enlarge {
    font-size: 70%;
  }

And

  ol {
    font-size: 130%;
  }
  ul > ol {
    font-size: 70%;
  }

And

  ol {
    font-size: 130%;
  }
  ol > ul {
    font-size: 70%;
  }

All are setting the font size bigger for everything in my

Thanks!

-Tom

Body:
Another idea is to use ol > li > ul {...} instead of ol > ul {...}. Anyway, this depends on the markup that you are planning to use. Just keep in mind that > means direct child and this is the reason why ol > ul didn't work.

ol {
  font-size: 130%;
}

ol > li > ul {
  font-size: 70%;
}

<ol>
  <li>Larger
    <ul>
      <li>Normal
      </li>
    </ul>
  </li>
</ol>


问:
Alexa skill 2 intents and open slot
Is it possible that Alexa reacts right when I have in a sample utterances something like this, opened slots?

```<code>MyNameIsIntent {firstname}
ProjektIntent {projekt}
</code>```

Right now she always goes back to  MyNameIsIntent even if she ask a question for a ProjektIntent

The bad conversation:

```<code>Alexa: Welcome, what is your name?
Me: Frank
Alexa Hi Frank, Tell me what project is interesting for you?
Me: Teleshoping
Alexa: Hi Teleshoping, Tell me what project is interesting for you?
</code>```

Im totally new to Alexa, could you give me please a tip if it is possible that Alexa answers the right question? I tried to do it with a session atributes but it doesn't work

答:
An utterance file like that won't work.  Alexa uses the text of the utterance - the stuff aside from the slot name, of which you have none - to choose an intent.

So, unfortunately you can't design your interactions to allow for a response of just 'Teleshoping'.  Instead, the user would have to say something like 'I'm interested in Teleshoping' (you would need to tell them to say it like that), and the sample utterance would be 'I'm interested in {projekt}'.

Title: Alexa skill 2 intents and open slot

Body:
Is it possible that Alexa reacts right when I have in a sample utterances something like this, opened slots?

MyNameIsIntent {firstname}
ProjektIntent {projekt}

Right now she always goes back to  MyNameIsIntent even if she ask a question for a ProjektIntent

The bad conversation:

Alexa: Welcome, what is your name?
Me: Frank
Alexa Hi Frank, Tell me what project is interesting for you?
Me: Teleshoping
Alexa: Hi Teleshoping, Tell me what project is interesting for you?

Im totally new to Alexa, could you give me please a tip if it is possible that Alexa answers the right question? I tried to do it with a session atributes but it doesn't work


问:
Display date according to the time zone of device
2010-06-14 02:21:49-0400
or 2010-06-14 02:21:49+0400

The above is the string coming from my webservice...
is there a way to convert this string to the date according to the local machine time zone

I used Simpledateformatter .. but not able to display correctly.. please help

答:
Use java.text.SimpleDateFormat for date formatting (from date string to date object). Pattern will be yyyy-MM-dd HH:mm:ssZ

Example:

```<code>String dateStr = "2010-06-14 02:21:49-0400";
String pattern = "yyyy-MM-dd HH:mm:ssZ";
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
Date date = sdf.parse(dateStr);
</code>```

PS To use TimeZone, you can use TimeZone.getDefault() and add it to SimpleDateFormat.

```<code>SimpleDateFormat sdf = new SimpleDateFormat(pattern);
sdf.setTimeZone(TimeZone.getDefault());
Date date = sdf.parse(dateStr);
</code>```

Body:
Use java.text.SimpleDateFormat for date formatting (from date string to date object). Pattern will be yyyy-MM-dd HH:mm:ssZ

Example:

String dateStr = "2010-06-14 02:21:49-0400";
String pattern = "yyyy-MM-dd HH:mm:ssZ";
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
Date date = sdf.parse(dateStr);

PS To use TimeZone, you can use TimeZone.getDefault() and add it to SimpleDateFormat.

SimpleDateFormat sdf = new SimpleDateFormat(pattern);
sdf.setTimeZone(TimeZone.getDefault());
Date date = sdf.parse(dateStr);


问:
Start an external activity to scan barcode
I want to start the barcode scanner from my app and get the tag

Here is what I have so far :

scan.h

```<code>class DecodeBarCode : public QObject
{
    Q_OBJECT

    BarCodeReceiver *m_receiver;

public:
    explicit DecodeBarCode(QObject *parent = 0);
    ~DecodeBarCode();

    Q_INVOKABLE void useZXingApp();

signals:
    void tagFound(QString tag);
};

class BarCodeReceiver : public QAndroidActivityResultReceiver
{
    DecodeBarCode *m_decoder;
public:
    BarCodeReceiver(DecodeBarCode *decoder) : m_decoder(decoder) {}

    virtual void handleActivityResult(int receiverRequestCode, int resultCode, const QAndroidJniObject &data) {
        emit m_decoder->tagFound("Receiver worked");
    }

};
</code>```

scan.cpp

```<code>DecodeBarCode::DecodeBarCode(QObject *parent) : QObject(parent)
{
    m_receiver = new BarCodeReceiver(this);
}

DecodeBarCode::~DecodeBarCode()
{
    delete m_receiver;
}

void DecodeBarCode::useZXingApp()
{
    QAndroidJniObject intent = QAndroidJniObject::fromString("com/google/zxing/client/android/SCAN");
    if (intent.isValid()) {
        QtAndroid::startActivity(intent,0,m_receiver); // CRASH HERE
    } else {
        emit tagFound("Invalid"); // TEMP
    }
}
</code>```

That is the first time I use JNI, never used it in java nor c++/Qt

There must be something very wrong, what is it ?

答: use this library to save your life :) https://github.com/zxing/zxing</p>

Body:
I want to start the barcode scanner from my app and get the tag

Here is what I have so far :

scan.h

class DecodeBarCode : public QObject
{
    Q_OBJECT

    BarCodeReceiver *m_receiver;

public:
    explicit DecodeBarCode(QObject *parent = 0);
    ~DecodeBarCode();

    Q_INVOKABLE void useZXingApp();

signals:
    void tagFound(QString tag);
};

class BarCodeReceiver : public QAndroidActivityResultReceiver
{
    DecodeBarCode *m_decoder;
public:
    BarCodeReceiver(DecodeBarCode *decoder) : m_decoder(decoder) {}

    virtual void handleActivityResult(int receiverRequestCode, int resultCode, const QAndroidJniObject &data) {
        emit m_decoder->tagFound("Receiver worked");
    }

};

scan.cpp

DecodeBarCode::DecodeBarCode(QObject *parent) : QObject(parent)
{
    m_receiver = new BarCodeReceiver(this);
}

DecodeBarCode::~DecodeBarCode()
{
    delete m_receiver;
}

void DecodeBarCode::useZXingApp()
{
    QAndroidJniObject intent = QAndroidJniObject::fromString("com/google/zxing/client/android/SCAN");
    if (intent.isValid()) {
        QtAndroid::startActivity(intent,0,m_receiver); // CRASH HERE
    } else {
        emit tagFound("Invalid"); // TEMP
    }
}

That is the first time I use JNI, never used it in java nor c++/Qt

There must be something very wrong, what is it ?


问:
F#, implement fold3, fold4, fold_n
I am interested to implement fold3, fold4 etc., similar to List.fold and List.fold2. e.g.

```<code>// TESTCASE
let polynomial (x:double) a b c = a*x + b*x*x + c*x*x*x
let A = [2.0; 3.0; 4.0; 5.0]
let B = [1.5; 1.0; 0.5; 0.2]
let C = [0.8; 0.01; 0.001; 0.0001]

let result = fold3 polynomial 0.7 A B C
// 2.0 * (0.7   ) + 1.5 * (0.7   )^2 + 0.8    * (0.7   )^3 -> 2.4094
// 3.0 * (2.4094) + 1.0 * (2.4094)^2 + 0.01   * (2.4094)^3 -> 13.173
// 4.0 * (13.173) + 0.5 * (13.173)^2 + 0.001  * (13.173)^3 -> 141.75
// 5.0 * (141.75) + 0.2 * (141.75)^2 + 0.0001 * (141.75)^3 -> 5011.964
//
// Output: result = 5011.964
</code>```

My first method is grouping the 3 lists A, B, C, into a list of tuples, and then apply list.fold

```<code>let fold3 f x A B C =
    List.map3 (fun a b c -> (a,b,c)) A B C
       |> List.fold (fun acc (a,b,c) -> f acc a b c) x

// e.g. creates [(2.0,1.5,0.8);  (3.0,1.0,0.01); ......]
</code>```

My second method is to declare a mutable data, and use List.map3

```<code>let mutable result = 0.7
List.map3 (fun a b c ->
               result <- polynomial result a b c  // Change mutable data
               // Output intermediate data
               result) A B C
// Output from List.map3: [2.4094; 13.17327905; 141.7467853; 5011.963942]
// result mutable: 5011.963942
</code>```

I would like to know if there are other ways to solve this problem. Thank you.

答:
I think the existing answers provide great options if you want to generalize folding, which was your original question. However, if I simply wanted to call the polynomial function on inputs specified in A, B and C, then I would probably do not want to introduce fairly complex constructs like applicative functors with fancy operators to my code base.

The problem becomes a lot easier if you transpose the input data, so that rather than having a list [A; B; C] with lists for individual variables, you have a transposed list with inputs for calculating each polynomial. To do this, we'll need the transpose function:

```<code>let rec transpose = function
  | (_::_)::_ as M -> List.map List.head M :: transpose (List.map List.tail M)
  | _ -> []
</code>```

Now you can create a list with inputs, transpose it and calculate all polynomials simply using List.map:

```<code>transpose [A; B; C]
|> List.map (function
  | [a; b; c] -> polynomial 0.7 a b c
  | _ -> failwith "wrong number of arguments")
</code>```

Title: F#, implement fold3, fold4, fold_n

Body:
I am interested to implement fold3, fold4 etc., similar to List.fold and List.fold2. e.g.

// TESTCASE
let polynomial (x:double) a b c = a*x + b*x*x + c*x*x*x
let A = [2.0; 3.0; 4.0; 5.0]
let B = [1.5; 1.0; 0.5; 0.2]
let C = [0.8; 0.01; 0.001; 0.0001]

let result = fold3 polynomial 0.7 A B C
// 2.0 * (0.7   ) + 1.5 * (0.7   )^2 + 0.8    * (0.7   )^3 -> 2.4094
// 3.0 * (2.4094) + 1.0 * (2.4094)^2 + 0.01   * (2.4094)^3 -> 13.173
// 4.0 * (13.173) + 0.5 * (13.173)^2 + 0.001  * (13.173)^3 -> 141.75
// 5.0 * (141.75) + 0.2 * (141.75)^2 + 0.0001 * (141.75)^3 -> 5011.964
//
// Output: result = 5011.964

My first method is grouping the 3 lists A, B, C, into a list of tuples, and then apply list.fold

let fold3 f x A B C =
    List.map3 (fun a b c -> (a,b,c)) A B C
       |> List.fold (fun acc (a,b,c) -> f acc a b c) x

// e.g. creates [(2.0,1.5,0.8);  (3.0,1.0,0.01); ......]

My second method is to declare a mutable data, and use List.map3

let mutable result = 0.7
List.map3 (fun a b c ->
               result <- polynomial result a b c  // Change mutable data
               // Output intermediate data
               result) A B C
// Output from List.map3: [2.4094; 13.17327905; 141.7467853; 5011.963942]
// result mutable: 5011.963942

I would like to know if there are other ways to solve this problem. Thank you.

Body:
I think the existing answers provide great options if you want to generalize folding, which was your original question. However, if I simply wanted to call the polynomial function on inputs specified in A, B and C, then I would probably do not want to introduce fairly complex constructs like applicative functors with fancy operators to my code base.

The problem becomes a lot easier if you transpose the input data, so that rather than having a list [A; B; C] with lists for individual variables, you have a transposed list with inputs for calculating each polynomial. To do this, we'll need the transpose function:

let rec transpose = function
  | (_::_)::_ as M -> List.map List.head M :: transpose (List.map List.tail M)
  | _ -> []

Now you can create a list with inputs, transpose it and calculate all polynomials simply using List.map:

transpose [A; B; C]
|> List.map (function
  | [a; b; c] -> polynomial 0.7 a b c
  | _ -> failwith "wrong number of arguments")


问:
How to swap values (array, int) in nodes? - C language
I'd like to swap values in these two nodes - especially char name[30] . I used strcpy, but it shows me: "overlapping memory".

```<code>typedef struct node {
    char name[30];
    int points;
} LISTnode;

    int main() {

        LISTnode *p, *t;
        p = (LISTnode*)malloc(sizeof(LISTnode));
        t = (LISTnode*)malloc(sizeof(LISTnode));

        p->points = 30;
        t->points = 20;
        strcpy( p->name, "Peter" );
        strcpy( t->name, "Thomas" );

        return 0;
    }
</code>```

答:
Here you are.

```<code>#include <stdlib.h>
#include <stdio.h>
#include <string.h>

typedef struct node {
    char name[30];
    int points;
} LISTnode;

void swap( LISTnode *a, LISTnode *b )
{
    LISTnode tmp = *a;

    *a = *b;
    *b = tmp;
}

int main(void)
{
    LISTnode *p, *t;
    p = (LISTnode*)malloc(sizeof(LISTnode));
    t = (LISTnode*)malloc(sizeof(LISTnode));

    p->points = 30;
    t->points = 20;
    strcpy( p->name, "Peter" );
    strcpy( t->name, "Thomas" );

    printf( "*p = { %d, %s }\n", p->points, p->name );
    printf( "*t = { %d, %s }\n", t->points, t->name );

    putchar( '\n' );

    swap( p, t );

    printf( "*p = { %d, %s }\n", p->points, p->name );
    printf( "*t = { %d, %s }\n", t->points, t->name );

    free( p );
    free( t );

    return 0;
}
</code>```

The program output is

```<code>*p = { 30, Peter }
*t = { 20, Thomas }

*p = { 20, Thomas }
*t = { 30, Peter }
</code>```

Body:
I'd like to swap values in these two nodes - especially char name[30] . I used strcpy, but it shows me: "overlapping memory".

typedef struct node {
    char name[30];
    int points;
} LISTnode;

    int main() {

        LISTnode *p, *t;
        p = (LISTnode*)malloc(sizeof(LISTnode));
        t = (LISTnode*)malloc(sizeof(LISTnode));

        p->points = 30;
        t->points = 20;
        strcpy( p->name, "Peter" );
        strcpy( t->name, "Thomas" );

        return 0;
    }

Body:
Here you are.

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

typedef struct node {
    char name[30];
    int points;
} LISTnode;

void swap( LISTnode *a, LISTnode *b )
{
    LISTnode tmp = *a;

    *a = *b;
    *b = tmp;
}

int main(void)
{
    LISTnode *p, *t;
    p = (LISTnode*)malloc(sizeof(LISTnode));
    t = (LISTnode*)malloc(sizeof(LISTnode));

    p->points = 30;
    t->points = 20;
    strcpy( p->name, "Peter" );
    strcpy( t->name, "Thomas" );

    printf( "*p = { %d, %s }\n", p->points, p->name );
    printf( "*t = { %d, %s }\n", t->points, t->name );

    putchar( '\n' );

    swap( p, t );

    printf( "*p = { %d, %s }\n", p->points, p->name );
    printf( "*t = { %d, %s }\n", t->points, t->name );

    free( p );
    free( t );

    return 0;
}

The program output is

*p = { 30, Peter }
*t = { 20, Thomas }

*p = { 20, Thomas }
*t = { 30, Peter }


问:
Cannot find name 'require' after upgrading to Angular4
I want to use Chart.js within my Angular project.
In previous Angular2 versions, I have been doing this well by using a 'chart.loader.ts' which has:

```<code>export const { Chart } = require('chart.js');
</code>```

Then in the component code I just

```<code>import { Chart } from './chart.loader';
</code>```

But after upgrading to cli 1.0.0 and Angular 4, I get the error: "Cannot find name 'require'".

To reproduce the error:

```<code>ng new newapp
cd newapp
npm install chart.js --save
echo "export const { Chart } = require('chart.js');" >> src/app/chart.loader.ts
ng serve
</code>```

In my 'tsconfig.json', I have

```<code>"typeRoots": [
  "node_modules/@types"
],
</code>```

And in 'node_modules/@types/node/index.d.ts' there is:

```<code>declare var require: NodeRequire;
</code>```

So I'm confused.

BTW, I constantly encounter the warning:

```<code>[tslint] The selector of the component "OverviewComponent" should have prefix "app"(component-selector)
</code>```

Though I have set the "prefix": "" in my '.angular-cli.json'. Could it because changing from 'angular-cli.json' to '.angular-cli.json' the cause?

答:
Still not sure the answer, but a possible workaround is</p>

```<code>import * as Chart from 'chart.js';
</code>```

Body:
I want to use Chart.js within my Angular project.
In previous Angular2 versions, I have been doing this well by using a 'chart.loader.ts' which has:

export const { Chart } = require('chart.js');

Then in the component code I just

import { Chart } from './chart.loader';

But after upgrading to cli 1.0.0 and Angular 4, I get the error: "Cannot find name 'require'".

To reproduce the error:

ng new newapp
cd newapp
npm install chart.js --save
echo "export const { Chart } = require('chart.js');" >> src/app/chart.loader.ts
ng serve

In my 'tsconfig.json', I have

"typeRoots": [
  "node_modules/@types"
],

And in 'node_modules/@types/node/index.d.ts' there is:

declare var require: NodeRequire;

So I'm confused.

BTW, I constantly encounter the warning:

[tslint] The selector of the component "OverviewComponent" should have prefix "app"(component-selector)

Though I have set the "prefix": "" in my '.angular-cli.json'. Could it because changing from 'angular-cli.json' to '.angular-cli.json' the cause?

Body:
Still not sure the answer, but a possible workaround is

import * as Chart from 'chart.js';


问:
Return RESTful/json response instead of login form in Spring boot OAUTH2
I'm struggling to return a json response when the user is nog logged in, instead of returning a html login form.

The application is only using @RestController's and I do not want any web support.

```<code>    http
        .authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .and()
                .httpBasic().disable();
</code>```

When I do a get request using the browser or postman, I receive back the default spring HTML login form.

```<code>security.basic.enabled=true
</code>```

I'm using OATH2, and when I request a token it works great and I get a response like this:

```<code>{
  "access_token": "227803d1-fe94-4e31-b496-3a03bafb9479",
  "token_type": "bearer",
  "refresh_token": "322f4ee9-4c48-4e06-a129-f4b6af93d664",
  "expires_in": 43199,
  "scope": "read write"
}
</code>```

Somehow, it works correct in this example:

https://github.com/royclarkson/spring-rest-service-oauth

And when I'm not authorized, I want back something like this:

```<code>{
  "error": "unauthorized",
  "error_description": "An Authentication object was not found in the SecurityContext"
}
</code>```

But I'm getting a login form, and I want the response above. What am I doing wrong? I litterally can't uderstand why it works in the GitHub example, and not in my case. Is there a way to completely disable the login form, and force the json response?

答:
AuthenticationEntryPoint is used for exception handling in spring security.

If you have added the oauth2 to your pom, you can use OAuth2AuthenticationEntryPoint for you entry point, the Entry point is for spring security exception handling, if you are using the basic for your authentication, you can config like this

```<code>http
  .httpBasic().authenticationEntryPoint(getCustomerEntryPoint());

@Bean
protected AuthenticationEntryPoint getCustomerEntryPoint() {
    return new OAuth2AuthenticationEntryPoint();
}
</code>```

as you can see the exception handling in OAuth2AuthenticationEntryPoint

```<code>// Try to extract a SpringSecurityException from the stacktrace
    Throwable[] causeChain = throwableAnalyzer.determineCauseChain(e);
    Exception ase = (OAuth2Exception) throwableAnalyzer.getFirstThrowableOfType(
            OAuth2Exception.class, causeChain);

    if (ase != null) {
        return handleOAuth2Exception((OAuth2Exception) ase);
    }

    ase = (AuthenticationException) throwableAnalyzer.getFirstThrowableOfType(AuthenticationException.class,
            causeChain);
    if (ase != null) {
        return handleOAuth2Exception(new UnauthorizedException(e.getMessage(), e));
    }

    ase = (AccessDeniedException) throwableAnalyzer
            .getFirstThrowableOfType(AccessDeniedException.class, causeChain);
    if (ase instanceof AccessDeniedException) {
        return handleOAuth2Exception(new ForbiddenException(ase.getMessage(), ase));
    }

    ase = (HttpRequestMethodNotSupportedException) throwableAnalyzer
            .getFirstThrowableOfType(HttpRequestMethodNotSupportedException.class, causeChain);
    if (ase instanceof HttpRequestMethodNotSupportedException) {
        return handleOAuth2Exception(new MethodNotAllowed(ase.getMessage(), ase));
    }

    return handleOAuth2Exception(new ServerErrorException(e.getMessage(), e));
</code>```

it will try to get OAuth2Exception, AuthenticationException, AccessDeniedException in order, I think you can use this.

And you can also config the ExceptionTranslationFilter, this filter is in the spring security chain, and it will catch and handler the exception after it, like AuthenticationException, AccessDeniedException, and it is main entry point and will be helpful for most authentication method, like FormLogin.

```<code>http
  .exceptionHandling().authenticationEntryPoint(getCustomerEntryPoint());
</code>```

If you are not use the spring oauth2, now you understand the AuthenticationEntryPoint, so you can also implement you own AuthenticationEntryPoint and custom your exception response, just overrider the commence method, like

BasicAuthenticationEntryPoint: it will return 'WWW-Authenticate' header
LoginUrlAuthenticationEntryPoint: it will redirect to target url when no authentcation

Body:
I'm struggling to return a json response when the user is nog logged in, instead of returning a html login form.

The application is only using @RestController's and I do not want any web support.

    http
        .authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .and()
                .httpBasic().disable();

When I do a get request using the browser or postman, I receive back the default spring HTML login form.

security.basic.enabled=true

I'm using OATH2, and when I request a token it works great and I get a response like this:

{
  "access_token": "227803d1-fe94-4e31-b496-3a03bafb9479",
  "token_type": "bearer",
  "refresh_token": "322f4ee9-4c48-4e06-a129-f4b6af93d664",
  "expires_in": 43199,
  "scope": "read write"
}

Somehow, it works correct in this example:

https://github.com/royclarkson/spring-rest-service-oauth

And when I'm not authorized, I want back something like this:

{
  "error": "unauthorized",
  "error_description": "An Authentication object was not found in the SecurityContext"
}

But I'm getting a login form, and I want the response above. What am I doing wrong? I litterally can't uderstand why it works in the GitHub example, and not in my case. Is there a way to completely disable the login form, and force the json response?

Body:
AuthenticationEntryPoint is used for exception handling in spring security.

If you have added the oauth2 to your pom, you can use OAuth2AuthenticationEntryPoint for you entry point, the Entry point is for spring security exception handling, if you are using the basic for your authentication, you can config like this

http
  .httpBasic().authenticationEntryPoint(getCustomerEntryPoint());

@Bean
protected AuthenticationEntryPoint getCustomerEntryPoint() {
    return new OAuth2AuthenticationEntryPoint();
}

as you can see the exception handling in OAuth2AuthenticationEntryPoint

// Try to extract a SpringSecurityException from the stacktrace
    Throwable[] causeChain = throwableAnalyzer.determineCauseChain(e);
    Exception ase = (OAuth2Exception) throwableAnalyzer.getFirstThrowableOfType(
            OAuth2Exception.class, causeChain);

    if (ase != null) {
        return handleOAuth2Exception((OAuth2Exception) ase);
    }

    ase = (AuthenticationException) throwableAnalyzer.getFirstThrowableOfType(AuthenticationException.class,
            causeChain);
    if (ase != null) {
        return handleOAuth2Exception(new UnauthorizedException(e.getMessage(), e));
    }

    ase = (AccessDeniedException) throwableAnalyzer
            .getFirstThrowableOfType(AccessDeniedException.class, causeChain);
    if (ase instanceof AccessDeniedException) {
        return handleOAuth2Exception(new ForbiddenException(ase.getMessage(), ase));
    }

    ase = (HttpRequestMethodNotSupportedException) throwableAnalyzer
            .getFirstThrowableOfType(HttpRequestMethodNotSupportedException.class, causeChain);
    if (ase instanceof HttpRequestMethodNotSupportedException) {
        return handleOAuth2Exception(new MethodNotAllowed(ase.getMessage(), ase));
    }

    return handleOAuth2Exception(new ServerErrorException(e.getMessage(), e));

it will try to get OAuth2Exception, AuthenticationException, AccessDeniedException in order, I think you can use this.

And you can also config the ExceptionTranslationFilter, this filter is in the spring security chain, and it will catch and handler the exception after it, like AuthenticationException, AccessDeniedException, and it is main entry point and will be helpful for most authentication method, like FormLogin.

http
  .exceptionHandling().authenticationEntryPoint(getCustomerEntryPoint());

If you are not use the spring oauth2, now you understand the AuthenticationEntryPoint, so you can also implement you own AuthenticationEntryPoint and custom your exception response, just overrider the commence method, like

BasicAuthenticationEntryPoint: it will return 'WWW-Authenticate' header
LoginUrlAuthenticationEntryPoint: it will redirect to target url when no authentcation


问:
Wildfly - Allow connections to SSL sites without certs
Is there a way for a web application to be configured (through web.xml) to allow connections to SSL sites withour certificates similar to curl's -k option?

-k, --insecure      Allow connections to SSL sites without certs (H)

e.g. using curl we can do this:

```<code># curl -vk --data "appip=adsfa123&login=testt@jelastic.com&password=adfas1123" https://app.sample-jelastic-server.com/1.0/users/authentication/cross/signin
</code>```

My problem is that my web application is not able to access sites with HTTPS from within the container (or from server).

It is throwing this error:

at
  io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
  at
  io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)
  at
  io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)

With this, I think if we can configure the web.xml to allow connections to SSL site without certs then that should fix that.

答:
You need to add the following in the standalone.conf file.

JAVA_OPTS="$JAVA_OPTS -Djavax.net.ssl.trustStore=/<Path>/conf/xyz.keystore -Djavax.net.ssl.trustStorePassword=password"

In the xyz.keystore, add the certificates of the application you are trying to invoke. The system keystore is automatically added by the wildfly.

You can debug the ssl request and response you can add another configuration to the wildfly start up -Djavax.net.debug=all more on it here

Body:
Is there a way for a web application to be configured (through web.xml) to allow connections to SSL sites withour certificates similar to curl's -k option?

-k, --insecure      Allow connections to SSL sites without certs (H)

e.g. using curl we can do this:

# curl -vk --data "appip=adsfa123&login=testt@jelastic.com&password=adfas1123" https://app.sample-jelastic-server.com/1.0/users/authentication/cross/signin

My problem is that my web application is not able to access sites with HTTPS from within the container (or from server).

It is throwing this error:

at
  io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
  at
  io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)
  at
  io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)

With this, I think if we can configure the web.xml to allow connections to SSL site without certs then that should fix that.