问:
How to make UWP apps compatible with windows 8.1
I have installed Visual studio 2017 and Visual studio 2015.

Using visual studio 2015 I am able to create Xamarin.winphone projects and I am able to run this app on windows 8,8.1,10

Using visual studio 2017 I am able to create Xamarin.uwp projects and while Creating it I would like to support windows 8 as well .. but in minimum version I am not able to find it

答:
Using visual studio 2017 I am able to create Xamarin.uwp projects and while Creating it I would like to support windows 8 as well .. but in minimum version I am not able to find it

The solution with windows 8 client project has no longer been supported by Xamarin template. But you could add windows 8 client project manually. Please   follow Adding a Windows Phone App.

It is xamarin native PCL project in your screenshot. The PCL project is a protable library referenced by each native platforms. You could also add a new windowsphone native project that reference PCL project. Please refer to the following steps.

Create a cross platform app.

Add a new WindowsPhone native project that reference PCL project.

Please notice that you could not use Xamrin.Forms control in your native project. For example you could not use Entry in "myproject.IOS" , it is suitable to use UITextField.

```<code>public ViewController(IntPtr handle) : base(handle)
{
     UITextField textInPut = new UITextField();
     textInPut.Frame = new CGRect(0, 0, 120, 44);
     textInPut.Text = "Xamarin IOS Native ";
     View.AddSubview(textInPut);
}
</code>```

The code sample has uploaded to github. Please check.

Body:
Using visual studio 2017 I am able to create Xamarin.uwp projects and while Creating it I would like to support windows 8 as well .. but in minimum version I am not able to find it

The solution with windows 8 client project has no longer been supported by Xamarin template. But you could add windows 8 client project manually. Please   follow Adding a Windows Phone App.

It is xamarin native PCL project in your screenshot. The PCL project is a protable library referenced by each native platforms. You could also add a new windowsphone native project that reference PCL project. Please refer to the following steps.

Create a cross platform app.

Add a new WindowsPhone native project that reference PCL project.

Please notice that you could not use Xamrin.Forms control in your native project. For example you could not use Entry in "myproject.IOS" , it is suitable to use UITextField.

public ViewController(IntPtr handle) : base(handle)
{
     UITextField textInPut = new UITextField();
     textInPut.Frame = new CGRect(0, 0, 120, 44);
     textInPut.Text = "Xamarin IOS Native ";
     View.AddSubview(textInPut);
}

The code sample has uploaded to github. Please check.


来源: stackexchange

问:
How can I convert a md5 hash to an integral type in Java?
I am trying to convert a md5 hash to a long like I can in python,

```<code>>>> int(hashlib.md5("abc").hexdigest(),16)
191415658344158766168031473277922803570L
</code>```

When I digest "abc", I get (in Hex): "0X900150983CD24FB0D6963F7D28E17F72"

What is the correct way to do this hash conversion in Java?

```<code>public static void main(String[] args) {
    byte[] md5hex = DigestUtils.md5("abc");
    String hex = new String(Hex.encodeHex(md5hex));
    System.out.println(hex);
    long lv = Long.parseLong("0X" + hex.toUpperCase(), 16);
    System.out.println(lv);
    int hext = Integer.parseInt("12346789", 16);
    System.out.println(hext);
}
</code>```

答:
First, let's take a good hex encoder like the one in this answer from maybeWeCouldStealAVan

```<code>private final static char[] hexArray = "0123456789ABCDEF".toCharArray();

public static String bytesToHex(byte[] bytes) {
    char[] hexChars = new char[bytes.length * 2];
    for (int j = 0; j < bytes.length; j++) {
        int v = bytes[j] & 0xFF;
        hexChars[j * 2] = hexArray[v >>> 4];
        hexChars[j * 2 + 1] = hexArray[v & 0x0F];
    }
    return new String(hexChars);
}
</code>```

Then use MessageDigest and BigInteger (an arbitrary precision integer type, which is what your python code is using)

```<code>public static void main(String[] args) {
    try {
        byte[] md5hex = MessageDigest.getInstance("MD5").digest("abc".getBytes());
        System.out.println(new BigInteger(bytesToHex(md5hex), 16));
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
}
</code>```

and I get

```<code>191415658344158766168031473277922803570
</code>```

Also, if you do

```<code>System.out.println(bytesToHex(md5hex));
</code>```

I too get

```<code>900150983cd24fb0d6963f7d28e17f72
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to convert a md5 hash to a long like I can in python,

>>> int(hashlib.md5("abc").hexdigest(),16)
191415658344158766168031473277922803570L

When I digest "abc", I get (in Hex): "0X900150983CD24FB0D6963F7D28E17F72"

What is the correct way to do this hash conversion in Java?

public static void main(String[] args) {
    byte[] md5hex = DigestUtils.md5("abc");
    String hex = new String(Hex.encodeHex(md5hex));
    System.out.println(hex);
    long lv = Long.parseLong("0X" + hex.toUpperCase(), 16);
    System.out.println(lv);
    int hext = Integer.parseInt("12346789", 16);
    System.out.println(hext);
}

Body:
First, let's take a good hex encoder like the one in this answer from maybeWeCouldStealAVan

private final static char[] hexArray = "0123456789ABCDEF".toCharArray();

public static String bytesToHex(byte[] bytes) {
    char[] hexChars = new char[bytes.length * 2];
    for (int j = 0; j < bytes.length; j++) {
        int v = bytes[j] & 0xFF;
        hexChars[j * 2] = hexArray[v >>> 4];
        hexChars[j * 2 + 1] = hexArray[v & 0x0F];
    }
    return new String(hexChars);
}

Then use MessageDigest and BigInteger (an arbitrary precision integer type, which is what your python code is using)

public static void main(String[] args) {
    try {
        byte[] md5hex = MessageDigest.getInstance("MD5").digest("abc".getBytes());
        System.out.println(new BigInteger(bytesToHex(md5hex), 16));
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
}

and I get

191415658344158766168031473277922803570

Also, if you do

System.out.println(bytesToHex(md5hex));

I too get

900150983cd24fb0d6963f7d28e17f72


问:
Linux USB: turning the power on and off?
How can I programmatically enable and disable the power to a particular USB port on Linux? Is such a thing even possible? Mac answers appreciated as well!

I was trying for a BOC (don't pretend you weren't try to get one too!) and ended up with one of these, and would like to get some use out of the thing by hooking it up to our server monitor.

答:
Don't buy an expensive smart hub just for turning USB gadgets on and off.

All you need is a microcontroller.

Arduino Nano™  ATmega328 *

The Nano is a 16MHz 8-bit computer with 2K RAM and 32K of flash storage.

It has 22 programmable pins (8 analog and 14  digital).

It can read/write USB, and is powered by its 5.0V microUSB port (up to 12.0V external).

```<code>// USB Blinker
// Blink LED while receiving USB stream
//
// For Arduino Nano™

int LED = 13;

// setup() is run once at powerup or when reset button is pressed
//
void setup() {
        pinMode(LED, OUTPUT);   // Configure pin D13 as output
        Serial.begin(9600);     // Open 9600bps USB stream
}

// loop() runs forever at 16Mhz, blinking the LED at 1Hz when receiving USB data.
//
void loop() {
        if (Serial.available() > 0) {           // When stream is buffering
                digitalWrite(LED, HIGH);        //   turn on LED
                delay(500);                     //   wait half second
                digitalWrite(LED, LOW);         //   turn off LED
                delay(500);                     //   wait half second
                while (Serial.available() > 0)  //   drain the buffer
                        Serial.read();
         }
}
</code>```

Exquisite tiny cases are available (also free 3d printables).

C4Labs Zebra Black Ice Case

* Use Genuine Arduino Nano™ only. Beware of counterfeits.

UPDATE: Miniaturised ATtiny and wireless microcontollers are also available.

ContentLicense: CC BY-SA 4.0

Body:
Don't buy an expensive smart hub just for turning USB gadgets on and off.

All you need is a microcontroller.

Arduino Nano™  ATmega328 *

The Nano is a 16MHz 8-bit computer with 2K RAM and 32K of flash storage.

It has 22 programmable pins (8 analog and 14  digital).

It can read/write USB, and is powered by its 5.0V microUSB port (up to 12.0V external).

// USB Blinker
// Blink LED while receiving USB stream
//
// For Arduino Nano™

int LED = 13;

// setup() is run once at powerup or when reset button is pressed
//
void setup() {
        pinMode(LED, OUTPUT);   // Configure pin D13 as output
        Serial.begin(9600);     // Open 9600bps USB stream
}

// loop() runs forever at 16Mhz, blinking the LED at 1Hz when receiving USB data.
//
void loop() {
        if (Serial.available() > 0) {           // When stream is buffering
                digitalWrite(LED, HIGH);        //   turn on LED
                delay(500);                     //   wait half second
                digitalWrite(LED, LOW);         //   turn off LED
                delay(500);                     //   wait half second
                while (Serial.available() > 0)  //   drain the buffer
                        Serial.read();
         }
}

Exquisite tiny cases are available (also free 3d printables).

C4Labs Zebra Black Ice Case

* Use Genuine Arduino Nano™ only. Beware of counterfeits.

UPDATE: Miniaturised ATtiny and wireless microcontollers are also available.


问:
fatal error: unexpectedly found nil while unwrapping an Optional value
I am trying to run this code but I keep on getting this error:

fatal error: unexpectedly found nil while unwrapping an Optional value

I don't understand what it means or why I'm getting it. Any hint?

```<code>import UIKit

class ViewController: UIViewController {

var lastNumber: String = ""
@IBOutlet var answerField: UILabel
@IBOutlet var operaterLabel: UILabel

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func buttonTapped(theButton: UIButton) {
    if answerField.text == "0"
    {
        answerField.text = theButton.titleLabel.text
    }
    else
    {
        answerField.text = answerField.text + theButton.titleLabel.text
    }
}

@IBAction func plusTapped(theButton: UIButton) {
    // error is talking about the next line
    if operaterLabel.text == ""
    {
        operaterLabel.text = "+"
        lastNumber = answerField.text
        answerField.text = "0"
    }
    else
    {
        enterTapped(nil)
        operaterLabel.text = "+"
    }

}

@IBAction func minusTapped(theButton: UIButton) {
    if operaterLabel.text == ""
    {
        operaterLabel.text = "-"
        lastNumber = answerField.text
        answerField.text = "0"
    }
    else
    {
        enterTapped(nil)
        operaterLabel.text = "-"
    }

}

@IBAction func clearTapped(AnyObject) {
    answerField.text = "0"
    operaterLabel.text = ""
    lastNumber = ""

}

@IBAction func enterTapped(AnyObject?) {

    var num1 = lastNumber.toInt()
    var num2 = answerField.text.toInt()
    if !num1 || !num2
    {
        showError()
        return
    }
    var answer = 0
    if operaterLabel.text == "-"
    {
        var answer = num1! - num2!
    }
    else if operaterLabel.text == "+"
    {
        var answer = num1! + num2!
    }
    else
    {
        showError()
        return
    }
    answerField.text = "\(answer)"

}

func showError()
{
    println("Ther was an error")
}
}
</code>```

答:
This error usually occurs because we try to change UILabel text after the view is loaded. Remember that UILabels once loaded in the view cannot be changed in any way they can only be set within viewdidload() function. You can check this by putting your text assigning code in the viewDidLoad() function which will set UILabels when loading the view, It will work.
But now if your application is built in such a way that it is setting UILabels after the view is loaded then the only solution is that you will need to create UILabels dynamically/Programatically where ever you want in the code and assign what ever you want because they will be created/instantiated with that text/label. </p>

Body:
I am trying to run this code but I keep on getting this error:

fatal error: unexpectedly found nil while unwrapping an Optional value

I don't understand what it means or why I'm getting it. Any hint?

import UIKit

class ViewController: UIViewController {

var lastNumber: String = ""
@IBOutlet var answerField: UILabel
@IBOutlet var operaterLabel: UILabel

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func buttonTapped(theButton: UIButton) {
    if answerField.text == "0"
    {
        answerField.text = theButton.titleLabel.text
    }
    else
    {
        answerField.text = answerField.text + theButton.titleLabel.text
    }
}

@IBAction func plusTapped(theButton: UIButton) {
    // error is talking about the next line
    if operaterLabel.text == ""
    {
        operaterLabel.text = "+"
        lastNumber = answerField.text
        answerField.text = "0"
    }
    else
    {
        enterTapped(nil)
        operaterLabel.text = "+"
    }

}

@IBAction func minusTapped(theButton: UIButton) {
    if operaterLabel.text == ""
    {
        operaterLabel.text = "-"
        lastNumber = answerField.text
        answerField.text = "0"
    }
    else
    {
        enterTapped(nil)
        operaterLabel.text = "-"
    }

}

@IBAction func clearTapped(AnyObject) {
    answerField.text = "0"
    operaterLabel.text = ""
    lastNumber = ""

}

@IBAction func enterTapped(AnyObject?) {

    var num1 = lastNumber.toInt()
    var num2 = answerField.text.toInt()
    if !num1 || !num2
    {
        showError()
        return
    }
    var answer = 0
    if operaterLabel.text == "-"
    {
        var answer = num1! - num2!
    }
    else if operaterLabel.text == "+"
    {
        var answer = num1! + num2!
    }
    else
    {
        showError()
        return
    }
    answerField.text = "\(answer)"

}

func showError()
{
    println("Ther was an error")
}
}


问:
MySQL - sort on condition
I am working on a problem that will sort my output by following rules:

if g.grade>8, then

```<code>order by g.grade asc, s.name asc
</code>```

if g.grade <=8, then

```<code>order by g.grade desc, s.marks asc
</code>```

How to do this?

答:
Use case when:

```<code>ORDER BY CASE WHEN g.grade > 8 THEN g.grade ELSE (0 - g.grade) END asc,
         CASE WHEN g.grade > 8 THEN s.name ELSE s.marks END asc
</code>```

Title: MySQL - sort on condition

Body:
I am working on a problem that will sort my output by following rules:

if g.grade>8, then

order by g.grade asc, s.name asc

if g.grade <=8, then

order by g.grade desc, s.marks asc

How to do this?

Body:
Use case when:

ORDER BY CASE WHEN g.grade > 8 THEN g.grade ELSE (0 - g.grade) END asc,
         CASE WHEN g.grade > 8 THEN s.name ELSE s.marks END asc


问:
How to create a truly blank project in Visual Studio (2017)
It seems like there should be a way to do this, but I just can't seem to do it. I love VS and I want to use it to develop web apps that are strictly HTML/Javascript based. In other words, no C#, no VB, no resulting /bin folder, no web config, no nothing. A blank project meaning "truly 100% blank" and not trying force me into some Microsoft technology or otherwise. I just want to use VS to write the code because it's still the best HTML/Javascript/Typescript/Everything-else-script editor out there.

Any thoughts on this? Can it even be done? Or is VS just too dependent on "Microsoft thinking" to allow this?

答: I haven't heard or found a template online that will do this. I'm assuming you meant just HTML, JS/TypeScript, CSS/SASS etc. without .NET for "truly blank". Me I just delete the files I don't use :)</p>


问:
ProcessStartInfo does not contain a definition for 'Verb'
I do have this issue whereby ProcessStartInfo does not contain definition verb so i can not do 'runas'. On VisualStudio 2015 a project 'foo' that uses ProcessStartInfo does have this definition 'verb' - confirmed by examining the class. Other project running on VisualStudio 2017 does NOT seem to recognize this method. Moreover, the method is missing from the class itself. Now i am not sure why and how this is possible?

Full error code:

```<code>Severity    Code    Description Project File    Line    Suppression State
Error   CS1061  'ProcessStartInfo' does not contain a definition for 'Verb'
and no extension method 'Verb' accepting a first argument of type
'ProcessStartInfo' could be found (are you missing a using directive or an
assembly reference?)    project3cx  C:\Users\Boss\Documents\Visual Studio
2017\Projects\project\project3cx\Program.cs 64  Active
</code>```

The only difference between ProcessStartInfo class is that the version 4.0.0.0

```<code>#region Assembly System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
// C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5.2\System.dll
#endregion
</code>```

Does have definition 'verb' and version 4.1.0.0 does not have defitnion verb.

```<code>#region Assembly System.Diagnostics.Process, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
// C:\Users\Boss\.nuget\packages\system.diagnostics.process\4.3.0\ref\netstandard1.4\System.Diagnostics.Process.dll
#endregion
</code>```

I can also see that one project assembly is managed by nuget, the other is not. I have installed/updated nuget System.Diagnostics package but to no avail. Any help ?

答:
The only difference between ProcessStartInfo class is that the version 4.0.0.0. Does have definition 'verb' and version 4.1.0.0 does not have defitnion verb.

Just as Hans commented, you need to "Pay attention to the project template you selected". I repeat the answer here  more detail so that other community members who get the same issues can find the answer more easily.

According to the reply to the question on GitHub, the ProcessStartInfo.Verb is not supported on .NET Core/.NET Standard:

I've tagged it as a bug since this API shouldn't be showing up in our docs since it's not supported on .NET Core. It needs to be deleted from the article. @chenkennt, @bradygaster another case of APIs that are not really part of .NET Core showing up on docs.

Besides, both Verb as well as Verbs are coming back as part of .NE Standard 2.0.

Body:
I do have this issue whereby ProcessStartInfo does not contain definition verb so i can not do 'runas'. On VisualStudio 2015 a project 'foo' that uses ProcessStartInfo does have this definition 'verb' - confirmed by examining the class. Other project running on VisualStudio 2017 does NOT seem to recognize this method. Moreover, the method is missing from the class itself. Now i am not sure why and how this is possible?

Full error code:

Severity    Code    Description Project File    Line    Suppression State
Error   CS1061  'ProcessStartInfo' does not contain a definition for 'Verb'
and no extension method 'Verb' accepting a first argument of type
'ProcessStartInfo' could be found (are you missing a using directive or an
assembly reference?)    project3cx  C:\Users\Boss\Documents\Visual Studio
2017\Projects\project\project3cx\Program.cs 64  Active

The only difference between ProcessStartInfo class is that the version 4.0.0.0

#region Assembly System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
// C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5.2\System.dll
#endregion

Does have definition 'verb' and version 4.1.0.0 does not have defitnion verb.

#region Assembly System.Diagnostics.Process, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
// C:\Users\Boss\.nuget\packages\system.diagnostics.process\4.3.0\ref\netstandard1.4\System.Diagnostics.Process.dll
#endregion

I can also see that one project assembly is managed by nuget, the other is not. I have installed/updated nuget System.Diagnostics package but to no avail. Any help ?


问:
Is this common practice to avoid key not found in a dictionary
I was wondering, whether the following style is a common practice to avoid key not found in a dictionary?</p>

```<code># default is 0
value = my_dic[100] if 100 in my_dic else 0
</code>```

答:
If you need the "default value" everywhere, consider defaultdict as a possible alternative. (A factory/callback approach offers a good bit of flexibility with the "default value".)

Happy coding.

ContentLicense: CC BY-SA 2.5

Body:
I was wondering, whether the following style is a common practice to avoid key not found in a dictionary?

# default is 0
value = my_dic[100] if 100 in my_dic else 0


问:
UrlHelper.Link returns undesired parameters
If I call UrlHelper.Link within an API call which has a parameter matching an optional parameter of the API endpoint I'm attempting to obtain an URL for, UrlHelper.Link returns a URL with values from the current request no matter how I try to exclude the optional parameter from the link.

e.g.

```<code>[HttpGet]
[Route("api/Test/Stuff/{id}")]
public async Task<IHttpActionResult> GetStuff(int id) // id = 78
{
    string link = Url.Link("Mary", new
    {
        first = "Hello",
        second = "World"
    });

    string link2 = Url.Link("Mary", new
    {
        first = "Hello",
        second = "World",
        id = (int?)null
    });

    string link3 = Url.Link("Mary", new
    {
        first = "Hello",
        second = "World",
        id = ""
    });

    return Ok(new
    {
        link,
        link2,
        link3
    });
}

[HttpGet]
[Route("api/Test/Another/{first}", Name = "Mary")]
public async Task<IHttpActionResult> AnotherMethod(
[FromUri]string first,
[FromUri]string second = null,
[FromUri]int? id = null)
{
    // Stuff
    return Ok();
}
</code>```

GET http://localhost:53172/api/Test/Stuff/8

returns

```<code>{
  "link": "http://localhost:53172/api/Test/Another/Hello?second=World",
  "link2": "http://localhost:53172/api/Test/Another/Hello?second=World&id=8",
  "link3": "http://localhost:53172/api/Test/Another/Hello?second=World&id=8"
}
</code>```

How do you get Url.Link to actually use the values you pass it rather than pull it from the current api request when they are not presented or assigned to null or empty string?

I believe the issue is very similar to ....

UrlHelper.Action includes undesired additional parameters

But this is Web API not MVC, not an action and the answers provided do not seem to yield an obvious solution to this issue.

EDIT: I've updated the code as the original code didn't actually replicate the issue.  I've also included a request URL and the response returned, which I've tested.  Whilst this code demonstrates the issue, the code I'm trying to find a fix for is not passing an anonymous type to UrlHelper, instead its a class which generates a timestamp and hash and has 4 optional parameters. If there's another solution which doesn't require omitting the optional parameters in the structure passed to UrlHelper I'd like to have it, as it'll save me from making a lot of changes to the code.

答:
Do not include the id when passing the route values. In fact it should not allow you to compile as

Cannot assign <null> to anonymous type property

```<code>public async Task<IHttpActionResult> GetStuff(int id) // id = 78 {
    string myUrl = Url.Link(
        "Mary",
        new
        {
            first = "Hello World"
        });

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

Tested with web api 2 and id was not included when linking to other action.

```<code>[RoutePrefix("api/urlhelper")]
public class UrlHeplerController : ApiController {

    [HttpGet]
    [Route("")]
    public IHttpActionResult GetStuff(int id) {
        string myUrl = Url.Link(
            "Mary",
            new {
                first = "Hello World",
           });
        return Ok(myUrl);
    }

    [HttpGet]
    [Route(Name = "Mary")]
    public IHttpActionResult AnotherMethod(
    [FromUri]string first,
    [FromUri]string second = null,
    [FromUri]int? id = null) {
        // Stuff
        return Ok();
    }
}
</code>```

Calling

```<code>client.GetAsync("/api/urlhelper?id=78")
</code>```

routed to the GetStuff action and the link generated

```<code>"http://localhost/api/urlhelper?first=Hello%20World"
</code>```

Even when tested with

```<code>string myUrl = Url.Link(
    "Mary",
    new {
        first = "Hello World",
        id = ""
    });
</code>```

id was not included in the generated link.

Body:
If I call UrlHelper.Link within an API call which has a parameter matching an optional parameter of the API endpoint I'm attempting to obtain an URL for, UrlHelper.Link returns a URL with values from the current request no matter how I try to exclude the optional parameter from the link.

e.g.

[HttpGet]
[Route("api/Test/Stuff/{id}")]
public async Task<IHttpActionResult> GetStuff(int id) // id = 78
{
    string link = Url.Link("Mary", new
    {
        first = "Hello",
        second = "World"
    });

    string link2 = Url.Link("Mary", new
    {
        first = "Hello",
        second = "World",
        id = (int?)null
    });

    string link3 = Url.Link("Mary", new
    {
        first = "Hello",
        second = "World",
        id = ""
    });

    return Ok(new
    {
        link,
        link2,
        link3
    });
}

[HttpGet]
[Route("api/Test/Another/{first}", Name = "Mary")]
public async Task<IHttpActionResult> AnotherMethod(
[FromUri]string first,
[FromUri]string second = null,
[FromUri]int? id = null)
{
    // Stuff
    return Ok();
}

GET http://localhost:53172/api/Test/Stuff/8

returns

{
  "link": "http://localhost:53172/api/Test/Another/Hello?second=World",
  "link2": "http://localhost:53172/api/Test/Another/Hello?second=World&id=8",
  "link3": "http://localhost:53172/api/Test/Another/Hello?second=World&id=8"
}

How do you get Url.Link to actually use the values you pass it rather than pull it from the current api request when they are not presented or assigned to null or empty string?

I believe the issue is very similar to ....

UrlHelper.Action includes undesired additional parameters

But this is Web API not MVC, not an action and the answers provided do not seem to yield an obvious solution to this issue.

EDIT: I've updated the code as the original code didn't actually replicate the issue.  I've also included a request URL and the response returned, which I've tested.  Whilst this code demonstrates the issue, the code I'm trying to find a fix for is not passing an anonymous type to UrlHelper, instead its a class which generates a timestamp and hash and has 4 optional parameters. If there's another solution which doesn't require omitting the optional parameters in the structure passed to UrlHelper I'd like to have it, as it'll save me from making a lot of changes to the code.

Body:
Do not include the id when passing the route values. In fact it should not allow you to compile as

Cannot assign <null> to anonymous type property

public async Task<IHttpActionResult> GetStuff(int id) // id = 78 {
    string myUrl = Url.Link(
        "Mary",
        new
        {
            first = "Hello World"
        });

    //...other code
}

Tested with web api 2 and id was not included when linking to other action.

[RoutePrefix("api/urlhelper")]
public class UrlHeplerController : ApiController {

    [HttpGet]
    [Route("")]
    public IHttpActionResult GetStuff(int id) {
        string myUrl = Url.Link(
            "Mary",
            new {
                first = "Hello World",
           });
        return Ok(myUrl);
    }

    [HttpGet]
    [Route(Name = "Mary")]
    public IHttpActionResult AnotherMethod(
    [FromUri]string first,
    [FromUri]string second = null,
    [FromUri]int? id = null) {
        // Stuff
        return Ok();
    }
}

Calling

client.GetAsync("/api/urlhelper?id=78")

routed to the GetStuff action and the link generated

"http://localhost/api/urlhelper?first=Hello%20World"

Even when tested with

string myUrl = Url.Link(
    "Mary",
    new {
        first = "Hello World",
        id = ""
    });

id was not included in the generated link.


问:
Deleting String Pointers Memory in Struct
With the struct declaration:

```<code>struct Dat {
   int count; // number of files
   string *files;
   Dat(): count(0), files(nullptr) {}
   ~Dat() {
      delete[] files;
   }
}
</code>```

And then I built files like so:

```<code>buildFiles(int argc, char *argv, Dat my) {
   my.files = new string[my.count]; // my.files = new string[3]
   int filedex = 0;
   for (int i=0; i<argc; ++i) {
      if (some condition for argv[i]) { // only looking for filenames from argv
         my.files[filedex] = argv[i]; // store filename in my structure
         filedex++;
      }
   }
   if (filedex != my.count) cerr << "BAD";
}

int main (int argc, char *argv[])
{
   Dat my;
   // functions that define my.count to be non-zero, e.g. my.count = 3
   buildsFiles(argc, argv, my);
   // blahblah
   return 0;
}
</code>```

How do I now delete the dynamically allocated variables, files?
I've tried delete[] my.files and delete[] my->files but neither seem to work. I'm very new to c++ so any help would be much appreciated.

答:
Have a look at this code, which will detect memory leaks:

```<code>#include <crtdbg.h>

#define DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__)
#define new DEBUG_NEW

struct A
{
    int* num;
};

int main()
{
    A a;
    a.num = new int[10];

    delete[] a.num;

    _CrtDumpMemoryLeaks();

}
</code>```

This excerpt has no memory leaks. Because for every new[] a delete[] was called.

But if you were to comment out delete[] a.num;, then it would detect a leak:

```<code>Detected memory leaks!
Dumping objects ->main.cpp(14) : {66} normal block at 0x0000024280E47630, 40 bytes long.
 Data: <                > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
Object dump complete.
</code>```

So for every new you need one delete and for every new[] you need one delete[].

Body:
With the struct declaration:

struct Dat {
   int count; // number of files
   string *files;
   Dat(): count(0), files(nullptr) {}
   ~Dat() {
      delete[] files;
   }
}

And then I built files like so:

buildFiles(int argc, char *argv, Dat my) {
   my.files = new string[my.count]; // my.files = new string[3]
   int filedex = 0;
   for (int i=0; i<argc; ++i) {
      if (some condition for argv[i]) { // only looking for filenames from argv
         my.files[filedex] = argv[i]; // store filename in my structure
         filedex++;
      }
   }
   if (filedex != my.count) cerr << "BAD";
}

int main (int argc, char *argv[])
{
   Dat my;
   // functions that define my.count to be non-zero, e.g. my.count = 3
   buildsFiles(argc, argv, my);
   // blahblah
   return 0;
}

How do I now delete the dynamically allocated variables, files?
I've tried delete[] my.files and delete[] my->files but neither seem to work. I'm very new to c++ so any help would be much appreciated.

Body:
Have a look at this code, which will detect memory leaks:

#include <crtdbg.h>

#define DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__)
#define new DEBUG_NEW

struct A
{
    int* num;
};

int main()
{
    A a;
    a.num = new int[10];

    delete[] a.num;

    _CrtDumpMemoryLeaks();

}

This excerpt has no memory leaks. Because for every new[] a delete[] was called.

But if you were to comment out delete[] a.num;, then it would detect a leak:

Detected memory leaks!
Dumping objects ->main.cpp(14) : {66} normal block at 0x0000024280E47630, 40 bytes long.
 Data: <                > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
Object dump complete.

So for every new you need one delete and for every new[] you need one delete[].


问:
User logged in (ID), in back. Jhipster 4.1.1
In a Jhipster 4.4.1 application with Mongodb, JWT.
I need the user logged in for a query, and I do not know how I can retrieve it in a java controller (Resource)
In SecurityUtils I do not see how to get the ID

```<code>public static String getCurrentUserLogin() {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    Authentication authentication = securityContext.getAuthentication();
    String userName = null;
    if (authentication != null) {
        if (authentication.getPrincipal() instanceof UserDetails) {
            UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal();
            userName = springSecurityUser.getUsername();
        } else if (authentication.getPrincipal() instanceof String) {
            userName = (String) authentication.getPrincipal();
        }
    }
    return userName;
}
</code>```

I can capture the user ID logged in, without consulting the database.

Thank you

答:
If you need the current user, then you can query against login as given by getCurrentUserLogin() in your question because it's unique anyway.

If you really want the ID, then have a poke around AccountResource and you'll see that UserDTO and User have a .getID() method.

Body:
In a Jhipster 4.4.1 application with Mongodb, JWT.
I need the user logged in for a query, and I do not know how I can retrieve it in a java controller (Resource)
In SecurityUtils I do not see how to get the ID

public static String getCurrentUserLogin() {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    Authentication authentication = securityContext.getAuthentication();
    String userName = null;
    if (authentication != null) {
        if (authentication.getPrincipal() instanceof UserDetails) {
            UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal();
            userName = springSecurityUser.getUsername();
        } else if (authentication.getPrincipal() instanceof String) {
            userName = (String) authentication.getPrincipal();
        }
    }
    return userName;
}

I can capture the user ID logged in, without consulting the database.

Thank you


问:
Android gradle apk splits, getting versionCode & versionName in code
We start splitting APKs to reduce APK size. And we cannot figure out why the versionCode we get in code (Java) is always the default one.

Here is the relevant gradle:

```<code>defaultConfig {
    applicationId applicationIdPrefix
    versionCode 1000
    versionName "3.3.0"

// This is the configuration we want to publish
defaultPublishConfig "productionRelease"

applicationVariants.all { variant ->
  def apkName = "$projectName-${variant.name}-v${versionString}.${baseVersionCode}.apk"

  variant.outputs.each { output ->
    // Redefine the versionCode and the apkName to include ABI when available
    def abiName = output.getFilter(OutputFile.ABI)
    def baseAbiVersionCode = project.ext.abiCodes.get(abiName)

    if (baseAbiVersionCode != null) {
      output.versionCodeOverride = variant.versionCode + baseAbiVersionCode
      output.versionNameOverride = "$versionString (${output.versionCodeOverride})"
</code>```

And this is how to retrieve the versionName and versionCode:

```<code>BuildConfig.VERSION_NAME
BuildConfig.VERSION_CODE
</code>```

They are always 3.3.0 and 1000. Why? We want to get these values because we want to display them under settings.

答:
In short, changed to this and problem solved:

```<code>PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
String version = pInfo.versionName;
int verCode = pInfo.versionCode;
</code>```

This following does not gives us the correct version name and version code after we split our APK. I guess what happened is that that BuildConfig.java is generated during grade sync.

```<code>String versionName = BuildConfig.VERSION_NAME;
int versionCode = BuildConfig.VERSION_CODE;
</code>```

Maybe that’s why it is outdated and doesn’t match our actual version code, which was override with these 2 lines of gradle:

```<code>output.versionCodeOverride = variant.versionCode + baseAbiVersionCode
output.versionNameOverride = "$versionString (${output.versionCodeOverride})".
</code>```

Body:
We start splitting APKs to reduce APK size. And we cannot figure out why the versionCode we get in code (Java) is always the default one.

Here is the relevant gradle:

defaultConfig {
    applicationId applicationIdPrefix
    versionCode 1000
    versionName "3.3.0"

// This is the configuration we want to publish
defaultPublishConfig "productionRelease"

applicationVariants.all { variant ->
  def apkName = "$projectName-${variant.name}-v${versionString}.${baseVersionCode}.apk"

  variant.outputs.each { output ->
    // Redefine the versionCode and the apkName to include ABI when available
    def abiName = output.getFilter(OutputFile.ABI)
    def baseAbiVersionCode = project.ext.abiCodes.get(abiName)

    if (baseAbiVersionCode != null) {
      output.versionCodeOverride = variant.versionCode + baseAbiVersionCode
      output.versionNameOverride = "$versionString (${output.versionCodeOverride})"

And this is how to retrieve the versionName and versionCode:

BuildConfig.VERSION_NAME
BuildConfig.VERSION_CODE

They are always 3.3.0 and 1000. Why? We want to get these values because we want to display them under settings.

Body:
In short, changed to this and problem solved:

PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
String version = pInfo.versionName;
int verCode = pInfo.versionCode;

This following does not gives us the correct version name and version code after we split our APK. I guess what happened is that that BuildConfig.java is generated during grade sync.

String versionName = BuildConfig.VERSION_NAME;
int versionCode = BuildConfig.VERSION_CODE;

Maybe that’s why it is outdated and doesn’t match our actual version code, which was override with these 2 lines of gradle:

output.versionCodeOverride = variant.versionCode + baseAbiVersionCode
output.versionNameOverride = "$versionString (${output.versionCodeOverride})".


问:
invalid length for a base-64 char array or string- azure server
i have server running on azure, after hours of debugging i changed the azure to run on 64 bit machine and now when i try to encrypt or decrypt i have this error: "invalid length for a base-64 char array or string" what could it be?
(when i run local tests all works)</p>

```<code>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;

namespace Server
{
    public class Crypto
    {
        static readonly string PasswordHash = "P@@Sw0rd";
        static readonly string SaltKey = "S@LT&KEY";
        static readonly string VIKey = "@1B2c3D4e5F6g7H8";

        public static string Encrypt(string plainText)
        {
            byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

            byte[] keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8);
            var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.Zeros };
            var encryptor = symmetricKey.CreateEncryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey));

            byte[] cipherTextBytes;

            using (var memoryStream = new MemoryStream())
            {
                using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                {
                    cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                    cryptoStream.FlushFinalBlock();
                    cipherTextBytes = memoryStream.ToArray();
                    cryptoStream.Close();
                }
                memoryStream.Close();
            }

            StringBuilder crypt = new StringBuilder(Convert.ToBase64String(cipherTextBytes));
            if (crypt.Length > 0)
            {
                for (int i = 0; i < 3; i++)
                {
                    if (crypt[crypt.Length - 1 - i] == '=')
                    {
                        crypt[crypt.Length - 1 - i] = '*';
                    }
                    else break;
                }
            }
            return crypt.ToString();
        }

        public static string Decrypt(string encryptedText)
        {
            StringBuilder crypt = new StringBuilder(encryptedText);
            if (crypt.Length > 0)
            {
                for (int i = 0; i < 3; i++)
                {
                    if (crypt[crypt.Length - 1 - i] == '*')
                    {
                        crypt[crypt.Length - 1 - i] = '=';
                    }
                    else break;
                }
            }
            byte[] cipherTextBytes = Convert.FromBase64String(crypt.ToString());
            byte[] keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8);
            var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.None };

            var decryptor = symmetricKey.CreateDecryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey));
            var memoryStream = new MemoryStream(cipherTextBytes);
            var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
            byte[] plainTextBytes = new byte[cipherTextBytes.Length];

            int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
            memoryStream.Close();
            cryptoStream.Close();
            return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount).TrimEnd("\0".ToCharArray());
        }
    }
}
</code>```

答:
After tested your code on my Azure Web App(x64 platform), I found it worked good on my side. Here is my test code.

```<code>public ActionResult TestCrypto()
{
    string encryptedText = Crypto.Encrypt("123456");
    string text = "Encrypted Text : " + encryptedText + "<br/>";
    string originalText = Crypto.Decrypt(encryptedText);
    text += "Origial Text : " + originalText;
    return Content(text);
}
</code>```

Here is the result I got from server.

I suggest you test the upper code in your server and post the result.

invalid length for a base-64 char array or string

The exception often occurs when decrypting the encrypted text. If you store the encrypted text in a database, sometimes the encrypted text lost some data due to the column used to store the data doesn't have enough space. For example, the column type which you defined is nvarchar(32) and the length of encrypted text is 56 which is more than 32. Please make sure the encrypted text haven't been changed before you decrypt it.

Body:
i have server running on azure, after hours of debugging i changed the azure to run on 64 bit machine and now when i try to encrypt or decrypt i have this error: "invalid length for a base-64 char array or string" what could it be?
(when i run local tests all works)

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;

namespace Server
{
    public class Crypto
    {
        static readonly string PasswordHash = "P@@Sw0rd";
        static readonly string SaltKey = "S@LT&KEY";
        static readonly string VIKey = "@1B2c3D4e5F6g7H8";

        public static string Encrypt(string plainText)
        {
            byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

            byte[] keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8);
            var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.Zeros };
            var encryptor = symmetricKey.CreateEncryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey));

            byte[] cipherTextBytes;

            using (var memoryStream = new MemoryStream())
            {
                using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                {
                    cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                    cryptoStream.FlushFinalBlock();
                    cipherTextBytes = memoryStream.ToArray();
                    cryptoStream.Close();
                }
                memoryStream.Close();
            }

            StringBuilder crypt = new StringBuilder(Convert.ToBase64String(cipherTextBytes));
            if (crypt.Length > 0)
            {
                for (int i = 0; i < 3; i++)
                {
                    if (crypt[crypt.Length - 1 - i] == '=')
                    {
                        crypt[crypt.Length - 1 - i] = '*';
                    }
                    else break;
                }
            }
            return crypt.ToString();
        }

        public static string Decrypt(string encryptedText)
        {
            StringBuilder crypt = new StringBuilder(encryptedText);
            if (crypt.Length > 0)
            {
                for (int i = 0; i < 3; i++)
                {
                    if (crypt[crypt.Length - 1 - i] == '*')
                    {
                        crypt[crypt.Length - 1 - i] = '=';
                    }
                    else break;
                }
            }
            byte[] cipherTextBytes = Convert.FromBase64String(crypt.ToString());
            byte[] keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8);
            var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.None };

            var decryptor = symmetricKey.CreateDecryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey));
            var memoryStream = new MemoryStream(cipherTextBytes);
            var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
            byte[] plainTextBytes = new byte[cipherTextBytes.Length];

            int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
            memoryStream.Close();
            cryptoStream.Close();
            return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount).TrimEnd("\0".ToCharArray());
        }
    }
}

Body:
After tested your code on my Azure Web App(x64 platform), I found it worked good on my side. Here is my test code.

public ActionResult TestCrypto()
{
    string encryptedText = Crypto.Encrypt("123456");
    string text = "Encrypted Text : " + encryptedText + "<br/>";
    string originalText = Crypto.Decrypt(encryptedText);
    text += "Origial Text : " + originalText;
    return Content(text);
}

Here is the result I got from server.

I suggest you test the upper code in your server and post the result.

invalid length for a base-64 char array or string

The exception often occurs when decrypting the encrypted text. If you store the encrypted text in a database, sometimes the encrypted text lost some data due to the column used to store the data doesn't have enough space. For example, the column type which you defined is nvarchar(32) and the length of encrypted text is 56 which is more than 32. Please make sure the encrypted text haven't been changed before you decrypt it.


问:
How to derive own distinguish type from Int?
I would like to define two data types in Perl 6 deriving from Int but being incompatible with Int or each other at the same time.

For instance:

Distance derived from Int with a range 0 up to 32000, and

Offset derived from Int with a range from -32000 up to 32000

I would like the types Distance, Offset and Int being distinguishable and incompatible to each other on default.

So (pseudo Perl 6):

```<code>  my Distance $d = Distance(12);  // ok
  my Offset $o = Offset(-1);      // ok
  my Distance $d2 = $o;           // BUMMER!

  sub myprint(Int $i) { say $i }

  say $d + $o;                    // BUMMER!
  myprint $d;                     // BUMMER!
  myprint Int($d);                // ok
</code>```

And so on! I want the Perl 6 compiler to complain if I ever try to mix Distances and Offsets implicitly.

In the books I've read so far there was no hint how to achieve this. Asking Google for some days also offer me no any answer whether this is possible, and if it is, how?

I found about subset but this only put some restriction on a type, but does not render it incompatible to the original type. Furthermore it is not distinguishable from the original type if its restrictions are met in both the original type and its subset.

So I would like to ask here if anybody know if this is possible in Perl 6? And if yes, how would I have to do it?

答:
Update, 2021 And now there's RakuAST![1]

Curt's answer catches the errors chi wanted caught. This complementary answer is my initial exploration of Chi's follow on question asking:

Why, when compiling/running Curt's code, does Rakudo wait until run-time to report two of the three errors?

At the end of this initial exploration I arrive at wrapping Curt's code in a BEGIN block. This code appears to report all errors at compile-time (one by one of course, after commenting out each prior error). (Click for runnable snippet.)[2]

This is a strawman answer, set up for Perl 6 core devs to shoot down.

An initial run of Curt's code results in:

===SORRY!=== ... Calling myprint(Distance) will never work...

The leading ===SORRY!=== signifies a "compile-time"[3] error.

But if we comment out the failing line and try again we get:

Type check failed in assignment to $d2...

This error message is a "run-time"[3] message -- it doesn't start with ===SORRY!===.

Why did the compiler wait until "run-time" to complain?

The answer appears to lie in a combination of Perl 6's mostly-dynamic-by-default nature and the code that fails:

```<code>my Distance $d2 = $o;              # Bummer! Type check fail
</code>```

The my Distance $d2 part of this line is fully processed (introducing a new lexically scoped symbol $d2) when the compiler first encounters this declaration at "compile-time". But the = part of this line is a "run-time" operator; the initializing assignment, and corresponding type check, occur at "run-time".

But a dev may want to force the type check, and hence a type check error, to occur at compile-time. Now what?

BEGIN time

Perl 6 supports program execution space/time travel via phasers. The first phaser is the BEGIN phaser which "Runs at compile time, as soon as possible" and can be used like this:

```<code>BEGIN my Distance $d2 = $o;
</code>```

If you re-compile with  the above change, the error now appears at compile-time[3]:

```<code>===SORRY!=== Error while compiling...
An exception occurred while evaluating a BEGIN...
Type check failed in assignment to $d2...
</code>```

If we now comment out the latest failing line and try again we get:

Cannot resolve caller Numeric(Distance: )...

There's no leading ===SORRY!=== so this is again a "run-time" error.

Rerunning the code with the failing line altered to:

```<code>BEGIN say $d + $o;
</code>```

yields:

```<code>0
12
</code>```

on stdout, and on stderr we get:

```<code>Use of uninitialized value of type Distance in numeric context...
Use of uninitialized value of type Offset in numeric context...
</code>```

Uhoh. There's not only no compile-time error, there's no run-time error either! (The run-time warnings may give the game away about the 0. Because the my... lines declaring $d and $o were not prefixed with BEGIN, these symbols have not yet been initialized at compile-time, which is the time that the BEGIN say $d + $o; line gets run. But all of this is moot; we've clearly taken a step backwards.)

What happens if we wrap all of Curt's code in a single BEGIN block?

BEGIN { ... Curt's code goes here ... }

```<code>BEGIN {
class Distance...
class Offset...

my Distance $d = Distance.new(12)...

sub myprint(Int $i) { say $i }

say $d + $o;...
}
</code>```

Bingo! The errors are now all revealed as they were with Curt's original code but the reporting seems to happen at compile-time (one by one, after commenting out each prior error).

Footnotes

[1] In a comment I just wrote below Curt's answer, I've just written[1a]:

Hi @chi. I only just noticed your comment![1a] (Better late than never?) A Raku compiler is allowed to do as much static analysis as it likes but, 4 years after you wrote this SO, the only Raku compiler that's currently of practical note, Rakudo, currently does relatively little, because analysis makes compilation slower, and a top priority for Rakudo is to quickly start running code. That said, Rakudo is evolving, and after the RakuAST work is completed, it's reasonable to anticipate folk developing deeper static analysis modules.

[1a] Of course, I wrote my comment before I looked at my answer! This reflects my process; when I become aware that someone has upvoted (or downvoted) one of my older answers, I typically go check on the question as if I had not answered it -- ignoring my answer -- as a way to quickly get back up to speed on what was asked/said, while I still have a relatively fresh perspective that's not limited by the one I developed when I originally answered it. I had completely forgotten what my answer was, so was naturally struck by the fact it seemed I had not noticed @chi's comment, and had not replied. Further, my immediate reaction was/is that the new RakuAST work was relevant, as jnthn explains, thus my comment, and now my addition of this info to this answer.

[2] Code copied here in case glot.io ever goes away:

```<code># See https://stackoverflow.com/a/44360950/1077672

BEGIN { # to end of file

class Distance
{
    has Int $!value handles<Int>;

    method new($value where 0 <= * <= 32000) { self.bless(:$value) }

    submethod BUILD(:$!value) {}
}

class Offset
{
    has Int $!value handles<Int>;

    method new($value where -32000 <= * <= 32000) { self.bless(:$value) }

    submethod BUILD(:$!value) {}
}

my Distance $d = Distance.new(12); # ok
my Offset $o = Offset.new(-1);     # ok
my Distance $d2 = $o;              # Bummer! Type check fail

sub myprint(Int $i) { say $i }

say $d + $o;                       # Bummer!, can't add those objects
myprint $d;                        # Bummer!, $d isn't an Int, can't print
myprint Int($d);                   # ok, prints 12, converting with Int

}
</code>```

[3] I scare quoted many references to "compile-time" and "run-time" because they have ambiguous meaning in Perl 6. Perl 6 lets user code do just about anything, including running the compiler, during run-time, and lets user code do just about anything, including run-time things, during compile-time. So from one perspective there can be one or more run-time phases within a compile-time phase and vice versa. But from a second perspective, there's the compile-time phase, i.e. when you're sitting there during a development session and you've just run the compiler. Likewise there's the run time phase, i.e. when your code is, for example, running "in production". Where I do not scare quote run-time / compile-time, I mean to refer to this second perspective.

Body:
I would like to define two data types in Perl 6 deriving from Int but being incompatible with Int or each other at the same time.

For instance:

Distance derived from Int with a range 0 up to 32000, and

Offset derived from Int with a range from -32000 up to 32000

I would like the types Distance, Offset and Int being distinguishable and incompatible to each other on default.

So (pseudo Perl 6):

  my Distance $d = Distance(12);  // ok
  my Offset $o = Offset(-1);      // ok
  my Distance $d2 = $o;           // BUMMER!

  sub myprint(Int $i) { say $i }

  say $d + $o;                    // BUMMER!
  myprint $d;                     // BUMMER!
  myprint Int($d);                // ok

And so on! I want the Perl 6 compiler to complain if I ever try to mix Distances and Offsets implicitly.

In the books I've read so far there was no hint how to achieve this. Asking Google for some days also offer me no any answer whether this is possible, and if it is, how?

I found about subset but this only put some restriction on a type, but does not render it incompatible to the original type. Furthermore it is not distinguishable from the original type if its restrictions are met in both the original type and its subset.

So I would like to ask here if anybody know if this is possible in Perl 6? And if yes, how would I have to do it?

Body:
Update, 2021 And now there's RakuAST![1]

Curt's answer catches the errors chi wanted caught. This complementary answer is my initial exploration of Chi's follow on question asking:

Why, when compiling/running Curt's code, does Rakudo wait until run-time to report two of the three errors?

At the end of this initial exploration I arrive at wrapping Curt's code in a BEGIN block. This code appears to report all errors at compile-time (one by one of course, after commenting out each prior error). (Click for runnable snippet.)[2]

This is a strawman answer, set up for Perl 6 core devs to shoot down.

An initial run of Curt's code results in:

===SORRY!=== ... Calling myprint(Distance) will never work...

The leading ===SORRY!=== signifies a "compile-time"[3] error.

But if we comment out the failing line and try again we get:

Type check failed in assignment to $d2...

This error message is a "run-time"[3] message -- it doesn't start with ===SORRY!===.

Why did the compiler wait until "run-time" to complain?

The answer appears to lie in a combination of Perl 6's mostly-dynamic-by-default nature and the code that fails:

my Distance $d2 = $o;              # Bummer! Type check fail

The my Distance $d2 part of this line is fully processed (introducing a new lexically scoped symbol $d2) when the compiler first encounters this declaration at "compile-time". But the = part of this line is a "run-time" operator; the initializing assignment, and corresponding type check, occur at "run-time".

But a dev may want to force the type check, and hence a type check error, to occur at compile-time. Now what?

BEGIN time

Perl 6 supports program execution space/time travel via phasers. The first phaser is the BEGIN phaser which "Runs at compile time, as soon as possible" and can be used like this:

BEGIN my Distance $d2 = $o;

If you re-compile with  the above change, the error now appears at compile-time[3]:

===SORRY!=== Error while compiling...
An exception occurred while evaluating a BEGIN...
Type check failed in assignment to $d2...

If we now comment out the latest failing line and try again we get:

Cannot resolve caller Numeric(Distance: )...

There's no leading ===SORRY!=== so this is again a "run-time" error.

Rerunning the code with the failing line altered to:

BEGIN say $d + $o;

yields:

0
12

on stdout, and on stderr we get:

Use of uninitialized value of type Distance in numeric context...
Use of uninitialized value of type Offset in numeric context...

Uhoh. There's not only no compile-time error, there's no run-time error either! (The run-time warnings may give the game away about the 0. Because the my... lines declaring $d and $o were not prefixed with BEGIN, these symbols have not yet been initialized at compile-time, which is the time that the BEGIN say $d + $o; line gets run. But all of this is moot; we've clearly taken a step backwards.)

What happens if we wrap all of Curt's code in a single BEGIN block?

BEGIN { ... Curt's code goes here ... }

BEGIN {
class Distance...
class Offset...

my Distance $d = Distance.new(12)...

sub myprint(Int $i) { say $i }

say $d + $o;...
}

Bingo! The errors are now all revealed as they were with Curt's original code but the reporting seems to happen at compile-time (one by one, after commenting out each prior error).

Footnotes

[1] In a comment I just wrote below Curt's answer, I've just written[1a]:

Hi @chi. I only just noticed your comment![1a] (Better late than never?) A Raku compiler is allowed to do as much static analysis as it likes but, 4 years after you wrote this SO, the only Raku compiler that's currently of practical note, Rakudo, currently does relatively little, because analysis makes compilation slower, and a top priority for Rakudo is to quickly start running code. That said, Rakudo is evolving, and after the RakuAST work is completed, it's reasonable to anticipate folk developing deeper static analysis modules.

[1a] Of course, I wrote my comment before I looked at my answer! This reflects my process; when I become aware that someone has upvoted (or downvoted) one of my older answers, I typically go check on the question as if I had not answered it -- ignoring my answer -- as a way to quickly get back up to speed on what was asked/said, while I still have a relatively fresh perspective that's not limited by the one I developed when I originally answered it. I had completely forgotten what my answer was, so was naturally struck by the fact it seemed I had not noticed @chi's comment, and had not replied. Further, my immediate reaction was/is that the new RakuAST work was relevant, as jnthn explains, thus my comment, and now my addition of this info to this answer.

[2] Code copied here in case glot.io ever goes away:

# See https://stackoverflow.com/a/44360950/1077672

BEGIN { # to end of file

class Distance
{
    has Int $!value handles<Int>;

    method new($value where 0 <= * <= 32000) { self.bless(:$value) }

    submethod BUILD(:$!value) {}
}

class Offset
{
    has Int $!value handles<Int>;

    method new($value where -32000 <= * <= 32000) { self.bless(:$value) }

    submethod BUILD(:$!value) {}
}

my Distance $d = Distance.new(12); # ok
my Offset $o = Offset.new(-1);     # ok
my Distance $d2 = $o;              # Bummer! Type check fail

sub myprint(Int $i) { say $i }

say $d + $o;                       # Bummer!, can't add those objects
myprint $d;                        # Bummer!, $d isn't an Int, can't print
myprint Int($d);                   # ok, prints 12, converting with Int

}

[3] I scare quoted many references to "compile-time" and "run-time" because they have ambiguous meaning in Perl 6. Perl 6 lets user code do just about anything, including running the compiler, during run-time, and lets user code do just about anything, including run-time things, during compile-time. So from one perspective there can be one or more run-time phases within a compile-time phase and vice versa. But from a second perspective, there's the compile-time phase, i.e. when you're sitting there during a development session and you've just run the compiler. Likewise there's the run time phase, i.e. when your code is, for example, running "in production". Where I do not scare quote run-time / compile-time, I mean to refer to this second perspective.


问:
How to use UITableViews to create static and dynamic rows with Swift
This question follows up from this: Use UICollectionViews to create dynamic and multiple features.

I am able to create a static cell which displays the name and image of the recipe similar like this app:

Where I am stuck is creating a dynamic row which changes based on the amount of data inside i.e. utensils or nutritional values like the image below:

I know how to display rows of data on tableView normally. But not sure how to embed it into a section inside a tableView. I attempted to add multiple prototype cells and assign them to a subclass of UITableViewCell's. Then I try to use if statements in my cellForRow but this isn't soling my issue.

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

    if indexPath.row == 0 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! FirstCell
        //set the data here

        cell.recipeTitle.text = recipe.name
        cell.imageView.image = UIImage(named: "url")
        return cell
    }
    else if indexPath.row == 1 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell2", for: indexPath) as! SecondCell
        //set the data here
        return cell
    }
    else {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell3", for: indexPath) as! ThirdCell
        //set the data here
        return cell
    }
}
</code>```

I have also looked at this demonstration: https://medium.com/ios-os-x-development/ios-how-to-build-a-table-view-with-multiple-cell-types-2df91a206429, which is near to what I want to achieve but I have found it quite difficult to adapt to it.

If someone could direct me on how best to approach this or a good example then I would really appreciate it.

答:
First you can't have static cells and dynamic cells in the same tableView. So how do you work around that? Define each of the static cells in the sections they belong in as well as the dynamic cells in the sections they belong to. That, however doesn't look like what you are trying to do. You just want multiple sections in the same tableView, each section with a different list of data

To do this you will need the number of sections so use the tableView(_:numberOfSections:) function.

```<code>override func numberOfSections(in tableView: UITableView) -> Int {
    return 3
}
</code>```

You can then(and probably should) give each of those sections a title by initializing an array with the titles in your tableViewController(assuming thats what you are using. It could also just be a tableView).

```<code>let headerTitles = ["Nutritional Values", "Utensils", "Ingredients"]
</code>```

Then use the tableView(_:titleForHeaderInSection:)

```<code>override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    if section < headerTitles.count {
        return headerTitles[section]
    }
    return nil
}
</code>```

Now you can start defining your rows by the sections.

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

    if indexPath.section == 0 {
        //Setup up the first row
        if indexPath.row == 0 {
            //I'm not sure where or how you defined First/SecondCell but this may not work depending on those two questions.
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! FirstCell
            return cell
        } else if indexPath.row == 1 {
            let cell = Bundle.main.loadNibNamed("StaticCell", owner: self, options: nil)?.first as! StaticCell
            return cell
        }

    } else if indexPath.section == 1 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath) as! SecondCell
        //setup cell1 n your storyboard to have a label with a tag # of 12(or whatever number you want to use)
        //you also want an array with your utensil data accessible here
        let label = cell.viewWithTag(12) as! UILabel
        label.text = utensilNames[indexPath.row]
            return cell

    } else if indexPath.section == 2 {
        let cellIngredients = tableView.dequeueReusableCell(withIdentifier: "Ingredients", for: indexPath)

        tableView.deselectRow(at: indexPath, animated: true)
        return cellIngreidents
    }
    cell = tableView.dequeueReusableCell(withIdentifier: "cell")!
    return cell
}
</code>```

The point here is to use sections then rows to distribute your data.

Just to clarify Section 0 Row 0 - N would be where you're static rows are setup. I found it best to use XIB files subclassing TableViewCell.
Hope this helps.

EDIT So the way I'm looking at the "static" cells is in the first section the xib is the only put exactly where you tell it to be placed. In the example above the first section in the second cell is the

Body:
This question follows up from this: Use UICollectionViews to create dynamic and multiple features.

I am able to create a static cell which displays the name and image of the recipe similar like this app:

Where I am stuck is creating a dynamic row which changes based on the amount of data inside i.e. utensils or nutritional values like the image below:

I know how to display rows of data on tableView normally. But not sure how to embed it into a section inside a tableView. I attempted to add multiple prototype cells and assign them to a subclass of UITableViewCell's. Then I try to use if statements in my cellForRow but this isn't soling my issue.

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

    if indexPath.row == 0 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! FirstCell
        //set the data here

        cell.recipeTitle.text = recipe.name
        cell.imageView.image = UIImage(named: "url")
        return cell
    }
    else if indexPath.row == 1 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell2", for: indexPath) as! SecondCell
        //set the data here
        return cell
    }
    else {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell3", for: indexPath) as! ThirdCell
        //set the data here
        return cell
    }
}

I have also looked at this demonstration: https://medium.com/ios-os-x-development/ios-how-to-build-a-table-view-with-multiple-cell-types-2df91a206429, which is near to what I want to achieve but I have found it quite difficult to adapt to it.

If someone could direct me on how best to approach this or a good example then I would really appreciate it.

Body:
First you can't have static cells and dynamic cells in the same tableView. So how do you work around that? Define each of the static cells in the sections they belong in as well as the dynamic cells in the sections they belong to. That, however doesn't look like what you are trying to do. You just want multiple sections in the same tableView, each section with a different list of data

To do this you will need the number of sections so use the tableView(_:numberOfSections:) function.

override func numberOfSections(in tableView: UITableView) -> Int {
    return 3
}

You can then(and probably should) give each of those sections a title by initializing an array with the titles in your tableViewController(assuming thats what you are using. It could also just be a tableView).

let headerTitles = ["Nutritional Values", "Utensils", "Ingredients"]

Then use the tableView(_:titleForHeaderInSection:)

override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    if section < headerTitles.count {
        return headerTitles[section]
    }
    return nil
}

Now you can start defining your rows by the sections.

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

    if indexPath.section == 0 {
        //Setup up the first row
        if indexPath.row == 0 {
            //I'm not sure where or how you defined First/SecondCell but this may not work depending on those two questions.
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! FirstCell
            return cell
        } else if indexPath.row == 1 {
            let cell = Bundle.main.loadNibNamed("StaticCell", owner: self, options: nil)?.first as! StaticCell
            return cell
        }

    } else if indexPath.section == 1 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath) as! SecondCell
        //setup cell1 n your storyboard to have a label with a tag # of 12(or whatever number you want to use)
        //you also want an array with your utensil data accessible here
        let label = cell.viewWithTag(12) as! UILabel
        label.text = utensilNames[indexPath.row]
            return cell

    } else if indexPath.section == 2 {
        let cellIngredients = tableView.dequeueReusableCell(withIdentifier: "Ingredients", for: indexPath)

        tableView.deselectRow(at: indexPath, animated: true)
        return cellIngreidents
    }
    cell = tableView.dequeueReusableCell(withIdentifier: "cell")!
    return cell
}

The point here is to use sections then rows to distribute your data.

Just to clarify Section 0 Row 0 - N would be where you're static rows are setup. I found it best to use XIB files subclassing TableViewCell.
Hope this helps.

EDIT So the way I'm looking at the "static" cells is in the first section the xib is the only put exactly where you tell it to be placed. In the example above the first section in the second cell is the


问:
Having trouble with Requests.get()
Following code worked yesterday, now it gets hung in terminal, giving error list index out of range, however when I run the same code using IDE it works perfectly.

I do not understand what is going on. And no the url isn't invalid.

```<code>import requests
import bs4
import webbrowser
import csv

def CheckStock(url):
'''checks for shoes in stock'''
    headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
    RawHTML = requests.get(url, headers=headers)
    Page = bs4.BeautifulSoup(RawHTML.text, "lxml")
    ListOfRawSizes = Page.select('.size-dropdown-block')
    Sizes = str(ListOfRawSizes[0].getText()).replace('\t', '')
    Sizes = Sizes.replace('\n\n', ' ')
    Sizes = Sizes.split()
    Sizes.remove('Select')
    Sizes.remove('size')
    return Sizes
</code>```

答:
The problem is if your page doesn't contain any elements with a .size-dropdown-block class, your ListOfRawSizes[0] index will be out of range. You can't ask for the first item in a list if the list is empty, that will throw the index out of range error. This is most likely caused by the page being different from the previous day to when you tried it now.

You need to check if ListOfRawSizes has any items in it before trying to index the list. Fortunately, python makes it easy to check if a list is empty, if ListOfRawSizes: will be true if the list has at least one item.

```<code>ListOfRawSizes = Page.select('.size-dropdown-block')

# check to see if the list of raw sizes is not empty
if ListOfRawSizes:
    # we have at least one size so get the first item and do our work
    Sizes = str(ListOfRawSizes[0].getText()).replace('\t', '')
    Sizes = Sizes.replace('\n\n', ' ')
    Sizes = Sizes.split()
    Sizes.remove('Select')
    Sizes.remove('size')
    return Sizes
# if we hit the else clause, our list must be empty
else:
    # ...so return an empty list
    return []
</code>```

Additionally, you really shouldn't name your variables starting with capital letters. This could very easily conflict with class names. Variables in Python follow "snake case" convention; All lowercase with underscores to separate words. (eg: this_is_snake_case).

Title: Having trouble with Requests.get()

Body:
Following code worked yesterday, now it gets hung in terminal, giving error list index out of range, however when I run the same code using IDE it works perfectly.

I do not understand what is going on. And no the url isn't invalid.

import requests
import bs4
import webbrowser
import csv

def CheckStock(url):
'''checks for shoes in stock'''
    headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
    RawHTML = requests.get(url, headers=headers)
    Page = bs4.BeautifulSoup(RawHTML.text, "lxml")
    ListOfRawSizes = Page.select('.size-dropdown-block')
    Sizes = str(ListOfRawSizes[0].getText()).replace('\t', '')
    Sizes = Sizes.replace('\n\n', ' ')
    Sizes = Sizes.split()
    Sizes.remove('Select')
    Sizes.remove('size')
    return Sizes

Body:
The problem is if your page doesn't contain any elements with a .size-dropdown-block class, your ListOfRawSizes[0] index will be out of range. You can't ask for the first item in a list if the list is empty, that will throw the index out of range error. This is most likely caused by the page being different from the previous day to when you tried it now.

You need to check if ListOfRawSizes has any items in it before trying to index the list. Fortunately, python makes it easy to check if a list is empty, if ListOfRawSizes: will be true if the list has at least one item.

ListOfRawSizes = Page.select('.size-dropdown-block')

# check to see if the list of raw sizes is not empty
if ListOfRawSizes:
    # we have at least one size so get the first item and do our work
    Sizes = str(ListOfRawSizes[0].getText()).replace('\t', '')
    Sizes = Sizes.replace('\n\n', ' ')
    Sizes = Sizes.split()
    Sizes.remove('Select')
    Sizes.remove('size')
    return Sizes
# if we hit the else clause, our list must be empty
else:
    # ...so return an empty list
    return []

Additionally, you really shouldn't name your variables starting with capital letters. This could very easily conflict with class names. Variables in Python follow "snake case" convention; All lowercase with underscores to separate words. (eg: this_is_snake_case).


问:
Rails doesn't automatically load a template when in a namespace
Take routing like the following:

```<code>  namespace :auth do
    get 'login', to: 'auth#login'
  end
</code>```

With a simple empty method in the controller:

```<code>def login
end
</code>```

Without the namespace, it picks up the login template automatically with no problem. When I move it to the namespace, however, it switches to a 204 No Content response and shows a rails warning page. I can add render to my controller method, but it should be automatic. Where am I going wrong?

答:
The path to the views must be something like:

```<code>app/views/namespace/controller/view.html.erb
</code>```

So, in your case both namespace and controller have the same name, so the path to the views should be:

```<code>app/views/auth/auth/login.html
</code>```

Instead of:

```<code>app/views/auth/login.html
</code>```

Body:
Take routing like the following:

  namespace :auth do
    get 'login', to: 'auth#login'
  end

With a simple empty method in the controller:

def login
end

Without the namespace, it picks up the login template automatically with no problem. When I move it to the namespace, however, it switches to a 204 No Content response and shows a rails warning page. I can add render to my controller method, but it should be automatic. Where am I going wrong?

Body:
The path to the views must be something like:

app/views/namespace/controller/view.html.erb

So, in your case both namespace and controller have the same name, so the path to the views should be:

app/views/auth/auth/login.html

Instead of:

app/views/auth/login.html


问:
I can not get Json array from spring rest controller and fill jQuery DataTable
I have this method in controller

```<code>@RequestMapping(value = "/updateWithParams", method = RequestMethod.GET)
    @ResponseBody
    public List<ResolutionDto> updateWithParams() {
        List<ResolutionDto> list = new ArrayList<>();
        List<Resolution> resolutions = resolutionService.findAll();
        for (Resolution resolution : resolutions) {
            list.add(new ResolutionDto(resolution.getId(), resolution.getName(), resolution.getStatus(), resolution.getDateCreated(), resolution.getUserName()));
        }
        return list;
    }
</code>```

It is ResolutionDto

```<code>@Data
@AllArgsConstructor
public class ResolutionDto {
    public Long id;
    private String name;
    private Integer status;
    private Date dateCreated;
    private String userName;
}
</code>```

And on Client side I want get this array like JSON array and fill jQuery DataTable.

```<code>function loadTable() {
        $.ajax({
            type: 'GET',
            dataType: "json",
            url: '/updateWithParams',
            success: function (data) {
                var jsdata = JSON.parse(data);
                var datatable = $('#example').dataTable().api();
                datatable.fnAddData(jsdata);
            },
            error: function (xhr, str) {
                alert("error");
            }
        });
    }
</code>```

But it not work. I thik problem in this line var jsdata = JSON.parse(data);

but I do not understand how fix it

答:
JSON.parse() is not needed anymore, because it was automatically parsed.
Try this:

```<code>$.ajax({
url: "url",
type: "get|post",
contentType: "application/json",
success: function(data) {
// try printing, to test
data.foreach(function(obj, index)) {
console.log(obj.name);
}
}
    });
</code>```

Body:
I have this method in controller

@RequestMapping(value = "/updateWithParams", method = RequestMethod.GET)
    @ResponseBody
    public List<ResolutionDto> updateWithParams() {
        List<ResolutionDto> list = new ArrayList<>();
        List<Resolution> resolutions = resolutionService.findAll();
        for (Resolution resolution : resolutions) {
            list.add(new ResolutionDto(resolution.getId(), resolution.getName(), resolution.getStatus(), resolution.getDateCreated(), resolution.getUserName()));
        }
        return list;
    }

It is ResolutionDto

@Data
@AllArgsConstructor
public class ResolutionDto {
    public Long id;
    private String name;
    private Integer status;
    private Date dateCreated;
    private String userName;
}

And on Client side I want get this array like JSON array and fill jQuery DataTable.

function loadTable() {
        $.ajax({
            type: 'GET',
            dataType: "json",
            url: '/updateWithParams',
            success: function (data) {
                var jsdata = JSON.parse(data);
                var datatable = $('#example').dataTable().api();
                datatable.fnAddData(jsdata);
            },
            error: function (xhr, str) {
                alert("error");
            }
        });
    }

But it not work. I thik problem in this line var jsdata = JSON.parse(data);

but I do not understand how fix it

Body:
JSON.parse() is not needed anymore, because it was automatically parsed.
Try this:

$.ajax({
url: "url",
type: "get|post",
contentType: "application/json",
success: function(data) {
// try printing, to test
data.foreach(function(obj, index)) {
console.log(obj.name);
}
}
    });


问:
Bootstrap dropdown menu not dropping down?
The options for Bootstraps drop-down menu are not displaying. Tried moving min.js files, container divs etc, and nothing seems to be working. It seems others having this issue had bootstraps and ajax scripts in the wrong place. I believe mine are in the right place. What am I doing wrong?

```<code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Concept Noise</title>

<!-- Bootstrap -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/css/bootstrap.min.css" integrity="sha384-y3tfxAZXuh4HwSYylfB+J125MxIs6mR5FOHamPBG064zB+AFeWH94NdvaCBm8qnd" crossorigin="anonymous">

<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
  <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
  <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>

<style>

    .jumbotron{
        background: url(http://imgstore.wdwmagic.com/imgstore/ElementGalleryItems/attractions/Fullsize/Mission-SPACE_Full_1489.jpg) no-repeat center center;
        color: white;
        height: 550px;
        text-shadow: black 0.3em 0.3em 0.3em;
        text-align: center;
        color: #ffffff;
    }

    .jumbotron h1{

        margin-top: 10%;
        font-size: 80px;
    }

    .jumbotron p{

        margin-top: 2%;
    }

    #button {

        margin-top: 10%;
        border: 1px solid #FFFFFF;
    }

    .btn, .btn:hover, .btn:active, .btn:visited {
        background-color: #2D92FF !important;
    }

    .btn-xl {
        padding: 10px;
        font-size: 20px;
        border-radius: 4px;
        width:30%;
 }

</style>

<body>

 <nav class="navbar navbar-light bg-faded navbar-fixed-top" id="navbar">
      <a class="navbar-brand" href="#">Concept Noise</a>
      <ul class="nav navbar-nav">
        <li class="nav-item">
          <a class="nav-link" href="#jumbotron">Destinations<span class="sr-only">(current)</span></a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#about">About</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#news">News</a>
        </li>
        <li class="nav-item">
          <a class="nav-link">Easter Egg?</a>
        </li>
      </ul>
 </nav>

  <div class="jumbotron">

    <h1>Concept Noise</h1>

    <p>Choose your destination, travel to another world.</p>

    <p><button type="button" id = "button" class="btn btn-xl btn-info">Epcot 1982</button></p>

  </div>

    <div class="page-header">
        <h1>Destinations</h1>
    </div>

    <div class="dropdown">
      <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Please select your Destination
      <span class="caret"></span></button>
      <ul class="dropdown-menu">
        <li><a href=""></a>Avatar land</li>
        <li><a href="#">The African Sehrengetty</a></li>
        <li><a href="#">Tommorowland 1970</a></li>
        <li><a href="#">Futureworld 1982</a></li>
      </ul>
    </div>

    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">

$(document).ready( function() {
    $('.dropdown-toggle').dropdown();
});

</script>

<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>

</body>
</code>```

答:
In head section paste this:

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/css/bootstrap.min.css" integrity="sha384-y3tfxAZXuh4HwSYylfB+J125MxIs6mR5FOHamPBG064zB+AFeWH94NdvaCBm8qnd" crossorigin="anonymous">
</code>```

Erase all script lines from body section including jquery "dropdown" code. $(document).ready( function() {
    $('.dropdown-toggle').dropdown();
}); Not sure why are you using 1.12.4 version of jquery since the current one is 3.2.1, here is the link https://www.w3schools.com/jquery/jquery_get_started.asp

Also, I would suggest not to use full width container but just div class="container" because your dropdown is all the way to the left, unless you will move it to the right a bit when clicked on it.

The second suggestion is to make it responsive as well. When resizing the window it should show hamburger menu for tablets and mobile devices.

Body:
The options for Bootstraps drop-down menu are not displaying. Tried moving min.js files, container divs etc, and nothing seems to be working. It seems others having this issue had bootstraps and ajax scripts in the wrong place. I believe mine are in the right place. What am I doing wrong?

<!DOCTYPE html>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Concept Noise</title>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/css/bootstrap.min.css" integrity="sha384-y3tfxAZXuh4HwSYylfB+J125MxIs6mR5FOHamPBG064zB+AFeWH94NdvaCBm8qnd" crossorigin="anonymous">

      Concept Noise

          Destinations(current)

          About

          News

          Easter Egg?

Concept Noise

Choose your destination, travel to another world.

<button type="button" id = "button" class="btn btn-xl btn-info">Epcot 1982</button>

Destinations

      <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Please select your Destination
      </button>

Avatar land

The African Sehrengetty

Tommorowland 1970

Futureworld 1982

Body:
In head section paste this:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/css/bootstrap.min.css" integrity="sha384-y3tfxAZXuh4HwSYylfB+J125MxIs6mR5FOHamPBG064zB+AFeWH94NdvaCBm8qnd" crossorigin="anonymous">

Erase all script lines from body section including jquery "dropdown" code. $(document).ready( function() {
    $('.dropdown-toggle').dropdown();
}); Not sure why are you using 1.12.4 version of jquery since the current one is 3.2.1, here is the link https://www.w3schools.com/jquery/jquery_get_started.asp

Also, I would suggest not to use full width container but just div class="container" because your dropdown is all the way to the left, unless you will move it to the right a bit when clicked on it.

The second suggestion is to make it responsive as well. When resizing the window it should show hamburger menu for tablets and mobile devices.


问:
How import old repo files in new git server
I recently recover after a hard failure of my server. I still access to my old files system but can't boot on it. (access as external HDD)
I rebuild the server from scratch and to finish this I need to import the repo from the old git server.

So my question is : How to import old repo from a git server on Ubuntu 12.0 to new git server on Ubuntu 16.0 ?

Which files do I need to copy and where ?

答:
You can use git bundle to import old repo to a new git server and keep the commit histories:

```<code># In local copy of old server repo
git bundle create repo.bundle --all
# In an empty folder, copy the repo.bundle in it and run below commands,
git clone repo.bundle oldServer
cd oldServer
# checkout all branches locally
git remote add new <URL for new server>
git push new --all
</code>```

Body:
You can use git bundle to import old repo to a new git server and keep the commit histories:

# In local copy of old server repo
git bundle create repo.bundle --all
# In an empty folder, copy the repo.bundle in it and run below commands,
git clone repo.bundle oldServer
cd oldServer
# checkout all branches locally
git remote add new <URL for new server>
git push new --all


问:
What's the proper way to copy a carrierwave file from one record to another?
I need to copy a file from one carrier wave object to another. They are different tables and different types of uploaders.

I started with:

```<code>user.avatar = image.content
</code>```

(where user and image are model instances, avatar and content are the carrierwave mounted uploaders) which worked sometimes. It seems to work all the time locally, with a file storage, but intermittent when using fog and s3.

In a mailing list post I found this code:

```<code>user.avatar = image.content.file
</code>```

that again worked sometimes.

My working solution so far is:

```<code>require "open-uri"

begin
  user.avatar = open(image.url)
rescue Errno::ENOENT => e
  begin
    user.avatar = open(image.path)
  rescue Errno::ENOENT => e
    # Ok, whatever.
  end
end
</code>```

which is not only ugly, but fails to pass the extension validation because the opening of a remote file doesn't maintain the extension (jpg, png, etc.).

答:
I just wanted to copy an avatar reference from one object to another, and what worked for me was:

```<code>objectB.avatar.retrieve_from_store!(objectA.avatar.identifier)
objectB.save
</code>```

Body:
I need to copy a file from one carrier wave object to another. They are different tables and different types of uploaders.

I started with:

user.avatar = image.content

(where user and image are model instances, avatar and content are the carrierwave mounted uploaders) which worked sometimes. It seems to work all the time locally, with a file storage, but intermittent when using fog and s3.

In a mailing list post I found this code:

user.avatar = image.content.file

that again worked sometimes.

My working solution so far is:

require "open-uri"

begin
  user.avatar = open(image.url)
rescue Errno::ENOENT => e
  begin
    user.avatar = open(image.path)
  rescue Errno::ENOENT => e
    # Ok, whatever.
  end
end

which is not only ugly, but fails to pass the extension validation because the opening of a remote file doesn't maintain the extension (jpg, png, etc.).

Body:
I just wanted to copy an avatar reference from one object to another, and what worked for me was:

objectB.avatar.retrieve_from_store!(objectA.avatar.identifier)
objectB.save


问:
replace method not working
I'm trying to remove the width and height attribute from the iframes and remove all newline characters from my input. So I made this:

```<code>var convert;
$(".button1").click(function(){
  console.log("done");
  var convert = document.getElementById("convert").value;
  convert = convert.replace(/\r?\n/g, '');
  //convert = convert.replace("width=\'500\' height=\'294\'")
  convert= convert.replace("width=", '');
  convert = convert.replace("height=", '');
  convert= convert.replace("'500'", '');
  convert= convert.replace("'294'", '');
  console.log(convert);
})
</code>```

But it has inconsistent outcome. Sometimes it works and sometimes it doesn't.

I've tried the commented out part too, but that doesn't work either.

It always manages to remove the newlines and make the input a one-line string, but it never manages to wipe out all the width and height attributes from a big string like this:

```<code><li> <h1 class="liname">বীরশ্রেষ্ঠ মোস্তফা কামালঃ-</h1> <div class="iframe"><iframe src="https://www.youtube.com/embed/uZuzPrQ9X_w?&theme=dark&autohide=2&fs=0&rel=0"frameborder="0"></iframe></div> </li> <li> <h1 class="liname">বীরশ্রেষ্ঠ মতিউর রহমান:-</h1> <div class="iframe"><iframe width='500' height='294' src="https://www.youtube.com/embed/u1thP64dhrk?&theme=dark&autohide=2&modestbranding=1&fs=0&showinfo=0&rel=0"frameborder="0"></iframe></div> </li> <li> <h1 class="liname">বীরশ্রেষ্ঠ নূর মোহাম্মদ:-</h1> <div class="iframe"><iframe width='500' height='294' src="https://www.youtube.com/embed/Xjf6CO2bWW8?&theme=dark&autohide=2&modestbranding=1&fs=0&showinfo=0&rel=0"frameborder="0"></iframe></div> </li> <li> <h1 class="liname">বীরশ্রেষ্ঠ মোহাম্মদ রুহুল আমিন :-</h1> <div class="iframe"><iframe width='500' height='294' src="https://www.youtube.com/embed/CpDdMNNkkck?&theme=dark&autohide=2&modestbranding=1&fs=0&showinfo=0&rel=0"frameborder="0"></iframe></div> </li> <li> <h1 class="liname">বীরশ্রেষ্ঠ মুন্সী আবদুর রউফ:-</h1> <div class="iframe"><iframe width='500' height='294' src="https://www.youtube.com/embed/oUgsJSUHZlM?&theme=dark&autohide=2&modestbranding=1&fs=0&showinfo=0&rel=0"frameborder="0"></iframe></div> </li> <li> <h1 class="liname">বীরশ্রেষ্ঠ হামিদুর রহমান :-</h1> <div class="iframe"><iframe width='500' height='294' src="https://www.youtube.com/embed/74hSM6rGwq4?&theme=dark&autohide=2&modestbranding=1&fs=0&showinfo=0&rel=0"frameborder="0"></iframe></div> </li> <li> <h1 class="liname">বীরশ্রেষ্ঠ জাহাঙ্গীর :-</h1> <div class="iframe"><iframe width='500' height='294' src="https://www.youtube.com/embed/ctVFVaAmG7w?&theme=dark&autohide=2&modestbranding=1&fs=0&showinfo=0&rel=0"frameborder="0"></iframe></div> </li>
</code>```

The above code line is the input after removing the newlines.

The actual HTML code with newlines is below:

```<code><li>
  <h1 class="liname">বীরশ্রেষ্ঠ মোস্তফা কামালঃ-</h1>
  <div class="iframe"><iframe src="https://www.youtube.com/embed/uZuzPrQ9X_w?&theme=dark&autohide=2&fs=0&rel=0"frameborder="0"></iframe></div>
</li>
<li>
  <h1 class="liname">বীরশ্রেষ্ঠ মতিউর রহমান:-</h1>
  <div class="iframe"><iframe width='500' height='294' src="https://www.youtube.com/embed/u1thP64dhrk?&theme=dark&autohide=2&modestbranding=1&fs=0&showinfo=0&rel=0"frameborder="0"></iframe></div>
</li>
<li>
  <h1 class="liname">বীরশ্রেষ্ঠ নূর মোহাম্মদ:-</h1>
  <div class="iframe"><iframe width='500' height='294' src="https://www.youtube.com/embed/Xjf6CO2bWW8?&theme=dark&autohide=2&modestbranding=1&fs=0&showinfo=0&rel=0"frameborder="0"></iframe></div>
</li>
<li>
  <h1 class="liname">বীরশ্রেষ্ঠ মোহাম্মদ রুহুল আমিন :-</h1>
  <div class="iframe"><iframe width='500' height='294' src="https://www.youtube.com/embed/CpDdMNNkkck?&theme=dark&autohide=2&modestbranding=1&fs=0&showinfo=0&rel=0"frameborder="0"></iframe></div>
</li>
<li>
  <h1 class="liname">বীরশ্রেষ্ঠ মুন্সী আবদুর রউফ:-</h1>
  <div class="iframe"><iframe width='500' height='294' src="https://www.youtube.com/embed/oUgsJSUHZlM?&theme=dark&autohide=2&modestbranding=1&fs=0&showinfo=0&rel=0"frameborder="0"></iframe></div>
</li>
<li>
  <h1 class="liname">বীরশ্রেষ্ঠ হামিদুর রহমান :-</h1>
  <div class="iframe"><iframe width='500' height='294' src="https://www.youtube.com/embed/74hSM6rGwq4?&theme=dark&autohide=2&modestbranding=1&fs=0&showinfo=0&rel=0"frameborder="0"></iframe></div>
</li>
<li>
  <h1 class="liname">বীরশ্রেষ্ঠ জাহাঙ্গীর :-</h1>
  <div class="iframe"><iframe width='500' height='294' src="https://www.youtube.com/embed/ctVFVaAmG7w?&theme=dark&autohide=2&modestbranding=1&fs=0&showinfo=0&rel=0"frameborder="0"></iframe></div>
</li>
</code>```

答:
I do not what is your code about, but all you need to do is: </p>

```<code>$(".button1").click(function(){
    $('iframe').removeAttr('width').removeAttr('height');
 })
</code>```

Title: replace method not working

Body:
I'm trying to remove the width and height attribute from the iframes and remove all newline characters from my input. So I made this:

var convert;
$(".button1").click(function(){
  console.log("done");
  var convert = document.getElementById("convert").value;
  convert = convert.replace(/\r?\n/g, '');
  //convert = convert.replace("width=\'500\' height=\'294\'")
  convert= convert.replace("width=", '');
  convert = convert.replace("height=", '');
  convert= convert.replace("'500'", '');
  convert= convert.replace("'294'", '');
  console.log(convert);
})

But it has inconsistent outcome. Sometimes it works and sometimes it doesn't.

I've tried the commented out part too, but that doesn't work either.

It always manages to remove the newlines and make the input a one-line string, but it never manages to wipe out all the width and height attributes from a big string like this:

বীরশ্রেষ্ঠ মোস্তফা কামালঃ-

বীরশ্রেষ্ঠ মতিউর রহমান:-

বীরশ্রেষ্ঠ নূর মোহাম্মদ:-

বীরশ্রেষ্ঠ মোহাম্মদ রুহুল আমিন :-

বীরশ্রেষ্ঠ মুন্সী আবদুর রউফ:-

বীরশ্রেষ্ঠ হামিদুর রহমান :-

বীরশ্রেষ্ঠ জাহাঙ্গীর :-

The above code line is the input after removing the newlines.

The actual HTML code with newlines is below:

বীরশ্রেষ্ঠ মোস্তফা কামালঃ-

বীরশ্রেষ্ঠ মতিউর রহমান:-

বীরশ্রেষ্ঠ নূর মোহাম্মদ:-

বীরশ্রেষ্ঠ মোহাম্মদ রুহুল আমিন :-

বীরশ্রেষ্ঠ মুন্সী আবদুর রউফ:-

বীরশ্রেষ্ঠ হামিদুর রহমান :-

বীরশ্রেষ্ঠ জাহাঙ্গীর :-

Body:
I do not what is your code about, but all you need to do is:

$(".button1").click(function(){
    $('iframe').removeAttr('width').removeAttr('height');
 })