问:
How can I assign a placeholder datatype to custom classes dictionary in C#?
So I'm noticing that I am using a lot of the same code over and over and over again... So I want to make a universal class where possible, so I don't have the same function redefined in multiple places...

As an example I wanted to try and do this with a SortedDictionary. To do this, I need to be able to assign the data types of the dictionary when I create the custom SortedDictionary.

Is this possible? Something like this:

```<code>using System.Collections.Generic;

namespace Controller.Framework
{
   class CSortedDictionary
   {
      private SortedDictionary<CustomDataType, CustomDataType> m_dictionary;
   }
}

// Create custom dictionary...
CSortedDictionary<int, List<string>> custom_dictionary
    = new CSortedDictionary<int, List<string>>();
</code>```

答:
I'm not clear on what you are asking, but I think you just want to create your own generic which wraps the generic SortedDictionary.

```<code>using System.Collections.Generic;

namespace Controller.Framework
{
   class CSortedDictionary<CustomDataType1, CustomDataType2>
   {
      private SortedDictionary<CustomDataType1, CustomDataType2> m_dictionary;

      // other methods which work on m_dictionary;
   }
}

// Create custom dictionary...
var custom_dictionary = new CSortedDictionary<int, List<string>>();
</code>```

Or inherit as Sergey says

```<code>using System.Collections.Generic;

namespace Controller.Framework
{
   class CSortedDictionary<CustomDataType1, CustomDataType2>: SortedDictionary<CustomDataType1, CustomDataType2>
   {
      // other methods which work on m_dictionary;
   }
}

// Create custom dictionary...
var custom_dictionary = new CSortedDictionary<int, List<string>>();
</code>```

Maybe you want to consider an extension method for SortedDictionary, although this is frowned upon.

```<code>using System.Collections.Generic;

namespace Controller.Framework
{
   public static class CSortedDictionaryExtensions
   {
      public static DoSomething<CustomDataType1, CustomDataType2>(this SortedDictionary<CustomDataType1, CustomDataType2> dictionary){
        dictionary.SomeMethod();
      }

      // other methods which work on m_dictionary;
   }
}

// Create custom dictionary...
var dictionary = new SortedDictionary<int, List<string>>();
dictionary.DoSomething();
</code>```

[written but not compiled]

Body:
So I'm noticing that I am using a lot of the same code over and over and over again... So I want to make a universal class where possible, so I don't have the same function redefined in multiple places...

As an example I wanted to try and do this with a SortedDictionary. To do this, I need to be able to assign the data types of the dictionary when I create the custom SortedDictionary.

Is this possible? Something like this:

using System.Collections.Generic;

namespace Controller.Framework
{
   class CSortedDictionary
   {
      private SortedDictionary<CustomDataType, CustomDataType> m_dictionary;
   }
}

// Create custom dictionary...
CSortedDictionary<int, List<string>> custom_dictionary
    = new CSortedDictionary<int, List<string>>();

Body:
I'm not clear on what you are asking, but I think you just want to create your own generic which wraps the generic SortedDictionary.

using System.Collections.Generic;

namespace Controller.Framework
{
   class CSortedDictionary<CustomDataType1, CustomDataType2>
   {
      private SortedDictionary<CustomDataType1, CustomDataType2> m_dictionary;

      // other methods which work on m_dictionary;
   }
}

// Create custom dictionary...
var custom_dictionary = new CSortedDictionary<int, List<string>>();

Or inherit as Sergey says

using System.Collections.Generic;

namespace Controller.Framework
{
   class CSortedDictionary<CustomDataType1, CustomDataType2>: SortedDictionary<CustomDataType1, CustomDataType2>
   {
      // other methods which work on m_dictionary;
   }
}

// Create custom dictionary...
var custom_dictionary = new CSortedDictionary<int, List<string>>();

Maybe you want to consider an extension method for SortedDictionary, although this is frowned upon.

using System.Collections.Generic;

namespace Controller.Framework
{
   public static class CSortedDictionaryExtensions
   {
      public static DoSomething<CustomDataType1, CustomDataType2>(this SortedDictionary<CustomDataType1, CustomDataType2> dictionary){
        dictionary.SomeMethod();
      }

      // other methods which work on m_dictionary;
   }
}

// Create custom dictionary...
var dictionary = new SortedDictionary<int, List<string>>();
dictionary.DoSomething();

[written but not compiled]


来源: stackexchange

问:
Will returned array be copied by value or returned as reference in MATLAB?
I wanted to ask how values in MATLAB are returned? Are they copied or passed by reference?

take a look at this example with matrix A:

```<code>function main
    A = foo(10);

    return;
end

function [resultMatrix] = foo(count)
    resultMatrix = zeros(count, count);
    return;
end
</code>```

Does the copy operation take place when function returns matrix and assigns it to variable A ?

答:
MATLAB uses a system known as copy-on-write in which a copy of the data is only made when it is necessary (i.e. when the data is modified). When returning a variable from a function, it is not modified between when it was created inside of the function and when it was stored in a different variable by the calling function. So in your case, you can think of the variable as being passed by reference. Once the data is modified, however, a copy will be made

You can check this behavior using format debug which will actually tell us the memory location of the data (detailed more in this post)

So if we modify your code slightly so that we print the memory location of each variable we can track when a copy is made

```<code>function main()
    A = foo(10);

    % Print the address of the variable A
    fprintf('Address of A in calling function: %s\n', address(A));

    % Modify A
    B = A + 1;

    % Print the address of the variable B
    fprintf('Address of B in calling function: %s\n', address(B));
end

function result = foo(count)
    result = zeros(count);

    % Print the address of the variable inside of the function
    fprintf('Address of result in foo: %s\n', address(result));

end

function loc = address(x)
    % Store the current display format
    fmt = get(0, 'format');

    % Turn on debugging display and parse it
    format debug
    loc = regexp(evalc('disp(x)'), '(?<=pr\s*=\s*)[a-z0-9]*', 'match', 'once');

    % Revert the display format to what it was
    format(fmt);
end
</code>```

And this yields the following (or similar) output

```<code>Address of result in foo: 7f96d9d591c0
Address of A in calling function: 7f96d9d591c0
Address of B in calling function: 7f96d9c74400
</code>```

As a side-note, you don't need to explicitly use return in your case since the function will naturally return when it encounters the end. return is only necessary when you need to use it to alter the flow of your program and exit a function pre-maturely.

ContentLicense: CC BY-SA 3.0

Body:
I wanted to ask how values in MATLAB are returned? Are they copied or passed by reference?

take a look at this example with matrix A:

function main
    A = foo(10);

    return;
end

function [resultMatrix] = foo(count)
    resultMatrix = zeros(count, count);
    return;
end

Does the copy operation take place when function returns matrix and assigns it to variable A ?

Body:
MATLAB uses a system known as copy-on-write in which a copy of the data is only made when it is necessary (i.e. when the data is modified). When returning a variable from a function, it is not modified between when it was created inside of the function and when it was stored in a different variable by the calling function. So in your case, you can think of the variable as being passed by reference. Once the data is modified, however, a copy will be made

You can check this behavior using format debug which will actually tell us the memory location of the data (detailed more in this post)

So if we modify your code slightly so that we print the memory location of each variable we can track when a copy is made

function main()
    A = foo(10);

    % Print the address of the variable A
    fprintf('Address of A in calling function: %s\n', address(A));

    % Modify A
    B = A + 1;

    % Print the address of the variable B
    fprintf('Address of B in calling function: %s\n', address(B));
end

function result = foo(count)
    result = zeros(count);

    % Print the address of the variable inside of the function
    fprintf('Address of result in foo: %s\n', address(result));

end

function loc = address(x)
    % Store the current display format
    fmt = get(0, 'format');

    % Turn on debugging display and parse it
    format debug
    loc = regexp(evalc('disp(x)'), '(?<=pr\s*=\s*)[a-z0-9]*', 'match', 'once');

    % Revert the display format to what it was
    format(fmt);
end

And this yields the following (or similar) output

Address of result in foo: 7f96d9d591c0
Address of A in calling function: 7f96d9d591c0
Address of B in calling function: 7f96d9c74400

As a side-note, you don't need to explicitly use return in your case since the function will naturally return when it encounters the end. return is only necessary when you need to use it to alter the flow of your program and exit a function pre-maturely.


问:
Why doesn't my Google Maps app not print out tapped coordinates?
I have the following code which if I compile it's not working: if I change zoom value, and recompile it again it's like "nothing changed". Also, when I tap, the print function does not print anything. What might be the issue?</p>

```<code>import UIKit
import GoogleMaps
import MapKit

class ViewController: UIViewController, GMSMapViewDelegate, UIAlertViewDelegate {
@IBOutlet weak var mapView: GMSMapView!
var markersArray: Array<CLLocationCoordinate2D> = []

override func viewDidLoad() {
//set default position of the mapView
let camera = GMSCameraPosition.camera(withLatitude: 1.285, longitude: 10.848, zoom: 10)
let mapView = GMSMapView.map(withFrame: self.view.bounds, camera:camera)
//mapView.mapType = kGMSTypeSatellite - use of unresolved identifier 'kGMSTypeSatellite'
mapView.isMyLocationEnabled = true
mapView.settings.compassButton = true
mapView.settings.myLocationButton = true
mapView.camera = camera
mapView.delegate = self
}

func mapView(_ mapView: GMSMapView, didTapAt coordinate: CLLocationCoordinate2D){
var lat : String = coordinate.latitude.description
var lng : String = coordinate.longitude.description
markersArray.append(coordinate)
print(markersArray)
print(lat)
print(lng)
    print(coordinate.latitude)
    print(coordinate.longitude)
}
</code>```

答:
I believe your issue is that you are creating a second map view on the line:

```<code>let mapView = GMSMapView.map(withFrame: self.view.bounds, camera:camera)
</code>```

and setting its delegate to self. You never add this map to the view. The map view you see and touch is from your storyboard which you have an outlet:

```<code>@IBOutlet weak var mapView: GMSMapView!
</code>```

Which is not the same. You create a local variable with the same name. You never set this outlet's delegate. Instead of creating a new map view, simply set the camera position of the outlet:

```<code>override func viewDidLoad() {
  //set default position of the mapView
  let camera = GMSCameraPosition.camera(withLatitude: 1.285, longitude: 10.848, zoom: 10)
  mapView.position = camera
  mapView.isMyLocationEnabled = true
  mapView.settings.compassButton = true
  mapView.settings.myLocationButton = true
  mapView.camera = camera
  mapView.delegate = self
 }
</code>```

Body:
I have the following code which if I compile it's not working: if I change zoom value, and recompile it again it's like "nothing changed". Also, when I tap, the print function does not print anything. What might be the issue?

import UIKit
import GoogleMaps
import MapKit

class ViewController: UIViewController, GMSMapViewDelegate, UIAlertViewDelegate {
@IBOutlet weak var mapView: GMSMapView!
var markersArray: Array<CLLocationCoordinate2D> = []

override func viewDidLoad() {
//set default position of the mapView
let camera = GMSCameraPosition.camera(withLatitude: 1.285, longitude: 10.848, zoom: 10)
let mapView = GMSMapView.map(withFrame: self.view.bounds, camera:camera)
//mapView.mapType = kGMSTypeSatellite - use of unresolved identifier 'kGMSTypeSatellite'
mapView.isMyLocationEnabled = true
mapView.settings.compassButton = true
mapView.settings.myLocationButton = true
mapView.camera = camera
mapView.delegate = self
}

func mapView(_ mapView: GMSMapView, didTapAt coordinate: CLLocationCoordinate2D){
var lat : String = coordinate.latitude.description
var lng : String = coordinate.longitude.description
markersArray.append(coordinate)
print(markersArray)
print(lat)
print(lng)
    print(coordinate.latitude)
    print(coordinate.longitude)
}

Body:
I believe your issue is that you are creating a second map view on the line:

let mapView = GMSMapView.map(withFrame: self.view.bounds, camera:camera)

and setting its delegate to self. You never add this map to the view. The map view you see and touch is from your storyboard which you have an outlet:

@IBOutlet weak var mapView: GMSMapView!

Which is not the same. You create a local variable with the same name. You never set this outlet's delegate. Instead of creating a new map view, simply set the camera position of the outlet:

override func viewDidLoad() {
  //set default position of the mapView
  let camera = GMSCameraPosition.camera(withLatitude: 1.285, longitude: 10.848, zoom: 10)
  mapView.position = camera
  mapView.isMyLocationEnabled = true
  mapView.settings.compassButton = true
  mapView.settings.myLocationButton = true
  mapView.camera = camera
  mapView.delegate = self
 }


问:
Swift 3 CGAffineTransform on CGRect
Basically my goal is to make an atom-like movement similar to this around my logo
https://media.giphy.com/media/9oHZQ2gEez8ti/giphy.gif

```<code>let rect = CGRect(origin: CGPoint(x: Logo.position.x - (Logo.frame.width/3.6), y: Logo.position.y - (Logo.frame.height/2) - kViewSize.height/32), size: CGSize(width: Logo.frame.width/2, height: Logo.frame.height + kViewSize.height/16))
let ellipse = CGPath(ellipseIn: rect, transform: nil)
YellowMagic.run(SKAction.repeatForever(SKAction.follow(ellipse, asOffset: false, orientToPath: false, duration: 1.5)))
</code>```

With the above code I get the middle ellipse, and the sprite runs around the path as desired.

The problem is getting the other two ellipses by rotating the path. I don't think that rotating a path is possible, so I tried rotating the rect with the following code.

```<code>var rect2 = rect
rect2 = rect2.applying(CGAffineTransform(rotationAngle: CGFloat(M_PI/4)))
let ellipse2 = CGPath(ellipseIn: rect2, transform: nil)
</code>```

The above code doesn't rotate the rectangle, in fact it makes the rectangle a square. There must be a simpler solution that I am missing here. Any help is greatly appretiated. Thanks!

答:
I modified the function found here and produced the following function:

```<code>func createPathRotatedAroundBoundingBoxCenter(path: CGPath, radians: CGFloat) -> CGPath {
    let bounds = path.boundingBox; // might want to use   CGPathGetPathBoundingBox
    let center = CGPoint(x: bounds.midX, y: bounds.midY)
    var transform = CGAffineTransform(translationX: 0, y: 0)
    transform = transform.translatedBy(x: center.x, y: center.y)
    transform = transform.rotated(by: radians)
    transform = transform.translatedBy(x: -center.x, y: -center.y)
    return path.copy(using: &transform)!
}
</code>```

I then modified my code for the desired result.

```<code>let rect = CGRect(origin: CGPoint(x: Logo.position.x - (Logo.frame.width/3.6), y: Logo.position.y - (Logo.frame.height/2) - kViewSize.height/32), size: CGSize(width: Logo.frame.width/2, height: Logo.frame.height + kViewSize.height/16))
let ellipse = CGPath(ellipseIn: rect, transform: nil)
let ellipse2a = CGPath(ellipseIn: rect, transform: nil)
let ellipse3a = CGPath(ellipseIn: rect, transform: nil)
let ellipse2 = createPathRotatedAroundBoundingBoxCenter(path: ellipse2b, radians: CGFloat(M_PI/4.0))
let ellipse3 = createPathRotatedAroundBoundingBoxCenter(path: ellipse3b, radians: CGFloat(-M_PI/4.0))
YellowMagic.run(SKAction.repeatForever(SKAction.follow(ellipse, asOffset: false, orientToPath: false, duration: 1)))
RedMagic.run(SKAction.repeatForever(SKAction.follow(ellipse2, asOffset: false, orientToPath: false, duration: 1)))
GreenMagic.run(SKAction.repeatForever(SKAction.follow(ellipse3, asOffset: false, orientToPath: false, duration: 1)))
</code>```

Title: Swift 3 CGAffineTransform on CGRect

Body:
Basically my goal is to make an atom-like movement similar to this around my logo
https://media.giphy.com/media/9oHZQ2gEez8ti/giphy.gif

let rect = CGRect(origin: CGPoint(x: Logo.position.x - (Logo.frame.width/3.6), y: Logo.position.y - (Logo.frame.height/2) - kViewSize.height/32), size: CGSize(width: Logo.frame.width/2, height: Logo.frame.height + kViewSize.height/16))
let ellipse = CGPath(ellipseIn: rect, transform: nil)
YellowMagic.run(SKAction.repeatForever(SKAction.follow(ellipse, asOffset: false, orientToPath: false, duration: 1.5)))

With the above code I get the middle ellipse, and the sprite runs around the path as desired.

The problem is getting the other two ellipses by rotating the path. I don't think that rotating a path is possible, so I tried rotating the rect with the following code.

var rect2 = rect
rect2 = rect2.applying(CGAffineTransform(rotationAngle: CGFloat(M_PI/4)))
let ellipse2 = CGPath(ellipseIn: rect2, transform: nil)

The above code doesn't rotate the rectangle, in fact it makes the rectangle a square. There must be a simpler solution that I am missing here. Any help is greatly appretiated. Thanks!

Body:
I modified the function found here and produced the following function:

func createPathRotatedAroundBoundingBoxCenter(path: CGPath, radians: CGFloat) -> CGPath {
    let bounds = path.boundingBox; // might want to use   CGPathGetPathBoundingBox
    let center = CGPoint(x: bounds.midX, y: bounds.midY)
    var transform = CGAffineTransform(translationX: 0, y: 0)
    transform = transform.translatedBy(x: center.x, y: center.y)
    transform = transform.rotated(by: radians)
    transform = transform.translatedBy(x: -center.x, y: -center.y)
    return path.copy(using: &transform)!
}

I then modified my code for the desired result.

let rect = CGRect(origin: CGPoint(x: Logo.position.x - (Logo.frame.width/3.6), y: Logo.position.y - (Logo.frame.height/2) - kViewSize.height/32), size: CGSize(width: Logo.frame.width/2, height: Logo.frame.height + kViewSize.height/16))
let ellipse = CGPath(ellipseIn: rect, transform: nil)
let ellipse2a = CGPath(ellipseIn: rect, transform: nil)
let ellipse3a = CGPath(ellipseIn: rect, transform: nil)
let ellipse2 = createPathRotatedAroundBoundingBoxCenter(path: ellipse2b, radians: CGFloat(M_PI/4.0))
let ellipse3 = createPathRotatedAroundBoundingBoxCenter(path: ellipse3b, radians: CGFloat(-M_PI/4.0))
YellowMagic.run(SKAction.repeatForever(SKAction.follow(ellipse, asOffset: false, orientToPath: false, duration: 1)))
RedMagic.run(SKAction.repeatForever(SKAction.follow(ellipse2, asOffset: false, orientToPath: false, duration: 1)))
GreenMagic.run(SKAction.repeatForever(SKAction.follow(ellipse3, asOffset: false, orientToPath: false, duration: 1)))


问:
Decode (and render) H264 RTP packets
I wrote some code that stores on the disk some RTP packets with H264 stream. I would like to be able to extract H264 data from the RTP packets and render that data somewhere to test and see if my code works. How can I do this?

I suppose gstreamer can give me a hand. If I store the packets in a file on the disk, would it be possible using gstreamer to extract, decode and render somewhere? Or to create an h264 video file to play it and see what's inside?
Thanks!

答:
Try this to capture RTP stream to file capture.rtp:

```<code>gst-launch -v -e \
v4l2src device=/dev/video0 \
    ! x264enc bitrate=200 \
    ! rtph264pay \
    ! filesink location=capture.rtp
</code>```

and this to decode and render it:

```<code>gst-launch -v \
    filesrc location=capture.rtp \
    ! application/x-rtp,media=video,clock-rate=90000,payload=96,encoding-name=H264 \
    ! rtph264depay               \
    ! ffdec_h264                 \
    ! xvimagesink
</code>```

ContentLicense: CC BY-SA 2.5

Title: Decode (and render) H264 RTP packets

Body:
Try this to capture RTP stream to file capture.rtp:

gst-launch -v -e \
v4l2src device=/dev/video0 \
    ! x264enc bitrate=200 \
    ! rtph264pay \
    ! filesink location=capture.rtp

and this to decode and render it:

gst-launch -v \
    filesrc location=capture.rtp \
    ! application/x-rtp,media=video,clock-rate=90000,payload=96,encoding-name=H264 \
    ! rtph264depay               \
    ! ffdec_h264                 \
    ! xvimagesink


问:
Xamarin.ios run a WCF Service function using await
I've followed the following example which works well.

https://developer.xamarin.com/guides/cross-platform/application_fundamentals/web_services/walkthrough_working_with_WCF/

The only issue is, the example uses button clicks to load data. Now i have two separate calls different functions, and i need one to wait for the other, for example:

So when i call function2 for example, i want to wait for function1 first.

```<code>_client.function1Async();
_client.function2Async();
</code>```

I could put the function2 call inside the function1Completed handler, but i was looking to use async wait with it. When i use async task, i get an error saying cannot await a void. But the web service async function in the example is a void

If i had 6 calls that i wanted to run, it would become very messy.

```<code>void _client_function1Completed(object sender,UpdateOrdersByWardCompletedEventArgs e
{
}

void _client_function2Completed(object sender,UpdateOrdersByWardCompletedEventArgs e
{
}
</code>```

Hope this makes sense.

答:
You could Task.ContinueWith
ContinueWith creates a continuation that executes asynchronously when task 1 completes.

var task1 = Task.Factory.StartNew( () => {  func1();  } );

Task task2 = task1 .ContinueWith( (i) => { func2();  } );

Body:
I've followed the following example which works well.

https://developer.xamarin.com/guides/cross-platform/application_fundamentals/web_services/walkthrough_working_with_WCF/

The only issue is, the example uses button clicks to load data. Now i have two separate calls different functions, and i need one to wait for the other, for example:

So when i call function2 for example, i want to wait for function1 first.

_client.function1Async();
_client.function2Async();

I could put the function2 call inside the function1Completed handler, but i was looking to use async wait with it. When i use async task, i get an error saying cannot await a void. But the web service async function in the example is a void

If i had 6 calls that i wanted to run, it would become very messy.

void _client_function1Completed(object sender,UpdateOrdersByWardCompletedEventArgs e
{
}

void _client_function2Completed(object sender,UpdateOrdersByWardCompletedEventArgs e
{
}

Hope this makes sense.


问:
Insert list evenly in another list
I am wanting to merge 2 lists together with jQuery but I am not even sure where to start. Instead of prepending or appeding the list I need to place each item between the other list. Not quite sure the best way to word this but basically I have the following HTML

```<code><ul>
  <li>A<li>
  <li>B<li>
  <li>C<li>
  <li>D<li>
  <li>E<li>
</ul>

<ul>
  <li>1<li>
  <li>2<li>
  <li>3<li>
  <li>4<li>
  <li>5<li>
</ul>
</code>```

And I am wanting a way to get the following:

```<code><ul>
  <li>A<li>
  <li>1<li>
  <li>B<li>
  <li>2<li>
  <li>C<li>
  <li>3<li>
  <li>D<li>
  <li>4<li>
  <li>E<li>
  <li>5<li>
</ul>
</code>```

答:
Considering that:

Both list have the same length

And you want the result in the second list

Following code should work (see inline comments):

```<code>// Getting all li items from each list
var firstLIs = $('ul#first li');
var secondLIs = $('ul#second li');

// Getting the length of the list
var total = firstLIs.length;
// Var that will store the result (merged LIs)
var content = [];

for (var i = 0; i < total; i++) {
  // Feeding our content array with LI items from both list
  content.push(firstLIs[i], secondLIs[i]);
}

// Overriding content from second list with the newly merged LIs
$('ul#second').html(content);
</code>```

See working JSFiddle example

Title: Insert list evenly in another list

Body:
I am wanting to merge 2 lists together with jQuery but I am not even sure where to start. Instead of prepending or appeding the list I need to place each item between the other list. Not quite sure the best way to word this but basically I have the following HTML

A

B

C

D

E

1

2

3

4

5

And I am wanting a way to get the following:

A

1

B

2

C

3

D

4

E

5

Body:
Considering that:

Both list have the same length

And you want the result in the second list

Following code should work (see inline comments):

// Getting all li items from each list
var firstLIs = $('ul#first li');
var secondLIs = $('ul#second li');

// Getting the length of the list
var total = firstLIs.length;
// Var that will store the result (merged LIs)
var content = [];

for (var i = 0; i < total; i++) {
  // Feeding our content array with LI items from both list
  content.push(firstLIs[i], secondLIs[i]);
}

// Overriding content from second list with the newly merged LIs
$('ul#second').html(content);

See working JSFiddle example


问:
Difference between these implementations in linux kernel
In Linux kernel code, I can see the macro which expands to

```<code>(1<<0)
</code>```

What does it imply? We can directly use 1 in that place why (1<<0)?

Basically what is the difference between

```<code>(AVIVO_D1CRTC_CONTROL & (1<<0))
</code>```

and

```<code>(AVIVO_D1CRTC_CONTROL & (1))
</code>```

答:
What does it imply? We can directly use 1 in that place why (1<<0)?

The bit-shift is consistent with the Boolean expression it is in.

This is not an arithmetic expression, and the numeric value of this literal constant is not salient.

What is salient is to convey the quantity of bits and the bit position(s) employed in this bit-masking operation.

You are unfortunately citing a degenerate case which does not demonstrate the advantage (in a logical expression) of using a bit-shift over the numeric value .

Admittedly it is easier to type, read, and comprehend 1 than (1 << 0).

But now that 32-bit processors and devices are ubiquitous, the larger registers and their bit definitions & bit masks will involve high powers of two.

So even though every programmer should know the bit values of a byte (i.e. the first eight powers of two), how many can do the same up to 2^31?

IOW which of the following macros is easiest to understand which bit is being defined?

```<code>#define AVIVO_CRTC_DISP_READ_REQUEST_DISABLE             16777216
#define AVIVO_CRTC_DISP_READ_REQUEST_DISABLE             0x1000000
#define AVIVO_CRTC_DISP_READ_REQUEST_DISABLE             (1 << 24)
</code>```

Devices have control and status bits accessed through registers.  The device datasheets have register descriptions that map out the bits in each register.

The modern convention is to number the register bits right to left starting with zero (like the powers of two in a binary number).

These control and status bits in the registers are often identified by the bit number, so incorporating this bit number in its definition (using a bit shift expression) is practical and more efficient than converting it to a numeric value.

It is then very easy to correlate these register diagrams with the macros for the bit definitions that use bit shifts.

Basically what is the difference between

In terms of generated object code: no difference.

To the compiler: the macro substitution and evaluation of the expression requires a trivial amount of extra compile time.

For readability and maintainability of the code: the bit-shift is the preferred choice.

Body:
In Linux kernel code, I can see the macro which expands to

(1<<0)

What does it imply? We can directly use 1 in that place why (1<<0)?

Basically what is the difference between

(AVIVO_D1CRTC_CONTROL & (1<<0))

and

(AVIVO_D1CRTC_CONTROL & (1))

Body:
What does it imply? We can directly use 1 in that place why (1<<0)?

The bit-shift is consistent with the Boolean expression it is in.

This is not an arithmetic expression, and the numeric value of this literal constant is not salient.

What is salient is to convey the quantity of bits and the bit position(s) employed in this bit-masking operation.

You are unfortunately citing a degenerate case which does not demonstrate the advantage (in a logical expression) of using a bit-shift over the numeric value .

Admittedly it is easier to type, read, and comprehend 1 than (1 << 0).

But now that 32-bit processors and devices are ubiquitous, the larger registers and their bit definitions & bit masks will involve high powers of two.

So even though every programmer should know the bit values of a byte (i.e. the first eight powers of two), how many can do the same up to 2^31?

IOW which of the following macros is easiest to understand which bit is being defined?

#define AVIVO_CRTC_DISP_READ_REQUEST_DISABLE             16777216
#define AVIVO_CRTC_DISP_READ_REQUEST_DISABLE             0x1000000
#define AVIVO_CRTC_DISP_READ_REQUEST_DISABLE             (1 << 24)

Devices have control and status bits accessed through registers.  The device datasheets have register descriptions that map out the bits in each register.

The modern convention is to number the register bits right to left starting with zero (like the powers of two in a binary number).

These control and status bits in the registers are often identified by the bit number, so incorporating this bit number in its definition (using a bit shift expression) is practical and more efficient than converting it to a numeric value.

It is then very easy to correlate these register diagrams with the macros for the bit definitions that use bit shifts.

Basically what is the difference between

In terms of generated object code: no difference.

To the compiler: the macro substitution and evaluation of the expression requires a trivial amount of extra compile time.

For readability and maintainability of the code: the bit-shift is the preferred choice.


问:
Html / Php form not adding to SQL database
I've been working on this for hours now and including rebuilding my whole code I cannot figure out what is wrong. The HTML form is supposed to populate the patients SQL database but it is not working. I have a similar form that I am using on another part of the website that works flawlessly but this on doesn't seem to and a can't figure out why.

thanks for your help

Here is a picture of thedatabase fields :
Database fields

Heres the code:

<?php

//session_start();

//if( isset($_SESSION['user_id']) ){
//  header("Location: /");
//}

require 'connection.php';

$message = '';

if(!empty($_POST['name']) && !empty($_POST['dob']) && !empty($_POST['nok']) && !empty($_POST['nok_add']) && !empty($_POST['nok_phone'])&& !empty($_POST['doa'])&& !empty($_POST['allergies'])):

  // Enter the new user in the database
  $sql = "INSERT INTO patients (name, dob, nok, nok_add, nok_phone, doa, allergies) VALUES (:name, :dob, :nok, :nok_add, :nok_phone, :doa, :allergies)";
  $stmt = $conn->prepare($sql);

  $stmt->bindParam(':name', $_POST['name']);
  $stmt->bindParam(':dob', $_POST['dob']);
  $stmt->bindParam(':nok', $_POST['nok']);
  $stmt->bindParam(':nok_add', $_POST['nok_add']);
  $stmt->bindParam(':nok_phone', $_POST['nok_phone']);
  $stmt->bindParam(':doa', $_POST['doa']);
  $stmt->bindParam(':allergies', $_POST['allergies']);

  if( $stmt->execute() ):
    $message = 'Successfully created new user';
  else:
    $message = 'Sorry there must have been an issue creating your account';
  endif;

endif;

?>

    <title>Patient Add</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" type="text/css" href="assets/css/style.css">
      <link href="//fonts.googleapis.com/css?fami=Roboto:400,300,200,100&subset=latin,cyrillic" rel="stylesheet">

Patient Add

    <button onClick="window.location='manager_select.php';" class="_button">Back</button>
    <form method="POST" id="add">

Enter the Patient's Details

      Name:
      <input type="text" name="name">

      Date of Birth:
      <input type="text" name="dob">

      Next of Kin:
      <input type="text" name="nok">

      Address:
      <input type="text" name="nok_add">

      Phone:
      <input type="text" name="nok_phone">

      Date of Admission:
      <input type="text" name="dob">

      Allergies:
      <input type="text" name="allergies">

      <?php if(!empty($message)): ?>

<?= $message ?>

      <?php endif; ?>
      <input type="submit">

    </form>

Copyright Ghyll Court Residental Home 2017

  </script>

```

答:
As answered on your duplicate post (also answering here for completeness), you're checking for a "doa" field in your if statement, which doesn't exist. Your form defines "dob" twice: once for Date of Birth, and once for Date of Admission:

```<code><label for="dob">Date of Birth:</label>
<input type="text" name="dob">

...

<label for="doa">Date of Admission:</label>
<input type="text" name="dob">
</code>```

Body:
As answered on your duplicate post (also answering here for completeness), you're checking for a "doa" field in your if statement, which doesn't exist. Your form defines "dob" twice: once for Date of Birth, and once for Date of Admission:

<label for="dob">Date of Birth:</label>
<input type="text" name="dob">

...

<label for="doa">Date of Admission:</label>
<input type="text" name="dob">


问:
Python curve fit with change point
As I'm really struggleing to get from R-code, to Python code, I would like to ask some help. The code I want to use has been provided to my from withing the mathematics forum of stackexchange.

https://math.stackexchange.com/questions/2205573/curve-fitting-on-dataset

I do understand what is going on. But I'm really having a hard time trying to solve the R-code, as I have never seen anything of it. I have written the function to return the sum of squares. But I'm stuck at how I could use a function similar to the optim function. And also I don't really like the guesswork at the initial values. I would like it better to run and re-run a type of optim function untill I get the wanted result, because my needs for a nearly perfect curve fit are really high.

```<code>def model (par,x):
    n = len(x)
    res = []
    for i in range(1,n):
        A0 = par[3] + (par[4]-par[1])*par[6] + (par[5]-par[2])*par[6]**2
        if(x[i] == par[6]):
            res[i] = A0 + par[1]*x[i] + par[2]*x[i]**2
        else:
            res[i] = par[3] + par[4]*x[i] + par[5]*x[i]**2
    return res
</code>```

This is my model function...

```<code>def sum_squares (par, x, y):
    ss = sum((y-model(par,x))^2)
    return ss
</code>```

And this is the sum of squares

But I have no idea on how to convert this:

```<code> #I found these initial values with a few minutes of guess and check.
 par0 <- c(7,-1,-395,70,-2.3,10)
 sol <- optim(par= par0, fn=sqerror, x=x, y=y)$par
</code>```

To Python code...

答:
I wrote an open source Python package (BSD license) that has a genetic algorithm (Differential Evolution) front end to the scipy Levenberg-Marquardt solver, it functions similarly to what you describe in your question.  The github URL is:

https://github.com/zunzun/pyeq3

It comes with a "user-defined function" example that's fairly easy to use:

https://github.com/zunzun/pyeq3/blob/master/Examples/Simple/FitUserDefinedFunction_2D.py

along with command-line, GUI, cluster, parallel, and web-based examples.  You can install the package with "pip3 install pyeq3" to see if it might suit your needs.

Title: Python curve fit with change point

Body:
As I'm really struggleing to get from R-code, to Python code, I would like to ask some help. The code I want to use has been provided to my from withing the mathematics forum of stackexchange.

https://math.stackexchange.com/questions/2205573/curve-fitting-on-dataset

I do understand what is going on. But I'm really having a hard time trying to solve the R-code, as I have never seen anything of it. I have written the function to return the sum of squares. But I'm stuck at how I could use a function similar to the optim function. And also I don't really like the guesswork at the initial values. I would like it better to run and re-run a type of optim function untill I get the wanted result, because my needs for a nearly perfect curve fit are really high.

def model (par,x):
    n = len(x)
    res = []
    for i in range(1,n):
        A0 = par[3] + (par[4]-par[1])*par[6] + (par[5]-par[2])*par[6]**2
        if(x[i] == par[6]):
            res[i] = A0 + par[1]*x[i] + par[2]*x[i]**2
        else:
            res[i] = par[3] + par[4]*x[i] + par[5]*x[i]**2
    return res

This is my model function...

def sum_squares (par, x, y):
    ss = sum((y-model(par,x))^2)
    return ss

And this is the sum of squares

But I have no idea on how to convert this:

 #I found these initial values with a few minutes of guess and check.
 par0 <- c(7,-1,-395,70,-2.3,10)
 sol <- optim(par= par0, fn=sqerror, x=x, y=y)$par

To Python code...


问:
Expected Type error in Stripe objective-c
I am integrating Stripe Payment gateway in my app. But there is "Expected a type" error. I exactly don't know what is the issue. The issue comes in this line,

```<code>- (void)paymentViewController:(PaymentViewController *)controller didFinishWithToken:(STPToken *)token email:(NSString *)email error:(NSError *)error;
</code>```

This method is inside PaymentViewController.h file.

    I simply drag and drop the "stripe.framework" with  "PaymentViewController.h" and "PaymentViewController.m" file.

Can anyone help me? Thanks in advance.

答:
It sounds like something isn't quite right about how you have added the Stripe SDK to the your project.

If you are using the Stripe SDK as a dynamic framework, then you should ensure that you did the following:

Head to https://github.com/stripe/stripe-ios/releases/latest and download and unzip Stripe.framework.zip.

Drag Stripe.framework to the "Embedded Binaries" section of your Xcode project's "General" settings. Make sure to select "Copy items if needed".

Head to the "Build Phases" section of your Xcode project settings, and create a new "Run Script Build Phase". Paste the following snippet into the text field:

bash "${BUILT_PRODUCTS_DIR}/${FRAMEWORKS_FOLDER_PATH}/Stripe.framework/integrate-dynamic-framework.sh"

If you are using Stripe as a static framework (which is only suggested if you must support iOS 7, then make sure that you have done the following instead:

Head to https://github.com/stripe/stripe-ios/releases/latest and download and unzip StripeiOS-Static.zip.

In Xcode, with your project open, click on "File" then "Add files to Project...".

Select Stripe.framework in the directory you just unzipped.

Make sure "Copy items if needed" is checked.

Click "Add".

In Xcode, click on "File", then "Add files to Project...".

Select Stripe.bundle, located within Stripe.framework.

Make sure "Copy items if needed" is checked.

Click "Add".

Once you've done either of these sets of steps, you should save your project, and then clean your project via the "Product" > "Clean" menubar option. Then try rebuilding your project.

Body:
I am integrating Stripe Payment gateway in my app. But there is "Expected a type" error. I exactly don't know what is the issue. The issue comes in this line,

- (void)paymentViewController:(PaymentViewController *)controller didFinishWithToken:(STPToken *)token email:(NSString *)email error:(NSError *)error;

This method is inside PaymentViewController.h file.

    I simply drag and drop the "stripe.framework" with  "PaymentViewController.h" and "PaymentViewController.m" file.

Can anyone help me? Thanks in advance.


问:
Can PL/pgSQL return a function from a function? Or even a set of functions?
Can I declare a PL/pgSQL function where the return type is a function?  Or even a set of functions?  Is there even a function type in the language?

I was noodling with the idea of a library of PL/pgSQL functions that could handle function chaining to make using the library easier.  Syntax akin to method dispatch isn't possible, but returning a function from a function should allow for some basic syntax magic.  Unfortunately I don't have enough of a mastery of PL/pgSQL yet to try to describe what I'm asking in a code example, I hope the question is clear enough as stated.

A variant of this question, Is SQL a functional language was asked 8 years ago, but my question is a little more specific (besides, the #1 answer on that question is incorrect!).

答: No, I don't think you can. There is a type created implicitly for every table, which reflects the row structure of the table; but there's nothing equivalent for functions.</p>


问:
Bundle.main.path(forResource:ofType:inDirectory:) returns nil
Try not to laugh or cry -- I'm just getting back into coding after 20 years out...

I've spent more than 4 hours looking at references and trying code snippets to get Bundle.main.path to open my text file so I can read in data for my app (my next step is to appropriately parse it).

```<code>if let filepath = Bundle.main.path(forResource: "newTest", ofType: "txt")
{
    do
    {
        let contents = try String(contentsOfFile: filepath)
        print(contents)

    }
    catch
    {
        print("Contents could not be loaded.")
    }
}
else
{
    print("newTest.txt not found.")
}
</code>```

The result is: "newTest.txt not found." regardless of how I try to drag&drop the file into the project, create the file inside Xcode or use the File -> Add Files to ... menu item.

答:
The issue is that the file isn't being copied to your app bundle. To fix it:

Click your project

Click your target

Select Build Phases

Expand Copy Bundle Resources

Click '+' and select your file.

Body:
Try not to laugh or cry -- I'm just getting back into coding after 20 years out...

I've spent more than 4 hours looking at references and trying code snippets to get Bundle.main.path to open my text file so I can read in data for my app (my next step is to appropriately parse it).

if let filepath = Bundle.main.path(forResource: "newTest", ofType: "txt")
{
    do
    {
        let contents = try String(contentsOfFile: filepath)
        print(contents)

    }
    catch
    {
        print("Contents could not be loaded.")
    }
}
else
{
    print("newTest.txt not found.")
}

The result is: "newTest.txt not found." regardless of how I try to drag&drop the file into the project, create the file inside Xcode or use the File -> Add Files to ... menu item.

ContentLicense: CC BY-SA 4.0


问:
How to sort contents of an <xsl:variable>
```<code><?xml version="1.0" encoding="UTF-8"?>
<sortedResults xmlns="urn:com-avaneesh-abc:v1">
    <result time-zone="America/Chicago" event-end-dt-tm="2013-06-11T15:37:00.000-05:00"
                        event-id="16886888"/>
    <result time-zone="America/Chicago" event-end-dt-tm="2013-06-13T15:37:00.000-05:00"
                        event-id="16886890"/>
    <result time-zone="America/Chicago" event-end-dt-tm="2013-06-10T15:37:00.000-05:00"
                        event-id="16886884"/>
    <result time-zone="America/Chicago" event-end-dt-tm="2013-06-10T15:37:00.000-05:00"
                        event-id="16886878"/>
    <result time-zone="America/Chicago" event-end-dt-tm="2013-06-13T15:37:00.000-05:00"
                        event-id="16886886"/>
    <result time-zone="America/Chicago" event-end-dt-tm="2013-06-11T15:37:00.000-05:00"
                        event-id="1688687416886876"/>
</sortedResults>
</code>```

I would like to sort the above sample XML which is part of an <xsl:variable> to be sorted by the event-end-dt-tm of each and every <result> and move the latest date under one XML tag <first>, oldest under <last> and the remaining ones under tag <other>. I tried to use <xsl:sort>, but it's not sorting as expected.

答:
This XSLT-1.0 will sort all <result> children of <sortedResults> by the attribute @event-end-dt-tm while being namespace aware to the namespace urn:com-avaneesh-abc:v1:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:ava="urn:com-avaneesh-abc:v1">
  <xsl:output method="xml" />

  <xsl:template match="/ava:sortedResults">
    <xsl:apply-templates>
      <xsl:sort select="@event-end-dt-tm" />
    </xsl:apply-templates>
  </xsl:template>

  <xsl:template match="ava:result">
    <!-- Put your desired processing here !!! -->
    <xsl:value-of select="@event-id" /><xsl:text>
</xsl:text>  <!-- For example the @event-id followed by a newline -->
  </xsl:template>

</xsl:stylesheet>
</code>```

Body:
<?xml version="1.0" encoding="UTF-8"?>
<sortedResults xmlns="urn:com-avaneesh-abc:v1">
    <result time-zone="America/Chicago" event-end-dt-tm="2013-06-11T15:37:00.000-05:00"
                        event-id="16886888"/>
    <result time-zone="America/Chicago" event-end-dt-tm="2013-06-13T15:37:00.000-05:00"
                        event-id="16886890"/>
    <result time-zone="America/Chicago" event-end-dt-tm="2013-06-10T15:37:00.000-05:00"
                        event-id="16886884"/>
    <result time-zone="America/Chicago" event-end-dt-tm="2013-06-10T15:37:00.000-05:00"
                        event-id="16886878"/>
    <result time-zone="America/Chicago" event-end-dt-tm="2013-06-13T15:37:00.000-05:00"
                        event-id="16886886"/>
    <result time-zone="America/Chicago" event-end-dt-tm="2013-06-11T15:37:00.000-05:00"
                        event-id="1688687416886876"/>
</sortedResults>

I would like to sort the above sample XML which is part of an <xsl:variable> to be sorted by the event-end-dt-tm of each and every <result> and move the latest date under one XML tag <first>, oldest under <last> and the remaining ones under tag <other>. I tried to use <xsl:sort>, but it's not sorting as expected.

Body:
This XSLT-1.0 will sort all <result> children of <sortedResults> by the attribute @event-end-dt-tm while being namespace aware to the namespace urn:com-avaneesh-abc:v1:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:ava="urn:com-avaneesh-abc:v1">
  <xsl:output method="xml" />

  <xsl:template match="/ava:sortedResults">
    <xsl:apply-templates>
      <xsl:sort select="@event-end-dt-tm" />
    </xsl:apply-templates>
  </xsl:template>

  <xsl:template match="ava:result">
    <!-- Put your desired processing here !!! -->
    <xsl:value-of select="@event-id" /><xsl:text>&#10;</xsl:text>  <!-- For example the @event-id followed by a newline -->
  </xsl:template>

</xsl:stylesheet>


问:
C - Variable Argument with Sprintf?
I have a function;

```<code>void foo(const char* format, ...)
{
    char buffer[1080];

    // Supposed way to handle C Variable Arguments?
    va_list argptr;
    va_start(argptr, format);
    sprintf(buffer, format, argptr);
    va_end(argptr);

    printf_s("%s.\n", buffer);
}

int main()
{
    int val = 53;
    foo("%d", val);
}
</code>```

Everytime I run this, I get MASSIVE numbers that change every during each run. 12253360,  5306452, etc. I don't understand why.

Is it something with my sprintf call or is it the way I'm doing the va_list argptr;? Is my buffer too large?

Thanks.

答:
The technique you are apparently attempting to use suggests that you need vsprintf (or, better, vsnprintf)

```<code>va_list argptr;
va_start(argptr, format);
vsnprintf(buffer, sizeof buffer, format, argptr);
va_end(argptr);
</code>```

That's the very reason such functions from v... group exist in standard library.

Calling sprintf the way you do it makes no sense at all - it cannot be used with an externally supplied va_list.

If you want to implement a variable-sized buffer you can do it as follows

```<code>void foo(const char* format, ...)
{
    static char *buffer;
    static size_t buffer_size;

    va_list argptr;
    va_start(argptr, format);
    int length = vsnprintf(buffer, buffer_size, format, argptr);
    va_end(argptr);

    if (length + 1 > buffer_size)
    {
      buffer_size = length + 1;
      buffer = realloc(buffer, buffer_size);
      /* Yes, `realloc` should be done differently to properly handle
         possible failures. But that's beside the point in this context */

      va_start(argptr, format);
      vsnprintf(buffer, buffer_size, format, argptr);
      va_end(argptr);
    }

    printf("%s.\n", buffer);
}
</code>```

You can, of course, change the memory management strategy to something different, like use a fixed local buffer of 512 bytes in the first call, and then use a temporary dynamically allocated buffer in the second call only if 512 proves to be insufficient. And so on...

Title: C - Variable Argument with Sprintf?

Body:
I have a function;

void foo(const char* format, ...)
{
    char buffer[1080];

    // Supposed way to handle C Variable Arguments?
    va_list argptr;
    va_start(argptr, format);
    sprintf(buffer, format, argptr);
    va_end(argptr);

    printf_s("%s.\n", buffer);
}

int main()
{
    int val = 53;
    foo("%d", val);
}

Everytime I run this, I get MASSIVE numbers that change every during each run. 12253360,  5306452, etc. I don't understand why.

Is it something with my sprintf call or is it the way I'm doing the va_list argptr;? Is my buffer too large?

Thanks.

Body:
The technique you are apparently attempting to use suggests that you need vsprintf (or, better, vsnprintf)

va_list argptr;
va_start(argptr, format);
vsnprintf(buffer, sizeof buffer, format, argptr);
va_end(argptr);

That's the very reason such functions from v... group exist in standard library.

Calling sprintf the way you do it makes no sense at all - it cannot be used with an externally supplied va_list.

If you want to implement a variable-sized buffer you can do it as follows

void foo(const char* format, ...)
{
    static char *buffer;
    static size_t buffer_size;

    va_list argptr;
    va_start(argptr, format);
    int length = vsnprintf(buffer, buffer_size, format, argptr);
    va_end(argptr);

    if (length + 1 > buffer_size)
    {
      buffer_size = length + 1;
      buffer = realloc(buffer, buffer_size);
      /* Yes, `realloc` should be done differently to properly handle
         possible failures. But that's beside the point in this context */

      va_start(argptr, format);
      vsnprintf(buffer, buffer_size, format, argptr);
      va_end(argptr);
    }

    printf("%s.\n", buffer);
}

You can, of course, change the memory management strategy to something different, like use a fixed local buffer of 512 bytes in the first call, and then use a temporary dynamically allocated buffer in the second call only if 512 proves to be insufficient. And so on...


问:
View value of variables in some kind of output in IBM RPG
I am trying to learn IBM RPG and rewrite a program for my employer. I need a way to see whether my variables are getting assigned to the values i expect them too but i dont know how to output something to my screen to just display the values. Is there a way to send a break message containing the variables in the RPG program, not the CL program?  Thanks</p>

答:
The suggestion of a Debugger is the best one.  I work in RPG400(pre ILE). For that, i can list the steps I use. Hopefully this might be a help if you arent doing ILE Or RPG4. I have an RPG program, ABRKR being called by ABROADC (the CL).
Im going to debug ABRKR and NOT step thru the CL, I know that works.
Disclaimer: Green screen programming coming.

On the command line, type   STRISDB   & press F4

Type in the name of the program, library .....(yatta yatta)

Press ENTER to finish it up....
Im calling the ABROADC. Notice the Invoke Program

Press ENTER to start the ball rolling

Once in the program, press F5 to Start stepping thru the program

you can step thru your code 1 line at a time by pressing F5

to check a variable value, position the cursor on the variable & press F11

Press ENTER or F12 to back out of the detail screen.

Press F3 to exit the debugger... OR ...

Position the cursor to any line you want, press F13 (shift F1) to jump to that line of code.  If you found what you wanted & want the program to run to its end, just jump to the *INLR or LR indicator where you turn it on & press ENTER. The job will run to completion.

My apologies to everyone who hates fixed format, and old tech. I am making an effort to answer the question.


问:
Proper way of using BeginTransaction with Dapper.IDbConnection
Which is the proper way of using BeginTransaction() with IDbConnection in Dapper ?

I have created a method in which i have to use BeginTransaction(). Here is the code.

```<code>using (IDbConnection cn = DBConnection)
{
    var oTransaction = cn.BeginTransaction();

    try
    {
        // SAVE BASIC CONSULT DETAIL
        var oPara = new DynamicParameters();
        oPara.Add("@PatientID", iPatientID, dbType: DbType.Int32);
        ..........blah......blah............
    }
    catch (Exception ex)
    {
        oTransaction.Rollback();
        return new SaveResponse { Success = false, ResponseString = ex.Message };
    }
}
</code>```

When i executed above method - i got an exception -

Invalid operation. The connection is closed.

This is because you can't begin a transaction before the connection is opened. So when i add this line: cn.Open();, the error gets resolved. But i have read somewhere that manually opening the connection is bad practice!! Dapper opens a connection only when it needs to.

In Entity framework you can handle a transaction using a TransactionScope.

So my question is what is a good practice to handle transaction without adding the line cn.Open()... in Dapper ? I guess there should be some proper way for this.

答:
Take a look at Tim Schreiber solution which is simple yet powerful and implemented using repository pattern and has Dapper Transactions in mind.

The Commit() in the code below shows it.

```<code>public class UnitOfWork : IUnitOfWork
{
    private IDbConnection _connection;
    private IDbTransaction _transaction;
    private IBreedRepository _breedRepository;
    private ICatRepository _catRepository;
    private bool _disposed;

    public UnitOfWork(string connectionString)
    {
        _connection = new SqlConnection(connectionString);
        _connection.Open();
        _transaction = _connection.BeginTransaction();
    }

    public IBreedRepository BreedRepository
    {
        get { return _breedRepository ?? (_breedRepository = new BreedRepository(_transaction)); }
    }

    public ICatRepository CatRepository
    {
        get { return _catRepository ?? (_catRepository = new CatRepository(_transaction)); }
    }

    public void Commit()
    {
        try
        {
            _transaction.Commit();
        }
        catch
        {
            _transaction.Rollback();
            throw;
        }
        finally
        {
            _transaction.Dispose();
            _transaction = _connection.BeginTransaction();
            resetRepositories();
        }
    }

    private void resetRepositories()
    {
        _breedRepository = null;
        _catRepository = null;
    }

    public void Dispose()
    {
        dispose(true);
        GC.SuppressFinalize(this);
    }

    private void dispose(bool disposing)
    {
        if (!_disposed)
        {
            if(disposing)
            {
                if (_transaction != null)
                {
                    _transaction.Dispose();
                    _transaction = null;
                }
                if(_connection != null)
                {
                    _connection.Dispose();
                    _connection = null;
                }
            }
            _disposed = true;
        }
    }

    ~UnitOfWork()
    {
        dispose(false);
    }
}
</code>```

Body:
Which is the proper way of using BeginTransaction() with IDbConnection in Dapper ?

I have created a method in which i have to use BeginTransaction(). Here is the code.

using (IDbConnection cn = DBConnection)
{
    var oTransaction = cn.BeginTransaction();

    try
    {
        // SAVE BASIC CONSULT DETAIL
        var oPara = new DynamicParameters();
        oPara.Add("@PatientID", iPatientID, dbType: DbType.Int32);
        ..........blah......blah............
    }
    catch (Exception ex)
    {
        oTransaction.Rollback();
        return new SaveResponse { Success = false, ResponseString = ex.Message };
    }
}

When i executed above method - i got an exception -

Invalid operation. The connection is closed.

This is because you can't begin a transaction before the connection is opened. So when i add this line: cn.Open();, the error gets resolved. But i have read somewhere that manually opening the connection is bad practice!! Dapper opens a connection only when it needs to.

In Entity framework you can handle a transaction using a TransactionScope.

So my question is what is a good practice to handle transaction without adding the line cn.Open()... in Dapper ? I guess there should be some proper way for this.

Body:
Take a look at Tim Schreiber solution which is simple yet powerful and implemented using repository pattern and has Dapper Transactions in mind.

The Commit() in the code below shows it.

public class UnitOfWork : IUnitOfWork
{
    private IDbConnection _connection;
    private IDbTransaction _transaction;
    private IBreedRepository _breedRepository;
    private ICatRepository _catRepository;
    private bool _disposed;

    public UnitOfWork(string connectionString)
    {
        _connection = new SqlConnection(connectionString);
        _connection.Open();
        _transaction = _connection.BeginTransaction();
    }

    public IBreedRepository BreedRepository
    {
        get { return _breedRepository ?? (_breedRepository = new BreedRepository(_transaction)); }
    }

    public ICatRepository CatRepository
    {
        get { return _catRepository ?? (_catRepository = new CatRepository(_transaction)); }
    }

    public void Commit()
    {
        try
        {
            _transaction.Commit();
        }
        catch
        {
            _transaction.Rollback();
            throw;
        }
        finally
        {
            _transaction.Dispose();
            _transaction = _connection.BeginTransaction();
            resetRepositories();
        }
    }

    private void resetRepositories()
    {
        _breedRepository = null;
        _catRepository = null;
    }

    public void Dispose()
    {
        dispose(true);
        GC.SuppressFinalize(this);
    }

    private void dispose(bool disposing)
    {
        if (!_disposed)
        {
            if(disposing)
            {
                if (_transaction != null)
                {
                    _transaction.Dispose();
                    _transaction = null;
                }
                if(_connection != null)
                {
                    _connection.Dispose();
                    _connection = null;
                }
            }
            _disposed = true;
        }
    }

    ~UnitOfWork()
    {
        dispose(false);
    }
}


问:
Show sharedpreference inside RecyclerView Adapter
I have problem to pass context from Activity to Adapter.

I am calling my sharedpreference like this:

```<code>    SharedPreferences pref = PreferenceManager
            .getDefaultSharedPreferences(ctx);
    String userObject = pref.getString(key, null);
</code>```

And this one need context, so i am using : getApplicationContext()

But this not work in the Adapter (RecyclerView), is there someone facing the same issue ?

Adding the adapter into the Manifest file will solve the problem ? (Just a suggestion)

答:
I suggest you to separate your preference-managing code into singleton class so you can get access to the preferences anywhere, just like this

```<code>public class SharedPreferenceManager {
private static final SharedPreferenceManager ourInstance = new SharedPreferenceManager();

public static SharedPreferenceManager getInstance() {
    return ourInstance;
}

private SharedPreferenceManager() {
}

private SharedPreferences preferences;

public void init(Context ctx) {
    preferences = PreferenceManager.getDefaultSharedPreferences(ctx);
}

public String getValueByKey(String key) {
    return preferences.getString(key, "");
}..other functions....}
</code>```

you should call the SharedPreferenceManager.getInstance().init(this) in your onCreate() in the activity

and after you can get access to SP wherever you want: SharedPreferenceManager.getInstance().getValueByKey("somekey")

Body:
I have problem to pass context from Activity to Adapter.

I am calling my sharedpreference like this:

    SharedPreferences pref = PreferenceManager
            .getDefaultSharedPreferences(ctx);
    String userObject = pref.getString(key, null);

And this one need context, so i am using : getApplicationContext()

But this not work in the Adapter (RecyclerView), is there someone facing the same issue ?

Adding the adapter into the Manifest file will solve the problem ? (Just a suggestion)

Body:
I suggest you to separate your preference-managing code into singleton class so you can get access to the preferences anywhere, just like this

public class SharedPreferenceManager {
private static final SharedPreferenceManager ourInstance = new SharedPreferenceManager();

public static SharedPreferenceManager getInstance() {
    return ourInstance;
}

private SharedPreferenceManager() {
}

private SharedPreferences preferences;

public void init(Context ctx) {
    preferences = PreferenceManager.getDefaultSharedPreferences(ctx);
}

public String getValueByKey(String key) {
    return preferences.getString(key, "");
}..other functions....}

you should call the SharedPreferenceManager.getInstance().init(this) in your onCreate() in the activity

and after you can get access to SP wherever you want: SharedPreferenceManager.getInstance().getValueByKey("somekey")


问:
Type Mismatch Error using randomForest in R
I am trying to use random forest in R for classifying some kaggle data but I keep getting the following error whenever I try to use the model which I have created.

```<code>Error in predict.randomForest(fit, newdata = test, type = "class") :
  Type of predictors in new data do not match that of the training data
</code>```

I am totally lost as to the reason for this error and Google has not been of much help. Any help or insight will be appreciated. The simple code snippet is given below and its in response to one of the kaggle problems.

```<code>fit = randomForest(as.factor(IsBadBuy) ~ VehicleAge + WheelTypeID + Transmission + WarrantyCost + VehOdo + Auction,
                   data=training, importance=TRUE, do.trace=100, keep.forest=TRUE)

prediction = predict(fit, newdata=test, type='class')

t = table(observed=test[, 'IsBadBuy'], predict=prediction)
</code>```

答:
For a R newbie like me...
They are right when they say "The error message means exactly what it says: there is at least one variable in your training data whose type does not match the equivalent variable in your test data."

Do run the following to confirm nothing is obviously different:

str(training) and str(NewData)

That will list the training and new data's features and types.  The reason why you might still be confused, as I was, is the datatypes might appear to match and yet the error. It's probably that while a feature/column in both sets is listed as a factor the levels are not the same. My new data was much smaller, didn't have all the levels the training data did. That will blow you up with this error. The fix is: when you are processing your new data and go to factor it, pass in all the possible levels. That will get you to match and things will work.

```<code>dataframe$ColToFactor <- factor(dataframe$ColToFactor, levels=c("PossibleLvl1", "PossibleLvl2", "PossibleLvl3", account for all possible))
</code>```

That was the deal for me.

Body:
I am trying to use random forest in R for classifying some kaggle data but I keep getting the following error whenever I try to use the model which I have created.

Error in predict.randomForest(fit, newdata = test, type = "class") :
  Type of predictors in new data do not match that of the training data

I am totally lost as to the reason for this error and Google has not been of much help. Any help or insight will be appreciated. The simple code snippet is given below and its in response to one of the kaggle problems.

fit = randomForest(as.factor(IsBadBuy) ~ VehicleAge + WheelTypeID + Transmission + WarrantyCost + VehOdo + Auction,
                   data=training, importance=TRUE, do.trace=100, keep.forest=TRUE)

prediction = predict(fit, newdata=test, type='class')

t = table(observed=test[, 'IsBadBuy'], predict=prediction)

Body:
For a R newbie like me...
They are right when they say "The error message means exactly what it says: there is at least one variable in your training data whose type does not match the equivalent variable in your test data."

Do run the following to confirm nothing is obviously different:

str(training) and str(NewData)

That will list the training and new data's features and types.  The reason why you might still be confused, as I was, is the datatypes might appear to match and yet the error. It's probably that while a feature/column in both sets is listed as a factor the levels are not the same. My new data was much smaller, didn't have all the levels the training data did. That will blow you up with this error. The fix is: when you are processing your new data and go to factor it, pass in all the possible levels. That will get you to match and things will work.

dataframe$ColToFactor <- factor(dataframe$ColToFactor, levels=c("PossibleLvl1", "PossibleLvl2", "PossibleLvl3", account for all possible))

That was the deal for me.


问:
jQuery in rails: replace input field with another input type
Within my js.erb file, I successfully grab the input element I want to replace.  As a test: I can easily replace that input element with a
 element:

```<code>$(‘.selector_for_input_element’).replaceWith("<p>hello world</p>");
</code>```

I can even successfully do the same thing with content_tag:

```<code>$('.selector_for_input_element').replaceWith("<%= content_tag(:p, "hello world") %>");
</code>```

However: when I attempt to replace the input element (which happens to be a select box) with a text field: nothing happens:

```<code>$('.selector_for_input_element').replaceWith("<%= text_field_tag("name") %>");
</code>```

With the rails form helpers: how can I successfully swap out the selected input element, and replace it with a text field?

答:
Moving the comments to an answer.
For anyone else looking, the issue is related to string safety in .js.erb.

Flipping quotes to '' on the outside and "" on the inside of the JS statement worked.

Body:
Within my js.erb file, I successfully grab the input element I want to replace.  As a test: I can easily replace that input element with a
 element:

$(‘.selector_for_input_element’).replaceWith("
hello world
");

I can even successfully do the same thing with content_tag:

$('.selector_for_input_element').replaceWith("<%= content_tag(:p, "hello world") %>");

However: when I attempt to replace the input element (which happens to be a select box) with a text field: nothing happens:

$('.selector_for_input_element').replaceWith("<%= text_field_tag("name") %>");

With the rails form helpers: how can I successfully swap out the selected input element, and replace it with a text field?


问:
Cake NuGetRestore always wants MSBuild14?
While trying to rig up a solution to build with Cake v0.19.1 on a machine that has only ever known Visual Studio 2017, I can't seem to get NuGetRestore to accept a setting of MSBuildVersion = NuGetMSBuildVersion.MSBuild15.

Is there some magic step to getting a specific MSBuild version into NuGetRestore that I am missing?

Output

```<code>...

========================================
RestoreNuGet
========================================
Executing task: RestoreNuGet
Failed to load msbuild Toolset
  Could not load file or assembly 'Microsoft.Build, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.
An error occurred when executing task 'RestoreNuGet'.
Error: NuGet: Process returned an error (exit code 1).
</code>```

Trimmed-down build.cake

```<code>var target = Argument("target", "Default");
var solution = "./some-random.sln";

Task("Default")
.Does(() => {
    NuGetRestore(
        solution,
        new NuGetRestoreSettings {
            MSBuildVersion = NuGetMSBuildVersion.MSBuild15,
        }
    );
});

RunTarget(target);
</code>```

Update: getting NuGet v4

Per @devlead's answer, I pointed the build.ps1 file at the v4.0.0 of NuGet and got this output.

```<code>Cannot find the specified version of msbuild: '15'
An error occurred when executing task 'RestoreNuGet'.
Error: NuGet: Process returned an error (exit code 1).
</code>```

In my full build.cake, I use vswhere for later MSBuildSettings which I can get to dump out the MSBuild path it found (and I confirmed that exe exists in Explorer).

```<code>C:/Program Files (x86)/Microsoft Visual Studio/2017/Enterprise/MSBuild/15.0/Bin/amd64/MSBuild.exe
</code>```

答:
Make sure you're using the latest version of NuGet.exe, currently it's
v4.0.0 which is the latest version, but you can also see a list of available at https://dist.nuget.org

If you're using the default build.ps1 you could modify it to always download specific version of NuGet.exe

You can do this be remove the Test.Path parts - so it won't look for nuget.exe any where else but your tools folder.
Then change the download uri to not use latest stable (currently v3.5.0) but a specific version by in build.ps1 changing

```<code>$NUGET_URL = "https://dist.nuget.org/win-x86-commandline/latest/nuget.exe"
</code>```

to

```<code>$NUGET_URL = "https://dist.nuget.org/win-x86-commandline/v4.0.0/nuget.exe"
</code>```

will ensure you always download v4.0.0 of the exe.

It's also possible with a little PowerShell to verify correct version in tools, example

```<code>if ((Get-ChildItem $NUGET_EXE `
    | % VersionInfo `
    | % ProductVersion `
    | ? { $_ -eq '4.0.0' }|Measure-Object).Count -eq 1)
{
   'Correct version'
} else {
   'Incorrect version'
}
</code>```

Body:
While trying to rig up a solution to build with Cake v0.19.1 on a machine that has only ever known Visual Studio 2017, I can't seem to get NuGetRestore to accept a setting of MSBuildVersion = NuGetMSBuildVersion.MSBuild15.

Is there some magic step to getting a specific MSBuild version into NuGetRestore that I am missing?

Output

...

========================================
RestoreNuGet
========================================
Executing task: RestoreNuGet
Failed to load msbuild Toolset
  Could not load file or assembly 'Microsoft.Build, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.
An error occurred when executing task 'RestoreNuGet'.
Error: NuGet: Process returned an error (exit code 1).

Trimmed-down build.cake

var target = Argument("target", "Default");
var solution = "./some-random.sln";

Task("Default")
.Does(() => {
    NuGetRestore(
        solution,
        new NuGetRestoreSettings {
            MSBuildVersion = NuGetMSBuildVersion.MSBuild15,
        }
    );
});

RunTarget(target);

Update: getting NuGet v4

Per @devlead's answer, I pointed the build.ps1 file at the v4.0.0 of NuGet and got this output.

Cannot find the specified version of msbuild: '15'
An error occurred when executing task 'RestoreNuGet'.
Error: NuGet: Process returned an error (exit code 1).

In my full build.cake, I use vswhere for later MSBuildSettings which I can get to dump out the MSBuild path it found (and I confirmed that exe exists in Explorer).

C:/Program Files (x86)/Microsoft Visual Studio/2017/Enterprise/MSBuild/15.0/Bin/amd64/MSBuild.exe

Body:
Make sure you're using the latest version of NuGet.exe, currently it's
v4.0.0 which is the latest version, but you can also see a list of available at https://dist.nuget.org

If you're using the default build.ps1 you could modify it to always download specific version of NuGet.exe

You can do this be remove the Test.Path parts - so it won't look for nuget.exe any where else but your tools folder.
Then change the download uri to not use latest stable (currently v3.5.0) but a specific version by in build.ps1 changing

$NUGET_URL = "https://dist.nuget.org/win-x86-commandline/latest/nuget.exe"

to

$NUGET_URL = "https://dist.nuget.org/win-x86-commandline/v4.0.0/nuget.exe"

will ensure you always download v4.0.0 of the exe.

It's also possible with a little PowerShell to verify correct version in tools, example

if ((Get-ChildItem $NUGET_EXE `
    | % VersionInfo `
    | % ProductVersion `
    | ? { $_ -eq '4.0.0' }|Measure-Object).Count -eq 1)
{
   'Correct version'
} else {
   'Incorrect version'
}


问:
STL std::map, pass by ref to const and the necessity of const_casting
I have a simple question regarding const_cast and best practices regarding STL containers. Consider the following where class Foo has a private STL std::map from Widget* to int:

Declaration:

```<code>#include <map>
using std::map;

class Widget;

class Foo {
public:
     Foo(int n);
     virtual ~Foo();

     bool hasWidget(const Widget&);

private:
     map<Widget*,int> widget_map;
};
</code>```

Definition:

```<code>#include <map>
#include "Foo.h"
#include "Widget.h"

using std::map;

Foo::Foo(int n)
{
     for (int i = 0; i < n; i++) {
          widget_map[new Widget()] = 1;
     }
}

Foo::~Foo()
{
     map<Widget*, int>::iterator it;
     for (it = widget_map.begin(); it != widget_map.end(); it++) {
          delete it->first;
     }
}

bool Foo::hasWidget(const Widget& w)
{
     map<Widget*, int>::iterator it;
     it = this->widget_map.find(const_cast<Widget*>(&w));
     return ( ! ( it == widget_map.end() ) );
}
</code>```

Given that hasWidget takes a reference to const as its parameter, the constness needs to be cast away when calling map::find (wiget_map being from Wiget* to int). As far as I can tell, this approach is both sensible and desirable -- but I'm reluctant to accept it as such without feedback from more experienced C++ programmers.

It seems to me that this is one of the few cases of using const_cast appropriately given that we're passing the result of the cast to an STL method. Am I correct?

I realise that other permutations of this question have been posed already (for example, const_cast for vector with object) but none seem to directly address the above.

Thanks in advance.

答:
I think I'm going to fall in the 'subjective and argumentative' through my answer, but I'll give it a shot...

I'm not horrified by the const_cast, but I'm skeptical on your design. The member function hasWidget takes its parameter by const ref : what does this say to the client ? From a client point of view, if I didn't know the implementation, I would probably think that each Widget is compared by value with the parameter. For me, the interface does not reflect the actual behavior, which compares the Widget by address.

For example, the current signature allows a temporary Widget to be passed, although the return value could never be true in this case. I would personally change the signature to (note that I added a const) :

```<code>bool hasWidget(const Widget *) const;
</code>```

Body:
I have a simple question regarding const_cast and best practices regarding STL containers. Consider the following where class Foo has a private STL std::map from Widget* to int:

Declaration:

#include <map>
using std::map;

class Widget;

class Foo {
public:
     Foo(int n);
     virtual ~Foo();

     bool hasWidget(const Widget&);

private:
     map<Widget*,int> widget_map;
};

Definition:

#include <map>
#include "Foo.h"
#include "Widget.h"

using std::map;

Foo::Foo(int n)
{
     for (int i = 0; i < n; i++) {
          widget_map[new Widget()] = 1;
     }
}

Foo::~Foo()
{
     map<Widget*, int>::iterator it;
     for (it = widget_map.begin(); it != widget_map.end(); it++) {
          delete it->first;
     }
}

bool Foo::hasWidget(const Widget& w)
{
     map<Widget*, int>::iterator it;
     it = this->widget_map.find(const_cast<Widget*>(&w));
     return ( ! ( it == widget_map.end() ) );
}

Given that hasWidget takes a reference to const as its parameter, the constness needs to be cast away when calling map::find (wiget_map being from Wiget* to int). As far as I can tell, this approach is both sensible and desirable -- but I'm reluctant to accept it as such without feedback from more experienced C++ programmers.

It seems to me that this is one of the few cases of using const_cast appropriately given that we're passing the result of the cast to an STL method. Am I correct?

I realise that other permutations of this question have been posed already (for example, const_cast for vector with object) but none seem to directly address the above.

Thanks in advance.

Body:
I think I'm going to fall in the 'subjective and argumentative' through my answer, but I'll give it a shot...

I'm not horrified by the const_cast, but I'm skeptical on your design. The member function hasWidget takes its parameter by const ref : what does this say to the client ? From a client point of view, if I didn't know the implementation, I would probably think that each Widget is compared by value with the parameter. For me, the interface does not reflect the actual behavior, which compares the Widget by address.

For example, the current signature allows a temporary Widget to be passed, although the return value could never be true in this case. I would personally change the signature to (note that I added a const) :

bool hasWidget(const Widget *) const;


问:
How to generate MANIFEST.MF file during compile phase
Standard way - using maven-jar-plugin - generates manifest file only during package phase and directly into jar file.

What I need is to generate manifest during compile phase and to be available in <target>/classes/META-INF.

My goal is to be able to read this manifest file in project running in debug mode in IntelliJ Idea. (Idea resolves in-project jar dependencies from <target>/classes instead of from <target>/*.jar - for hot-swap purpose).

The only solution I know of so far is to actually create my own MANIFEST.MF in src/main/java/resources/META-INF and let it be filtered+copied during resources phase. But I want to avoid this solution, I want the manifest to be generated standard way using <archive> configuration in pom file.

答:
You can do this with maven-bundle-plugin.</p>

```<code>   <plugin>
        <groupId>org.apache.felix</groupId>
        <artifactId>maven-bundle-plugin</artifactId>
        <version>3.3.0</version>
        <executions>
            <execution>
                <id>bundle-manifest</id>
                <phase>process-classes</phase>
                <goals>
                    <goal>manifest</goal>
                </goals>
            </execution>
        </executions>
        <configuration>
            <archive>
                <index>true</index>
                <manifest>
                    <addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
                    <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
                </manifest>
                <manifestEntries>
                    <Implementation-URL>${project.url}</Implementation-URL>
                    <Java-Version>${java.version}</Java-Version>
                    <Java-Vendor>${java.vendor}</Java-Vendor>
                    <Os-Name>${os.name}</Os-Name>
                    <Os-Arch>${os.arch}</Os-Arch>
                    <Os-Version>${os.version}</Os-Version>
                    <Scm-Url>${project.scm.url}</Scm-Url>
                    <Scm-Connection>${project.scm.connection}</Scm-Connection>
                </manifestEntries>
            </archive>
        </configuration>
    </plugin>
</code>```

Body:
You can do this with maven-bundle-plugin.

   <plugin>
        <groupId>org.apache.felix</groupId>
        <artifactId>maven-bundle-plugin</artifactId>
        <version>3.3.0</version>
        <executions>
            <execution>
                <id>bundle-manifest</id>
                <phase>process-classes</phase>
                <goals>
                    <goal>manifest</goal>
                </goals>
            </execution>
        </executions>
        <configuration>
            <archive>
                <index>true</index>
                <manifest>
                    <addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
                    <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
                </manifest>
                <manifestEntries>
                    <Implementation-URL>${project.url}</Implementation-URL>
                    <Java-Version>${java.version}</Java-Version>
                    <Java-Vendor>${java.vendor}</Java-Vendor>
                    <Os-Name>${os.name}</Os-Name>
                    <Os-Arch>${os.arch}</Os-Arch>
                    <Os-Version>${os.version}</Os-Version>
                    <Scm-Url>${project.scm.url}</Scm-Url>
                    <Scm-Connection>${project.scm.connection}</Scm-Connection>
                </manifestEntries>
            </archive>
        </configuration>
    </plugin>


问:
Assembly fill array with Consecutive numbers
I have problem with simple array in Assembly. Is that correct approach. I need to fill up array with consectuive numbers, in this case it is 10. Code as follow:

```<code>section .data
array TIMES 10 db 0

section .text
global _start
_start:
mov eax,10  ;counter
mov ebx,0   ;start from value 0
mov ecx,array;

loop:
mov [ecx],ebx
inc ecx     ;increase pointer to next array element
inc ebx     ;increase inputted value
dec eax     ;decrease iterator
jnz loop    ;if iterator not 0 loop

mov eax,1   ;eit
int 0x80
</code>```

Is that correct code?

While debuging using gdb. Breakpoint on line 11 (5 loop) show following outputs:

```<code>$1: $eax = 4
$2: $ebx = 6
$3: $ecx = 134516902

x/d $ecx-1   0x80490a5:   5
</code>```

How can i lookup for values from entire array? Only this place in me $ecx-1 shows correct value of inputed number. I am almost sure that I the issue is my code.

Kind Regards

答:
There are several ways you can approach this. In the example below, we are using the lodsb (load string of size byte) instruction to retrieve values from an array of byte size elements. I'm not suggesting that this is the most efficient method.  </p>

```<code>  1 section .data
  2         array  db       3,1,4,1,5,9,2,6,5
  3         len.array equ   $-array
  4
  5 section .text
  6         global _start
  7 _start:
  8         lea esi, [array]  ; load array pointer
  9         mov ecx, len.array  ; use length of array as counter
 10 loop:
 11         lodsb        ; load string byte - will place loads in al;
 12         dec ecx      ; decrements ecx
 13         cmp ecx, 0   ;
 14         jnz loop
 15
 16 _exit:
 17
 18         mov eax,1   ;exit
 19         int 0x80
</code>```

<p>(gdb) display $ax ; you can see ax is being populated with array elements as you step through the code. </p>

```<code>12              dec ecx
1: $ax = 3
(gdb)
13              cmp ecx, 0
1: $ax = 3
(gdb)
14              jnz loop
1: $ax = 3
(gdb)
11              lodsb
1: $ax = 3
(gdb)
12              dec ecx
1: $ax = 1
(gdb)
13              cmp ecx, 0
1: $ax = 1
(gdb)
14              jnz loop
1: $ax = 1
(gdb)
11              lodsb
1: $ax = 1
(gdb)
12              dec ecx
1: $ax = 4
(gdb)
13              cmp ecx, 0
1: $ax = 4
(gdb)
14              jnz loop
1: $ax = 4
(gdb)
11              lodsb
1: $ax = 4
</code>```

Body:
I have problem with simple array in Assembly. Is that correct approach. I need to fill up array with consectuive numbers, in this case it is 10. Code as follow:

section .data
array TIMES 10 db 0

section .text
global _start
_start:
mov eax,10  ;counter
mov ebx,0   ;start from value 0
mov ecx,array;

loop:
mov [ecx],ebx
inc ecx     ;increase pointer to next array element
inc ebx     ;increase inputted value
dec eax     ;decrease iterator
jnz loop    ;if iterator not 0 loop

mov eax,1   ;eit
int 0x80

Is that correct code?

While debuging using gdb. Breakpoint on line 11 (5 loop) show following outputs:

$1: $eax = 4
$2: $ebx = 6
$3: $ecx = 134516902

x/d $ecx-1   0x80490a5:   5

How can i lookup for values from entire array? Only this place in me $ecx-1 shows correct value of inputed number. I am almost sure that I the issue is my code.

Kind Regards

Body:
There are several ways you can approach this. In the example below, we are using the lodsb (load string of size byte) instruction to retrieve values from an array of byte size elements. I'm not suggesting that this is the most efficient method.

  1 section .data
  2         array  db       3,1,4,1,5,9,2,6,5
  3         len.array equ   $-array
  4
  5 section .text
  6         global _start
  7 _start:
  8         lea esi, [array]  ; load array pointer
  9         mov ecx, len.array  ; use length of array as counter
 10 loop:
 11         lodsb        ; load string byte - will place loads in al;
 12         dec ecx      ; decrements ecx
 13         cmp ecx, 0   ;
 14         jnz loop
 15
 16 _exit:
 17
 18         mov eax,1   ;exit
 19         int 0x80

(gdb) display $ax ; you can see ax is being populated with array elements as you step through the code.

12              dec ecx
1: $ax = 3
(gdb)
13              cmp ecx, 0
1: $ax = 3
(gdb)
14              jnz loop
1: $ax = 3
(gdb)
11              lodsb
1: $ax = 3
(gdb)
12              dec ecx
1: $ax = 1
(gdb)
13              cmp ecx, 0
1: $ax = 1
(gdb)
14              jnz loop
1: $ax = 1
(gdb)
11              lodsb
1: $ax = 1
(gdb)
12              dec ecx
1: $ax = 4
(gdb)
13              cmp ecx, 0
1: $ax = 4
(gdb)
14              jnz loop
1: $ax = 4
(gdb)
11              lodsb
1: $ax = 4


问:
Async queue operations
I have a queue that is increased by new elements every x seconds.

I want to perform an action on each of the items in the queue. But I want to "consume" one item before I carry on to the next item.
Each item is making an async call that needs to be completed before carrying over to the next item.

I am having issues making this work without blocking the application. Anyone have an example of how this can be done?

答:
This seems fairly straightforward. I assume everything is on a single thread. If things are on multiple threads then you have a slightly harder problem, but not much harder.

```<code>class C
{
  bool busy = false;
  FancyQueue q;
  public C()
  {
    q = new FancyQueue();
    q.Enqueued += HandleEnqueue;
  }
  Task HandleItem(Item x) { ... }
  async void HandleEnqueue()
  {
    if (busy)
      return;
    busy = true;
    while (!q.Empty)
      await HandleItem(q.Dequeue());
    busy = false;
  }
}
</code>```

Suppose the queue is empty. Somehow a new item arrives. The event handler is called. We set the busy flag and extract the item, and await its processing. We return to the message loop. Suppose another item arrives while we are waiting. We enter the handler, but it is marked as busy, so we bail out; we know that the item will be handled in the future. Finally, the first item is handled, so we resume the event handler, and hey, the queue is not empty, so we keep on going; we await handling the next item in the queue.

Once the queue is empty then we set busy back to false and the initial invocation of the event handler completes.

With this plan we never have two dequeued items "in flight" at the same time. Remember, "await" is a point in a workflow where the workflow does not continue until after the task is complete.

Title: Async queue operations

Body:
This seems fairly straightforward. I assume everything is on a single thread. If things are on multiple threads then you have a slightly harder problem, but not much harder.

class C
{
  bool busy = false;
  FancyQueue q;
  public C()
  {
    q = new FancyQueue();
    q.Enqueued += HandleEnqueue;
  }
  Task HandleItem(Item x) { ... }
  async void HandleEnqueue()
  {
    if (busy)
      return;
    busy = true;
    while (!q.Empty)
      await HandleItem(q.Dequeue());
    busy = false;
  }
}

Suppose the queue is empty. Somehow a new item arrives. The event handler is called. We set the busy flag and extract the item, and await its processing. We return to the message loop. Suppose another item arrives while we are waiting. We enter the handler, but it is marked as busy, so we bail out; we know that the item will be handled in the future. Finally, the first item is handled, so we resume the event handler, and hey, the queue is not empty, so we keep on going; we await handling the next item in the queue.

Once the queue is empty then we set busy back to false and the initial invocation of the event handler completes.

With this plan we never have two dequeued items "in flight" at the same time. Remember, "await" is a point in a workflow where the workflow does not continue until after the task is complete.


问:
Can jQuery detect when user resizes browser?
I wrote simple code with jQuery that hides navbar when user scrolls the page. I works great, but now I want add one more thing.

I want it to work like it does now when user viewport width is more than 768px.
But when user viewport is smaller then 768px I want that navbar to be visible all the time.

The code should be smart enough, that it can detect browser was resized by user and it should still work.

To sum up:

User start my page with chrome viewport 1024px - when he scrolls page down navbar is hiding, when he goes back to the top of the page navbar is reappearing.

Then user resizes chrome and has viewport 700px - when he scrolls page down navbar should be always on.

Any smart ideas how to achieve it?

```<code>$(document).ready(function() {
  $(".navbar").show();
  $(function() {
    $(window).scroll(function() {
      if ($(this).scrollTop() > 300) {
        $(".navbar").fadeOut();
      } else {
        $(".navbar").fadeIn();
      }
    });
  });
});
</code>```

答:
edited: actually, you would want the following, previous answer (window.width) only checks when you tell it this will whenever resized.</p>

```<code>var windowsize = $(window).width();  // if you need var outside of function for something

$(window).resize(function() {
    windowsize = $(window).width();
    if (windowsize > 700) {
    dowhatever();
  });
 }
});
</code>```

Body:
I wrote simple code with jQuery that hides navbar when user scrolls the page. I works great, but now I want add one more thing.

I want it to work like it does now when user viewport width is more than 768px.
But when user viewport is smaller then 768px I want that navbar to be visible all the time.

The code should be smart enough, that it can detect browser was resized by user and it should still work.

To sum up:

User start my page with chrome viewport 1024px - when he scrolls page down navbar is hiding, when he goes back to the top of the page navbar is reappearing.

Then user resizes chrome and has viewport 700px - when he scrolls page down navbar should be always on.

Any smart ideas how to achieve it?

$(document).ready(function() {
  $(".navbar").show();
  $(function() {
    $(window).scroll(function() {
      if ($(this).scrollTop() > 300) {
        $(".navbar").fadeOut();
      } else {
        $(".navbar").fadeIn();
      }
    });
  });
});

Body:
edited: actually, you would want the following, previous answer (window.width) only checks when you tell it this will whenever resized.

var windowsize = $(window).width();  // if you need var outside of function for something

$(window).resize(function() {
    windowsize = $(window).width();
    if (windowsize > 700) {
    dowhatever();
  });
 }
});


问:
Insert list evenly in another list
I am wanting to merge 2 lists together with jQuery but I am not even sure where to start. Instead of prepending or appeding the list I need to place each item between the other list. Not quite sure the best way to word this but basically I have the following HTML

```<code><ul>
  <li>A<li>
  <li>B<li>
  <li>C<li>
  <li>D<li>
  <li>E<li>
</ul>

<ul>
  <li>1<li>
  <li>2<li>
  <li>3<li>
  <li>4<li>
  <li>5<li>
</ul>
</code>```

And I am wanting a way to get the following:

```<code><ul>
  <li>A<li>
  <li>1<li>
  <li>B<li>
  <li>2<li>
  <li>C<li>
  <li>3<li>
  <li>D<li>
  <li>4<li>
  <li>E<li>
  <li>5<li>
</ul>
</code>```

答:
This is a concept called array stitching, and can be accomplished with the following code:

Note - This approach works even if your two arrays are of unequal lengths!

$(function () {
  var lists = $("ul");
  // create real arrays from jQuery collections
  var list1 = Array.apply(null, lists.eq(0).find("li"));
  var list2 = Array.apply(null, lists.eq(1).find("li"));
  function stitch(arr1, arr2) {
    var newArr = [];
    while (arr1.length && arr2.length) {
      newArr.push(arr1.shift());
      newArr.push(arr2.shift());
    }
    return newArr.concat(arr1, arr2);
  }
  var newList = stitch(list1, list2);
  $("#results").html(newList);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>A</li>
<li>B</li>
<li>C</li>
<li>D</li>
<li>E</li>
</ul>

<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>

<ul id="results">
</ul></code>```

What is really cool is the ability to use ES6 gather/spread syntax to easily create a generic function that can stitch together n number of arrays. Here's how that can be done:

$(function () {
  var lists = $("ul");
  // create real arrays from jQuery collections
  var list1 = Array.apply(null, lists.eq(0).find("li"));
  var list2 = Array.apply(null, lists.eq(1).find("li"));
  var list3 = Array.apply(null, lists.eq(2).find("li"));
  function stitch(...arrs) {
    var newArr = [];
    while (arrs.some(arr=>arr.length)) {
      arrs.forEach(arr=>{
        if (arr.length) {
          newArr.push(arr.shift());
        }
      });
    }
    return newArr;
  }
  var newList = stitch(list1, list2, list3);
  $("#results").html(newList);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>A</li>
<li>B</li>
<li>C</li>
<li>D</li>
<li>E</li>
</ul>

<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>4</li>
<li>5</li>
</ul>

<ul>
<li>Do</li>
<li>Re</li>
<li>Me</li>
<li>Fa</li>
<li>So</li>
<li>Fa</li>
<li>So</li>
</ul>
<ul id="results">
</ul></code>```

Title: Insert list evenly in another list

Body:
I am wanting to merge 2 lists together with jQuery but I am not even sure where to start. Instead of prepending or appeding the list I need to place each item between the other list. Not quite sure the best way to word this but basically I have the following HTML

A

B

C

D

E

1

2

3

4

5

And I am wanting a way to get the following:

A

1

B

2

C

3

D

4

E

5

Body:
This is a concept called array stitching, and can be accomplished with the following code:

Note - This approach works even if your two arrays are of unequal lengths!

$(function () {
  var lists = $("ul");
  // create real arrays from jQuery collections
  var list1 = Array.apply(null, lists.eq(0).find("li"));
  var list2 = Array.apply(null, lists.eq(1).find("li"));
  function stitch(arr1, arr2) {
    var newArr = [];
    while (arr1.length && arr2.length) {
      newArr.push(arr1.shift());
      newArr.push(arr2.shift());
    }
    return newArr.concat(arr1, arr2);
  }
  var newList = stitch(list1, list2);
  $("#results").html(newList);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>A</li>
<li>B</li>
<li>C</li>
<li>D</li>
<li>E</li>
</ul>

<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>

<ul id="results">
</ul>

What is really cool is the ability to use ES6 gather/spread syntax to easily create a generic function that can stitch together n number of arrays. Here's how that can be done:

$(function () {
  var lists = $("ul");
  // create real arrays from jQuery collections
  var list1 = Array.apply(null, lists.eq(0).find("li"));
  var list2 = Array.apply(null, lists.eq(1).find("li"));
  var list3 = Array.apply(null, lists.eq(2).find("li"));
  function stitch(...arrs) {
    var newArr = [];
    while (arrs.some(arr=>arr.length)) {
      arrs.forEach(arr=>{
        if (arr.length) {
          newArr.push(arr.shift());
        }
      });
    }
    return newArr;
  }
  var newList = stitch(list1, list2, list3);
  $("#results").html(newList);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>A</li>
<li>B</li>
<li>C</li>
<li>D</li>
<li>E</li>
</ul>

<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>4</li>
<li>5</li>
</ul>

<ul>
<li>Do</li>
<li>Re</li>
<li>Me</li>
<li>Fa</li>
<li>So</li>
<li>Fa</li>
<li>So</li>
</ul>
<ul id="results">
</ul>